@sinch/functions-runtime 0.5.16 → 0.5.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -985,6 +985,1628 @@ export interface IFunctionStorage {
985
985
  exists(key: string): Promise<boolean>;
986
986
  delete(key: string): Promise<void>;
987
987
  }
988
+ /**
989
+ * The config seam — the only thing this module needs from its host.
990
+ *
991
+ * `voice/v2/` is written to be liftable: the whole directory should compile after a plain
992
+ * copy into another repo, so it must not import from the rest of the runtime. It used to
993
+ * take a `FunctionContext`, which pulled the cache, storage and every Sinch SDK service type
994
+ * along behind it into the generated `.d.ts` for three optional property reads.
995
+ *
996
+ * {@link ClientContext} is those three reads and nothing else. `FunctionContext` satisfies it
997
+ * structurally, so `createClient(context)` inside a function handler still compiles unchanged
998
+ * and no caller had to be touched.
999
+ */
1000
+ /**
1001
+ * Anything that can supply the client's configuration.
1002
+ *
1003
+ * A Sinch Functions `FunctionContext` is the usual one. A CLI process can pass its own object,
1004
+ * or nothing at all — every field is optional and `process.env` is the fallback.
1005
+ */
1006
+ export interface ClientContext {
1007
+ /** Function configuration. Only `projectId` is read. */
1008
+ config?: {
1009
+ /** Sinch project id */
1010
+ projectId?: string;
1011
+ };
1012
+ /** Hostname this function is served on. Used to resolve relative stream paths. */
1013
+ host?: string;
1014
+ /** Environment variables. Defaults to `process.env`. */
1015
+ env?: Record<string, string | undefined>;
1016
+ }
1017
+ /**
1018
+ * Voice API v2 wire types
1019
+ *
1020
+ * Hand-written subset of the Voice API v2 OpenAPI schema (v2.0.59) covering the
1021
+ * commands and endpoints this client emits. Every schema in the spec is
1022
+ * `additionalProperties: false`, so unknown keys are rejected with a 400 — these
1023
+ * types deliberately mirror the wire shape exactly.
1024
+ *
1025
+ * The v2 shapes are NOT the v1 SVAML shapes. In particular there is no `say`
1026
+ * command in v2 (TTS goes through `messages`), and streaming is an endpoint type
1027
+ * on `to` rather than a `connectStream` action.
1028
+ */
1029
+ /** Audio codec for a STREAM endpoint. `PCM` (16-bit signed, mono) is the only supported value. */
1030
+ export type StreamCodec = "PCM";
1031
+ /** Audio sampling rate (Hz) for a STREAM endpoint. */
1032
+ export type SampleRate = 8000 | 16000 | 24000 | 44100 | 48000 | 96000;
1033
+ /**
1034
+ * Custom header sent in the call setup.
1035
+ *
1036
+ * On a STREAM leg every pair is set both as an HTTP header on the WebSocket
1037
+ * upgrade request and inside the `connect` message, which is how a call is
1038
+ * correlated to application state.
1039
+ */
1040
+ export interface CallHeader {
1041
+ /** Header name (1-255 characters) */
1042
+ key: string;
1043
+ /** Header value (up to 255 characters) */
1044
+ value?: string;
1045
+ }
1046
+ /** Routes the call to a phone number on the PSTN */
1047
+ export interface PhoneEndpoint {
1048
+ /** Discriminator */
1049
+ type: "PHONE";
1050
+ /** Phone destination */
1051
+ phone: {
1052
+ /** E.164 phone number, e.g. `+15551234567` */
1053
+ number: string;
1054
+ };
1055
+ }
1056
+ /** Routes the call to a SIP endpoint */
1057
+ export interface SipEndpoint {
1058
+ /** Discriminator */
1059
+ type: "SIP";
1060
+ /** SIP destination */
1061
+ sip: {
1062
+ /** SIP URI (`sip:` or `sips:`) */
1063
+ endpoint: string;
1064
+ /** Transport protocol */
1065
+ transport?: "UDP" | "TCP" | "TLS";
1066
+ /** Custom SIP headers */
1067
+ callHeaders?: CallHeader[];
1068
+ };
1069
+ }
1070
+ /** Stream protocol options. Always send all three fields — see StreamEndpoint. */
1071
+ export interface StreamOptions {
1072
+ /**
1073
+ * Stream protocol version. The schema (spec line 2871) types this as a plain integer with
1074
+ * a default of `1` and names no other accepted value; `1` is what this library emits.
1075
+ */
1076
+ version: number;
1077
+ /** Audio codec. Only `PCM` is supported. */
1078
+ codec: StreamCodec;
1079
+ /** Audio sampling rate in Hz */
1080
+ sampleRate: SampleRate;
1081
+ }
1082
+ /**
1083
+ * Routes the call to a WebSocket endpoint for real-time audio.
1084
+ *
1085
+ * @remarks
1086
+ * `streamOptions` is optional on the wire but should always be sent in full: the schema's
1087
+ * per-field default is 8 kHz (spec line 2904), which is not what any consumer of a stream
1088
+ * this library builds expects. What the platform does when the whole object is omitted is
1089
+ * not stated in the spec — sending it in full makes the question moot.
1090
+ */
1091
+ export interface StreamEndpoint {
1092
+ /** Discriminator */
1093
+ type: "STREAM";
1094
+ /** Stream destination */
1095
+ stream: {
1096
+ /** WebSocket URL (`ws://` or `wss://`) reachable from the public internet */
1097
+ endpoint: string;
1098
+ /** Codec and sample-rate negotiation */
1099
+ streamOptions?: StreamOptions;
1100
+ /** Headers delivered on the WebSocket upgrade and in the `connect` message */
1101
+ callHeaders?: CallHeader[];
1102
+ };
1103
+ }
1104
+ /**
1105
+ * Routes the call through the Voice Relay service — Sinch runs STT and TTS, and the
1106
+ * application exchanges **text** over the WebSocket instead of audio.
1107
+ *
1108
+ * @remarks
1109
+ * All three of `endpoint`, `ttsVoice` and `sttLanguage` are required by the schema
1110
+ * (spec 2.0.58, `voiceRelay`, lines 2946-2948).
1111
+ */
1112
+ export interface VoiceRelayEndpoint {
1113
+ /** Discriminator */
1114
+ type: "VOICE_RELAY";
1115
+ /** Relay destination */
1116
+ voiceRelay: {
1117
+ /** WebSocket URL that accepts the relay connection, e.g. `wss://acme.com/agent` */
1118
+ endpoint: string;
1119
+ /**
1120
+ * Allow barge-in during TTS playback. Defaults to `true` on the platform; when `false`
1121
+ * an interruption signal is still delivered over the socket.
1122
+ */
1123
+ enableInterruptions?: boolean;
1124
+ /** Platform TTS voice, e.g. `Emma` or `Brian` */
1125
+ ttsVoice: string;
1126
+ /** BCP-47 language tag for speech-to-text, e.g. `en-US` */
1127
+ sttLanguage: string;
1128
+ /** Headers delivered on the WebSocket upgrade and in the `connect` message */
1129
+ callHeaders?: CallHeader[];
1130
+ };
1131
+ }
1132
+ /** Call destination */
1133
+ export type To = PhoneEndpoint | SipEndpoint | StreamEndpoint | VoiceRelayEndpoint;
1134
+ /**
1135
+ * Routes the call *from* a SIP endpoint.
1136
+ *
1137
+ * @remarks
1138
+ * A distinct schema from {@link SipEndpoint} (spec `sipFrom`, line 2800): an origin carries
1139
+ * a `displayName` and neither `transport` nor `callHeaders`, and the schema is
1140
+ * `additionalProperties: false`, so sending a destination's SIP object as `from` is a 400.
1141
+ */
1142
+ export interface SipOriginEndpoint {
1143
+ /** Discriminator */
1144
+ type: "SIP";
1145
+ /** SIP origin */
1146
+ sip: {
1147
+ /** SIP URI (`sip:` or `sips:`) */
1148
+ endpoint: string;
1149
+ /** Caller identity shown to the callee, sent as the SIP `From` display name */
1150
+ displayName?: string;
1151
+ };
1152
+ }
1153
+ /**
1154
+ * Call origin. Only PHONE and SIP may originate a call — the `from` union (spec line 2693)
1155
+ * has no STREAM and no VOICE_RELAY member.
1156
+ */
1157
+ export type From = PhoneEndpoint | SipOriginEndpoint;
1158
+ /** Commands to run for each outcome of a `dial` */
1159
+ export interface CallEvents {
1160
+ /** Runs when the leg is answered */
1161
+ onAnswer?: Command[];
1162
+ /** Runs when the callee is busy */
1163
+ onBusy?: Command[];
1164
+ /** Runs when the callee rejects */
1165
+ onReject?: Command[];
1166
+ /** Runs when the dial timeout elapses without an answer */
1167
+ onTimeout?: Command[];
1168
+ /** Runs when the leg is hung up */
1169
+ onHangup?: Command[];
1170
+ /** Runs when the leg could not be set up */
1171
+ onFailure?: Command[];
1172
+ }
1173
+ /** A text-to-speech message item */
1174
+ export interface SayMessage {
1175
+ /** Discriminator */
1176
+ type: "SAY";
1177
+ /** TTS payload */
1178
+ say: {
1179
+ /** Text, or an SSML document when `format` is `SSML` */
1180
+ text: string;
1181
+ /** Text format. Defaults to `TEXT`. */
1182
+ format?: "TEXT" | "SSML";
1183
+ /** Voice name, e.g. `Emma`. Required by the API. */
1184
+ voiceName: string;
1185
+ };
1186
+ }
1187
+ /** A pre-recorded audio message item */
1188
+ export interface PlayMessage {
1189
+ /** Discriminator */
1190
+ type: "PLAY";
1191
+ /** Audio payload */
1192
+ play: {
1193
+ /** URL of the audio file to play */
1194
+ url: string;
1195
+ };
1196
+ }
1197
+ /** A single item in a `messages` command */
1198
+ export type Message = SayMessage | PlayMessage;
1199
+ /** Initiates a new outbound call leg within the session */
1200
+ export interface DialCommand {
1201
+ /** Discriminator */
1202
+ command: "dial";
1203
+ /** Identifier for this leg (1-32 chars, no whitespace), unique among live legs */
1204
+ callName?: string;
1205
+ /** Call origin. Optional — on a STREAM leg it is informational only. */
1206
+ from?: From;
1207
+ /** Call destination */
1208
+ to: To;
1209
+ /** Seconds to wait for an answer. Maximum 60. */
1210
+ dialTimeoutDurationSeconds?: number;
1211
+ /** Maximum leg duration in seconds. Maximum 14400. */
1212
+ maxCallDurationSeconds?: number;
1213
+ /** Per-outcome command sequences */
1214
+ events?: CallEvents;
1215
+ }
1216
+ /** Plays one or more TTS or audio messages on the call */
1217
+ export interface MessagesCommand {
1218
+ /** Discriminator */
1219
+ command: "messages";
1220
+ /** Name used to target this sequence from `stopMessages` */
1221
+ messagesName?: string;
1222
+ /** Ordered list of messages (1-10) */
1223
+ messages: Message[];
1224
+ /** Playback outcome handlers */
1225
+ events?: {
1226
+ /** Runs when every message has finished playing */
1227
+ onFinish?: Command[];
1228
+ /** Runs when playback fails */
1229
+ onFailure?: Command[];
1230
+ };
1231
+ }
1232
+ /** Adds the current leg to a named bridge. The bridge is created on first reference. */
1233
+ export interface BridgeCallCommand {
1234
+ /** Discriminator */
1235
+ command: "bridgeCall";
1236
+ /** Bridge name (1-32 chars, no whitespace) */
1237
+ bridgeName: string;
1238
+ }
1239
+ /** Ends a call leg */
1240
+ export interface HangupCommand {
1241
+ /** Discriminator */
1242
+ command: "hangup";
1243
+ /** Leg to end. Ends the current leg when omitted. */
1244
+ callName?: string;
1245
+ }
1246
+ /** Explicitly answers an inbound leg */
1247
+ export interface AnswerCommand {
1248
+ /** Discriminator */
1249
+ command: "answer";
1250
+ }
1251
+ /** Input method a menu accepts. `DTMF` is the only value in the spec's enum (line 3969). */
1252
+ export type MenuInputMethod = "DTMF";
1253
+ /**
1254
+ * Prompt played at the top of a menu (spec `menuPrompt`, line 3887).
1255
+ *
1256
+ * `messages` is required; `allowBargeIn` defaults to `true` on the platform.
1257
+ */
1258
+ export interface MenuPrompt {
1259
+ /** Ordered list of messages to play (1-10) */
1260
+ messages: Message[];
1261
+ /**
1262
+ * Let input cut the prompt short. When disabled, input is still collected during playback
1263
+ * and evaluated once it finishes.
1264
+ */
1265
+ allowBargeIn?: boolean;
1266
+ }
1267
+ /**
1268
+ * One named menu inside a `menu` command (spec `menuItem`, line 3908).
1269
+ *
1270
+ * A menu that defines neither `matches` nor `onFail` falls through to the service webhook
1271
+ * with the collected input, delivered as `call.menu`.
1272
+ */
1273
+ export interface MenuItem {
1274
+ /** Played when the menu is entered. Doubles as the repeat prompt when `repeatPrompt` is unset. */
1275
+ prompt?: MenuPrompt;
1276
+ /** Played again on each retry */
1277
+ repeatPrompt?: MenuPrompt;
1278
+ /** Seconds to wait for input before the attempt times out. 1-60, default 5. */
1279
+ inputTimeoutDurationSeconds?: number;
1280
+ /** How many times the menu repeats before `onFail` runs. 0-10, default 2. */
1281
+ repeatCount?: number;
1282
+ /** Fewest input characters collected before the input is evaluated. 1-100, default 1. */
1283
+ minimumInputLength?: number;
1284
+ /** Input character count that triggers evaluation. 1-100, default 1. */
1285
+ maximumInputLength?: number;
1286
+ /**
1287
+ * Character sequence that ends input and triggers evaluation immediately, e.g. `#`.
1288
+ * Digits, `*` and `#` only, up to 10 characters. Included in the evaluated input.
1289
+ */
1290
+ terminatingSequence?: string;
1291
+ /** Input methods accepted. Defaults to `['DTMF']`, which is also the only value. */
1292
+ inputMethods?: MenuInputMethod[];
1293
+ /**
1294
+ * Input pattern to command list. Keys may be regular expressions and are evaluated in
1295
+ * definition order — see {@link MenuItem} on why key order is load-bearing.
1296
+ */
1297
+ matches?: Record<string, Command[]>;
1298
+ /** Runs when no match was made within `repeatCount` attempts */
1299
+ onFail?: Command[];
1300
+ }
1301
+ /** Collects DTMF input against one or more named menus. Blocking. */
1302
+ export interface MenuCommand {
1303
+ /** Discriminator */
1304
+ command: "menu";
1305
+ /** Menu entered first */
1306
+ startMenu: string;
1307
+ /** Every menu reachable from this command, by name */
1308
+ menus: Record<string, MenuItem>;
1309
+ }
1310
+ /** Jumps to another menu. Legal only inside menu execution. Blocking. */
1311
+ export interface GotoMenuCommand {
1312
+ /** Discriminator */
1313
+ command: "gotoMenu";
1314
+ /** Menu to enter, as named in the enclosing `menu` command */
1315
+ menuName: string;
1316
+ }
1317
+ /** Delays the next command without affecting call audio. Blocking. */
1318
+ export interface PauseCommand {
1319
+ /** Discriminator */
1320
+ command: "pause";
1321
+ /** How long to wait, in milliseconds. Minimum 1. */
1322
+ durationMilliseconds: number;
1323
+ }
1324
+ /** How much of a message sequence `stopMessages` cancels */
1325
+ export type StopMessagesFlags = "ONLY_PLAYING" | "ALL_FROM_NOW_ON";
1326
+ /** Stops a named `messages` sequence. Non-blocking. */
1327
+ export interface StopMessagesCommand {
1328
+ /** Discriminator */
1329
+ command: "stopMessages";
1330
+ /** Sequence to stop, as named by `messagesName` on the `messages` command */
1331
+ messagesName: string;
1332
+ /**
1333
+ * Whether to stop only the playing message or the whole queue. The platform defaults to
1334
+ * `ALL_FROM_NOW_ON`.
1335
+ */
1336
+ flags?: StopMessagesFlags;
1337
+ }
1338
+ /** Commands to run for each answering-machine-detection outcome */
1339
+ export interface AmdEvents {
1340
+ /** Runs when a human is detected */
1341
+ onHuman?: Command[];
1342
+ /** Runs when a machine is detected */
1343
+ onMachine?: Command[];
1344
+ /** Runs when the answering machine's beep is detected */
1345
+ onBeep?: Command[];
1346
+ /** Runs when detection produced no verdict */
1347
+ onUnknown?: Command[];
1348
+ }
1349
+ /** Runs answering machine detection on the call. Non-blocking. */
1350
+ export interface AmdCommand {
1351
+ /** Discriminator */
1352
+ command: "amd";
1353
+ /** Per-outcome command sequences */
1354
+ events?: AmdEvents;
1355
+ }
1356
+ /**
1357
+ * Calls out to an application URL mid-call and runs the commands it returns. Blocking.
1358
+ *
1359
+ * @remarks
1360
+ * The event arrives as `call.webhook.<webhookName>` — `webhookName: 'my.custom.event'`
1361
+ * is delivered as `'call.webhook.my.custom.event'`.
1362
+ */
1363
+ export interface WebhookCommand {
1364
+ /** Discriminator */
1365
+ command: "webhook";
1366
+ /** Name for this webhook event (1-64 chars, no whitespace) */
1367
+ webhookName: string;
1368
+ /** URL to call. 5-second timeout. */
1369
+ url: string;
1370
+ /** URL retried immediately when `url` fails */
1371
+ fallbackUrl?: string;
1372
+ }
1373
+ /** Audio format of a recording. The platform defaults to `MP3`. */
1374
+ export type RecordingFormat = "MP3" | "WAV";
1375
+ /** Which streams a recording captures. The platform defaults to `COMBINED`. */
1376
+ export type RecordingType = "COMBINED" | "INBOUND" | "OUTBOUND";
1377
+ /** Storage service a recording is delivered to. The platform defaults to `AWS`. */
1378
+ export type RecordingDestination = "AWS" | "GCP" | "AZURE";
1379
+ /** Speech-to-text settings for a recording */
1380
+ export interface TranscriptionOptions {
1381
+ /** Transcribe the recording to text */
1382
+ isEnabled: boolean;
1383
+ /** BCP-47 language tag. The platform defaults to `en-US`. */
1384
+ locale?: string;
1385
+ }
1386
+ interface RecordingOptions$1 {
1387
+ /** Audio format. The platform defaults to `MP3`. */
1388
+ format?: RecordingFormat;
1389
+ /** Streams captured. The platform defaults to `COMBINED`. */
1390
+ recordingType?: RecordingType;
1391
+ /** Storage service. `s3://` for AWS, `gs://` for GCP, `azure://` for Azure. */
1392
+ destination: RecordingDestination;
1393
+ /** Destination URL, e.g. `s3://voice-recordings-prod/calls` */
1394
+ destinationUrl: string;
1395
+ /**
1396
+ * Colon-delimited credentials for the destination, e.g.
1397
+ * `accessKeyId:secretAccessKey:eu-central-1`.
1398
+ *
1399
+ * As sensitive as an IAM key — see {@link ../commands.js#RecordingCredentials}.
1400
+ */
1401
+ credentials: string;
1402
+ /** Speech-to-text settings */
1403
+ transcriptionOptions?: TranscriptionOptions;
1404
+ }
1405
+ /**
1406
+ * Commands to run for each recording outcome.
1407
+ *
1408
+ * @remarks
1409
+ * Unlike `dial` and `amd`, a `startRecording` with no `events` gets **nothing** — not the service
1410
+ * webhook. Verified in `calling-ng`, `AddCallBehaviorWebhookVisitor.Visit(StartRecording)`, which
1411
+ * only iterates `onFinish` and `onFailure` and never attaches a webhook to either. So there is no
1412
+ * service-webhook mode for recordings, and a recording whose `onFailure` you did not write is a
1413
+ * recording whose failure nobody hears about.
1414
+ */
1415
+ export interface RecordingEvents {
1416
+ /**
1417
+ * Runs when the recording stops. Does **not** mean the file reached the destination.
1418
+ */
1419
+ onFinish?: Command[];
1420
+ /** Runs when the recording could not be started */
1421
+ onFailure?: Command[];
1422
+ }
1423
+ /** Starts recording the call. Non-blocking. */
1424
+ export interface StartRecordingCommand {
1425
+ /** Discriminator */
1426
+ command: "startRecording";
1427
+ /**
1428
+ * Identifier for this recording (1-32 chars, no whitespace). Without it the recording can
1429
+ * only be stopped by the call disconnecting.
1430
+ */
1431
+ recordingName?: string;
1432
+ /** Destination, encoding and transcription */
1433
+ recordingOptions: RecordingOptions$1;
1434
+ /** Per-outcome command sequences */
1435
+ events?: RecordingEvents;
1436
+ }
1437
+ /** Stops a named recording. Non-blocking. */
1438
+ export interface StopRecordingCommand {
1439
+ /** Discriminator */
1440
+ command: "stopRecording";
1441
+ /** Recording to stop, as named by `recordingName` on the `startRecording` command */
1442
+ recordingName: string;
1443
+ }
1444
+ /** Any SVAML v2 command this client can emit */
1445
+ export type Command = DialCommand | MessagesCommand | BridgeCallCommand | HangupCommand | AnswerCommand | MenuCommand | GotoMenuCommand | PauseCommand | StopMessagesCommand | AmdCommand | WebhookCommand | StartRecordingCommand | StopRecordingCommand;
1446
+ /** Direction of the call, relative to the Sinch calling platform (spec `callDirection`). */
1447
+ export type CallDirection = "INBOUND" | "OUTBOUND";
1448
+ /** How the call was initiated — PSTN, a SIP trunk, or the API (spec `originationType`). */
1449
+ export type OriginationType = "PHONE" | "SIP" | "SERVER";
1450
+ /**
1451
+ * Kind of endpoint the call is connected to (spec `callType`).
1452
+ *
1453
+ * The same four values as the `to` union's discriminators, which is what makes this the
1454
+ * cheap way to tell a media leg from a phone leg without reaching into `to`.
1455
+ */
1456
+ export type CallType = "PHONE" | "SIP" | "STREAM" | "VOICE_RELAY";
1457
+ /**
1458
+ * Outcome or state of the call (spec `callResult`).
1459
+ *
1460
+ * Mixes transitional states — `QUEUED`, `INITIATED`, `IN_PROGRESS` — with the final ones, so
1461
+ * a value here is not on its own evidence that the call has ended.
1462
+ */
1463
+ export type CallResult = "QUEUED" | "INITIATED" | "IN_PROGRESS" | "COMPLETED" | "REJECTED" | "NO_ANSWER" | "CANCEL" | "BUSY" | "FAILED";
1464
+ /**
1465
+ * Why the call ended in the reported {@link CallResult} (spec `callReason`).
1466
+ *
1467
+ * `callResult` is what happened; this is the cause — who hung up, a routing failure, an
1468
+ * invalid script.
1469
+ */
1470
+ export type CallReason = "OK" | "NOT_AVAILABLE" | "CALLER_HANGUP" | "CALLEE_HANGUP" | "MANAGER_HANGUP" | "DID_NOT_FOUND" | "INVALID_SCRIPT" | "UNKNOWN_PRODUCT" | "NO_MORE_ROUTES" | "ERROR";
1471
+ /** A monetary amount with a currency (spec `money`). */
1472
+ export interface Money {
1473
+ /** ISO 4217 three-letter currency code, e.g. `USD` */
1474
+ currencyCode: string;
1475
+ /** Amount as a decimal string, up to 4 places — a string to keep the precision */
1476
+ amount: string;
1477
+ }
1478
+ /**
1479
+ * State of a call, as reported by the API and by every `call.*` webhook (spec `call`).
1480
+ *
1481
+ * Optional here means the same thing it means in the schema: the field is absent until the
1482
+ * call reaches the point that produces it. `answerTime` is missing on an unanswered call,
1483
+ * `endTime` and `callDurationSeconds` on an ongoing one, `bridgeId` until the leg joins a
1484
+ * bridge, `batchId` unless the call came from a batch, `callReason` until there is one.
1485
+ *
1486
+ * `callName` is deliberately absent, and its absence is load-bearing: naming a leg is
1487
+ * something a `dial` command, a `webhookResponse` and the PATCH target do, never something
1488
+ * the call resource reports back. Code that reads `call.callName` reads `undefined` on every
1489
+ * payload the platform sends.
1490
+ */
1491
+ export interface Call {
1492
+ /** ULID of this call leg */
1493
+ callId: string;
1494
+ /** UUID of the project that owns the call */
1495
+ projectId: string;
1496
+ /** UUID of the voice service that handled it */
1497
+ serviceId: string;
1498
+ /** ULID of the session. Shared by every leg of the same call. */
1499
+ sessionId: string;
1500
+ /** ULID of the bridge this leg is on, once it joins one */
1501
+ bridgeId?: string;
1502
+ /** ULID of the batch that placed this call, for batch calls only */
1503
+ batchId?: string;
1504
+ /** Call origin. Absent on legs with no reportable origin. */
1505
+ from?: From;
1506
+ /** Call destination */
1507
+ to?: To;
1508
+ /** RFC 3339 timestamp of when call setup started */
1509
+ startTime: string;
1510
+ /** RFC 3339 timestamp of the last update. Absent when nothing has updated the call. */
1511
+ updateTime?: string;
1512
+ /** What kind of endpoint the leg is connected to */
1513
+ callType: CallType;
1514
+ /** Inbound or outbound */
1515
+ direction: CallDirection;
1516
+ /** RFC 3339 timestamp of the answer. Absent when the call was not answered. */
1517
+ answerTime?: string;
1518
+ /** RFC 3339 timestamp of the end. Absent while the call is ongoing. */
1519
+ endTime?: string;
1520
+ /** Duration in seconds. Absent while the call is ongoing. */
1521
+ callDurationSeconds?: number;
1522
+ /** Current outcome or state */
1523
+ callResult: CallResult;
1524
+ /** Cause behind `callResult`, once there is one */
1525
+ callReason?: CallReason;
1526
+ /** How the call was initiated */
1527
+ originationType: OriginationType;
1528
+ /** Rate charged for this call, **per minute**, in the given currency */
1529
+ callRate: Money;
1530
+ /** Absolute URI of this call resource */
1531
+ callResourceUrl: string;
1532
+ }
1533
+ /** `201` response from `POST /calls` */
1534
+ export interface CallResponse {
1535
+ /** Project that owns the session */
1536
+ projectId: string;
1537
+ /** Voice service that handled the request */
1538
+ serviceId: string;
1539
+ /** Identifier of the created session */
1540
+ sessionId: string;
1541
+ /** Present only when the request started a batch */
1542
+ batchId?: string;
1543
+ }
1544
+ /** Addresses a live call for a PATCH. Either form is accepted by the API. */
1545
+ export type PatchTarget = {
1546
+ /** Call id, from a webhook payload or a session lookup */
1547
+ callId: string;
1548
+ } | {
1549
+ /** Session id returned by `POST /calls` */
1550
+ sessionId: string;
1551
+ /** Leg name within that session */
1552
+ callName: string;
1553
+ };
1554
+ /**
1555
+ * Webhook event names emitted by Voice API v2.
1556
+ *
1557
+ * @remarks
1558
+ * These are the sixteen names in the spec's event enum (lines 2264-2280), plus the open
1559
+ * `call.webhook.<name>` family a `webhook` command raises. Earlier drafts documented a
1560
+ * `webhook.` prefix; `Client.onCall` tolerates both.
1561
+ */
1562
+ export type EventType = "call.incoming" | "call.answered" | "call.busy" | "call.rejected" | "call.timeout" | "call.hangup" | "call.failed" | "call.amd.human" | "call.amd.machine" | "call.amd.beep" | "call.amd.unknown" | "call.message.finished" | "call.message.failed" | "call.recording.finished" | "call.recording.failed" | "call.menu" | (string & Record<never, never>);
1563
+ /** Payload delivered to the webhook endpoint */
1564
+ export interface WebhookRequest {
1565
+ /** Event that triggered this notification */
1566
+ event: EventType;
1567
+ /**
1568
+ * State of the call when the event fired. One shape for every event — `webhookRequest.call`
1569
+ * is a single `$ref` to the `call` schema, and only *which* optional fields are populated
1570
+ * varies by event.
1571
+ */
1572
+ call: Call;
1573
+ /** Present for `call.menu` and for `webhook` commands in a menu context */
1574
+ menu?: {
1575
+ /** Name of the menu that fired */
1576
+ menuName: string;
1577
+ /** The input sequence collected from the caller. Required by the schema (spec line 2321). */
1578
+ input: string;
1579
+ };
1580
+ }
1581
+ /**
1582
+ * Body returned from a webhook endpoint.
1583
+ *
1584
+ * @remarks
1585
+ * This is an object with a `commands` array, not a bare array.
1586
+ */
1587
+ export interface WebhookResponse {
1588
+ /** Ordered command list. At least one command. */
1589
+ commands: Command[];
1590
+ /** Names the inbound leg. Ignored on responses to anything but `call.incoming`. */
1591
+ callName?: string;
1592
+ /** Call-level event handlers */
1593
+ events?: {
1594
+ /** Runs when the call hangs up */
1595
+ onHangup?: Command[];
1596
+ };
1597
+ }
1598
+ /** What the command builder and its helpers need from the network, and nothing more. */
1599
+ export interface CallTransport {
1600
+ /**
1601
+ * Create a call.
1602
+ *
1603
+ * The body is deliberately permissive rather than `CallRequest`: {@link Client.raw} is an
1604
+ * escape hatch for bodies this module does not model, and validation belongs to
1605
+ * `toCallRequest`, not to the transport.
1606
+ *
1607
+ * @param body - A `callRequest` body, or any object the API accepts
1608
+ * @throws If the API rejects the request
1609
+ */
1610
+ createCall(body: object): Promise<CallResponse>;
1611
+ /**
1612
+ * Run commands against a live call.
1613
+ *
1614
+ * @param target - The live call, addressed by `callId` or by `sessionId` + `callName`
1615
+ * @param commands - Ordered command list to execute against the addressed leg
1616
+ * @throws If the API rejects the request
1617
+ */
1618
+ patchCall(target: PatchTarget, commands: Command[]): Promise<void>;
1619
+ }
1620
+ /** A call destination: an E.164 number, a `sip:`/`wss:` URI, or a full endpoint object. */
1621
+ export type Destination = string | To;
1622
+ /** A call origin: an E.164 number, a `sip:` URI, or a full endpoint object. */
1623
+ export type Origin = string | From;
1624
+ type Headers$1 = Record<string, string> | CallHeader[];
1625
+ /**
1626
+ * Anything that can stand in for a command list.
1627
+ *
1628
+ * Three spellings of one idea, because the six positions read differently: a builder value
1629
+ * reads best when a flow is named and reused (`{ onAnswer: greeting }`), a callback reads
1630
+ * best when it is defined in place (`.match('1', c => c.dial(sales))`), and a bare array is
1631
+ * what hand-written command literals already are. Every nesting point in this module and in
1632
+ * {@link ../client.js} takes this same type — that is the consistency that matters, rather
1633
+ * than forcing one spelling on positions where it reads badly.
1634
+ */
1635
+ export type Flow = CommandBuilder | Command[] | ((builder: CommandBuilder) => CommandBuilder | void);
1636
+ /** Options for a single TTS message */
1637
+ export interface SayOptions {
1638
+ /** Voice name. Defaults to {@link DEFAULT_VOICE}. */
1639
+ voiceName?: string;
1640
+ /** Set to `SSML` when `text` is an SSML document */
1641
+ format?: "TEXT" | "SSML";
1642
+ }
1643
+ /**
1644
+ * The six per-outcome command lists on a `dial`.
1645
+ *
1646
+ * Supplying **any** of them switches the platform out of service-webhook mode for **all**
1647
+ * of them — see {@link completeEvents}.
1648
+ */
1649
+ export interface DialEvents {
1650
+ /**
1651
+ * Runs when the leg is answered.
1652
+ *
1653
+ * Required whenever any other event is named: an `events` block detaches the service
1654
+ * webhook from every outcome, so a block without this one answers the leg into silence.
1655
+ */
1656
+ onAnswer?: Flow;
1657
+ /** Runs when the callee is busy. Defaults to hangup. */
1658
+ onBusy?: Flow;
1659
+ /** Runs when the callee rejects. Defaults to hangup. */
1660
+ onReject?: Flow;
1661
+ /** Runs when the dial timeout elapses without an answer. Defaults to hangup. */
1662
+ onTimeout?: Flow;
1663
+ /** Runs when the leg is hung up. Never defaulted unless `endOnHangup` names another leg. */
1664
+ onHangup?: Flow;
1665
+ /** Runs when the leg could not be set up. Defaults to hangup. */
1666
+ onFailure?: Flow;
1667
+ }
1668
+ /** Everything a single `dial` command can carry */
1669
+ export interface DialOptions extends DialEvents {
1670
+ /** Caller identity presented to the callee */
1671
+ from?: Origin;
1672
+ /** Seconds to wait for an answer. Maximum 60. */
1673
+ timeout?: number;
1674
+ /** Maximum call duration in seconds. Maximum 14400. */
1675
+ maxDuration?: number;
1676
+ /** Identifier for this leg (1-32 chars, no whitespace), unique among live legs */
1677
+ callName?: string;
1678
+ /**
1679
+ * Leg to end when *this* leg hangs up after connecting.
1680
+ *
1681
+ * This is the only thing that makes `onHangup` default at all. On a single-leg call there
1682
+ * is nothing to end — the call is already over — so leaving this unset is what "onHangup
1683
+ * is not defaulted" means in code.
1684
+ */
1685
+ endOnHangup?: string;
1686
+ /**
1687
+ * Leg to end when this leg *never connects* — busy, rejected, timed out or failed.
1688
+ *
1689
+ * Unset means end this leg, which is right for the first leg of a call: whatever it would
1690
+ * have been bridged to has not been dialled yet.
1691
+ */
1692
+ endOnFailure?: string;
1693
+ }
1694
+ /**
1695
+ * The four answering-machine-detection outcomes.
1696
+ *
1697
+ * @remarks
1698
+ * These are the AMD *result* events, not a `dial`'s six lifecycle events: they mean the call is
1699
+ * up and something answered, so none of them is a failure and none gets a hangup default.
1700
+ *
1701
+ * **They do share `dial`'s all-or-nothing rule.** Confirmed in `calling-ng`,
1702
+ * `Svaml/Visitors/AddCallBehaviorWebhookVisitor.cs` (`Visit(Amd)`) with
1703
+ * `Svaml/SvamlCommandFactory.cs` (`new Amd(command.Events is not null)`): sending an `events`
1704
+ * object detaches the service webhook from **all four** outcomes, so naming `onHuman` alone
1705
+ * silently stops machine, beep and unknown from being handled by anything. Nothing errors.
1706
+ *
1707
+ * The builder answers that by always emitting a complete four-outcome block once any one is
1708
+ * named — see {@link completeAmdEvents} for why the unnamed ones default to an empty list and
1709
+ * what that does and does not buy. Name all four, or name none and let the service webhook take
1710
+ * `call.amd.*`.
1711
+ */
1712
+ export interface AmdEventOptions {
1713
+ /** Runs when a human is detected */
1714
+ onHuman?: Flow;
1715
+ /** Runs when a machine is detected */
1716
+ onMachine?: Flow;
1717
+ /** Runs when the answering machine's beep is detected */
1718
+ onBeep?: Flow;
1719
+ /** Runs when detection produced no verdict */
1720
+ onUnknown?: Flow;
1721
+ }
1722
+ /** Options for a `webhook` command */
1723
+ export interface WebhookOptions {
1724
+ /**
1725
+ * URL retried immediately when the primary URL fails. After repeated consecutive failures
1726
+ * the platform sends only here until the primary recovers.
1727
+ */
1728
+ fallbackUrl?: string;
1729
+ }
1730
+ /**
1731
+ * Credentials for the storage service a recording is delivered to.
1732
+ *
1733
+ * @remarks
1734
+ * **This is a long-lived secret travelling inside a call flow.** The v2 schema takes the
1735
+ * credential as one required colon-delimited string on the `startRecording` command, so it is
1736
+ * present in the `POST /calls` body, in any webhook response or `PATCH` that starts a
1737
+ * recording, and in every copy of those a log or an error message makes. There is no
1738
+ * presigned-URL form and no STS session-token slot — the third component is the region, not a
1739
+ * token — so the value cannot be made short-lived and must be treated as being exactly as
1740
+ * sensitive as the IAM key it contains.
1741
+ *
1742
+ * Take it structured, as here, rather than concatenating secrets at the call site, and log
1743
+ * v2 bodies only through `redactCredentials`. The client scrubs it out of API error text on
1744
+ * its own, which is the one path that would otherwise carry it into a stack trace.
1745
+ *
1746
+ * @example
1747
+ * ```typescript
1748
+ * { accessKeyId: 'AKIA...', secretAccessKey: process.env.RECORDING_SECRET!, region: 'eu-central-1' }
1749
+ * // → 'AKIA...:<secret>:eu-central-1'
1750
+ * ```
1751
+ */
1752
+ export interface RecordingCredentials {
1753
+ /** Access key id */
1754
+ accessKeyId: string;
1755
+ /** Secret access key. The sensitive half. */
1756
+ secretAccessKey: string;
1757
+ /** Storage region, e.g. `eu-central-1` */
1758
+ region: string;
1759
+ }
1760
+ /** Everything a `startRecording` command can carry */
1761
+ export interface StartRecordingOptions {
1762
+ /** Destination URL, e.g. `s3://voice-recordings-prod/calls` */
1763
+ destinationUrl: string;
1764
+ /**
1765
+ * Credentials for the destination. Prefer the structured form; the raw colon-delimited
1766
+ * string is there for credential formats this library does not model.
1767
+ */
1768
+ credentials: RecordingCredentials | string;
1769
+ /**
1770
+ * Storage service. Defaults to `AWS`, and is always emitted — the schema lists
1771
+ * `destination` as required, whatever its documented default.
1772
+ */
1773
+ destination?: RecordingDestination;
1774
+ /**
1775
+ * Identifier for this recording (1-32 chars, no whitespace). Without it the recording can
1776
+ * only be stopped by the call disconnecting, never by {@link CommandBuilder.stopRecording}.
1777
+ */
1778
+ recordingName?: string;
1779
+ /** Audio format. The platform defaults to `MP3`; omitted from the body when unset. */
1780
+ format?: RecordingFormat;
1781
+ /** Streams captured. The platform defaults to `COMBINED`; omitted from the body when unset. */
1782
+ recordingType?: RecordingType;
1783
+ /**
1784
+ * Transcribe the recording to text. Setting this, or {@link transcriptionLocale}, emits
1785
+ * `transcriptionOptions`; a locale on its own implies `isEnabled: true`.
1786
+ */
1787
+ transcribe?: boolean;
1788
+ /** BCP-47 language tag for transcription. The platform defaults to `en-US`. */
1789
+ transcriptionLocale?: string;
1790
+ /**
1791
+ * Runs when the recording stops. Note this fires on *stop*, not on delivery — the file may
1792
+ * still be in flight to the destination.
1793
+ *
1794
+ * Unlike a `dial` or an `amd`, naming neither this nor {@link onFailure} does **not** hand the
1795
+ * outcome to the service webhook — see {@link RecordingEvents}. Nothing is emitted
1796
+ * and nothing is notified.
1797
+ */
1798
+ onFinish?: Flow;
1799
+ /**
1800
+ * Runs when the recording could not be started. The only way to hear about a failed recording:
1801
+ * there is no service-webhook fallback for this command.
1802
+ */
1803
+ onFailure?: Flow;
1804
+ }
1805
+ /** Anything that can stand in for a menu prompt: a builder, a callback, or plain text. */
1806
+ export type PromptFlow = string | PromptBuilder | ((prompt: PromptBuilder) => PromptBuilder | void);
1807
+ declare class PromptBuilder {
1808
+ private readonly messages;
1809
+ private barge;
1810
+ /**
1811
+ * Speak text.
1812
+ *
1813
+ * @param text - Text to synthesise, or an SSML document when `format` is `SSML`
1814
+ * @param options - Voice and format overrides
1815
+ */
1816
+ say(text: string, options?: SayOptions): this;
1817
+ /**
1818
+ * Play an audio file.
1819
+ *
1820
+ * @param url - Publicly reachable URL of the audio file
1821
+ */
1822
+ play(url: string): this;
1823
+ /**
1824
+ * Let input interrupt the prompt instead of waiting for it to finish. Emits
1825
+ * `allowBargeIn`, which the platform defaults to `true`.
1826
+ *
1827
+ * @param enabled - Pass `false` to state the opposite explicitly
1828
+ */
1829
+ bargeIn(enabled?: boolean): this;
1830
+ /** Emit the prompt. @throws If nothing was queued to play */
1831
+ build(): MenuPrompt;
1832
+ }
1833
+ declare class MenuItemBuilder {
1834
+ private readonly item;
1835
+ private readonly matchOrder;
1836
+ private readonly matches;
1837
+ /**
1838
+ * Prompt played when the menu is entered.
1839
+ *
1840
+ * @param prompt - Plain text, a {@link PromptBuilder}, or a callback receiving one
1841
+ */
1842
+ prompt(prompt: PromptFlow): this;
1843
+ /**
1844
+ * Prompt played on each retry. Falls back to `prompt` when unset.
1845
+ *
1846
+ * @param prompt - Plain text, a {@link PromptBuilder}, or a callback receiving one
1847
+ */
1848
+ repeatPrompt(prompt: PromptFlow): this;
1849
+ /**
1850
+ * How long to wait for input before repeating.
1851
+ *
1852
+ * @param seconds - Seconds of silence that count as no input
1853
+ */
1854
+ inputTimeout(seconds: number): this;
1855
+ /**
1856
+ * How many times the prompt repeats before `onFail` runs.
1857
+ *
1858
+ * @param times - Repeat count
1859
+ */
1860
+ repeatCount(times: number): this;
1861
+ /**
1862
+ * Fewest input characters collected before the menu evaluates them. Emits
1863
+ * `minimumInputLength`. 1-100, default 1.
1864
+ *
1865
+ * @param count - Minimum input length
1866
+ */
1867
+ minLength(count: number): this;
1868
+ /**
1869
+ * Input character count that triggers evaluation. Emits `maximumInputLength`. 1-100,
1870
+ * default 1.
1871
+ *
1872
+ * @param count - Maximum input length
1873
+ */
1874
+ maxLength(count: number): this;
1875
+ /**
1876
+ * Character sequence that ends input and triggers evaluation immediately, e.g. `#`.
1877
+ *
1878
+ * The pair to {@link maxLength}: with a range of accepted lengths, this is how a shorter
1879
+ * entry is submitted without waiting out `inputTimeout`. The sequence itself is part of
1880
+ * the input the `matches` keys see.
1881
+ *
1882
+ * @param sequence - Digits, `*` and `#` only, up to 10 characters
1883
+ */
1884
+ terminatedBy(sequence: string): this;
1885
+ /**
1886
+ * What one input does.
1887
+ *
1888
+ * Keys may be literal digits or regular expressions, and the platform evaluates them in
1889
+ * definition order with first match winning — so the order these are written in is part of
1890
+ * the behaviour, not decoration. {@link build} refuses to emit a menu whose keys JSON
1891
+ * cannot carry in that order; see the error it throws.
1892
+ *
1893
+ * @param pattern - Digits, or a regular expression source
1894
+ * @param flow - Commands to run on a match
1895
+ */
1896
+ match(pattern: string, flow: Flow): this;
1897
+ /**
1898
+ * Commands to run once the caller is out of attempts.
1899
+ *
1900
+ * @param flow - Commands to run
1901
+ */
1902
+ onFail(flow: Flow): this;
1903
+ /**
1904
+ * Emit the menu.
1905
+ *
1906
+ * @throws If the `matches` keys cannot be serialised in the order they were written
1907
+ */
1908
+ build(): MenuItem;
1909
+ }
1910
+ /**
1911
+ * Ordered `svamlCommands` list.
1912
+ *
1913
+ * Commands come out in the order they were written. Consecutive `say` and `play` calls
1914
+ * collect into one `messages` command — `messages` is non-blocking in v2, so two separate
1915
+ * commands would play over each other instead of in sequence.
1916
+ *
1917
+ * A `hangup()` written directly after messages rides those messages' `onFinish`. That is how
1918
+ * "say this, then hang up" is expressed against a non-blocking command: a standalone `hangup`
1919
+ * queued next would fire while the audio was still playing. Written anywhere else it is a
1920
+ * plain `hangup` command in exactly that position, so `hangup().say('x')` emits hangup then
1921
+ * say — literally what it reads, and, as written, never reached on a live call.
1922
+ */
1923
+ export declare class CommandBuilder {
1924
+ private readonly list;
1925
+ private readonly pending;
1926
+ /**
1927
+ * Speak text on the call.
1928
+ *
1929
+ * @param text - Text to synthesise, or an SSML document when `format` is `SSML`
1930
+ * @param options - Voice and format overrides
1931
+ */
1932
+ say(text: string, options?: SayOptions): this;
1933
+ /**
1934
+ * Play an audio file on the call.
1935
+ *
1936
+ * @param url - Publicly reachable URL of the audio file
1937
+ */
1938
+ play(url: string): this;
1939
+ /**
1940
+ * End the call at this point in the sequence.
1941
+ *
1942
+ * Messages queued before it still play in full — and end the call whether they finish or
1943
+ * fail, since a failed playback would otherwise leave the call with nothing to do.
1944
+ * Anything queued after it is emitted after it, and on a live call is never reached.
1945
+ *
1946
+ * @param callName - Leg to end. Ends the current leg when omitted.
1947
+ */
1948
+ hangup(callName?: string): this;
1949
+ /** Explicitly answer an inbound leg. */
1950
+ answer(): this;
1951
+ /**
1952
+ * Add the current leg to a named bridge, creating the bridge on first reference.
1953
+ *
1954
+ * @param bridgeName - Bridge name (1-32 chars, no whitespace)
1955
+ */
1956
+ bridgeCall(bridgeName: string): this;
1957
+ /**
1958
+ * Dial another leg. Non-blocking — two dials in one list ring two legs in parallel.
1959
+ *
1960
+ * @param to - Who to call
1961
+ * @param options - Dial settings, named events and leg topology
1962
+ */
1963
+ dial(to: Destination, options?: DialOptions): this;
1964
+ /**
1965
+ * Collect DTMF input against a named menu. Blocking.
1966
+ *
1967
+ * Consecutive `menu()` calls extend one `menu` command, so a multi-level IVR is written as
1968
+ * a run of them and `gotoMenu` jumps between the names. The first one names `startMenu`.
1969
+ * Anything written between two menus (a `say`, a `dial`) breaks the run, and the next
1970
+ * `menu()` starts a second command — the list stays in the order it was written.
1971
+ *
1972
+ * @param name - Menu name, referenced by {@link gotoMenu} and reported on `call.menu`
1973
+ * @param define - Callback receiving the {@link MenuItemBuilder} for this menu
1974
+ *
1975
+ * @example
1976
+ * ```typescript
1977
+ * commands().menu('main', (m) =>
1978
+ * m
1979
+ * .prompt((p) => p.say('Press 1 for sales or 2 for support').bargeIn())
1980
+ * .match('1', (c) => c.dial(sales))
1981
+ * .match('2', (c) => c.dial(support))
1982
+ * .onFail((c) => c.say('Sorry, goodbye').hangup())
1983
+ * );
1984
+ * ```
1985
+ */
1986
+ menu(name: string, define: (menu: MenuItemBuilder) => MenuItemBuilder | void): this;
1987
+ /**
1988
+ * Jump to another menu in the enclosing `menu` command. Legal only inside menu execution.
1989
+ *
1990
+ * @param menuName - Menu to enter
1991
+ */
1992
+ gotoMenu(menuName: string): this;
1993
+ /**
1994
+ * Wait before running the next command. Blocking.
1995
+ *
1996
+ * The call stays connected and audio is unaffected — this delays the *script*, not the
1997
+ * media. So it is the way to let a non-blocking command get somewhere before the next one
1998
+ * runs: a beat after `amd` reports a beep, before the message that leaves the voicemail.
1999
+ *
2000
+ * @param durationMilliseconds - How long to wait, in milliseconds. Minimum 1.
2001
+ * @throws If the duration is below the schema's minimum of 1
2002
+ */
2003
+ pause(durationMilliseconds: number): this;
2004
+ /**
2005
+ * Stop a named `messages` sequence. Non-blocking.
2006
+ *
2007
+ * Targets a sequence by the `messagesName` it was started under, so it is only reachable
2008
+ * from a later command list — a `PATCH` on a live call, or a `dial` event — never from the
2009
+ * same list that queued the messages.
2010
+ *
2011
+ * @param messagesName - Sequence to stop (1-32 chars, no whitespace)
2012
+ * @param flags - `ONLY_PLAYING` cancels the current message and lets the queue continue.
2013
+ * Omitted, the platform applies `ALL_FROM_NOW_ON` and the whole queue goes.
2014
+ */
2015
+ stopMessages(messagesName: string, flags?: StopMessagesFlags): this;
2016
+ /**
2017
+ * Run answering machine detection on the call. Non-blocking.
2018
+ *
2019
+ * Detection runs in parallel with the rest of the list; the verdict arrives on one of the
2020
+ * four events, or — with no events named — as a `call.amd.*` webhook.
2021
+ *
2022
+ * These four are the AMD *result* outcomes, so none of them gets a hangup default the way a
2023
+ * `dial`'s never-connected outcomes do. They do follow `dial`'s all-or-nothing rule: naming
2024
+ * any one of them detaches the service webhook from all four, so this emits a **complete**
2025
+ * block once any is named, with the rest as empty lists. Confirmed in `calling-ng` — see
2026
+ * {@link AmdEventOptions}.
2027
+ *
2028
+ * @param events - Commands to run per detection outcome. Omit entirely for webhook mode.
2029
+ *
2030
+ * @example
2031
+ * ```typescript
2032
+ * commands()
2033
+ * .amd({
2034
+ * onHuman: (c) => c.say('Hi, do you have a moment?'),
2035
+ * onMachine: (c) => c.say('Sorry we missed you.').hangup(),
2036
+ * onBeep: (c) => c.pause(500).say('Sorry we missed you.').hangup(),
2037
+ * onUnknown: (c) => c.say('Hi, do you have a moment?'),
2038
+ * })
2039
+ * .say('Connecting you now.');
2040
+ *
2041
+ * // Naming none of them leaves all four to the service webhook as `call.amd.*`.
2042
+ * commands().amd();
2043
+ * ```
2044
+ */
2045
+ amd(events?: AmdEventOptions): this;
2046
+ /**
2047
+ * Ask the application what to do next. **Blocking** — the call waits for the response.
2048
+ *
2049
+ * The event is delivered as `call.webhook.<webhookName>`, so `webhookName: 'escalate'`
2050
+ * arrives as `'call.webhook.escalate'`. `Client.onCall` routes those by name to a handler
2051
+ * registered under `webhooks`, and to `manage` when no name matches.
2052
+ *
2053
+ * @param webhookName - Name for this event (1-64 chars, no whitespace)
2054
+ * @param url - URL to call. The platform allows it 5 seconds to answer.
2055
+ * @param options - Fallback URL
2056
+ *
2057
+ * @example
2058
+ * ```typescript
2059
+ * commands().say('One moment.').webhook('escalate', 'https://acme.com/voice');
2060
+ *
2061
+ * export const handler = voice.onCall({
2062
+ * webhooks: { escalate: () => commands().dial('+15550001111') },
2063
+ * });
2064
+ * ```
2065
+ */
2066
+ webhook(webhookName: string, url: string, options?: WebhookOptions): this;
2067
+ /**
2068
+ * Start recording the call. Non-blocking.
2069
+ *
2070
+ * **The credential is a long-lived storage secret carried inside the command body** — the
2071
+ * schema requires it and offers no short-lived alternative. See {@link RecordingCredentials}
2072
+ * before logging anything a `startRecording` is part of.
2073
+ *
2074
+ * @param options - Destination, credentials, encoding, transcription and outcome events
2075
+ * @throws If a structured credential component contains a colon
2076
+ *
2077
+ * @example
2078
+ * ```typescript
2079
+ * commands().startRecording({
2080
+ * recordingName: 'support',
2081
+ * destinationUrl: 's3://voice-recordings-prod/calls',
2082
+ * credentials: {
2083
+ * accessKeyId: process.env.RECORDING_KEY_ID!,
2084
+ * secretAccessKey: process.env.RECORDING_SECRET!,
2085
+ * region: 'eu-central-1',
2086
+ * },
2087
+ * transcribe: true,
2088
+ * });
2089
+ * ```
2090
+ */
2091
+ startRecording(options: StartRecordingOptions): this;
2092
+ /**
2093
+ * Stop a named recording. Non-blocking.
2094
+ *
2095
+ * A recording started without a `recordingName` cannot be targeted at all — it ends when
2096
+ * the call disconnects and not before.
2097
+ *
2098
+ * @param recordingName - Recording to stop (1-32 chars, no whitespace)
2099
+ */
2100
+ stopRecording(recordingName: string): this;
2101
+ /**
2102
+ * Append a hand-built command — the escape hatch for anything not modelled here.
2103
+ *
2104
+ * @param commands - Commands to append, in order
2105
+ */
2106
+ add(...commands: Command[]): this;
2107
+ /**
2108
+ * Emit the command list.
2109
+ *
2110
+ * Repeatable and non-consuming: the builder is a description of a flow, not a one-shot
2111
+ * handle, so the same one can be sent twice or nested in two places.
2112
+ */
2113
+ build(): Command[];
2114
+ private push;
2115
+ private flush;
2116
+ }
2117
+ /**
2118
+ * Start a command list.
2119
+ *
2120
+ * @example
2121
+ * ```typescript
2122
+ * const flow = commands().say('One moment, connecting you').bridgeCall('support');
2123
+ * ```
2124
+ */
2125
+ export declare function commands(): CommandBuilder;
2126
+ /**
2127
+ * Emit-target-agnostic description of a call flow.
2128
+ *
2129
+ * Build one of these with the client's planning methods, then hand it to
2130
+ * {@link toCallRequest} or {@link toWebhookResponse}.
2131
+ */
2132
+ export interface Plan {
2133
+ /** Ordered command list. Must contain at least one command. */
2134
+ commands: Command[];
2135
+ /**
2136
+ * Name for the inbound leg. Webhook responses only — the API ignores it
2137
+ * everywhere except a response to `call.incoming`, and `POST /calls` rejects it.
2138
+ */
2139
+ callName?: string;
2140
+ /**
2141
+ * Commands to run when the call hangs up. Webhook responses only; on a
2142
+ * call-create body the equivalent lives on the `dial` command's `events`.
2143
+ */
2144
+ onHangup?: Command[];
2145
+ }
2146
+ /** Options for {@link buildTransferCommands} and {@link Client.transfer}. */
2147
+ export interface TransferOptions {
2148
+ /**
2149
+ * Bridge the live legs are already joined in. Defaults to {@link DEFAULT_BRIDGE_NAME}.
2150
+ *
2151
+ * Bridges are **session-scoped**, so this default is safe rather than merely convenient:
2152
+ * `bridgeCall` joins the current call to a bridge "in the same session", and the session
2153
+ * is pinned by the patch target. Two unrelated calls both defaulting to `bridge` are in
2154
+ * two different sessions and therefore two different bridges — there is no way for the
2155
+ * default to connect strangers.
2156
+ *
2157
+ * Pass it explicitly for a call whose bridge was named — `bridgeName` on `bridge()`,
2158
+ * `callWithStream()` or `callWithRelay()` — or for a call this package did not place.
2159
+ * Getting it wrong is quiet: the new leg lands in a freshly created, empty bridge and
2160
+ * hears silence, since the platform creates a bridge on demand rather than failing.
2161
+ */
2162
+ bridgeName?: string;
2163
+ /** Caller identity presented to the party being dialled */
2164
+ from?: Origin;
2165
+ /** Seconds to wait for an answer. Defaults to 30; the platform maximum is 60. */
2166
+ timeout?: number;
2167
+ /**
2168
+ * Name for the new leg. Defaults to {@link DEFAULT_TRANSFER_LEG}.
2169
+ *
2170
+ * Must be unique among the session's live legs. Name it when something downstream reads
2171
+ * leg names off the webhook payload and has to tell this leg apart from the rest.
2172
+ */
2173
+ callName?: string;
2174
+ /**
2175
+ * Leg to end when the dialled party never answers — busy, rejected, timed out, failed —
2176
+ * or hangs up after the handover.
2177
+ *
2178
+ * The one thing this operation cannot infer, and the one that matters most. See
2179
+ * {@link buildTransferCommands} for what happens when it is left unset.
2180
+ */
2181
+ endLeg?: string;
2182
+ }
2183
+ /** Construction options for {@link Client} */
2184
+ export interface Options {
2185
+ /** Sinch project id. Defaults to `PROJECT_ID`, then `context.config.projectId`. */
2186
+ projectId?: string;
2187
+ /** Access Key ID (Basic auth username). Defaults to `PROJECT_ID_API_KEY`. */
2188
+ keyId?: string;
2189
+ /** Access Key Secret (Basic auth password). Defaults to `PROJECT_ID_API_SECRET`. */
2190
+ keySecret?: string;
2191
+ /** API host. Defaults to `https://voice.api.sinch.com`; set a regional host to skip the redirect. */
2192
+ host?: string;
2193
+ /** Public base URL of this function, used to resolve relative stream paths. Defaults to `context.host`. */
2194
+ publicUrl?: string;
2195
+ /** Injected fetch, for tests. Defaults to `globalThis.fetch`. */
2196
+ fetch?: typeof globalThis.fetch;
2197
+ }
2198
+ /** Options shared by the call-creating helpers */
2199
+ export interface CallOptions {
2200
+ /** Caller identity presented to the callee */
2201
+ from?: Origin;
2202
+ /** Seconds to wait for an answer. Maximum 60. */
2203
+ timeout?: number;
2204
+ /** Maximum call duration in seconds. Maximum 14400. */
2205
+ maxDuration?: number;
2206
+ }
2207
+ /**
2208
+ * Options for {@link Client.call}.
2209
+ *
2210
+ * Naming **any** event switches the platform out of service-webhook mode for every event —
2211
+ * see `completeEvents`. Naming none leaves the service webhook in charge, which is the mode
2212
+ * `callBehavior: WEBHOOK` on the service configures and the only mode inbound calls have.
2213
+ * Inline events are an optimisation on top of it, not an alternative to it.
2214
+ */
2215
+ export interface PlaceCallOptions extends CallOptions, DialEvents {
2216
+ /** Name for the dialled leg. Defaults to `origin`. */
2217
+ callName?: string;
2218
+ }
2219
+ /** Options for {@link Client.callWithStream} */
2220
+ export interface StreamCallOptions extends CallOptions {
2221
+ /** Headers delivered on the WebSocket upgrade and in the `connect` message */
2222
+ headers?: Headers$1;
2223
+ /** Audio sampling rate. Defaults to {@link DEFAULT_SAMPLE_RATE}. */
2224
+ sampleRate?: SampleRate;
2225
+ /** Bridge name joining the two legs. Defaults to `bridge`. */
2226
+ bridgeName?: string;
2227
+ }
2228
+ /** Options for {@link Client.callWithRelay} */
2229
+ export interface RelayCallOptions extends CallOptions {
2230
+ /** Platform TTS voice, e.g. `Emma`. Required on the wire; defaults to `DEFAULT_VOICE`. */
2231
+ ttsVoice?: string;
2232
+ /**
2233
+ * BCP-47 language tag for speech-to-text, e.g. `en-US`. Required on the wire; defaults to
2234
+ * {@link DEFAULT_STT_LANGUAGE}.
2235
+ */
2236
+ sttLanguage?: string;
2237
+ /** Let the caller talk over the platform's TTS. The platform defaults this to `true`. */
2238
+ enableInterruptions?: boolean;
2239
+ /** Headers delivered on the WebSocket upgrade and in the `connect` message */
2240
+ headers?: Headers$1;
2241
+ /** Bridge name joining the two legs. Defaults to `bridge`. */
2242
+ bridgeName?: string;
2243
+ }
2244
+ /** Options for {@link Client.bridge} */
2245
+ export interface BridgeOptions extends CallOptions {
2246
+ /** Bridge name joining the two legs. Defaults to `bridge`. */
2247
+ bridgeName?: string;
2248
+ }
2249
+ /** What a webhook handler may return. Returning nothing responds with `204 No Content`. */
2250
+ export type HandlerResult = Plan | Command[] | CommandBuilder | void | undefined;
2251
+ /** A single webhook handler */
2252
+ export type WebhookHandler = (event: WebhookRequest) => HandlerResult | Promise<HandlerResult>;
2253
+ /**
2254
+ * Handlers keyed by call lifecycle stage.
2255
+ *
2256
+ * These are the v1 callback names carried over. The v2 event they map to is
2257
+ * listed in {@link EVENT_MAP}.
2258
+ */
2259
+ export interface CallHandlers {
2260
+ /** `call.incoming` — an inbound call arrived (the v1 ICE callback) */
2261
+ incoming?: WebhookHandler;
2262
+ /** `call.answered` — an outbound call was answered (the v1 ACE callback) */
2263
+ answered?: WebhookHandler;
2264
+ /** `call.menu` and `call.webhook.*` — a mid-call decision point (the v1 PIE callback) */
2265
+ manage?: WebhookHandler;
2266
+ /** `call.hangup` and `call.failed` — the call ended (the v1 DICE callback) */
2267
+ completed?: WebhookHandler;
2268
+ /**
2269
+ * Handlers for `webhook` commands, keyed by the `webhookName` they were raised under.
2270
+ *
2271
+ * A `webhook` command names its own event: `webhook('escalate', url)` is delivered as
2272
+ * `call.webhook.escalate`. Registering the handler under the same name is what closes that
2273
+ * loop — without it every `webhook` command in a function funnels into the single `manage`
2274
+ * handler, which then has to re-parse the event string to tell them apart.
2275
+ *
2276
+ * Checked before `manage`, which still claims any `call.webhook.*` name not listed here.
2277
+ */
2278
+ webhooks?: Record<string, WebhookHandler>;
2279
+ /** Any event none of the above claims */
2280
+ fallback?: WebhookHandler;
2281
+ }
2282
+ /**
2283
+ * Client for the Sinch Voice API v2.
2284
+ *
2285
+ * The upper half of this package: it builds command lists, applies the leg-aware defaults and
2286
+ * dispatches webhooks. It sends nothing itself — the {@link CallTransport} does that, and by
2287
+ * default that is `HttpTransport`, which authenticates with HTTP Basic using the project
2288
+ * Access Key pair (`PROJECT_ID_API_KEY` / `PROJECT_ID_API_SECRET`) — not the v1
2289
+ * application key.
2290
+ */
2291
+ export declare class Client {
2292
+ private readonly publicUrl;
2293
+ /**
2294
+ * The lower layer, reached only through the interface this half of the module owns.
2295
+ *
2296
+ * This field and the `new HttpTransport` below are the whole coupling between the
2297
+ * command builder and the network. When `@sinch/voice@2` ships, an adapter over the
2298
+ * SDK replaces that one expression and nothing else in this file moves.
2299
+ */
2300
+ private readonly transport;
2301
+ /**
2302
+ * @param context - Function context, used for env and for the public host
2303
+ * @param options - Explicit overrides for anything the context cannot supply
2304
+ */
2305
+ constructor(context?: ClientContext, options?: Options);
2306
+ /**
2307
+ * Serialise without reaching the credentials.
2308
+ *
2309
+ * This client is `context.voice`, an enumerable member of the function context, so a
2310
+ * `JSON.stringify(context)` in user code or a structured log line walks straight into the
2311
+ * transport. The transport keeps the Access Key in `#` fields and redacts itself as well;
2312
+ * this stops anything later added to the client — the v1 SDK namespace `attachVoiceClient`
2313
+ * assigns onto `.v1`, for one — from being serialised by accident.
2314
+ */
2315
+ toJSON(): {
2316
+ client: string;
2317
+ transport: CallTransport;
2318
+ publicUrl?: string;
2319
+ };
2320
+ /**
2321
+ * Place an outbound call.
2322
+ *
2323
+ * Name the events you want handled inline and they are sent as a **complete** block, with
2324
+ * busy, rejected, timed-out and failed defaulting to hangup. Name none and no `events` key
2325
+ * is sent at all, which is what hands the call to the service webhook.
2326
+ *
2327
+ * There is no half-way house, and that is the platform's rule rather than this client's:
2328
+ * `events` present means the service webhook is attached to *none* of the six lists, so a
2329
+ * lone `onAnswer` would silently stop busy and hangup from being handled by anything.
2330
+ *
2331
+ * @param to - Who to call
2332
+ * @param options - Dial settings and named events
2333
+ * @throws If the API rejects the request
2334
+ *
2335
+ * @example
2336
+ * ```typescript
2337
+ * // Inline: say a line and hang up, failures end the call
2338
+ * await voice.call('+15559876543', {
2339
+ * from: '+15551234567',
2340
+ * onAnswer: (c) => c.say('Your appointment is confirmed.').hangup(),
2341
+ * });
2342
+ *
2343
+ * // A flow built once and reused
2344
+ * const greeting = commands().say('One moment').bridgeCall('support');
2345
+ * await voice.call('+15559876543', { onAnswer: greeting });
2346
+ *
2347
+ * // Service-webhook mode: no events named, so `call.answered` fires
2348
+ * await voice.call('+15559876543', { from: '+15551234567' });
2349
+ * ```
2350
+ */
2351
+ call(to: Destination, options?: PlaceCallOptions): Promise<CallResponse>;
2352
+ /**
2353
+ * Build the {@link call} flow without sending it.
2354
+ *
2355
+ * @param to - Who to call
2356
+ * @param options - Dial settings and named events
2357
+ */
2358
+ planCall(to: Destination, options?: PlaceCallOptions): Plan;
2359
+ /**
2360
+ * Call a destination and put a WebSocket audio stream on the same call.
2361
+ *
2362
+ * Dials the destination as leg `origin`; on answer that leg joins a bridge and a
2363
+ * second leg is dialled to the STREAM endpoint, which joins the same bridge.
2364
+ * Either leg hanging up ends the other.
2365
+ *
2366
+ * `streamOptions` is always sent in full — the platform defaults to 44100 Hz
2367
+ * when the object is omitted and to 8000 Hz when it is partially supplied.
2368
+ *
2369
+ * Both endpoints are positional, mirroring {@link bridge}: this dials two things and
2370
+ * bridges them, and neither of them has a sensible default. In particular there is no
2371
+ * honest default path for the audio leg — the runtime neither serves nor owns one — so
2372
+ * the socket URL is as required as the number.
2373
+ *
2374
+ * @param to - Who to call
2375
+ * @param stream - WebSocket endpoint for the audio leg. Either a full `ws://`/`wss://`
2376
+ * URL or an absolute path, resolved against this function's public URL.
2377
+ * @param options - Headers, sample rate, bridge name and dial settings
2378
+ * @throws If the stream path cannot be resolved, or if the API rejects the request
2379
+ *
2380
+ * @example
2381
+ * ```typescript
2382
+ * // Relative path, resolved against the function's public host
2383
+ * await voice.callWithStream('+15559876543', '/media', {
2384
+ * from: '+15551234567',
2385
+ * headers: { 'x-contact-id': 'abc123' },
2386
+ * });
2387
+ *
2388
+ * // Full URL, 8 kHz to match a PSTN-only path
2389
+ * await voice.callWithStream('+15559876543', 'wss://example.com/audio', {
2390
+ * from: '+15551234567',
2391
+ * sampleRate: 8000,
2392
+ * });
2393
+ * ```
2394
+ */
2395
+ callWithStream(to: Destination, stream: string, options?: StreamCallOptions): Promise<CallResponse>;
2396
+ /**
2397
+ * Build the {@link callWithStream} flow without sending it.
2398
+ *
2399
+ * @param to - Who to call
2400
+ * @param stream - WebSocket endpoint for the audio leg, as a URL or an absolute path
2401
+ * @param options - Headers, sample rate, bridge name and dial settings
2402
+ * @throws If the stream path cannot be resolved
2403
+ */
2404
+ planStreamCall(to: Destination, stream: string, options?: StreamCallOptions): Plan;
2405
+ /**
2406
+ * Call a destination and put the Voice Relay service on the same call.
2407
+ *
2408
+ * Same topology as {@link callWithStream} — dial the human, bridge a second leg — but the
2409
+ * second leg is a VOICE_RELAY endpoint rather than a raw audio socket: Sinch runs STT and
2410
+ * TTS, and the application exchanges text. The trade is that the application never owns
2411
+ * the TTS stream, which rules the relay out for anything that needs its own voice or
2412
+ * needs to inject filler speech while an LLM thinks.
2413
+ *
2414
+ * The relay socket is positional and required: the `voiceRelay` schema (spec line 2946)
2415
+ * requires `endpoint`, so there is no relay leg without one.
2416
+ *
2417
+ * @param to - Who to call
2418
+ * @param relay - WebSocket endpoint the relay connects to. Either a full `ws://`/`wss://`
2419
+ * URL or an absolute path, resolved against this function's public URL.
2420
+ * @param options - Voice, transcription language, barge-in, bridge name and dial settings
2421
+ * @throws If the API rejects the request
2422
+ */
2423
+ callWithRelay(to: Destination, relay: string, options?: RelayCallOptions): Promise<CallResponse>;
2424
+ /**
2425
+ * Build the {@link callWithRelay} flow without sending it.
2426
+ *
2427
+ * @param to - Who to call
2428
+ * @param relay - WebSocket endpoint the relay connects to, as a URL or an absolute path
2429
+ * @param options - Voice, transcription language, barge-in, bridge name and dial settings
2430
+ */
2431
+ planRelayCall(to: Destination, relay: string, options?: RelayCallOptions): Plan;
2432
+ /**
2433
+ * Call two destinations and bridge them together.
2434
+ *
2435
+ * @param a - First party, dialled as leg `origin`
2436
+ * @param b - Second party, dialled once `a` answers
2437
+ * @param options - Dial settings and bridge name
2438
+ *
2439
+ * @example
2440
+ * ```typescript
2441
+ * await voice.bridge('+15551110000', '+15552220000', { from: '+15551234567' });
2442
+ * ```
2443
+ */
2444
+ bridge(a: Destination, b: Destination, options?: BridgeOptions): Promise<CallResponse>;
2445
+ /**
2446
+ * Build the {@link bridge} flow without sending it.
2447
+ *
2448
+ * @param a - First party, dialled as leg `origin`
2449
+ * @param b - Second party, dialled once `a` answers
2450
+ * @param options - Dial settings and bridge name
2451
+ */
2452
+ planBridge(a: Destination, b: Destination, options?: BridgeOptions): Plan;
2453
+ /**
2454
+ * End one or more legs of a live call.
2455
+ *
2456
+ * @param target - The live call, addressed by `callId` or by `sessionId` + `callName`
2457
+ * @param callNames - Legs to end. Ends the addressed leg when omitted.
2458
+ *
2459
+ * @example
2460
+ * ```typescript
2461
+ * await voice.hangup({ sessionId }, 'origin', 'stream');
2462
+ * ```
2463
+ */
2464
+ hangup(target: PatchTarget, ...callNames: string[]): Promise<void>;
2465
+ /**
2466
+ * Build the {@link hangup} command list without sending it.
2467
+ *
2468
+ * @param callNames - Legs to end. Ends the addressed leg when omitted.
2469
+ */
2470
+ planHangup(...callNames: string[]): Command[];
2471
+ /**
2472
+ * Run commands against a live call — the escalation path.
2473
+ *
2474
+ * @param target - The live call, addressed by `callId` or by `sessionId` + `callName`
2475
+ * @param flow - Commands to execute in the context of the addressed leg, in any
2476
+ * {@link Flow} spelling
2477
+ * @throws If the API rejects the request
2478
+ *
2479
+ * @example
2480
+ * ```typescript
2481
+ * // Pull a human agent into an in-progress streamed call
2482
+ * await voice.patch({ sessionId, callName: 'origin' }, (c) =>
2483
+ * c.bridgeCall('escalation').dial('+15550001111', {
2484
+ * callName: 'agent',
2485
+ * onAnswer: (a) => a.bridgeCall('escalation'),
2486
+ * endOnFailure: 'origin',
2487
+ * })
2488
+ * );
2489
+ * ```
2490
+ */
2491
+ patch(target: PatchTarget, flow: Flow): Promise<void>;
2492
+ /**
2493
+ * Dial a party into a live call's bridge — the transfer v1 has no equivalent of.
2494
+ *
2495
+ * The named sugar over {@link patch}: it sends exactly
2496
+ * `patch(target, buildTransferCommands(to, options))`, and the value is entirely in what
2497
+ * that builder puts around the dial. See {@link buildTransferCommands} for why every
2498
+ * non-answer outcome has to end another leg.
2499
+ *
2500
+ * ### Why both a target and a bridge name
2501
+ *
2502
+ * They address different things and neither is redundant. {@link PatchTarget} pins the
2503
+ * **session** — by `callId`, or by `sessionId` plus the leg the commands run in the context
2504
+ * of. `bridgeName` then resolves **within** that session, because `bridgeCall` joins the
2505
+ * current call to a bridge "in the same session". That scoping is also what makes the
2506
+ * default safe: two unrelated calls both using `bridge` are in two different sessions, so
2507
+ * they cannot meet.
2508
+ *
2509
+ * The one genuinely ambiguous case is inside a single session: reuse a name for what you
2510
+ * meant as two bridges and you get one bridge, because joining a name that already exists
2511
+ * is documented to join it rather than create a second.
2512
+ *
2513
+ * @param target - The live call, addressed by `callId` or by `sessionId` + `callName`
2514
+ * @param to - Party to dial: an E.164 number, a `sip:` URI, or an endpoint object
2515
+ * @param options - Bridge, caller id, dial timeout, leg names
2516
+ * @throws If the API rejects the request
2517
+ *
2518
+ * @example
2519
+ * ```typescript
2520
+ * // A call placed by this client with default options: the bridge is already known
2521
+ * await voice.transfer({ sessionId, callName: 'origin' }, '+15550001111', {
2522
+ * endLeg: 'origin',
2523
+ * });
2524
+ *
2525
+ * // A call whose bridge was named, or one this package did not place
2526
+ * await voice.transfer({ callId }, 'sip:agent@pbx.example.com', {
2527
+ * bridgeName: 'agent',
2528
+ * endLeg: 'stream',
2529
+ * });
2530
+ * ```
2531
+ */
2532
+ transfer(target: PatchTarget, to: Destination, options?: TransferOptions): Promise<void>;
2533
+ /**
2534
+ * Post a call-create body verbatim — the escape hatch for anything this client
2535
+ * does not model.
2536
+ *
2537
+ * The body type is deliberately permissive rather than the `callRequest` shape: the wire
2538
+ * command types are internal to this module, so anything hand-built here is unchecked by
2539
+ * design. Use {@link toCallRequest} on a plan when you want the shape validated.
2540
+ *
2541
+ * @param body - A `callRequest` body, or any object the API accepts
2542
+ * @throws If the API rejects the request
2543
+ */
2544
+ raw(body: object): Promise<CallResponse>;
2545
+ /**
2546
+ * Build a webhook dispatcher over the v2 call lifecycle.
2547
+ *
2548
+ * Handlers may return a plan, a command builder, a bare command array, or nothing.
2549
+ * Nothing means "no commands" and yields `undefined`, which a handler should
2550
+ * turn into a `204`.
2551
+ *
2552
+ * @param handlers - Handlers keyed by lifecycle stage
2553
+ * @returns A function that maps a webhook payload to a response body
2554
+ *
2555
+ * @example
2556
+ * ```typescript
2557
+ * export const handleVoiceWebhook = voice.onCall({
2558
+ * incoming: () => commands().answer().say('Thanks for calling').hangup(),
2559
+ * completed: (event) => {
2560
+ * console.log('call ended', event.call.callId);
2561
+ * },
2562
+ * });
2563
+ * ```
2564
+ */
2565
+ onCall(handlers: CallHandlers): (event: WebhookRequest) => Promise<WebhookResponse | undefined>;
2566
+ /**
2567
+ * The bridged shape: dial one leg, and on answer join a bridge and dial the second into it.
2568
+ *
2569
+ * The leg-aware defaults live here because this is where the topology is known. The second
2570
+ * leg names the first in both `endOnHangup` and `endOnFailure` — every way it can fail ends
2571
+ * the first one too, or `callWithStream` strands the human on a bridge with nothing on the
2572
+ * other side, and a stream-first plan leaves an answered WebSocket leg (with its billed
2573
+ * STT/TTS/LLM sockets) running to the platform's 14400-second ceiling talking to nobody.
2574
+ *
2575
+ * The first leg names the second in `endOnHangup` only. Its failure events fire *before*
2576
+ * the second leg has been dialled, so naming it there would target a leg that does not
2577
+ * exist; a bare hangup is the leg-aware answer for the first leg of a call.
2578
+ */
2579
+ private planBridged;
2580
+ private resolveStreamEndpoint;
2581
+ }
2582
+ /**
2583
+ * Create a Voice API v2 client.
2584
+ *
2585
+ * @param context - Function context, used for env and for the public host
2586
+ * @param options - Explicit overrides for anything the context cannot supply
2587
+ *
2588
+ * @example
2589
+ * ```typescript
2590
+ * const voice = createClient(context);
2591
+ * const voiceEu = createClient(context, { host: 'https://eu1.voice.api.sinch.com' });
2592
+ * ```
2593
+ */
2594
+ export declare function createClient(context?: ClientContext, options?: Options): Client;
2595
+ /**
2596
+ * What `context.voice` is: the Voice API v2 client, with the v1 SDK namespace still reachable
2597
+ * on `.v1`.
2598
+ *
2599
+ * The unversioned name is the current API, so `context.voice.call(...)` is v2 and a function
2600
+ * written against v1 moves one word: `context.voice.callouts` becomes
2601
+ * `context.voice.v1.callouts`. `v1` keeps the type the property had before — `undefined`
2602
+ * unless `VOICE_APPLICATION_KEY` and `VOICE_APPLICATION_SECRET` are set — because the v1
2603
+ * client is still built from those application credentials, while v2 authenticates with the
2604
+ * project Access Key pair.
2605
+ */
2606
+ export type VoiceClient = Client & {
2607
+ /** Voice API v1 client, when `VOICE_APPLICATION_KEY` and `VOICE_APPLICATION_SECRET` are set */
2608
+ v1?: VoiceService;
2609
+ };
988
2610
  /**
989
2611
  * Function configuration with environment variables
990
2612
  */
@@ -1035,10 +2657,12 @@ export interface FunctionContext {
1035
2657
  /** Environment variables */
1036
2658
  env?: Record<string, string | undefined>;
1037
2659
  /**
1038
- * Sinch Voice SDK client.
1039
- * Available when `VOICE_APPLICATION_KEY` and `VOICE_APPLICATION_SECRET` are set.
2660
+ * Voice API v2 client — place calls, bridge legs, attach media streams, dispatch webhooks.
2661
+ * Always present; the credentials are only checked when a request is actually sent.
2662
+ * The v1 SDK client is on `context.voice.v1`.
2663
+ * @see {@link VoiceClient}
1040
2664
  */
1041
- voice?: VoiceService;
2665
+ voice: VoiceClient;
1042
2666
  /**
1043
2667
  * Sinch Conversation SDK client.
1044
2668
  * Available when `CONVERSATION_APP_ID` is set.
@@ -1310,7 +2934,7 @@ export type AmdResult = Voice.AnsweringMachineDetection;
1310
2934
  /** @deprecated Import from '@sinch/voice' instead @internal */
1311
2935
  export type DisconnectReason = Voice.DiceReasonEnum;
1312
2936
  /** @deprecated Import from '@sinch/voice' instead @internal */
1313
- export type CallResult = Voice.ResultEnum;
2937
+ type CallResult$1 = Voice.ResultEnum;
1314
2938
  /**
1315
2939
  * Union type for all voice callback data
1316
2940
  */
@@ -1346,6 +2970,14 @@ export type DiceHandler = (context: FunctionContext, callbackData: DiceCallback)
1346
2970
  * Notify handler
1347
2971
  */
1348
2972
  export type NotifyHandler = (context: FunctionContext, callbackData: NotifyCallback) => Promise<void>;
2973
+ /**
2974
+ * Voice API v2 webhook handler — the `voiceWebhook` export.
2975
+ *
2976
+ * Receives the parsed CloudEvents body, not a `FunctionRequest`: v2 posts one event shape to
2977
+ * one URL, so there is nothing to route on inside the handler. Return a plan, a command list
2978
+ * or a `commands()` builder and the host emits the wire body; return nothing for a `204`.
2979
+ */
2980
+ export type VoiceWebhookHandler = (context: FunctionContext, event: WebhookRequest) => HandlerResult | Promise<HandlerResult>;
1349
2981
  /**
1350
2982
  * Voice function export structure
1351
2983
  *
@@ -1376,6 +3008,15 @@ export interface VoiceFunction {
1376
3008
  dice?: DiceHandler;
1377
3009
  /** Handle notify events */
1378
3010
  notify?: NotifyHandler;
3011
+ /**
3012
+ * Handle the Voice API v2 call lifecycle — every `call.*` event this function's service
3013
+ * posts, whatever URL it posts to. Build one with `onCall()`.
3014
+ *
3015
+ * The `ApiHandler` arm is the host's other accepted shape: a handler that returns a full
3016
+ * `{ statusCode, body }` response gets it emitted untouched, which is what
3017
+ * `@sinch/agents` returns from its own `voiceWebhook`.
3018
+ */
3019
+ voiceWebhook?: VoiceWebhookHandler | ApiHandler;
1379
3020
  /** Default handler for GET / */
1380
3021
  default?: ApiHandler;
1381
3022
  /** Root route handler — TypeScript-friendly alias for 'default' */
@@ -1464,6 +3105,124 @@ export type AuthConfig = string[] | "*";
1464
3105
  * @returns true if credentials match, false otherwise
1465
3106
  */
1466
3107
  export declare function validateBasicAuth(authHeader: string | undefined, expectedKey: string, expectedSecret: string): boolean;
3108
+ /**
3109
+ * Security Configuration for Sinch Functions
3110
+ *
3111
+ * Provides webhook signature validation modes and helpers.
3112
+ */
3113
+ /**
3114
+ * Webhook protection mode
3115
+ * - "never": No validation (development only)
3116
+ * - "deploy": Validate in production (default)
3117
+ * - "always": Always validate
3118
+ */
3119
+ export type WebhookProtectionMode = "never" | "deploy" | "always";
3120
+ /**
3121
+ * Security configuration options for webhook validation.
3122
+ * Controls signature verification for both Voice and Conversation webhooks.
3123
+ */
3124
+ export interface SecurityOptions {
3125
+ /**
3126
+ * Controls webhook signature validation for all webhook types.
3127
+ * @default 'deploy'
3128
+ */
3129
+ webhookProtection: WebhookProtectionMode;
3130
+ }
3131
+ /**
3132
+ * Default security options
3133
+ */
3134
+ export declare const defaultSecurityOptions: SecurityOptions;
3135
+ /**
3136
+ * Determines if webhook validation should be performed based on current environment
3137
+ *
3138
+ * @param mode - The protection mode from configuration
3139
+ * @param isDevelopment - Whether running in development environment
3140
+ * @returns True if validation should be performed
3141
+ */
3142
+ export declare function shouldValidateWebhook(mode: WebhookProtectionMode | string | undefined, isDevelopment: boolean): boolean;
3143
+ export declare function getProtectionMode(config?: Record<string, unknown>): WebhookProtectionMode;
3144
+ /**
3145
+ * Create security options from environment and configuration
3146
+ *
3147
+ * @param config - Optional configuration object
3148
+ * @returns Security options
3149
+ */
3150
+ export declare function createSecurityOptions(config?: Record<string, unknown>): SecurityOptions;
3151
+ /** How far the `x-timestamp` header may sit from now before the request is treated as a replay. */
3152
+ export declare const VOICE_TIMESTAMP_SKEW_MS: number;
3153
+ /** Warning emitted once per process while no service secret is configured. */
3154
+ export declare const VOICE_MISSING_SECRET_WARNING: string;
3155
+ /** The parts of an inbound webhook the signature covers. */
3156
+ export interface VoiceSignedRequest {
3157
+ /** HTTP method, always `POST` for a webhook. */
3158
+ method: string;
3159
+ /** Absolute request path, without query string or fragment. */
3160
+ path: string;
3161
+ /** Verbatim `Content-Type` header value, parameters included. */
3162
+ contentType?: string;
3163
+ /** Verbatim `x-timestamp` header value. */
3164
+ timestamp?: string;
3165
+ /** Verbatim `Authorization` header value. */
3166
+ authorization?: string;
3167
+ /**
3168
+ * Raw request body, exactly as delivered. `''` for a request that carried no body;
3169
+ * `undefined` when the host could not capture the raw bytes, which is a validation failure
3170
+ * with its own message rather than a signature mismatch.
3171
+ */
3172
+ body?: string;
3173
+ }
3174
+ /** Credentials and clock the validation runs against. */
3175
+ export interface VoiceSignatureOptions {
3176
+ /** Service secret, Base64 as issued by Sinch. */
3177
+ serviceSecret: string;
3178
+ /** When set, the id in the `Authorization` header must equal it. */
3179
+ serviceId?: string;
3180
+ /** Current time in epoch milliseconds. Defaults to `Date.now()`. */
3181
+ now?: number;
3182
+ /** Accepted clock skew. Defaults to {@link VOICE_TIMESTAMP_SKEW_MS}. */
3183
+ skewMs?: number;
3184
+ }
3185
+ /** Outcome of a signature check. `reason` is for logs, never for the response body. */
3186
+ export interface VoiceSignatureResult {
3187
+ valid: boolean;
3188
+ reason?: string;
3189
+ }
3190
+ /**
3191
+ * Verify the `Authorization` signature on a Voice v2 webhook.
3192
+ *
3193
+ * @param request - The request as delivered, raw body included
3194
+ * @param options - Service secret, optional service id, and clock
3195
+ * @returns Whether the request is genuine, with a log-safe reason when it is not
3196
+ */
3197
+ export declare function validateVoiceSignature(request: VoiceSignedRequest, options: VoiceSignatureOptions): VoiceSignatureResult;
3198
+ /** How the caller's webhook protection mode and environment reach the gate. */
3199
+ export interface VoiceGateOptions {
3200
+ /** Protection mode, from `WEBHOOK_PROTECTION` (legacy `PROTECT_VOICE_CALLBACKS`). */
3201
+ mode: WebhookProtectionMode;
3202
+ /** Whether the host is running outside production. */
3203
+ isDevelopment: boolean;
3204
+ /** Current time in epoch milliseconds. Defaults to `Date.now()`. */
3205
+ now?: number;
3206
+ /** Environment to read credentials from. Defaults to `process.env`. */
3207
+ env?: NodeJS.ProcessEnv;
3208
+ }
3209
+ /** Clear the once-per-process warning latch. @internal */
3210
+ export declare function resetVoiceSignatureWarning(): void;
3211
+ /**
3212
+ * Decide whether a Voice v2 webhook may proceed.
3213
+ *
3214
+ * Gated by the same `WEBHOOK_PROTECTION` modes as the v1 callbacks, with one deliberate
3215
+ * exception: when the mode says validate but `VOICE_SERVICE_SECRET` is unset, the request is
3216
+ * allowed and a single warning is logged. Sinch does not yet expose a service's secret through
3217
+ * any API or portal, so enforcing without one would reject every legitimate webhook and take
3218
+ * every v2 function down. Templates ship `WEBHOOK_PROTECTION=deploy` today and start enforcing
3219
+ * the moment a secret is set, with no code or configuration change.
3220
+ *
3221
+ * @param request - The request as delivered, raw body included
3222
+ * @param options - Protection mode, environment and clock
3223
+ * @returns Whether the request may proceed, with a log-safe reason when it may not
3224
+ */
3225
+ export declare function verifyVoiceWebhook(request: VoiceSignedRequest, options: VoiceGateOptions): VoiceSignatureResult;
1467
3226
  /**
1468
3227
  * Get the landing page HTML content
1469
3228
  * Exported so production runtime can also use it
@@ -1534,14 +3293,13 @@ export interface FormattedResponse {
1534
3293
  /**
1535
3294
  * Voice callback function names @internal
1536
3295
  *
1537
- * Membership here is what makes a route signature-validated — see the `isVoiceCallback` gate
1538
- * below. Deliberately v1-only: the validator is `validateAuthenticationHeader`, which is the v1
1539
- * scheme keyed on `VOICE_APPLICATION_KEY`/`SECRET`. Adding the v2 route (`voiceWebhook`) here
1540
- * would reject every legitimate v2 webhook, and on a v2-only function those credentials do not
1541
- * exist at all, so the gate would silently do nothing. v2 defends itself in
1542
- * `handleVoiceV2Webhook` instead — see the note there.
3296
+ * Membership here is what makes a route validated by the v1 scheme — see the `isVoiceV1Callback`
3297
+ * gate below. Deliberately v1-only: the validator is `validateAuthenticationHeader`, keyed on
3298
+ * `VOICE_APPLICATION_KEY`/`SECRET`. v2 is signed too, but by a different scheme keyed on the
3299
+ * service secret, so adding the v2 route (`voiceWebhook`) here would reject every legitimate v2
3300
+ * webhook. v2 has its own gate in `setupRequestHandler`, `verifyVoiceWebhook`.
1543
3301
  */
1544
- export declare const VOICE_CALLBACKS: readonly [
3302
+ export declare const VOICE_V1_CALLBACKS: readonly [
1545
3303
  "ice",
1546
3304
  "ace",
1547
3305
  "pie",
@@ -1553,18 +3311,40 @@ export declare const NOTIFICATION_EVENTS: readonly [
1553
3311
  "dice",
1554
3312
  "notify"
1555
3313
  ];
1556
- export type VoiceCallback = (typeof VOICE_CALLBACKS)[number];
3314
+ /** The export a Voice v2 `call.*` event is delivered to @internal */
3315
+ export declare const VOICE_WEBHOOK_HANDLER = "voiceWebhook";
3316
+ export type VoiceV1Callback = (typeof VOICE_V1_CALLBACKS)[number];
1557
3317
  export type NotificationEvent = (typeof NOTIFICATION_EVENTS)[number];
1558
3318
  /**
1559
3319
  * Check if a function name is a voice callback
1560
3320
  * @internal
1561
3321
  */
1562
- export declare function isVoiceCallback(functionName: string): functionName is VoiceCallback;
3322
+ export declare function isVoiceV1Callback(functionName: string): functionName is VoiceV1Callback;
1563
3323
  /**
1564
3324
  * Check if a function is a notification-only event
1565
3325
  * @internal
1566
3326
  */
1567
3327
  export declare function isNotificationEvent(functionName: string): functionName is NotificationEvent;
3328
+ /**
3329
+ * Check if a request routed to `voiceWebhook` actually carries a v2 event.
3330
+ *
3331
+ * `/webhook/voice` reaches that export by path too, and such a request is only a v2 webhook if
3332
+ * it carries a `call.*` event. Anything else — no event at all, or a customer's own body that
3333
+ * happens to have an `event` key — goes down the custom-endpoint path instead, where the
3334
+ * handler still receives a `FunctionRequest`.
3335
+ * @internal
3336
+ */
3337
+ export declare function isVoiceWebhook(body: unknown): body is WebhookRequest;
3338
+ /**
3339
+ * Collect the parts of an Express request the Voice v2 signature covers.
3340
+ *
3341
+ * The path comes off `originalUrl` with the query stripped, not `req.path`: inside the
3342
+ * `/{*splat}` mount `req.path` is always `/`, while the platform signed the absolute path of
3343
+ * the webhook URL it posted to. `rawBody` stays `undefined` when the parser captured no bytes,
3344
+ * which the validator reports on its own terms.
3345
+ * @internal
3346
+ */
3347
+ export declare function buildVoiceSignedRequest(req: SinchRequest): VoiceSignedRequest;
1568
3348
  /**
1569
3349
  * Extract function name from request path or body
1570
3350
  * @internal
@@ -1591,7 +3371,7 @@ export declare function formatCustomResponse(result: unknown): FormattedResponse
1591
3371
  * Validate voice callback request
1592
3372
  * @internal
1593
3373
  */
1594
- export declare function validateVoiceRequest(body: unknown): {
3374
+ export declare function validateVoiceV1Request(body: unknown): {
1595
3375
  valid: boolean;
1596
3376
  error?: string;
1597
3377
  expectedEvents?: string[];
@@ -1601,14 +3381,36 @@ export declare function validateVoiceRequest(body: unknown): {
1601
3381
  *
1602
3382
  * Note: Call-specific data like callId is available on the callback event data,
1603
3383
  * not on the context object.
3384
+ *
3385
+ * `voice` is deliberately absent: it is a lazy getter, and every host merges this object into
3386
+ * a larger one before running a function. Installing the getter here would mean the merge —
3387
+ * a spread — reads it and builds a throwaway Voice client on every request. {@link
3388
+ * attachVoiceClient} goes on last, once the finished context exists.
1604
3389
  * @internal
1605
3390
  */
1606
- export declare function buildBaseContext(req: Request, config?: Partial<FunctionConfig>): FunctionContext;
3391
+ export declare function buildBaseContext(req: Request, config?: Partial<FunctionConfig>): Omit<FunctionContext, "voice">;
1607
3392
  /**
1608
3393
  * Handle voice callback execution
1609
3394
  * @internal
1610
3395
  */
1611
- export declare function handleVoiceCallback(functionName: string, userFunction: SinchFunction, context: FunctionContext, callbackData: unknown, logger?: (...args: unknown[]) => void): Promise<FormattedResponse>;
3396
+ export declare function handleVoiceV1Callback(functionName: string, userFunction: SinchFunction, context: FunctionContext, callbackData: unknown, logger?: (...args: unknown[]) => void): Promise<FormattedResponse>;
3397
+ /**
3398
+ * Handle a Voice API v2 webhook.
3399
+ *
3400
+ * The Voice Platform signs every `call.*` event — `Authorization: service <serviceId>:<sig>`
3401
+ * over the raw body, `Content-Type`, `x-timestamp` and path — and `verifyVoiceWebhook` has
3402
+ * already checked it by the time a request gets here, whenever `VOICE_SERVICE_SECRET` is set.
3403
+ * Until Sinch exposes that secret the check logs one warning and lets the request through, so
3404
+ * a function that wants the endpoint locked before then lists `voiceWebhook` in its `auth`
3405
+ * export, which turns on Basic auth for it like any other handler.
3406
+ *
3407
+ * The plan-to-wire mapping belongs to the v2 client, so the handler's result is routed back
3408
+ * through `Client.onCall` rather than re-implementing `toWebhookResponse` over `resolveFlow`
3409
+ * here. A handler that returns a full `{ statusCode, body }` response instead — what
3410
+ * `@sinch/agents` does — is emitted untouched.
3411
+ * @internal
3412
+ */
3413
+ export declare function handleVoiceWebhook(userFunction: SinchFunction, context: FunctionContext, event: WebhookRequest, logger?: (...args: unknown[]) => void): Promise<FormattedResponse>;
1612
3414
  /**
1613
3415
  * Handle custom endpoint execution
1614
3416
  * @internal
@@ -1832,10 +3634,25 @@ export interface ConversationInitRequest {
1832
3634
  * Allows customizing the conversation for this specific caller
1833
3635
  */
1834
3636
  export interface ConversationInitResponse {
3637
+ /** Discriminator ElevenLabs requires to recognise the response */
3638
+ type?: "conversation_initiation_client_data";
1835
3639
  /** Dynamic variables to use in the conversation */
1836
- dynamic_variables?: Record<string, string>;
3640
+ dynamic_variables?: Record<string, string | number | boolean>;
1837
3641
  /** Override agent configuration for this call */
1838
3642
  conversation_config_override?: ConversationConfigOverride;
3643
+ /** Identifier for the end user, surfaced in ElevenLabs analytics */
3644
+ user_id?: string;
3645
+ /** Provenance of the conversation */
3646
+ source_info?: SourceInfo;
3647
+ }
3648
+ /**
3649
+ * Provenance information reported alongside a conversation
3650
+ */
3651
+ export interface SourceInfo {
3652
+ /** Where the conversation was initiated from (e.g., "sip_trunk") */
3653
+ source?: string;
3654
+ /** Version of the SDK or integration that started it */
3655
+ version?: string;
1839
3656
  }
1840
3657
  /**
1841
3658
  * Configuration override for a specific conversation
@@ -1843,7 +3660,7 @@ export interface ConversationInitResponse {
1843
3660
  export interface ConversationConfigOverride {
1844
3661
  agent?: AgentOverride;
1845
3662
  tts?: TtsOverride;
1846
- turn?: TurnOverride;
3663
+ conversation?: ConversationOverride;
1847
3664
  }
1848
3665
  /**
1849
3666
  * Agent-level configuration override
@@ -1854,26 +3671,40 @@ export interface AgentOverride {
1854
3671
  /** Language override (e.g., "en", "es") */
1855
3672
  language?: string;
1856
3673
  /** Custom prompt override */
3674
+ prompt?: PromptOverride;
3675
+ }
3676
+ /**
3677
+ * Prompt configuration override
3678
+ */
3679
+ export interface PromptOverride {
3680
+ /** System prompt text */
1857
3681
  prompt?: string;
3682
+ /** LLM to use (e.g., "gemini-2.0-flash") */
3683
+ llm?: string;
1858
3684
  }
1859
3685
  /**
1860
3686
  * Text-to-speech configuration override
3687
+ *
3688
+ * Flat by design: ElevenLabs drops a nested `voice_settings` object.
1861
3689
  */
1862
3690
  export interface TtsOverride {
1863
3691
  /** Voice ID to use */
1864
3692
  voice_id?: string;
1865
- /** Voice settings */
1866
- voice_settings?: {
1867
- stability?: number;
1868
- similarity_boost?: number;
1869
- };
3693
+ /** Voice stability (0-1) */
3694
+ stability?: number;
3695
+ /** Speaking rate multiplier */
3696
+ speed?: number;
3697
+ /** Similarity boost (0-1) */
3698
+ similarity_boost?: number;
1870
3699
  }
1871
3700
  /**
1872
- * Turn-taking configuration override
3701
+ * Conversation-level configuration override
1873
3702
  */
1874
- export interface TurnOverride {
1875
- /** Silence threshold in milliseconds */
1876
- silence_threshold_ms?: number;
3703
+ export interface ConversationOverride {
3704
+ /** Run the conversation without audio */
3705
+ text_only?: boolean;
3706
+ /** Maximum conversation duration in seconds */
3707
+ max_duration_seconds?: number;
1877
3708
  }
1878
3709
  /**
1879
3710
  * Post-call webhook payload from ElevenLabs
@@ -2437,49 +4268,6 @@ export declare abstract class ConversationController {
2437
4268
  */
2438
4269
  getWebhookHandler(): (req: Request, res: Response) => Promise<void>;
2439
4270
  }
2440
- /**
2441
- * Security Configuration for Sinch Functions
2442
- *
2443
- * Provides webhook signature validation modes and helpers.
2444
- */
2445
- /**
2446
- * Webhook protection mode
2447
- * - "never": No validation (development only)
2448
- * - "deploy": Validate in production (default)
2449
- * - "always": Always validate
2450
- */
2451
- export type WebhookProtectionMode = "never" | "deploy" | "always";
2452
- /**
2453
- * Security configuration options for webhook validation.
2454
- * Controls signature verification for both Voice and Conversation webhooks.
2455
- */
2456
- export interface SecurityOptions {
2457
- /**
2458
- * Controls webhook signature validation for all webhook types.
2459
- * @default 'deploy'
2460
- */
2461
- webhookProtection: WebhookProtectionMode;
2462
- }
2463
- /**
2464
- * Default security options
2465
- */
2466
- export declare const defaultSecurityOptions: SecurityOptions;
2467
- /**
2468
- * Determines if webhook validation should be performed based on current environment
2469
- *
2470
- * @param mode - The protection mode from configuration
2471
- * @param isDevelopment - Whether running in development environment
2472
- * @returns True if validation should be performed
2473
- */
2474
- export declare function shouldValidateWebhook(mode: WebhookProtectionMode | string | undefined, isDevelopment: boolean): boolean;
2475
- export declare function getProtectionMode(config?: Record<string, unknown>): WebhookProtectionMode;
2476
- /**
2477
- * Create security options from environment and configuration
2478
- *
2479
- * @param config - Optional configuration object
2480
- * @returns Security options
2481
- */
2482
- export declare function createSecurityOptions(config?: Record<string, unknown>): SecurityOptions;
2483
4271
  /**
2484
4272
  * Converts a phone number to local/national format.
2485
4273
  *
@@ -2560,6 +4348,38 @@ export declare function formatDuration(seconds: number): string;
2560
4348
  * @returns Normalized phone number
2561
4349
  */
2562
4350
  export declare function extractCallerNumber(cli: string | undefined): string | undefined;
4351
+ /**
4352
+ * Install `context.voice` on a context object, in place.
4353
+ *
4354
+ * @param context - Context under construction, without its `voice` member
4355
+ * @param v1 - The v1 SDK client to expose as `context.voice.v1`, if credentials produced one
4356
+ * @returns The same object, now carrying `voice`
4357
+ * @internal
4358
+ */
4359
+ export declare function attachVoiceClient<T extends object>(context: T, v1?: VoiceService): T & {
4360
+ voice: VoiceClient;
4361
+ };
4362
+ /**
4363
+ * Build a `voiceWebhook` export from handlers keyed by call lifecycle stage.
4364
+ *
4365
+ * ```typescript
4366
+ * export const voiceWebhook = onCall({
4367
+ * incoming: () => commands().answer().say('Thanks for calling').hangup(),
4368
+ * completed: (event) => console.log('call ended', event.call.callId),
4369
+ * });
4370
+ * ```
4371
+ *
4372
+ * The events reaching these handlers are signed by the Voice Platform, and the host verifies
4373
+ * that signature once `VOICE_SERVICE_SECRET` is set. While it is unset — Sinch does not expose
4374
+ * a service's secret yet — the host logs one warning and delivers the event anyway.
4375
+ *
4376
+ * The dispatch is `context.voice.onCall(handlers)`. That returns a wire `WebhookResponse`
4377
+ * and the host emits the wire body itself, so `events.onHangup` is unwrapped back onto the
4378
+ * plan here — left as-is the host's second mapping would drop it.
4379
+ *
4380
+ * @param handlers - Handlers keyed by lifecycle stage
4381
+ */
4382
+ export declare function onCall(handlers: CallHandlers): VoiceWebhookHandler;
2563
4383
  /**
2564
4384
  * Simple template renderer for HTML files
2565
4385
  * Replaces {{variableName}} placeholders with actual values
@@ -2801,6 +4621,7 @@ export declare class SecretsLoader {
2801
4621
  export declare const secretsLoader: SecretsLoader;
2802
4622
 
2803
4623
  export {
4624
+ CallResult$1 as CallResult,
2804
4625
  CamelCaseOptions as ParserCamelCaseOptions,
2805
4626
  JsonParsingOptions as ParserOptions,
2806
4627
  createLenientJsonParser as createJsonParser,