@sinch/functions-runtime 0.5.21 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,83 @@ 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
+ }
527
794
  /** Options for a single TTS message */
528
795
  export interface SayOptions {
529
796
  /** Voice name. Defaults to {@link DEFAULT_VOICE}. */
@@ -582,6 +849,69 @@ export interface DialOptions extends DialEvents {
582
849
  */
583
850
  endOnFailure?: string;
584
851
  }
852
+ /** The bridge every call this package builds joins unless told otherwise. */
853
+ export declare const DEFAULT_BRIDGE_NAME = "bridge";
854
+ /**
855
+ * Options for {@link CommandBuilder.bridgeTo} and the `dial*` verbs built on it.
856
+ *
857
+ * On a handler's builder none of these is needed: the leg names, the bridge, `from` and the
858
+ * teardown all come from the call being answered.
859
+ */
860
+ export interface BridgeToOptions {
861
+ /**
862
+ * Caller identity presented to the callee. Defaults by destination: a phone number sees the
863
+ * Sinch number the call is on, so the far party never sees the caller's; a SIP endpoint or
864
+ * agent sees the caller's own E.164 number, because for them it is identity. Streams carry none.
865
+ */
866
+ from?: Origin;
867
+ /** Seconds to wait for an answer. Maximum 60. */
868
+ timeout?: number;
869
+ /** Maximum call duration in seconds. Maximum 14400. */
870
+ maxDuration?: number;
871
+ /** Name for the dialled leg. Defaults by destination: `destination`, `stream` or `relay`. */
872
+ legName?: string;
873
+ /** Bridge both legs join. Defaults to `bridge`; name another for a hold room or a whisper. */
874
+ bridgeName?: string;
875
+ /**
876
+ * Name the live leg already has. Only for a flow no handler's builder answers — a batch body,
877
+ * a `PATCH` — since a handler's builder knows it. When set, the flow never names the live leg.
878
+ */
879
+ liveLeg?: string;
880
+ /**
881
+ * Runs when the leg never connects: busy, rejected, timed out or failed. Naming any one outcome
882
+ * detaches the service webhook from all six, so this names all four at once. Defaults to ending
883
+ * the live leg.
884
+ */
885
+ onNoAnswer?: Flow;
886
+ /** Runs when the callee is busy. Overrides `onNoAnswer` for this outcome. */
887
+ onBusy?: Flow;
888
+ /** Runs when the callee rejects. Overrides `onNoAnswer` for this outcome. */
889
+ onReject?: Flow;
890
+ /** Runs when nobody answers within `timeout`. Overrides `onNoAnswer` for this outcome. */
891
+ onTimeout?: Flow;
892
+ /** Runs when the leg could not be set up. Overrides `onNoAnswer` for this outcome. */
893
+ onFailure?: Flow;
894
+ }
895
+ /** SIP settings {@link CommandBuilder.dialSip} passes to `dial.sip` */
896
+ export interface DialSipOptions extends BridgeToOptions {
897
+ transport?: "UDP" | "TCP" | "TLS";
898
+ headers?: Headers$1;
899
+ }
900
+ /** Stream settings {@link CommandBuilder.dialStream} passes to `dial.stream` */
901
+ export interface DialStreamOptions extends BridgeToOptions {
902
+ sampleRate?: SampleRate;
903
+ headers?: Headers$1;
904
+ }
905
+ /** Relay settings {@link CommandBuilder.dialRelay} passes to `dial.relay` */
906
+ export interface DialRelayOptions extends BridgeToOptions {
907
+ ttsVoice?: string;
908
+ sttLanguage?: string;
909
+ enableInterruptions?: boolean;
910
+ headers?: Headers$1;
911
+ }
912
+ /** SIP settings and a leg cap for {@link CommandBuilder.dialAgent} with a SIP provider */
913
+ export interface DialAgentOptions extends BridgeToOptions, SipAgentOptions {
914
+ }
585
915
  /**
586
916
  * The four answering-machine-detection outcomes.
587
917
  *
@@ -729,9 +1059,12 @@ export declare class PromptBuilder {
729
1059
  * with the collected input, arriving as `call.menu`.
730
1060
  */
731
1061
  export declare class MenuItemBuilder {
1062
+ private readonly scope?;
732
1063
  private readonly item;
733
1064
  private readonly matchOrder;
734
1065
  private readonly matches;
1066
+ /** @param scope - The call the enclosing builder answers, handed to every option's flow */
1067
+ constructor(scope?: FlowScope | undefined);
735
1068
  /**
736
1069
  * Prompt played when the menu is entered.
737
1070
  *
@@ -798,6 +1131,18 @@ export declare class MenuItemBuilder {
798
1131
  * @throws If `pattern` does not compile as a regular expression
799
1132
  */
800
1133
  match(pattern: string, flow: Flow): this;
1134
+ /**
1135
+ * What one keypress sequence does — "press 1 for sales".
1136
+ *
1137
+ * `option` takes the tones literally and escapes `*` and `#` for you; {@link match} takes a
1138
+ * regular expression. Both feed the same ordered `matches` list, first match wins.
1139
+ *
1140
+ * @param digits - DTMF tones only: `0`-`9`, `*` and `#`
1141
+ * @param flow - Commands to run when the caller enters exactly these tones
1142
+ * @throws If `digits` contains anything but DTMF tones
1143
+ */
1144
+ option(digits: string, flow: Flow): this;
1145
+ private addMatch;
801
1146
  /**
802
1147
  * Commands to run once the caller is out of attempts.
803
1148
  *
@@ -807,13 +1152,62 @@ export declare class MenuItemBuilder {
807
1152
  /** Emit the menu. */
808
1153
  build(): MenuItem;
809
1154
  }
1155
+ /**
1156
+ * A menu written as one object — the settings {@link MenuItemBuilder} exposes, with `options`
1157
+ * standing in for a run of `option()` calls. No regular expressions here: a `match()` needs the
1158
+ * callback form.
1159
+ */
1160
+ export interface MenuDefinition {
1161
+ /** Prompt played when the menu is entered */
1162
+ prompt?: PromptFlow;
1163
+ /** Prompt played on each retry */
1164
+ repeatPrompt?: PromptFlow;
1165
+ /** Seconds of silence that count as no input */
1166
+ inputTimeout?: number;
1167
+ /** How many times the prompt repeats before `onFail` runs */
1168
+ repeatCount?: number;
1169
+ /** Fewest input characters collected before evaluating */
1170
+ minLength?: number;
1171
+ /** Input length that triggers evaluation */
1172
+ maxLength?: number;
1173
+ /** Sequence that ends input early, e.g. `#` */
1174
+ terminatedBy?: string;
1175
+ /**
1176
+ * What each keypress does, keyed by DTMF tones and escaped exactly as `option()` escapes them.
1177
+ * A plain object is safe here although JavaScript moves integer-like keys first: each key is
1178
+ * an anchored literal, so no two can match the same input and their order changes nothing.
1179
+ */
1180
+ options?: Record<string, Flow>;
1181
+ /** Commands to run once the caller is out of attempts */
1182
+ onFail?: Flow;
1183
+ }
1184
+ /** Start a flow that speaks. See {@link CommandBuilder.say}. */
1185
+ export declare function say(text: string, options?: SayOptions): CommandBuilder;
1186
+ /** Start a flow that plays audio. See {@link CommandBuilder.play}. */
1187
+ export declare function play(url: string): CommandBuilder;
1188
+ /** Start a flow with a menu. See {@link CommandBuilder.menu}. */
1189
+ export declare function menu(name: string, define: MenuDefinition | ((menu: MenuItemBuilder) => MenuItemBuilder | void)): CommandBuilder;
1190
+ /** Start a flow that bridges the caller to a destination. See {@link CommandBuilder.bridgeTo}. */
1191
+ export declare function bridgeTo(destination: Destination, options?: BridgeToOptions): CommandBuilder;
1192
+ /** Start a flow that connects the caller to a phone number. See {@link CommandBuilder.dialPhone}. */
1193
+ export declare function dialPhone(number: string, options?: BridgeToOptions): CommandBuilder;
1194
+ /** Start a flow that connects the caller to a SIP endpoint. See {@link CommandBuilder.dialSip}. */
1195
+ export declare function dialSip(address: string, options?: DialSipOptions): CommandBuilder;
1196
+ /** Start a flow that connects the caller to a media stream. See {@link CommandBuilder.dialStream}. */
1197
+ export declare function dialStream(endpoint: string, options?: DialStreamOptions): CommandBuilder;
1198
+ /** Start a flow that connects the caller to Voice Relay. See {@link CommandBuilder.dialRelay}. */
1199
+ export declare function dialRelay(endpoint: string, options?: DialRelayOptions): CommandBuilder;
1200
+ export declare function dialRelay(relay: DialableAgent, options?: BridgeToOptions): CommandBuilder;
1201
+ /** Start a flow that connects the caller to an AI voice agent. See {@link CommandBuilder.dialAgent}. */
1202
+ export declare function dialAgent(provider: SipAgentProvider | (string & Record<never, never>), number: string, options?: DialAgentOptions): CommandBuilder;
1203
+ export declare function dialAgent(agent: DialableAgent, options?: BridgeToOptions): CommandBuilder;
810
1204
  /**
811
1205
  * Emit-target-agnostic description of a call flow.
812
1206
  *
813
- * Build one of these with the client's planning methods, then hand it to
814
- * {@link toCallRequest} or {@link toWebhookResponse}.
1207
+ * Build one of these with a builder or with `client.flows`, then hand it to
1208
+ * {@link toCallBody} or {@link toWebhookBody}.
815
1209
  */
816
- export interface Plan {
1210
+ export interface CallFlow {
817
1211
  /** Ordered command list. Must contain at least one command. */
818
1212
  commands: Command[];
819
1213
  /**
@@ -828,7 +1222,7 @@ export interface Plan {
828
1222
  onHangup?: Command[];
829
1223
  }
830
1224
  /**
831
- * Emit a plan as a `POST /v2/projects/{projectId}/calls` body.
1225
+ * Emit a flow as a `POST /v2/projects/{projectId}/calls` body.
832
1226
  *
833
1227
  * Drops `callName` and `onHangup`: the `callRequest` schema forbids them and the
834
1228
  * API rejects unknown keys with a 400.
@@ -838,13 +1232,13 @@ export interface Plan {
838
1232
  *
839
1233
  * @example
840
1234
  * ```typescript
841
- * const body = toCallRequest({ commands: [{ command: 'hangup' }] });
1235
+ * const body = toCallBody({ commands: [{ command: 'hangup' }] });
842
1236
  * // { commands: [{ command: 'hangup' }] }
843
1237
  * ```
844
1238
  */
845
- export declare function toCallRequest(plan: Plan): CallRequest;
1239
+ export declare function toCallBody(plan: CallFlow): CallRequest;
846
1240
  /**
847
- * Emit a plan as a webhook-response body.
1241
+ * Emit a flow as a webhook-response body.
848
1242
  *
849
1243
  * The response is an object wrapping a `commands` array, not a bare array.
850
1244
  *
@@ -853,7 +1247,7 @@ export declare function toCallRequest(plan: Plan): CallRequest;
853
1247
  *
854
1248
  * @example
855
1249
  * ```typescript
856
- * const body = toWebhookResponse({
1250
+ * const body = toWebhookBody({
857
1251
  * commands: [{ command: 'answer' }],
858
1252
  * callName: 'incoming',
859
1253
  * onHangup: [{ command: 'hangup' }],
@@ -861,14 +1255,65 @@ export declare function toCallRequest(plan: Plan): CallRequest;
861
1255
  * // { commands: [...], callName: 'incoming', events: { onHangup: [...] } }
862
1256
  * ```
863
1257
  */
864
- export declare function toWebhookResponse(plan: Plan): WebhookResponse;
1258
+ export declare function toWebhookBody(plan: CallFlow): WebhookBody;
1259
+ /** The menu that fired and what the caller entered */
1260
+ export interface MenuInput {
1261
+ /** Name of the menu that fired */
1262
+ menuName: string;
1263
+ /** The input sequence collected from the caller */
1264
+ input: string;
1265
+ }
1266
+ interface DeprecatedCallField {
1267
+ /**
1268
+ * @deprecated The call is already flattened onto this object — read the field directly (e.g.
1269
+ * `call.callId`, not `call.call.callId`). This getter returns the object itself, kept only so
1270
+ * code written before the flatten still compiles and runs; it is not present on the wire —
1271
+ * non-enumerable, so it's absent from `JSON.stringify`, `toWebhookRequest`, and any other
1272
+ * spread of this object.
1273
+ */
1274
+ readonly call: Call;
1275
+ }
1276
+ type Flattened<T> = Call & DeprecatedCallField & T;
1277
+ /** Any event, flattened — what `fallback` receives */
1278
+ export type CallEvent = Flattened<{
1279
+ /** Event that triggered this webhook */
1280
+ event: EventType;
1281
+ /** Present for `call.menu`, and for a `webhook` command run inside a menu */
1282
+ menu?: MenuInput;
1283
+ }>;
1284
+ /** `call.incoming` — an inbound call arrived */
1285
+ export type IncomingCall = Flattened<{
1286
+ event: "call.incoming";
1287
+ }>;
1288
+ /** `call.answered` — an outbound call was answered */
1289
+ export type AnsweredCall = Flattened<{
1290
+ event: "call.answered";
1291
+ }>;
1292
+ /** `call.webhook.<name>` — a `webhook` command asked what to do next */
1293
+ export type WebhookCall = Flattened<{
1294
+ event: `call.webhook.${string}`;
1295
+ menu?: MenuInput;
1296
+ }>;
1297
+ /** `call.menu` with what the caller entered, or a `webhook` command's event */
1298
+ export type MenuCall = Flattened<{
1299
+ event: "call.menu";
1300
+ menu: MenuInput;
1301
+ }> | WebhookCall;
1302
+ /** `call.hangup` or `call.failed` — the call ended */
1303
+ export type CompletedCall = Flattened<{
1304
+ event: "call.hangup" | "call.failed";
1305
+ }>;
865
1306
  /**
866
- * The bridge every call this package builds joins unless told otherwise.
1307
+ * Flatten a webhook body into what a handler receives.
867
1308
  *
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.
1309
+ * @param request - The webhook body as the platform sent it
870
1310
  */
871
- export declare const DEFAULT_BRIDGE_NAME = "bridge";
1311
+ export declare function toCallEvent(request: WebhookRequest): CallEvent;
1312
+ /**
1313
+ * The webhook body again, from whichever of the two shapes a caller has — the options that take
1314
+ * "the call" (`connectAgent`, `transferTo*`) accept a handler's flattened call or a raw body.
1315
+ */
1316
+ export declare function toWebhookRequest(call: CallEvent | WebhookRequest): WebhookRequest;
872
1317
  /** Name given to the leg a transfer dials, when the caller does not name it. */
873
1318
  export declare const DEFAULT_TRANSFER_LEG = "transfer";
874
1319
  /** Options for {@link buildTransferCommands} and {@link Client.transfer}. */
@@ -943,6 +1388,31 @@ export interface TransferOptions {
943
1388
  * ```
944
1389
  */
945
1390
  export declare function buildTransferCommands(to: Destination, options?: TransferOptions): Command[];
1391
+ /** Options for the client's `transferTo*` methods. */
1392
+ export interface TransferToOptions {
1393
+ /** Bridge the leg is moved into. Defaults to `transferBridge`. */
1394
+ bridgeName?: string;
1395
+ /**
1396
+ * Name of the leg being moved — the one ended if the transfer fails or the new party hangs
1397
+ * up. Defaults to the `callName` of a `{ sessionId, callName }` target, else `origin` when
1398
+ * `call` says the call is outbound, else `caller`: the names a handler's builder and
1399
+ * `flows.call` give the live leg.
1400
+ */
1401
+ liveLeg?: string;
1402
+ /** Name for the dialled leg. Defaults to {@link DEFAULT_TRANSFER_LEG}. */
1403
+ legName?: string;
1404
+ /** Seconds to wait for an answer. Defaults to 30. */
1405
+ timeout?: number;
1406
+ /** Maximum duration of the new leg, in seconds */
1407
+ maxDuration?: number;
1408
+ /** Caller identity presented to the destination. Defaults from `call`, as `dial*` does. */
1409
+ from?: Origin;
1410
+ /**
1411
+ * The call's latest webhook, when the caller has it. Gives `from` and `liveLeg` the same
1412
+ * defaults as the builder's `dial*` helpers, and is required to transfer to a realtime agent.
1413
+ */
1414
+ call?: CallEvent | WebhookRequest;
1415
+ }
946
1416
  /** Construction options for {@link Client} */
947
1417
  export interface Options {
948
1418
  /** Sinch project id. Defaults to `PROJECT_ID`, then `context.config.projectId`. */
@@ -1015,8 +1485,30 @@ export interface BridgeOptions extends CallOptions {
1015
1485
  /** Bridge name joining the two legs. Defaults to `bridge`. */
1016
1486
  bridgeName?: string;
1017
1487
  }
1018
- /** A single webhook handler */
1019
- export type WebhookHandler = (event: WebhookRequest) => HandlerResult | Promise<HandlerResult>;
1488
+ /** {@link Client.flows}: each call-placing method's flow, built without sending it. */
1489
+ export interface ClientFlows {
1490
+ /** The {@link Client.call} flow */
1491
+ call(to: Destination, options?: PlaceCallOptions): CallFlow;
1492
+ /** The {@link Client.callWithStream} flow. @throws If the stream path cannot be resolved */
1493
+ streamCall(to: Destination, stream: string, options?: StreamCallOptions): CallFlow;
1494
+ /** The {@link Client.callWithRelay} flow */
1495
+ relayCall(to: Destination, relay: string, options?: RelayCallOptions): CallFlow;
1496
+ /** The {@link Client.bridge} flow */
1497
+ bridge(a: Destination, b: Destination, options?: BridgeOptions): CallFlow;
1498
+ /** The {@link Client.hangup} command list. Ends the addressed leg when no leg is named. */
1499
+ hangup(...callNames: string[]): Command[];
1500
+ }
1501
+ /**
1502
+ * A single webhook handler.
1503
+ *
1504
+ * @param call - The call, flattened, with the `event` that fired (and `menu`, for a menu)
1505
+ * beside its fields — `call.from`, `call.event`. Typed per handler slot; see {@link CallHandlers}.
1506
+ * @param builder - A command builder already primed with this call, one per request. Return
1507
+ * it (`.build()` is optional); its `dial*` helpers default `from`, the leg names and the
1508
+ * teardown from the call it answers.
1509
+ * @param request - The webhook body as the platform sent it. Omitted in every normal handler.
1510
+ */
1511
+ export type WebhookHandler<C extends CallEvent = CallEvent> = (call: C, builder: CommandBuilder, request?: WebhookRequest) => HandlerResult | Promise<HandlerResult>;
1020
1512
  /**
1021
1513
  * A lifecycle handler slot — every key of {@link CallHandlers} except `webhooks`, which is a
1022
1514
  * map of handlers rather than one.
@@ -1086,6 +1578,400 @@ export declare const REDACTED = "[redacted]";
1086
1578
  export declare function redactCredentials<T>(body: T): T;
1087
1579
  /** `JSON.stringify`, but honouring any {@link tagOrder} tag found on nested objects. */
1088
1580
  declare function stringify(value: unknown): string;
1581
+ /** Options for {@link connectAgent}. */
1582
+ export interface ConnectAgentOptions extends SipAgentOptions {
1583
+ /**
1584
+ * The `call.incoming` event, when available. Used to default `from` to the caller's E.164
1585
+ * number and to add the `X-Sinch-Call-Id` / `X-Caller-Number` / `X-Dialed-Number` SIP
1586
+ * headers the grok-voice template sends — how per-call context reaches the agent without an
1587
+ * API round trip. Omit it and none of that context rides along.
1588
+ */
1589
+ call?: CallEvent | WebhookRequest;
1590
+ /** Hard cap on call length, in seconds. Both providers bill per minute of audio. Default 1800. */
1591
+ maxDuration?: number;
1592
+ /** Bridge both legs join. Defaults to {@link DEFAULT_BRIDGE_NAME}. */
1593
+ bridgeName?: string;
1594
+ /** Name for the inbound leg. Defaults to `'caller'`. */
1595
+ callerLeg?: string;
1596
+ /** Name for the leg dialled to the agent. Defaults to `'agent'`. */
1597
+ agentLeg?: string;
1598
+ }
1599
+ /**
1600
+ * Answer the caller, bridge them, dial a SIP-based AI agent into the same bridge, and end the
1601
+ * agent leg when the caller hangs up.
1602
+ *
1603
+ * @param provider - `'elevenlabs'` or `'grok'`. `AgentProvider.ElevenLabs` / `.Grok` from
1604
+ * `@sinch/functions-runtime` work here too — this parameter is a plain string, not the v1
1605
+ * enum, since this package cannot import from the rest of the runtime.
1606
+ * @param number - The number in the SIP URI's user part: for Grok, the Direct SIP phone
1607
+ * number registered in the xAI console; for ElevenLabs, the number attached to the agent's
1608
+ * phone integration. Neither provider routes by agent id. Must be an E.164 number you
1609
+ * configured, never a value read off a caller-controlled webhook field — it is interpolated
1610
+ * straight into a SIP URI.
1611
+ * @param options - Caller context, extra headers, duration, transport/host/port overrides,
1612
+ * bridge and leg names.
1613
+ * @throws If `provider` is not a SIP-based provider this helper supports, if `number` is not
1614
+ * E.164, or if `options.host` contains a character a SIP host cannot
1615
+ *
1616
+ * Return the {@link CallFlow} directly from `incoming` — `callName` and `onHangup` are only
1617
+ * honoured on a response to `call.incoming`. Handing `.commands` on to something else and
1618
+ * dropping the rest of the plan silently loses the agent-leg teardown, and the SIP leg bills
1619
+ * until `maxDuration`. For the same reason it cannot be a menu option or answer `call.menu`:
1620
+ * use the handler builder's `dialAgent`, which knows which webhook it answers.
1621
+ *
1622
+ * @example
1623
+ * ```typescript
1624
+ * export const voiceWebhook = onCall({
1625
+ * incoming: (call) => connectAgent(AgentProvider.ElevenLabs, '+15551234567', { call }),
1626
+ * });
1627
+ * ```
1628
+ */
1629
+ export declare function connectAgent(provider: SipAgentProvider | (string & Record<never, never>), number: string, options?: ConnectAgentOptions): CallFlow;
1630
+ type VoiceClient = Client & {
1631
+ /** Voice API v1 client, when `VOICE_APPLICATION_KEY` and `VOICE_APPLICATION_SECRET` are set */
1632
+ v1?: VoiceService;
1633
+ };
1634
+ interface FunctionConfigData {
1635
+ /** Project ID */
1636
+ projectId: string;
1637
+ /** Function name */
1638
+ functionName: string;
1639
+ /** Environment (development, production) */
1640
+ environment: "development" | "production";
1641
+ /** Custom environment variables */
1642
+ variables?: Record<string, string>;
1643
+ }
1644
+ type FunctionConfig = FunctionConfigData & ConfigAccessors;
1645
+ interface FunctionContext {
1646
+ /** Configuration including environment variables */
1647
+ config: FunctionConfig;
1648
+ /**
1649
+ * Key-value cache with TTL support.
1650
+ * In-memory during development, persistent and shared in production.
1651
+ * @see {@link IFunctionCache} for available methods
1652
+ */
1653
+ cache: IFunctionCache;
1654
+ /** Request ID for tracing */
1655
+ requestId?: string;
1656
+ /** Timestamp of the request */
1657
+ timestamp?: string;
1658
+ /** Hostname from the incoming HTTP request (e.g. `my-fn.fn-dev.sinch.com`). Present in production; absent in local dev. */
1659
+ host?: string;
1660
+ /** Environment variables */
1661
+ env?: Record<string, string | undefined>;
1662
+ /**
1663
+ * Voice API v2 client — place calls, bridge legs, attach media streams, dispatch webhooks.
1664
+ * Always present; the credentials are only checked when a request is actually sent.
1665
+ * The v1 SDK client is on `context.voice.v1`.
1666
+ * @see {@link VoiceClient}
1667
+ */
1668
+ voice: VoiceClient;
1669
+ /**
1670
+ * Sinch Conversation SDK client.
1671
+ * Available when `CONVERSATION_APP_ID` is set.
1672
+ */
1673
+ conversation?: ConversationService;
1674
+ /**
1675
+ * Sinch SMS SDK client.
1676
+ * Available when `SMS_SERVICE_PLAN_ID` is set.
1677
+ */
1678
+ sms?: SmsService;
1679
+ /**
1680
+ * Sinch Numbers SDK client.
1681
+ * Available when `ENABLE_NUMBERS_API=true` is set.
1682
+ */
1683
+ numbers?: NumbersService;
1684
+ /**
1685
+ * Persistent file/blob storage.
1686
+ * Local filesystem during development, S3-backed in production.
1687
+ * @see {@link IFunctionStorage} for available methods
1688
+ */
1689
+ storage: IFunctionStorage;
1690
+ /**
1691
+ * File path to a SQLite database for persistent structured data.
1692
+ * The database file is managed by a Litestream sidecar in production
1693
+ * (continuous WAL replication to S3). In development, it's a local file.
1694
+ *
1695
+ * Use any SQLite library — `sql.js` (pure WASM, no native deps) or
1696
+ * `better-sqlite3` (native C++, fastest but requires build tooling).
1697
+ *
1698
+ * @example
1699
+ * ```typescript
1700
+ * // sql.js (recommended — works everywhere)
1701
+ * import initSqlJs from 'sql.js';
1702
+ * const SQL = await initSqlJs();
1703
+ * const buf = existsSync(context.database) ? readFileSync(context.database) : undefined;
1704
+ * const db = new SQL.Database(buf);
1705
+ * db.run('CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT)');
1706
+ * writeFileSync(context.database, Buffer.from(db.export()));
1707
+ *
1708
+ * // better-sqlite3 (fastest — needs python3/make/g++)
1709
+ * import Database from 'better-sqlite3';
1710
+ * const db = new Database(context.database);
1711
+ * db.exec('CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT)');
1712
+ * ```
1713
+ */
1714
+ database: string;
1715
+ /** Read a file from the assets/ directory (private, not served over HTTP) */
1716
+ assets(filename: string): Promise<string>;
1717
+ }
1718
+ type WebSocketHandler = (ws: import("ws").WebSocket, req: import("http").IncomingMessage) => void;
1719
+ interface SinchRuntime {
1720
+ /** Register a callback to run once at startup, before the server accepts requests. */
1721
+ onStartup(handler: (context: FunctionContext) => Promise<void> | void): void;
1722
+ /** Register a WebSocket upgrade handler at the given path. */
1723
+ onWebSocket(path: string, handler: WebSocketHandler): void;
1724
+ }
1725
+ interface ApplicationCredentials {
1726
+ applicationKey: string;
1727
+ applicationSecret: string;
1728
+ }
1729
+ interface ConfigSummary {
1730
+ environment: "production" | "development";
1731
+ variables: Record<string, string | undefined>;
1732
+ secrets: Record<string, string>;
1733
+ hasApplicationCredentials: boolean;
1734
+ }
1735
+ declare class UniversalConfig {
1736
+ private context;
1737
+ private env;
1738
+ /**
1739
+ * Create a new UniversalConfig instance
1740
+ *
1741
+ * @param context - Function execution context
1742
+ */
1743
+ constructor(context: FunctionContext);
1744
+ /**
1745
+ * Get a secret value (e.g., API keys, passwords, tokens)
1746
+ *
1747
+ * @param name - Secret name (e.g., 'PROJECT_ID_API_SECRET')
1748
+ * @param defaultValue - Optional default value if secret not found
1749
+ */
1750
+ getSecret(name: string): string | null;
1751
+ getSecret(name: string, defaultValue: string): string;
1752
+ getSecret(name: string, defaultValue: string | null): string | null;
1753
+ /**
1754
+ * Get an environment variable (non-secret configuration)
1755
+ *
1756
+ * @param name - Variable name (e.g., 'COMPANY_NAME', 'API_URL')
1757
+ * @param defaultValue - Optional default value
1758
+ */
1759
+ getVariable(name: string): string | null;
1760
+ getVariable(name: string, defaultValue: string): string;
1761
+ getVariable(name: string, defaultValue: string | null): string | null;
1762
+ /**
1763
+ * Check if a secret exists (has a value)
1764
+ *
1765
+ * @param name - Secret name
1766
+ */
1767
+ hasSecret(name: string): boolean;
1768
+ /**
1769
+ * Check if a variable exists (has a value)
1770
+ *
1771
+ * @param name - Variable name
1772
+ */
1773
+ hasVariable(name: string): boolean;
1774
+ /**
1775
+ * Get required secret (throws error if not found)
1776
+ *
1777
+ * @param name - Secret name
1778
+ * @throws Error if secret is not found
1779
+ */
1780
+ requireSecret(name: string): string;
1781
+ /**
1782
+ * Get required variable (throws error if not found)
1783
+ *
1784
+ * @param name - Variable name
1785
+ * @throws Error if variable is not found
1786
+ */
1787
+ requireVariable(name: string): string;
1788
+ /**
1789
+ * Get Sinch application credentials
1790
+ */
1791
+ getApplicationCredentials(): ApplicationCredentials | null;
1792
+ /**
1793
+ * Check if running in development mode
1794
+ */
1795
+ isDevelopment(): boolean;
1796
+ /**
1797
+ * Check if running in production mode
1798
+ */
1799
+ isProduction(): boolean;
1800
+ /**
1801
+ * Get cache client instance
1802
+ */
1803
+ getCache(): IFunctionCache | undefined;
1804
+ /**
1805
+ * Get comprehensive configuration summary (useful for debugging)
1806
+ * Excludes actual secret values for security
1807
+ */
1808
+ getConfigSummary(): ConfigSummary;
1809
+ }
1810
+ declare const CONFIG_ACCESSORS: readonly [
1811
+ "getSecret",
1812
+ "getVariable",
1813
+ "hasSecret",
1814
+ "hasVariable",
1815
+ "requireSecret",
1816
+ "requireVariable",
1817
+ "getApplicationCredentials",
1818
+ "isDevelopment",
1819
+ "isProduction",
1820
+ "getCache",
1821
+ "getConfigSummary"
1822
+ ];
1823
+ type ConfigAccessors = Pick<UniversalConfig, (typeof CONFIG_ACCESSORS)[number]>;
1824
+ type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
1825
+ interface FunctionRequest {
1826
+ /** HTTP method */
1827
+ method: HttpMethod;
1828
+ /** Request path */
1829
+ path: string;
1830
+ /** Query parameters */
1831
+ query?: Record<string, string | string[]>;
1832
+ /** Request headers (lowercase keys) */
1833
+ headers?: Record<string, string>;
1834
+ /** Request body (parsed JSON) */
1835
+ body?: unknown;
1836
+ /** Route parameters (e.g., /users/:id) */
1837
+ params?: Record<string, string>;
1838
+ }
1839
+ interface FunctionResponse {
1840
+ /** HTTP status code (default: 200) */
1841
+ statusCode: number;
1842
+ /** Response headers */
1843
+ headers?: Record<string, string>;
1844
+ /** Response body (will be JSON serialized) */
1845
+ body?: unknown;
1846
+ }
1847
+ type IceCallback = Omit<Voice.IceRequest, "callid" | "event"> & {
1848
+ callId?: string;
1849
+ event: "ice";
1850
+ };
1851
+ type AceCallback = Omit<Voice.AceRequest, "callid" | "event"> & {
1852
+ callId?: string;
1853
+ event: "ace";
1854
+ };
1855
+ type PieCallback = Omit<Voice.PieRequest, "callid" | "event"> & {
1856
+ callId?: string;
1857
+ event: "pie";
1858
+ };
1859
+ type DiceCallback = Omit<Voice.DiceRequest, "callid" | "event"> & {
1860
+ callId?: string;
1861
+ event: "dice";
1862
+ };
1863
+ type NotifyCallback = Omit<Voice.NotifyRequest, "callid" | "event"> & {
1864
+ callId?: string;
1865
+ event: "notify";
1866
+ };
1867
+ type ApiHandler = (context: FunctionContext, request: FunctionRequest) => Promise<FunctionResponse | unknown>;
1868
+ type IceHandler = (context: FunctionContext, callbackData: IceCallback) => Promise<SvamletResponse>;
1869
+ type AceHandler = (context: FunctionContext, callbackData: AceCallback) => Promise<SvamletResponse>;
1870
+ type PieHandler = (context: FunctionContext, callbackData: PieCallback) => Promise<SvamletResponse>;
1871
+ type DiceHandler = (context: FunctionContext, callbackData: DiceCallback) => Promise<void>;
1872
+ type NotifyHandler = (context: FunctionContext, callbackData: NotifyCallback) => Promise<void>;
1873
+ type VoiceWebhookHandler = (context: FunctionContext, event: WebhookRequest, request?: FunctionRequest) => HandlerResult | Promise<HandlerResult>;
1874
+ interface VoiceFunction {
1875
+ /** Handle ICE (Incoming Call Event) */
1876
+ ice?: IceHandler;
1877
+ /** Handle ACE (Answered Call Event) */
1878
+ ace?: AceHandler;
1879
+ /** Handle PIE (Prompt Input Event) */
1880
+ pie?: PieHandler;
1881
+ /** Handle DICE (Disconnect Call Event) */
1882
+ dice?: DiceHandler;
1883
+ /** Handle notify events */
1884
+ notify?: NotifyHandler;
1885
+ /**
1886
+ * Handle the Voice API v2 call lifecycle — every `call.*` event this function's service
1887
+ * posts, whatever URL it posts to. Build one with `onCall()`.
1888
+ *
1889
+ * The `ApiHandler` arm is the host's other accepted shape: a handler that returns a full
1890
+ * `{ statusCode, body }` response gets it emitted untouched, which is what
1891
+ * `@sinch/agents` returns from its own `voiceWebhook`.
1892
+ */
1893
+ voiceWebhook?: VoiceWebhookHandler | ApiHandler;
1894
+ /** Default handler for GET / */
1895
+ default?: ApiHandler;
1896
+ /** Root route handler — TypeScript-friendly alias for 'default' */
1897
+ home?: ApiHandler;
1898
+ /** Custom API endpoints (any other exported function) */
1899
+ [key: string]: unknown;
1900
+ }
1901
+ type PerCallValue<T> = T | ((call: Call, context: FunctionContext) => T | Promise<T>);
1902
+ type JsonSchema = Record<string, unknown>;
1903
+ interface TranscriptEntry {
1904
+ /** `'tool'` is a completed tool call, not spoken turn. */
1905
+ role: "user" | "agent" | "tool";
1906
+ /** Spoken/written text for `'user'`/`'agent'`; the tool's name for `'tool'`. */
1907
+ text: string;
1908
+ /** ISO 8601 */
1909
+ timestamp: string;
1910
+ /** Present only when `role` is `'tool'`. */
1911
+ tool?: string;
1912
+ args?: unknown;
1913
+ /** The handler's resolved value. Absent when the handler threw. */
1914
+ result?: unknown;
1915
+ /** The handler's thrown value, if it threw. */
1916
+ error?: unknown;
1917
+ latencyMs?: number;
1918
+ }
1919
+ interface RealtimeError {
1920
+ message: string;
1921
+ /** A machine-readable error code, when the vendor or transport provides one (e.g. `ECONNRESET`). */
1922
+ code?: string;
1923
+ /**
1924
+ * The vendor's own error payload, if any, for logging. For a connection-level `ws` error this is
1925
+ * always the sanitised `{ message, code? }` from `sanitizeVendorError` — never the raw `Error`
1926
+ * instance, which can carry the connection URL or headers (an API key, for a vendor that puts one
1927
+ * there). A vendor-sent JSON error frame is passed through as-is; that payload is the vendor's own
1928
+ * message body, not connection metadata.
1929
+ */
1930
+ raw?: unknown;
1931
+ }
1932
+ interface RealtimeSessionContext {
1933
+ /** The caller's leg's callId — the one `call.hangup` will report. */
1934
+ callId: string;
1935
+ storage: IFunctionStorage;
1936
+ config: UniversalConfig;
1937
+ /**
1938
+ * Aborted the moment this call's session ends, from whichever side (hangup, Sinch closing the
1939
+ * STREAM leg, a fatal vendor error). A tool `handler` that supports cancellation can watch this
1940
+ * to stop early instead of running a side effect for a call that is already over — see the
1941
+ * Deepgram adapter's `FunctionCallCancelled` handling.
1942
+ */
1943
+ signal: AbortSignal;
1944
+ /**
1945
+ * This call's transcript so far, in order — every entry `onTranscript` has already fired
1946
+ * with. Read from `onEnd` or a tool `handler`; appended to by the relay, never by an author.
1947
+ */
1948
+ readonly transcript: readonly TranscriptEntry[];
1949
+ /**
1950
+ * End the call. Closes the vendor session and the STREAM leg; `endOnFailure` on the caller's
1951
+ * leg (set by `realtimeAgent`'s own call plan) ends the caller's leg in turn.
1952
+ */
1953
+ hangup(): void;
1954
+ /**
1955
+ * Move the caller to a human number. Same move-the-live-leg mechanism as the voice builder's
1956
+ * `transferTo*`/`voiceRelay`'s `call.transferToPhone`: the caller's leg leaves this call's
1957
+ * bridge for a new one with `number`, and if that dial is busy, unanswered, or fails, the
1958
+ * caller's leg is dropped rather than returned here — this is a cold transfer, not a warm
1959
+ * one. This agent's own STREAM leg has nobody left to relay to once the caller moves, so it
1960
+ * ends right after the move, whether or not the destination ever answers.
1961
+ */
1962
+ transfer(number: string): Promise<void>;
1963
+ }
1964
+ type RealtimeAudioProvider = "openai" | "gemini" | "deepgram" | "grok";
1965
+ type RealtimeAgentProvider = RealtimeAudioProvider | "voice-relay";
1966
+ type RealtimeAgentHandle = VoiceFunction & {
1967
+ connect: VoiceCallHandler;
1968
+ } & v2.DialableAgent;
1969
+ type PerCallSetting = string | ((call: v2.Call, context: FunctionContext) => string);
1970
+ type RelayTransferOptions = Omit<v2.TransferToOptions, "call">;
1971
+
1972
+ declare namespace v2 {
1973
+ 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_TRANSFER_LEG, 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 };
1974
+ }
1089
1975
 
1090
1976
  export {
1091
1977
  Headers$1 as Headers,