@sinch/functions-runtime 0.5.22 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +417 -27
- package/dist/bin/sinch-runtime.js +10 -2
- package/dist/bin/sinch-runtime.js.map +1 -1
- package/dist/{chunk-JP6PANB3.js → chunk-TOTJB6SW.js} +4205 -409
- package/dist/chunk-TOTJB6SW.js.map +1 -0
- package/dist/index.d.ts +1175 -144
- package/dist/index.js +51 -3
- package/dist/voice/v2.d.ts +913 -85
- package/dist/voice/v2.js +31 -5
- package/package.json +6 -1
- package/dist/chunk-JP6PANB3.js.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1530,6 +1530,11 @@ export interface Call {
|
|
|
1530
1530
|
/** Absolute URI of this call resource */
|
|
1531
1531
|
callResourceUrl: string;
|
|
1532
1532
|
}
|
|
1533
|
+
/** Body of `POST /v2/projects/{projectId}/calls` */
|
|
1534
|
+
export interface CallRequest {
|
|
1535
|
+
/** Ordered command list. At least one command. */
|
|
1536
|
+
commands: Command[];
|
|
1537
|
+
}
|
|
1533
1538
|
/** `201` response from `POST /calls` */
|
|
1534
1539
|
export interface CallResponse {
|
|
1535
1540
|
/** Project that owns the session */
|
|
@@ -1584,7 +1589,7 @@ export interface WebhookRequest {
|
|
|
1584
1589
|
* @remarks
|
|
1585
1590
|
* This is an object with a `commands` array, not a bare array.
|
|
1586
1591
|
*/
|
|
1587
|
-
export interface
|
|
1592
|
+
export interface WebhookBody {
|
|
1588
1593
|
/** Ordered command list. At least one command. */
|
|
1589
1594
|
commands: Command[];
|
|
1590
1595
|
/** Names the inbound leg. Ignored on responses to anything but `call.incoming`. */
|
|
@@ -1602,7 +1607,7 @@ export interface CallTransport {
|
|
|
1602
1607
|
*
|
|
1603
1608
|
* The body is deliberately permissive rather than `CallRequest`: {@link Client.raw} is an
|
|
1604
1609
|
* escape hatch for bodies this module does not model, and validation belongs to
|
|
1605
|
-
* `
|
|
1610
|
+
* `toCallBody`, not to the transport.
|
|
1606
1611
|
*
|
|
1607
1612
|
* @param body - A `callRequest` body, or any object the API accepts
|
|
1608
1613
|
* @throws If the API rejects the request
|
|
@@ -1617,11 +1622,62 @@ export interface CallTransport {
|
|
|
1617
1622
|
*/
|
|
1618
1623
|
patchCall(target: PatchTarget, commands: Command[]): Promise<void>;
|
|
1619
1624
|
}
|
|
1625
|
+
declare const DEFAULT_SAMPLE_RATE: SampleRate;
|
|
1626
|
+
declare const DEFAULT_VOICE = "Emma";
|
|
1627
|
+
declare const DEFAULT_STT_LANGUAGE = "en-US";
|
|
1620
1628
|
/** A call destination: an E.164 number, a `sip:`/`wss:` URI, or a full endpoint object. */
|
|
1621
1629
|
export type Destination = string | To;
|
|
1622
1630
|
/** A call origin: an E.164 number, a `sip:` URI, or a full endpoint object. */
|
|
1623
1631
|
export type Origin = string | From;
|
|
1624
1632
|
type Headers$1 = Record<string, string> | CallHeader[];
|
|
1633
|
+
declare function phone(number: string): PhoneEndpoint;
|
|
1634
|
+
declare function sip(address: string, options?: {
|
|
1635
|
+
transport?: "UDP" | "TCP" | "TLS";
|
|
1636
|
+
headers?: Headers$1;
|
|
1637
|
+
}): SipEndpoint;
|
|
1638
|
+
declare function stream(endpoint: string, options?: {
|
|
1639
|
+
sampleRate?: SampleRate;
|
|
1640
|
+
headers?: Headers$1;
|
|
1641
|
+
}): StreamEndpoint;
|
|
1642
|
+
declare function relay(endpoint: string, options?: {
|
|
1643
|
+
ttsVoice?: string;
|
|
1644
|
+
sttLanguage?: string;
|
|
1645
|
+
enableInterruptions?: boolean;
|
|
1646
|
+
headers?: Headers$1;
|
|
1647
|
+
}): VoiceRelayEndpoint;
|
|
1648
|
+
declare const dial: {
|
|
1649
|
+
readonly phone: typeof phone;
|
|
1650
|
+
readonly sip: typeof sip;
|
|
1651
|
+
readonly stream: typeof stream;
|
|
1652
|
+
readonly relay: typeof relay;
|
|
1653
|
+
};
|
|
1654
|
+
declare function endpointNumber(value: From | To | undefined): string;
|
|
1655
|
+
/** SIP-based agent providers `dialAgent` and `connectAgent` can bridge to. */
|
|
1656
|
+
export type SipAgentProvider = "elevenlabs" | "grok";
|
|
1657
|
+
/**
|
|
1658
|
+
* An agent that is not a SIP provider — a `realtimeAgent` handle — that `dialAgent` can put
|
|
1659
|
+
* on a call.
|
|
1660
|
+
*/
|
|
1661
|
+
export interface DialableAgent {
|
|
1662
|
+
/**
|
|
1663
|
+
* Build this call's agent-leg destination. Called once per dial, when the flow is built.
|
|
1664
|
+
*
|
|
1665
|
+
* @param call - The webhook the handler's builder is answering
|
|
1666
|
+
* @param context - The context the voice client was created with, when it had one
|
|
1667
|
+
*/
|
|
1668
|
+
endpointFor(call: WebhookRequest, context: ClientContext | undefined): To;
|
|
1669
|
+
}
|
|
1670
|
+
/** SIP settings for an agent leg; each defaults to what the provider requires. */
|
|
1671
|
+
export interface SipAgentOptions {
|
|
1672
|
+
/** Extra SIP headers, merged over the per-call ones (these win on conflict). */
|
|
1673
|
+
headers?: Headers$1;
|
|
1674
|
+
/** SIP transport. Defaults to what the provider requires — TLS for Grok, TCP for ElevenLabs. */
|
|
1675
|
+
transport?: "UDP" | "TCP" | "TLS";
|
|
1676
|
+
/** SIP host. Defaults to the provider's fixed endpoint — override only for a sandbox or proxy. */
|
|
1677
|
+
host?: string;
|
|
1678
|
+
/** SIP port. Defaults to the provider's fixed endpoint. */
|
|
1679
|
+
port?: number;
|
|
1680
|
+
}
|
|
1625
1681
|
/**
|
|
1626
1682
|
* Anything that can stand in for a command list.
|
|
1627
1683
|
*
|
|
@@ -1633,6 +1689,34 @@ type Headers$1 = Record<string, string> | CallHeader[];
|
|
|
1633
1689
|
* than forcing one spelling on positions where it reads badly.
|
|
1634
1690
|
*/
|
|
1635
1691
|
export type Flow = CommandBuilder | Command[] | ((builder: CommandBuilder) => CommandBuilder | void);
|
|
1692
|
+
/**
|
|
1693
|
+
* What a handler's builder knows about the call it answers.
|
|
1694
|
+
*
|
|
1695
|
+
* The builder `onCall` hands a handler is primed with one of these, and it is handed down to
|
|
1696
|
+
* every flow nested inside that builder while the flow is resolved — so a `dialPhone` inside a
|
|
1697
|
+
* menu option, or inside another dial's `onNoAnswer`, defaults `from` and tears down against
|
|
1698
|
+
* the right leg without being told. A free `commands()` builder has none.
|
|
1699
|
+
*
|
|
1700
|
+
* @internal
|
|
1701
|
+
*/
|
|
1702
|
+
export interface FlowScope {
|
|
1703
|
+
/** The webhook being answered. Absent when only an explicit `liveLeg` is known. */
|
|
1704
|
+
readonly event?: WebhookRequest;
|
|
1705
|
+
/** The client's context, handed on to an agent that `dialAgent` builds a leg for */
|
|
1706
|
+
readonly context?: ClientContext;
|
|
1707
|
+
/** Name the live leg has, or gets from this response */
|
|
1708
|
+
readonly liveLeg: string;
|
|
1709
|
+
/**
|
|
1710
|
+
* `call.incoming` only: this response may name the live leg, and the call-level `onHangup`
|
|
1711
|
+
* it carries is the only place a dialled leg's teardown can live. The API ignores both on
|
|
1712
|
+
* every other webhook response.
|
|
1713
|
+
*/
|
|
1714
|
+
readonly namesLiveLeg: boolean;
|
|
1715
|
+
/** Bridge the live leg is already on — set inside a dial's never-connected outcomes */
|
|
1716
|
+
readonly joined?: string;
|
|
1717
|
+
/** Legs dialled under this scope that the call-level `onHangup` must end. Shared by copies. */
|
|
1718
|
+
readonly dialled: Set<string>;
|
|
1719
|
+
}
|
|
1636
1720
|
/** Options for a single TTS message */
|
|
1637
1721
|
export interface SayOptions {
|
|
1638
1722
|
/** Voice name. Defaults to {@link DEFAULT_VOICE}. */
|
|
@@ -1691,6 +1775,68 @@ export interface DialOptions extends DialEvents {
|
|
|
1691
1775
|
*/
|
|
1692
1776
|
endOnFailure?: string;
|
|
1693
1777
|
}
|
|
1778
|
+
declare const DEFAULT_BRIDGE_NAME = "bridge";
|
|
1779
|
+
/**
|
|
1780
|
+
* Options for {@link CommandBuilder.bridgeTo} and the `dial*` verbs built on it.
|
|
1781
|
+
*
|
|
1782
|
+
* On a handler's builder none of these is needed: the leg names, the bridge, `from` and the
|
|
1783
|
+
* teardown all come from the call being answered.
|
|
1784
|
+
*/
|
|
1785
|
+
export interface BridgeToOptions {
|
|
1786
|
+
/**
|
|
1787
|
+
* Caller identity presented to the callee. Defaults by destination: a phone number sees the
|
|
1788
|
+
* Sinch number the call is on, so the far party never sees the caller's; a SIP endpoint or
|
|
1789
|
+
* agent sees the caller's own E.164 number, because for them it is identity. Streams carry none.
|
|
1790
|
+
*/
|
|
1791
|
+
from?: Origin;
|
|
1792
|
+
/** Seconds to wait for an answer. Maximum 60. */
|
|
1793
|
+
timeout?: number;
|
|
1794
|
+
/** Maximum call duration in seconds. Maximum 14400. */
|
|
1795
|
+
maxDuration?: number;
|
|
1796
|
+
/** Name for the dialled leg. Defaults by destination: `destination`, `stream` or `relay`. */
|
|
1797
|
+
legName?: string;
|
|
1798
|
+
/** Bridge both legs join. Defaults to `bridge`; name another for a hold room or a whisper. */
|
|
1799
|
+
bridgeName?: string;
|
|
1800
|
+
/**
|
|
1801
|
+
* Name the live leg already has. Only for a flow no handler's builder answers — a batch body,
|
|
1802
|
+
* a `PATCH` — since a handler's builder knows it. When set, the flow never names the live leg.
|
|
1803
|
+
*/
|
|
1804
|
+
liveLeg?: string;
|
|
1805
|
+
/**
|
|
1806
|
+
* Runs when the leg never connects: busy, rejected, timed out or failed. Naming any one outcome
|
|
1807
|
+
* detaches the service webhook from all six, so this names all four at once. Defaults to ending
|
|
1808
|
+
* the live leg.
|
|
1809
|
+
*/
|
|
1810
|
+
onNoAnswer?: Flow;
|
|
1811
|
+
/** Runs when the callee is busy. Overrides `onNoAnswer` for this outcome. */
|
|
1812
|
+
onBusy?: Flow;
|
|
1813
|
+
/** Runs when the callee rejects. Overrides `onNoAnswer` for this outcome. */
|
|
1814
|
+
onReject?: Flow;
|
|
1815
|
+
/** Runs when nobody answers within `timeout`. Overrides `onNoAnswer` for this outcome. */
|
|
1816
|
+
onTimeout?: Flow;
|
|
1817
|
+
/** Runs when the leg could not be set up. Overrides `onNoAnswer` for this outcome. */
|
|
1818
|
+
onFailure?: Flow;
|
|
1819
|
+
}
|
|
1820
|
+
/** SIP settings {@link CommandBuilder.dialSip} passes to `dial.sip` */
|
|
1821
|
+
export interface DialSipOptions extends BridgeToOptions {
|
|
1822
|
+
transport?: "UDP" | "TCP" | "TLS";
|
|
1823
|
+
headers?: Headers$1;
|
|
1824
|
+
}
|
|
1825
|
+
/** Stream settings {@link CommandBuilder.dialStream} passes to `dial.stream` */
|
|
1826
|
+
export interface DialStreamOptions extends BridgeToOptions {
|
|
1827
|
+
sampleRate?: SampleRate;
|
|
1828
|
+
headers?: Headers$1;
|
|
1829
|
+
}
|
|
1830
|
+
/** Relay settings {@link CommandBuilder.dialRelay} passes to `dial.relay` */
|
|
1831
|
+
export interface DialRelayOptions extends BridgeToOptions {
|
|
1832
|
+
ttsVoice?: string;
|
|
1833
|
+
sttLanguage?: string;
|
|
1834
|
+
enableInterruptions?: boolean;
|
|
1835
|
+
headers?: Headers$1;
|
|
1836
|
+
}
|
|
1837
|
+
/** SIP settings and a leg cap for {@link CommandBuilder.dialAgent} with a SIP provider */
|
|
1838
|
+
export interface DialAgentOptions extends BridgeToOptions, SipAgentOptions {
|
|
1839
|
+
}
|
|
1694
1840
|
/**
|
|
1695
1841
|
* The four answering-machine-detection outcomes.
|
|
1696
1842
|
*
|
|
@@ -1831,9 +1977,12 @@ declare class PromptBuilder {
|
|
|
1831
1977
|
build(): MenuPrompt;
|
|
1832
1978
|
}
|
|
1833
1979
|
declare class MenuItemBuilder {
|
|
1980
|
+
private readonly scope?;
|
|
1834
1981
|
private readonly item;
|
|
1835
1982
|
private readonly matchOrder;
|
|
1836
1983
|
private readonly matches;
|
|
1984
|
+
/** @param scope - The call the enclosing builder answers, handed to every option's flow */
|
|
1985
|
+
constructor(scope?: FlowScope | undefined);
|
|
1837
1986
|
/**
|
|
1838
1987
|
* Prompt played when the menu is entered.
|
|
1839
1988
|
*
|
|
@@ -1900,6 +2049,18 @@ declare class MenuItemBuilder {
|
|
|
1900
2049
|
* @throws If `pattern` does not compile as a regular expression
|
|
1901
2050
|
*/
|
|
1902
2051
|
match(pattern: string, flow: Flow): this;
|
|
2052
|
+
/**
|
|
2053
|
+
* What one keypress sequence does — "press 1 for sales".
|
|
2054
|
+
*
|
|
2055
|
+
* `option` takes the tones literally and escapes `*` and `#` for you; {@link match} takes a
|
|
2056
|
+
* regular expression. Both feed the same ordered `matches` list, first match wins.
|
|
2057
|
+
*
|
|
2058
|
+
* @param digits - DTMF tones only: `0`-`9`, `*` and `#`
|
|
2059
|
+
* @param flow - Commands to run when the caller enters exactly these tones
|
|
2060
|
+
* @throws If `digits` contains anything but DTMF tones
|
|
2061
|
+
*/
|
|
2062
|
+
option(digits: string, flow: Flow): this;
|
|
2063
|
+
private addMatch;
|
|
1903
2064
|
/**
|
|
1904
2065
|
* Commands to run once the caller is out of attempts.
|
|
1905
2066
|
*
|
|
@@ -1909,6 +2070,35 @@ declare class MenuItemBuilder {
|
|
|
1909
2070
|
/** Emit the menu. */
|
|
1910
2071
|
build(): MenuItem;
|
|
1911
2072
|
}
|
|
2073
|
+
/**
|
|
2074
|
+
* A menu written as one object — the settings {@link MenuItemBuilder} exposes, with `options`
|
|
2075
|
+
* standing in for a run of `option()` calls. No regular expressions here: a `match()` needs the
|
|
2076
|
+
* callback form.
|
|
2077
|
+
*/
|
|
2078
|
+
export interface MenuDefinition {
|
|
2079
|
+
/** Prompt played when the menu is entered */
|
|
2080
|
+
prompt?: PromptFlow;
|
|
2081
|
+
/** Prompt played on each retry */
|
|
2082
|
+
repeatPrompt?: PromptFlow;
|
|
2083
|
+
/** Seconds of silence that count as no input */
|
|
2084
|
+
inputTimeout?: number;
|
|
2085
|
+
/** How many times the prompt repeats before `onFail` runs */
|
|
2086
|
+
repeatCount?: number;
|
|
2087
|
+
/** Fewest input characters collected before evaluating */
|
|
2088
|
+
minLength?: number;
|
|
2089
|
+
/** Input length that triggers evaluation */
|
|
2090
|
+
maxLength?: number;
|
|
2091
|
+
/** Sequence that ends input early, e.g. `#` */
|
|
2092
|
+
terminatedBy?: string;
|
|
2093
|
+
/**
|
|
2094
|
+
* What each keypress does, keyed by DTMF tones and escaped exactly as `option()` escapes them.
|
|
2095
|
+
* A plain object is safe here although JavaScript moves integer-like keys first: each key is
|
|
2096
|
+
* an anchored literal, so no two can match the same input and their order changes nothing.
|
|
2097
|
+
*/
|
|
2098
|
+
options?: Record<string, Flow>;
|
|
2099
|
+
/** Commands to run once the caller is out of attempts */
|
|
2100
|
+
onFail?: Flow;
|
|
2101
|
+
}
|
|
1912
2102
|
/**
|
|
1913
2103
|
* Ordered `svamlCommands` list.
|
|
1914
2104
|
*
|
|
@@ -1925,6 +2115,8 @@ declare class MenuItemBuilder {
|
|
|
1925
2115
|
export declare class CommandBuilder {
|
|
1926
2116
|
private readonly list;
|
|
1927
2117
|
private readonly pending;
|
|
2118
|
+
/** Set only on the builder `onCall` injects — see {@link FlowScope} */
|
|
2119
|
+
private scope?;
|
|
1928
2120
|
/**
|
|
1929
2121
|
* Speak text on the call.
|
|
1930
2122
|
*
|
|
@@ -1963,6 +2155,74 @@ export declare class CommandBuilder {
|
|
|
1963
2155
|
* @param options - Dial settings, named events and leg topology
|
|
1964
2156
|
*/
|
|
1965
2157
|
dial(to: Destination, options?: DialOptions): this;
|
|
2158
|
+
/**
|
|
2159
|
+
* Put another party on the call: join the live leg to a bridge, dial the destination into
|
|
2160
|
+
* it, and end each leg when the other goes. The mechanism under every `dial*` verb — reach for
|
|
2161
|
+
* it when a destination is hand-built, or to name the bridge or the leg.
|
|
2162
|
+
*
|
|
2163
|
+
* Never answers the live leg: answering commits billing and forfeits ringback, so an inbound
|
|
2164
|
+
* call that should be answered first says so with {@link answer}.
|
|
2165
|
+
*
|
|
2166
|
+
* @param destination - Who to connect
|
|
2167
|
+
* @param options - Leg and bridge names, `from`, timeouts, and what happens on no answer
|
|
2168
|
+
*/
|
|
2169
|
+
bridgeTo(destination: Destination, options?: BridgeToOptions): this;
|
|
2170
|
+
/**
|
|
2171
|
+
* Connect the caller to a phone number. `from` defaults to the Sinch number the call is on.
|
|
2172
|
+
*
|
|
2173
|
+
* @param number - E.164 number
|
|
2174
|
+
* @param options - See {@link BridgeToOptions}
|
|
2175
|
+
*
|
|
2176
|
+
* @example
|
|
2177
|
+
* ```typescript
|
|
2178
|
+
* incoming: (call, builder) =>
|
|
2179
|
+
* builder.answer().say(greeting).dialPhone(agent, { onNoAnswer: dialPhone(fallback) }),
|
|
2180
|
+
* ```
|
|
2181
|
+
*/
|
|
2182
|
+
dialPhone(number: string, options?: BridgeToOptions): this;
|
|
2183
|
+
/**
|
|
2184
|
+
* Connect the caller to a SIP endpoint. `from` defaults to the caller's E.164 number.
|
|
2185
|
+
*
|
|
2186
|
+
* @param address - SIP URI (`sip:` or `sips:`)
|
|
2187
|
+
* @param options - Transport and headers, plus {@link BridgeToOptions}
|
|
2188
|
+
*/
|
|
2189
|
+
dialSip(address: string, options?: DialSipOptions): this;
|
|
2190
|
+
/**
|
|
2191
|
+
* Connect the caller to a WebSocket media stream.
|
|
2192
|
+
*
|
|
2193
|
+
* @param endpoint - `ws://` or `wss://` URL
|
|
2194
|
+
* @param options - Sample rate and headers, plus {@link BridgeToOptions}
|
|
2195
|
+
*/
|
|
2196
|
+
dialStream(endpoint: string, options?: DialStreamOptions): this;
|
|
2197
|
+
/**
|
|
2198
|
+
* Connect the caller to a Voice Relay socket — platform-side speech to text and back.
|
|
2199
|
+
*
|
|
2200
|
+
* @param endpoint - WebSocket URL that accepts the relay connection, or a `voiceRelay` handle,
|
|
2201
|
+
* which builds its own endpoint from the call being answered. A handle's leg does not end the
|
|
2202
|
+
* caller when it hangs up — the relay ends the caller itself, so a transfer can drop the relay
|
|
2203
|
+
* leg and keep the caller — but failing to connect still does.
|
|
2204
|
+
* @param options - Voice, language, interruptions and headers, plus {@link BridgeToOptions}
|
|
2205
|
+
*/
|
|
2206
|
+
dialRelay(endpoint: string, options?: DialRelayOptions): this;
|
|
2207
|
+
dialRelay(relay: DialableAgent, options?: BridgeToOptions): this;
|
|
2208
|
+
/**
|
|
2209
|
+
* Connect the caller to an AI voice agent: a SIP provider by its number, or a realtime agent.
|
|
2210
|
+
*
|
|
2211
|
+
* Works anywhere a flow does — the whole call, one option of a menu, a `call.menu` response —
|
|
2212
|
+
* because the builder knows which webhook it answers: only on `call.incoming` does it name the
|
|
2213
|
+
* caller leg and end the agent leg when the caller hangs up. A SIP agent leg gets the caller's
|
|
2214
|
+
* E.164 number as `from`, the per-call `X-Sinch-Call-Id` / `X-Caller-Number` /
|
|
2215
|
+
* `X-Dialed-Number` headers, and a 1800-second cap, since both providers bill per minute.
|
|
2216
|
+
*
|
|
2217
|
+
* @example
|
|
2218
|
+
* ```typescript
|
|
2219
|
+
* incoming: (call, builder) => builder.answer().dialAgent('grok', agentNumber),
|
|
2220
|
+
* // or one option of a menu
|
|
2221
|
+
* .option('2', dialAgent(agent))
|
|
2222
|
+
* ```
|
|
2223
|
+
*/
|
|
2224
|
+
dialAgent(provider: SipAgentProvider | (string & Record<never, never>), number: string, options?: DialAgentOptions): this;
|
|
2225
|
+
dialAgent(agent: DialableAgent, options?: BridgeToOptions): this;
|
|
1966
2226
|
/**
|
|
1967
2227
|
* Collect DTMF input against a named menu. Blocking.
|
|
1968
2228
|
*
|
|
@@ -1972,20 +2232,26 @@ export declare class CommandBuilder {
|
|
|
1972
2232
|
* `menu()` starts a second command — the list stays in the order it was written.
|
|
1973
2233
|
*
|
|
1974
2234
|
* @param name - Menu name, referenced by {@link gotoMenu} and reported on `call.menu`
|
|
1975
|
-
* @param define -
|
|
2235
|
+
* @param define - A {@link MenuDefinition}, or a callback receiving the
|
|
2236
|
+
* {@link MenuItemBuilder} for this menu — the form to use for a regular-expression `match`
|
|
1976
2237
|
*
|
|
1977
2238
|
* @example
|
|
1978
2239
|
* ```typescript
|
|
2240
|
+
* builder.menu('main', {
|
|
2241
|
+
* prompt: 'Press 1 for sales or 2 for support',
|
|
2242
|
+
* options: { '1': dialPhone(sales), '2': dialPhone(support) },
|
|
2243
|
+
* onFail: say('Sorry, goodbye').hangup(),
|
|
2244
|
+
* });
|
|
2245
|
+
*
|
|
1979
2246
|
* commands().menu('main', (m) =>
|
|
1980
2247
|
* m
|
|
1981
2248
|
* .prompt((p) => p.say('Press 1 for sales or 2 for support').bargeIn())
|
|
1982
|
-
* .match('
|
|
1983
|
-
* .match('2', (c) => c.dial(support))
|
|
2249
|
+
* .match('[12]', (c) => c.dial(sales))
|
|
1984
2250
|
* .onFail((c) => c.say('Sorry, goodbye').hangup())
|
|
1985
2251
|
* );
|
|
1986
2252
|
* ```
|
|
1987
2253
|
*/
|
|
1988
|
-
menu(name: string, define: (menu: MenuItemBuilder) => MenuItemBuilder | void): this;
|
|
2254
|
+
menu(name: string, define: MenuDefinition | ((menu: MenuItemBuilder) => MenuItemBuilder | void)): this;
|
|
1989
2255
|
/**
|
|
1990
2256
|
* Jump to another menu in the enclosing `menu` command. Legal only inside menu execution.
|
|
1991
2257
|
*
|
|
@@ -2113,6 +2379,7 @@ export declare class CommandBuilder {
|
|
|
2113
2379
|
* handle, so the same one can be sent twice or nested in two places.
|
|
2114
2380
|
*/
|
|
2115
2381
|
build(): Command[];
|
|
2382
|
+
private resolveIn;
|
|
2116
2383
|
private push;
|
|
2117
2384
|
private flush;
|
|
2118
2385
|
}
|
|
@@ -2125,13 +2392,24 @@ export declare class CommandBuilder {
|
|
|
2125
2392
|
* ```
|
|
2126
2393
|
*/
|
|
2127
2394
|
export declare function commands(): CommandBuilder;
|
|
2395
|
+
declare function say(text: string, options?: SayOptions): CommandBuilder;
|
|
2396
|
+
declare function play(url: string): CommandBuilder;
|
|
2397
|
+
declare function menu(name: string, define: MenuDefinition | ((menu: MenuItemBuilder) => MenuItemBuilder | void)): CommandBuilder;
|
|
2398
|
+
declare function bridgeTo(destination: Destination, options?: BridgeToOptions): CommandBuilder;
|
|
2399
|
+
declare function dialPhone(number: string, options?: BridgeToOptions): CommandBuilder;
|
|
2400
|
+
declare function dialSip(address: string, options?: DialSipOptions): CommandBuilder;
|
|
2401
|
+
declare function dialStream(endpoint: string, options?: DialStreamOptions): CommandBuilder;
|
|
2402
|
+
declare function dialRelay(endpoint: string, options?: DialRelayOptions): CommandBuilder;
|
|
2403
|
+
declare function dialRelay(relay: DialableAgent, options?: BridgeToOptions): CommandBuilder;
|
|
2404
|
+
declare function dialAgent(provider: SipAgentProvider | (string & Record<never, never>), number: string, options?: DialAgentOptions): CommandBuilder;
|
|
2405
|
+
declare function dialAgent(agent: DialableAgent, options?: BridgeToOptions): CommandBuilder;
|
|
2128
2406
|
/**
|
|
2129
2407
|
* Emit-target-agnostic description of a call flow.
|
|
2130
2408
|
*
|
|
2131
|
-
* Build one of these with
|
|
2132
|
-
* {@link
|
|
2409
|
+
* Build one of these with a builder or with `client.flows`, then hand it to
|
|
2410
|
+
* {@link toCallBody} or {@link toWebhookBody}.
|
|
2133
2411
|
*/
|
|
2134
|
-
export interface
|
|
2412
|
+
export interface CallFlow {
|
|
2135
2413
|
/** Ordered command list. Must contain at least one command. */
|
|
2136
2414
|
commands: Command[];
|
|
2137
2415
|
/**
|
|
@@ -2145,6 +2423,63 @@ export interface Plan {
|
|
|
2145
2423
|
*/
|
|
2146
2424
|
onHangup?: Command[];
|
|
2147
2425
|
}
|
|
2426
|
+
declare function toCallBody(plan: CallFlow): CallRequest;
|
|
2427
|
+
declare function toWebhookBody(plan: CallFlow): WebhookBody;
|
|
2428
|
+
/** The menu that fired and what the caller entered */
|
|
2429
|
+
export interface MenuInput {
|
|
2430
|
+
/** Name of the menu that fired */
|
|
2431
|
+
menuName: string;
|
|
2432
|
+
/** The input sequence collected from the caller */
|
|
2433
|
+
input: string;
|
|
2434
|
+
}
|
|
2435
|
+
/**
|
|
2436
|
+
* Compatibility base every flattened handler-argument type carries, for code written before the
|
|
2437
|
+
* flatten (`call.call.from` instead of `call.from`).
|
|
2438
|
+
*/
|
|
2439
|
+
export interface DeprecatedCallField {
|
|
2440
|
+
/**
|
|
2441
|
+
* @deprecated The call is already flattened onto this object — read the field directly (e.g.
|
|
2442
|
+
* `call.callId`, not `call.call.callId`). This getter returns the object itself, kept only so
|
|
2443
|
+
* code written before the flatten still compiles and runs; it is not present on the wire —
|
|
2444
|
+
* non-enumerable, so it's absent from `JSON.stringify`, `toWebhookRequest`, and any other
|
|
2445
|
+
* spread of this object.
|
|
2446
|
+
*/
|
|
2447
|
+
readonly call: Call;
|
|
2448
|
+
}
|
|
2449
|
+
/** Intersects `T` (a `Call` plus its event/menu fields) with the deprecated `.call` compat field. */
|
|
2450
|
+
export type Flattened<T> = Call & DeprecatedCallField & T;
|
|
2451
|
+
/** Any event, flattened — what `fallback` receives */
|
|
2452
|
+
export type CallEvent = Flattened<{
|
|
2453
|
+
/** Event that triggered this webhook */
|
|
2454
|
+
event: EventType;
|
|
2455
|
+
/** Present for `call.menu`, and for a `webhook` command run inside a menu */
|
|
2456
|
+
menu?: MenuInput;
|
|
2457
|
+
}>;
|
|
2458
|
+
/** `call.incoming` — an inbound call arrived */
|
|
2459
|
+
export type IncomingCall = Flattened<{
|
|
2460
|
+
event: "call.incoming";
|
|
2461
|
+
}>;
|
|
2462
|
+
/** `call.answered` — an outbound call was answered */
|
|
2463
|
+
export type AnsweredCall = Flattened<{
|
|
2464
|
+
event: "call.answered";
|
|
2465
|
+
}>;
|
|
2466
|
+
/** `call.webhook.<name>` — a `webhook` command asked what to do next */
|
|
2467
|
+
export type WebhookCall = Flattened<{
|
|
2468
|
+
event: `call.webhook.${string}`;
|
|
2469
|
+
menu?: MenuInput;
|
|
2470
|
+
}>;
|
|
2471
|
+
/** `call.menu` with what the caller entered, or a `webhook` command's event */
|
|
2472
|
+
export type MenuCall = Flattened<{
|
|
2473
|
+
event: "call.menu";
|
|
2474
|
+
menu: MenuInput;
|
|
2475
|
+
}> | WebhookCall;
|
|
2476
|
+
/** `call.hangup` or `call.failed` — the call ended */
|
|
2477
|
+
export type CompletedCall = Flattened<{
|
|
2478
|
+
event: "call.hangup" | "call.failed";
|
|
2479
|
+
}>;
|
|
2480
|
+
declare function toCallEvent(request: WebhookRequest): CallEvent;
|
|
2481
|
+
declare function toWebhookRequest(call: CallEvent | WebhookRequest): WebhookRequest;
|
|
2482
|
+
declare const DEFAULT_TRANSFER_LEG = "transfer";
|
|
2148
2483
|
/** Options for {@link buildTransferCommands} and {@link Client.transfer}. */
|
|
2149
2484
|
export interface TransferOptions {
|
|
2150
2485
|
/**
|
|
@@ -2182,6 +2517,32 @@ export interface TransferOptions {
|
|
|
2182
2517
|
*/
|
|
2183
2518
|
endLeg?: string;
|
|
2184
2519
|
}
|
|
2520
|
+
declare function buildTransferCommands(to: Destination, options?: TransferOptions): Command[];
|
|
2521
|
+
/** Options for the client's `transferTo*` methods. */
|
|
2522
|
+
export interface TransferToOptions {
|
|
2523
|
+
/** Bridge the leg is moved into. Defaults to `transferBridge`. */
|
|
2524
|
+
bridgeName?: string;
|
|
2525
|
+
/**
|
|
2526
|
+
* Name of the leg being moved — the one ended if the transfer fails or the new party hangs
|
|
2527
|
+
* up. Defaults to the `callName` of a `{ sessionId, callName }` target, else `origin` when
|
|
2528
|
+
* `call` says the call is outbound, else `caller`: the names a handler's builder and
|
|
2529
|
+
* `flows.call` give the live leg.
|
|
2530
|
+
*/
|
|
2531
|
+
liveLeg?: string;
|
|
2532
|
+
/** Name for the dialled leg. Defaults to {@link DEFAULT_TRANSFER_LEG}. */
|
|
2533
|
+
legName?: string;
|
|
2534
|
+
/** Seconds to wait for an answer. Defaults to 30. */
|
|
2535
|
+
timeout?: number;
|
|
2536
|
+
/** Maximum duration of the new leg, in seconds */
|
|
2537
|
+
maxDuration?: number;
|
|
2538
|
+
/** Caller identity presented to the destination. Defaults from `call`, as `dial*` does. */
|
|
2539
|
+
from?: Origin;
|
|
2540
|
+
/**
|
|
2541
|
+
* The call's latest webhook, when the caller has it. Gives `from` and `liveLeg` the same
|
|
2542
|
+
* defaults as the builder's `dial*` helpers, and is required to transfer to a realtime agent.
|
|
2543
|
+
*/
|
|
2544
|
+
call?: CallEvent | WebhookRequest;
|
|
2545
|
+
}
|
|
2185
2546
|
/** Construction options for {@link Client} */
|
|
2186
2547
|
export interface Options {
|
|
2187
2548
|
/** Sinch project id. Defaults to `PROJECT_ID`, then `context.config.projectId`. */
|
|
@@ -2254,10 +2615,32 @@ export interface BridgeOptions extends CallOptions {
|
|
|
2254
2615
|
/** Bridge name joining the two legs. Defaults to `bridge`. */
|
|
2255
2616
|
bridgeName?: string;
|
|
2256
2617
|
}
|
|
2618
|
+
/** {@link Client.flows}: each call-placing method's flow, built without sending it. */
|
|
2619
|
+
export interface ClientFlows {
|
|
2620
|
+
/** The {@link Client.call} flow */
|
|
2621
|
+
call(to: Destination, options?: PlaceCallOptions): CallFlow;
|
|
2622
|
+
/** The {@link Client.callWithStream} flow. @throws If the stream path cannot be resolved */
|
|
2623
|
+
streamCall(to: Destination, stream: string, options?: StreamCallOptions): CallFlow;
|
|
2624
|
+
/** The {@link Client.callWithRelay} flow */
|
|
2625
|
+
relayCall(to: Destination, relay: string, options?: RelayCallOptions): CallFlow;
|
|
2626
|
+
/** The {@link Client.bridge} flow */
|
|
2627
|
+
bridge(a: Destination, b: Destination, options?: BridgeOptions): CallFlow;
|
|
2628
|
+
/** The {@link Client.hangup} command list. Ends the addressed leg when no leg is named. */
|
|
2629
|
+
hangup(...callNames: string[]): Command[];
|
|
2630
|
+
}
|
|
2257
2631
|
/** What a webhook handler may return. Returning nothing responds with `204 No Content`. */
|
|
2258
|
-
export type HandlerResult =
|
|
2259
|
-
/**
|
|
2260
|
-
|
|
2632
|
+
export type HandlerResult = CallFlow | Command[] | CommandBuilder | void | undefined;
|
|
2633
|
+
/**
|
|
2634
|
+
* A single webhook handler.
|
|
2635
|
+
*
|
|
2636
|
+
* @param call - The call, flattened, with the `event` that fired (and `menu`, for a menu)
|
|
2637
|
+
* beside its fields — `call.from`, `call.event`. Typed per handler slot; see {@link CallHandlers}.
|
|
2638
|
+
* @param builder - A command builder already primed with this call, one per request. Return
|
|
2639
|
+
* it (`.build()` is optional); its `dial*` helpers default `from`, the leg names and the
|
|
2640
|
+
* teardown from the call it answers.
|
|
2641
|
+
* @param request - The webhook body as the platform sent it. Omitted in every normal handler.
|
|
2642
|
+
*/
|
|
2643
|
+
export type WebhookHandler<C extends CallEvent = CallEvent> = (call: C, builder: CommandBuilder, request?: WebhookRequest) => HandlerResult | Promise<HandlerResult>;
|
|
2261
2644
|
/**
|
|
2262
2645
|
* Handlers keyed by call lifecycle stage.
|
|
2263
2646
|
*
|
|
@@ -2266,13 +2649,13 @@ export type WebhookHandler = (event: WebhookRequest) => HandlerResult | Promise<
|
|
|
2266
2649
|
*/
|
|
2267
2650
|
export interface CallHandlers {
|
|
2268
2651
|
/** `call.incoming` — an inbound call arrived (the v1 ICE callback) */
|
|
2269
|
-
incoming?: WebhookHandler
|
|
2652
|
+
incoming?: WebhookHandler<IncomingCall>;
|
|
2270
2653
|
/** `call.answered` — an outbound call was answered (the v1 ACE callback) */
|
|
2271
|
-
answered?: WebhookHandler
|
|
2654
|
+
answered?: WebhookHandler<AnsweredCall>;
|
|
2272
2655
|
/** `call.menu` and `call.webhook.*` — a mid-call decision point (the v1 PIE callback) */
|
|
2273
|
-
manage?: WebhookHandler
|
|
2656
|
+
manage?: WebhookHandler<MenuCall>;
|
|
2274
2657
|
/** `call.hangup` and `call.failed` — the call ended (the v1 DICE callback) */
|
|
2275
|
-
completed?: WebhookHandler
|
|
2658
|
+
completed?: WebhookHandler<CompletedCall>;
|
|
2276
2659
|
/**
|
|
2277
2660
|
* Handlers for `webhook` commands, keyed by the `webhookName` they were raised under.
|
|
2278
2661
|
*
|
|
@@ -2283,10 +2666,17 @@ export interface CallHandlers {
|
|
|
2283
2666
|
*
|
|
2284
2667
|
* Checked before `manage`, which still claims any `call.webhook.*` name not listed here.
|
|
2285
2668
|
*/
|
|
2286
|
-
webhooks?: Record<string, WebhookHandler
|
|
2669
|
+
webhooks?: Record<string, WebhookHandler<WebhookCall>>;
|
|
2287
2670
|
/** Any event none of the above claims */
|
|
2288
2671
|
fallback?: WebhookHandler;
|
|
2289
2672
|
}
|
|
2673
|
+
/**
|
|
2674
|
+
* A lifecycle handler slot — every key of {@link CallHandlers} except `webhooks`, which is a
|
|
2675
|
+
* map of handlers rather than one.
|
|
2676
|
+
*/
|
|
2677
|
+
export type HandlerKey = Exclude<keyof CallHandlers, "webhooks">;
|
|
2678
|
+
declare function resolveHandlerKey(event: string): HandlerKey | undefined;
|
|
2679
|
+
declare function resolveWebhookName(event: string): string | undefined;
|
|
2290
2680
|
/**
|
|
2291
2681
|
* Client for the Sinch Voice API v2.
|
|
2292
2682
|
*
|
|
@@ -2297,6 +2687,7 @@ export interface CallHandlers {
|
|
|
2297
2687
|
* application key.
|
|
2298
2688
|
*/
|
|
2299
2689
|
export declare class Client {
|
|
2690
|
+
private readonly context?;
|
|
2300
2691
|
private readonly publicUrl;
|
|
2301
2692
|
/**
|
|
2302
2693
|
* The lower layer, reached only through the interface this half of the module owns.
|
|
@@ -2306,11 +2697,22 @@ export declare class Client {
|
|
|
2306
2697
|
* SDK replaces that one expression and nothing else in this file moves.
|
|
2307
2698
|
*/
|
|
2308
2699
|
private readonly transport;
|
|
2700
|
+
/**
|
|
2701
|
+
* The flow each call-placing method sends, built without sending it — for a batch body, a
|
|
2702
|
+
* test, or a body posted through {@link raw} after {@link toCallBody}.
|
|
2703
|
+
*
|
|
2704
|
+
* @example
|
|
2705
|
+
* ```typescript
|
|
2706
|
+
* const flow = voice.flows.streamCall('+15559876543', '/media');
|
|
2707
|
+
* await voice.raw(toCallBody(flow));
|
|
2708
|
+
* ```
|
|
2709
|
+
*/
|
|
2710
|
+
readonly flows: ClientFlows;
|
|
2309
2711
|
/**
|
|
2310
2712
|
* @param context - Function context, used for env and for the public host
|
|
2311
2713
|
* @param options - Explicit overrides for anything the context cannot supply
|
|
2312
2714
|
*/
|
|
2313
|
-
constructor(context?: ClientContext, options?: Options);
|
|
2715
|
+
constructor(context?: ClientContext | undefined, options?: Options);
|
|
2314
2716
|
/**
|
|
2315
2717
|
* Serialise without reaching the credentials.
|
|
2316
2718
|
*
|
|
@@ -2363,7 +2765,7 @@ export declare class Client {
|
|
|
2363
2765
|
* @param to - Who to call
|
|
2364
2766
|
* @param options - Dial settings and named events
|
|
2365
2767
|
*/
|
|
2366
|
-
|
|
2768
|
+
private callFlow;
|
|
2367
2769
|
/**
|
|
2368
2770
|
* Call a destination and put a WebSocket audio stream on the same call.
|
|
2369
2771
|
*
|
|
@@ -2409,7 +2811,7 @@ export declare class Client {
|
|
|
2409
2811
|
* @param options - Headers, sample rate, bridge name and dial settings
|
|
2410
2812
|
* @throws If the stream path cannot be resolved
|
|
2411
2813
|
*/
|
|
2412
|
-
|
|
2814
|
+
private streamCallFlow;
|
|
2413
2815
|
/**
|
|
2414
2816
|
* Call a destination and put the Voice Relay service on the same call.
|
|
2415
2817
|
*
|
|
@@ -2436,7 +2838,7 @@ export declare class Client {
|
|
|
2436
2838
|
* @param relay - WebSocket endpoint the relay connects to, as a URL or an absolute path
|
|
2437
2839
|
* @param options - Voice, transcription language, barge-in, bridge name and dial settings
|
|
2438
2840
|
*/
|
|
2439
|
-
|
|
2841
|
+
private relayCallFlow;
|
|
2440
2842
|
/**
|
|
2441
2843
|
* Call two destinations and bridge them together.
|
|
2442
2844
|
*
|
|
@@ -2457,7 +2859,7 @@ export declare class Client {
|
|
|
2457
2859
|
* @param b - Second party, dialled once `a` answers
|
|
2458
2860
|
* @param options - Dial settings and bridge name
|
|
2459
2861
|
*/
|
|
2460
|
-
|
|
2862
|
+
private bridgeFlow;
|
|
2461
2863
|
/**
|
|
2462
2864
|
* End one or more legs of a live call.
|
|
2463
2865
|
*
|
|
@@ -2475,7 +2877,7 @@ export declare class Client {
|
|
|
2475
2877
|
*
|
|
2476
2878
|
* @param callNames - Legs to end. Ends the addressed leg when omitted.
|
|
2477
2879
|
*/
|
|
2478
|
-
|
|
2880
|
+
private hangupCommands;
|
|
2479
2881
|
/**
|
|
2480
2882
|
* Run commands against a live call — the escalation path.
|
|
2481
2883
|
*
|
|
@@ -2538,13 +2940,48 @@ export declare class Client {
|
|
|
2538
2940
|
* ```
|
|
2539
2941
|
*/
|
|
2540
2942
|
transfer(target: PatchTarget, to: Destination, options?: TransferOptions): Promise<void>;
|
|
2943
|
+
/**
|
|
2944
|
+
* Move a live leg to a phone number: out of its bridge, into a new one with that number.
|
|
2945
|
+
*
|
|
2946
|
+
* @param target - A `callId`, or `{ sessionId, callName }`
|
|
2947
|
+
* @param number - E.164 number
|
|
2948
|
+
* @param options - See {@link TransferToOptions}. A 30-second ring; if nobody answers, the leg
|
|
2949
|
+
* is dropped.
|
|
2950
|
+
*
|
|
2951
|
+
* @example
|
|
2952
|
+
* ```typescript
|
|
2953
|
+
* // An agent tool call has only the call id
|
|
2954
|
+
* await voice.transferToPhone(callId, human);
|
|
2955
|
+
* ```
|
|
2956
|
+
*/
|
|
2957
|
+
transferToPhone(target: string | PatchTarget, number: string, options?: TransferToOptions): Promise<void>;
|
|
2958
|
+
/** Move a live leg to a SIP endpoint. See {@link transferToPhone}. */
|
|
2959
|
+
transferToSip(target: string | PatchTarget, address: string, options?: TransferToOptions & {
|
|
2960
|
+
transport?: "UDP" | "TCP" | "TLS";
|
|
2961
|
+
headers?: Headers$1;
|
|
2962
|
+
}): Promise<void>;
|
|
2963
|
+
/** Move a live leg to a WebSocket media stream. See {@link transferToPhone}. */
|
|
2964
|
+
transferToStream(target: string | PatchTarget, endpoint: string, options?: TransferToOptions & {
|
|
2965
|
+
sampleRate?: SampleRate;
|
|
2966
|
+
headers?: Headers$1;
|
|
2967
|
+
}): Promise<void>;
|
|
2968
|
+
/** Move a live leg to Voice Relay. See {@link transferToPhone}. */
|
|
2969
|
+
transferToRelay(target: string | PatchTarget, endpoint: string, options?: TransferToOptions & Pick<RelayCallOptions, "ttsVoice" | "sttLanguage" | "enableInterruptions" | "headers">): Promise<void>;
|
|
2970
|
+
/**
|
|
2971
|
+
* Move a live leg to an AI voice agent: a SIP provider by its number, or a realtime agent.
|
|
2972
|
+
* A realtime agent builds its leg from the call, so pass the call's latest webhook as
|
|
2973
|
+
* `options.call`. See {@link transferToPhone}.
|
|
2974
|
+
*/
|
|
2975
|
+
transferToAgent(target: string | PatchTarget, provider: SipAgentProvider | (string & Record<never, never>), number: string, options?: TransferToOptions & SipAgentOptions): Promise<void>;
|
|
2976
|
+
transferToAgent(target: string | PatchTarget, agent: DialableAgent, options?: TransferToOptions): Promise<void>;
|
|
2977
|
+
private transferTo;
|
|
2541
2978
|
/**
|
|
2542
2979
|
* Post a call-create body verbatim — the escape hatch for anything this client
|
|
2543
2980
|
* does not model.
|
|
2544
2981
|
*
|
|
2545
2982
|
* The body type is deliberately permissive rather than the `callRequest` shape: the wire
|
|
2546
2983
|
* command types are internal to this module, so anything hand-built here is unchecked by
|
|
2547
|
-
* design. Use {@link
|
|
2984
|
+
* design. Use {@link toCallBody} on a flow when you want the shape validated.
|
|
2548
2985
|
*
|
|
2549
2986
|
* @param body - A `callRequest` body, or any object the API accepts
|
|
2550
2987
|
* @throws If the API rejects the request
|
|
@@ -2553,24 +2990,35 @@ export declare class Client {
|
|
|
2553
2990
|
/**
|
|
2554
2991
|
* Build a webhook dispatcher over the v2 call lifecycle.
|
|
2555
2992
|
*
|
|
2556
|
-
*
|
|
2557
|
-
*
|
|
2558
|
-
* turn into a
|
|
2993
|
+
* Each handler receives the webhook and a builder primed with the call it is for — one per
|
|
2994
|
+
* request. Handlers may return a plan, a command builder, a bare command array, or nothing.
|
|
2995
|
+
* Nothing means "no commands" and yields `undefined`, which a handler should turn into a
|
|
2996
|
+
* `204`.
|
|
2559
2997
|
*
|
|
2560
2998
|
* @param handlers - Handlers keyed by lifecycle stage
|
|
2561
|
-
* @returns A function that maps a webhook payload
|
|
2999
|
+
* @returns A function that maps a webhook payload (and, untouched, the raw request it came
|
|
3000
|
+
* in on) to a response body
|
|
2562
3001
|
*
|
|
2563
3002
|
* @example
|
|
2564
3003
|
* ```typescript
|
|
2565
3004
|
* export const handleVoiceWebhook = voice.onCall({
|
|
2566
|
-
* incoming: () =>
|
|
2567
|
-
* completed: (
|
|
2568
|
-
* console.log('call ended',
|
|
3005
|
+
* incoming: (call, builder) => builder.answer().say('Thanks for calling').hangup(),
|
|
3006
|
+
* completed: (call) => {
|
|
3007
|
+
* console.log('call ended', call.callId);
|
|
2569
3008
|
* },
|
|
2570
3009
|
* });
|
|
2571
3010
|
* ```
|
|
2572
3011
|
*/
|
|
2573
|
-
onCall(handlers: CallHandlers): (event: WebhookRequest) => Promise<
|
|
3012
|
+
onCall(handlers: CallHandlers): (event: WebhookRequest) => Promise<WebhookBody | undefined>;
|
|
3013
|
+
/**
|
|
3014
|
+
* What a handler's builder knows about the call it answers.
|
|
3015
|
+
*
|
|
3016
|
+
* Only a response to `call.incoming` may name the live leg, and it names it `caller`. No
|
|
3017
|
+
* webhook reports a leg's name back — the `call` schema has no `callName` — so on every other
|
|
3018
|
+
* event the name comes from whoever named it: `caller` for an inbound leg a handler's builder
|
|
3019
|
+
* answered, `origin` for an outbound leg `flows.call` placed.
|
|
3020
|
+
*/
|
|
3021
|
+
private openScope;
|
|
2574
3022
|
/**
|
|
2575
3023
|
* The bridged shape: dial one leg, and on answer join a bridge and dial the second into it.
|
|
2576
3024
|
*
|
|
@@ -2584,7 +3032,7 @@ export declare class Client {
|
|
|
2584
3032
|
* the second leg has been dialled, so naming it there would target a leg that does not
|
|
2585
3033
|
* exist; a bare hangup is the leg-aware answer for the first leg of a call.
|
|
2586
3034
|
*/
|
|
2587
|
-
private
|
|
3035
|
+
private bridgedFlow;
|
|
2588
3036
|
private resolveStreamEndpoint;
|
|
2589
3037
|
}
|
|
2590
3038
|
/**
|
|
@@ -2600,27 +3048,21 @@ export declare class Client {
|
|
|
2600
3048
|
* ```
|
|
2601
3049
|
*/
|
|
2602
3050
|
export declare function createClient(context?: ClientContext, options?: Options): Client;
|
|
2603
|
-
|
|
2604
|
-
|
|
3051
|
+
declare const DEFAULT_HOST = "https://voice.api.sinch.com";
|
|
3052
|
+
declare const REDACTED = "[redacted]";
|
|
3053
|
+
declare function redactCredentials<T>(body: T): T;
|
|
3054
|
+
declare function stringify(value: unknown): string;
|
|
2605
3055
|
/** Options for {@link connectAgent}. */
|
|
2606
|
-
interface ConnectAgentOptions$1 {
|
|
3056
|
+
interface ConnectAgentOptions$1 extends SipAgentOptions {
|
|
2607
3057
|
/**
|
|
2608
3058
|
* The `call.incoming` event, when available. Used to default `from` to the caller's E.164
|
|
2609
3059
|
* number and to add the `X-Sinch-Call-Id` / `X-Caller-Number` / `X-Dialed-Number` SIP
|
|
2610
3060
|
* headers the grok-voice template sends — how per-call context reaches the agent without an
|
|
2611
3061
|
* API round trip. Omit it and none of that context rides along.
|
|
2612
3062
|
*/
|
|
2613
|
-
call?: WebhookRequest;
|
|
2614
|
-
/** Extra SIP headers, merged with the ones derived from `call` (these win on conflict). */
|
|
2615
|
-
headers?: Headers$1;
|
|
3063
|
+
call?: CallEvent | WebhookRequest;
|
|
2616
3064
|
/** Hard cap on call length, in seconds. Both providers bill per minute of audio. Default 1800. */
|
|
2617
3065
|
maxDuration?: number;
|
|
2618
|
-
/** SIP transport. Defaults to what the provider requires — TLS for Grok, TCP for ElevenLabs. */
|
|
2619
|
-
transport?: "UDP" | "TCP" | "TLS";
|
|
2620
|
-
/** SIP host. Defaults to the provider's fixed endpoint — override only for a sandbox or proxy. */
|
|
2621
|
-
host?: string;
|
|
2622
|
-
/** SIP port. Defaults to the provider's fixed endpoint. */
|
|
2623
|
-
port?: number;
|
|
2624
3066
|
/** Bridge both legs join. Defaults to {@link DEFAULT_BRIDGE_NAME}. */
|
|
2625
3067
|
bridgeName?: string;
|
|
2626
3068
|
/** Name for the inbound leg. Defaults to `'caller'`. */
|
|
@@ -2645,10 +3087,11 @@ interface ConnectAgentOptions$1 {
|
|
|
2645
3087
|
* @throws If `provider` is not a SIP-based provider this helper supports, if `number` is not
|
|
2646
3088
|
* E.164, or if `options.host` contains a character a SIP host cannot
|
|
2647
3089
|
*
|
|
2648
|
-
* Return the {@link
|
|
3090
|
+
* Return the {@link CallFlow} directly from `incoming` — `callName` and `onHangup` are only
|
|
2649
3091
|
* honoured on a response to `call.incoming`. Handing `.commands` on to something else and
|
|
2650
3092
|
* dropping the rest of the plan silently loses the agent-leg teardown, and the SIP leg bills
|
|
2651
|
-
* until `maxDuration`.
|
|
3093
|
+
* until `maxDuration`. For the same reason it cannot be a menu option or answer `call.menu`:
|
|
3094
|
+
* use the handler builder's `dialAgent`, which knows which webhook it answers.
|
|
2652
3095
|
*
|
|
2653
3096
|
* @example
|
|
2654
3097
|
* ```typescript
|
|
@@ -2657,7 +3100,7 @@ interface ConnectAgentOptions$1 {
|
|
|
2657
3100
|
* });
|
|
2658
3101
|
* ```
|
|
2659
3102
|
*/
|
|
2660
|
-
export declare function connectAgent(provider: SipAgentProvider | (string & Record<never, never>), number: string, options?: ConnectAgentOptions$1):
|
|
3103
|
+
export declare function connectAgent(provider: SipAgentProvider | (string & Record<never, never>), number: string, options?: ConnectAgentOptions$1): CallFlow;
|
|
2661
3104
|
/**
|
|
2662
3105
|
* What `context.voice` is: the Voice API v2 client, with the v1 SDK namespace still reachable
|
|
2663
3106
|
* on `.v1`.
|
|
@@ -2674,9 +3117,9 @@ export type VoiceClient = Client & {
|
|
|
2674
3117
|
v1?: VoiceService;
|
|
2675
3118
|
};
|
|
2676
3119
|
/**
|
|
2677
|
-
*
|
|
3120
|
+
* The data half of {@link FunctionConfig}, as a host builds it.
|
|
2678
3121
|
*/
|
|
2679
|
-
export interface
|
|
3122
|
+
export interface FunctionConfigData {
|
|
2680
3123
|
/** Project ID */
|
|
2681
3124
|
projectId: string;
|
|
2682
3125
|
/** Function name */
|
|
@@ -2686,6 +3129,12 @@ export interface FunctionConfig {
|
|
|
2686
3129
|
/** Custom environment variables */
|
|
2687
3130
|
variables?: Record<string, string>;
|
|
2688
3131
|
}
|
|
3132
|
+
/**
|
|
3133
|
+
* Function configuration: the project, function and environment, plus the
|
|
3134
|
+
* {@link ConfigAccessors} — `context.config.getVariable('COMPANY_NAME', 'Acme')`,
|
|
3135
|
+
* `context.config.requireSecret('API_KEY')` and the rest of `UniversalConfig`'s methods.
|
|
3136
|
+
*/
|
|
3137
|
+
export type FunctionConfig = FunctionConfigData & ConfigAccessors;
|
|
2689
3138
|
/**
|
|
2690
3139
|
* Main function context object passed to all handlers
|
|
2691
3140
|
*
|
|
@@ -2844,14 +3293,18 @@ export declare class UniversalConfig {
|
|
|
2844
3293
|
* @param name - Secret name (e.g., 'PROJECT_ID_API_SECRET')
|
|
2845
3294
|
* @param defaultValue - Optional default value if secret not found
|
|
2846
3295
|
*/
|
|
2847
|
-
getSecret(name: string
|
|
3296
|
+
getSecret(name: string): string | null;
|
|
3297
|
+
getSecret(name: string, defaultValue: string): string;
|
|
3298
|
+
getSecret(name: string, defaultValue: string | null): string | null;
|
|
2848
3299
|
/**
|
|
2849
3300
|
* Get an environment variable (non-secret configuration)
|
|
2850
3301
|
*
|
|
2851
3302
|
* @param name - Variable name (e.g., 'COMPANY_NAME', 'API_URL')
|
|
2852
3303
|
* @param defaultValue - Optional default value
|
|
2853
3304
|
*/
|
|
2854
|
-
getVariable(name: string
|
|
3305
|
+
getVariable(name: string): string | null;
|
|
3306
|
+
getVariable(name: string, defaultValue: string): string;
|
|
3307
|
+
getVariable(name: string, defaultValue: string | null): string | null;
|
|
2855
3308
|
/**
|
|
2856
3309
|
* Check if a secret exists (has a value)
|
|
2857
3310
|
*
|
|
@@ -2907,6 +3360,21 @@ export declare class UniversalConfig {
|
|
|
2907
3360
|
*/
|
|
2908
3361
|
export declare function createConfig(context: FunctionContext): UniversalConfig;
|
|
2909
3362
|
export declare const createUniversalConfig: typeof createConfig;
|
|
3363
|
+
declare const CONFIG_ACCESSORS: readonly [
|
|
3364
|
+
"getSecret",
|
|
3365
|
+
"getVariable",
|
|
3366
|
+
"hasSecret",
|
|
3367
|
+
"hasVariable",
|
|
3368
|
+
"requireSecret",
|
|
3369
|
+
"requireVariable",
|
|
3370
|
+
"getApplicationCredentials",
|
|
3371
|
+
"isDevelopment",
|
|
3372
|
+
"isProduction",
|
|
3373
|
+
"getCache",
|
|
3374
|
+
"getConfigSummary"
|
|
3375
|
+
];
|
|
3376
|
+
/** `context.config`'s methods — {@link UniversalConfig}'s, without the wrapper. */
|
|
3377
|
+
export type ConfigAccessors = Pick<UniversalConfig, (typeof CONFIG_ACCESSORS)[number]>;
|
|
2910
3378
|
/**
|
|
2911
3379
|
* HTTP request/response types for custom API endpoints
|
|
2912
3380
|
*/
|
|
@@ -3165,6 +3633,11 @@ export declare function setupJsonParsing(app: Express, options?: JsonParsingOpti
|
|
|
3165
3633
|
* - '*' — protect all handlers
|
|
3166
3634
|
*/
|
|
3167
3635
|
export type AuthConfig = string[] | "*";
|
|
3636
|
+
/**
|
|
3637
|
+
* Constant-time comparison of a provided (key, secret) pair against the expected one. Shared by
|
|
3638
|
+
* Basic Auth and the login form so both credential checks carry the same timing-attack defense.
|
|
3639
|
+
*/
|
|
3640
|
+
export declare function credentialsMatch(providedKey: string, providedSecret: string, expectedKey: string, expectedSecret: string): boolean;
|
|
3168
3641
|
/**
|
|
3169
3642
|
* Validates a Basic Auth header against expected credentials.
|
|
3170
3643
|
*
|
|
@@ -3174,6 +3647,55 @@ export type AuthConfig = string[] | "*";
|
|
|
3174
3647
|
* @returns true if credentials match, false otherwise
|
|
3175
3648
|
*/
|
|
3176
3649
|
export declare function validateBasicAuth(authHeader: string | undefined, expectedKey: string, expectedSecret: string): boolean;
|
|
3650
|
+
export interface AuthCredentialPair {
|
|
3651
|
+
user: string;
|
|
3652
|
+
password: string;
|
|
3653
|
+
}
|
|
3654
|
+
/** The credential pairs a request may authenticate with — project keys, ADMIN_USER, or both. */
|
|
3655
|
+
export declare function collectCredentials(opts: {
|
|
3656
|
+
authKey?: string;
|
|
3657
|
+
authSecret?: string;
|
|
3658
|
+
adminUser?: string;
|
|
3659
|
+
adminPassword?: string;
|
|
3660
|
+
}): AuthCredentialPair[];
|
|
3661
|
+
/** Whether a request carries valid Basic Auth or a valid session cookie for any credential pair. */
|
|
3662
|
+
export declare function isRequestAuthorized(headers: {
|
|
3663
|
+
authorization?: string;
|
|
3664
|
+
cookie?: string;
|
|
3665
|
+
}, credentials: AuthCredentialPair[]): boolean;
|
|
3666
|
+
/** Whether the `auth` list (a function's declarative export) protects the given name. */
|
|
3667
|
+
export declare function isGated(authConfig: AuthConfig | undefined, name: string): boolean;
|
|
3668
|
+
/** A GET a browser navigated to directly, as opposed to a script, curl, or a fetch() call. */
|
|
3669
|
+
export declare function isBrowserNavigation(method: string, acceptHeader: string | undefined): boolean;
|
|
3670
|
+
/** Only a same-origin relative path is safe to bounce back to after login. `//` is host-relative. */
|
|
3671
|
+
export declare function isSafeNextPath(next: unknown): next is string;
|
|
3672
|
+
/**
|
|
3673
|
+
* Reject an unauthenticated request. A browser navigating gets sent to the branded login page —
|
|
3674
|
+
* the native Basic Auth dialog can't be branded and looks like a fault. Everything else — curl,
|
|
3675
|
+
* a script, a fetch() call — gets 401 JSON with no `WWW-Authenticate`, so a browser never mounts
|
|
3676
|
+
* its own dialog: `curl -u` still works because it sends Basic pre-emptively.
|
|
3677
|
+
*/
|
|
3678
|
+
export declare function sendAuthChallenge(req: {
|
|
3679
|
+
method: string;
|
|
3680
|
+
originalUrl: string;
|
|
3681
|
+
headers: {
|
|
3682
|
+
accept?: string;
|
|
3683
|
+
};
|
|
3684
|
+
}, res: Response): void;
|
|
3685
|
+
/** Mutable state a static-file auth gate reads per-request, set once the user module is loaded. */
|
|
3686
|
+
export interface StaticAuthRef {
|
|
3687
|
+
authConfig?: AuthConfig;
|
|
3688
|
+
credentials: AuthCredentialPair[];
|
|
3689
|
+
}
|
|
3690
|
+
/**
|
|
3691
|
+
* Express middleware gating static files listed by path in `auth` (e.g. `auth: ['public/admin.html']`)
|
|
3692
|
+
* before `express.static` ever serves them. Must be mounted ahead of `express.static` in the
|
|
3693
|
+
* stack; it reads `ref` at request time, so it works even though `ref` is populated after the
|
|
3694
|
+
* user module loads, later than the middleware is registered.
|
|
3695
|
+
*
|
|
3696
|
+
* Root (`/`) is excluded — `default` gates it, handled where the static index is served.
|
|
3697
|
+
*/
|
|
3698
|
+
export declare function createStaticAuthGate(ref: StaticAuthRef, staticDirName: string): (req: Request, res: Response, next: NextFunction) => void;
|
|
3177
3699
|
/**
|
|
3178
3700
|
* Security Configuration for Sinch Functions
|
|
3179
3701
|
*
|
|
@@ -3315,6 +3837,12 @@ export interface AppOptions {
|
|
|
3315
3837
|
landingPageEnabled?: boolean;
|
|
3316
3838
|
/** Directory to serve static files from (optional) */
|
|
3317
3839
|
staticDir?: string;
|
|
3840
|
+
/**
|
|
3841
|
+
* Mutable auth state for gating static files listed by path in `auth` (e.g.
|
|
3842
|
+
* `auth: ['public/admin.html']`). Populate it once the user module (and its `auth` export) has
|
|
3843
|
+
* loaded — the gate middleware reads it per-request, not at registration time.
|
|
3844
|
+
*/
|
|
3845
|
+
staticAuthRef?: StaticAuthRef;
|
|
3318
3846
|
}
|
|
3319
3847
|
/**
|
|
3320
3848
|
* Options for setting up the request handler
|
|
@@ -3335,6 +3863,10 @@ export interface RequestHandlerOptions {
|
|
|
3335
3863
|
authKey?: string;
|
|
3336
3864
|
/** API secret for Basic Auth validation */
|
|
3337
3865
|
authSecret?: string;
|
|
3866
|
+
/** Admin username for Basic Auth / login form, alongside authKey (env: ADMIN_USER) */
|
|
3867
|
+
adminUser?: string;
|
|
3868
|
+
/** Admin password for Basic Auth / login form, alongside authSecret (env: ADMIN_PASSWORD) */
|
|
3869
|
+
adminPassword?: string;
|
|
3338
3870
|
/** Called when request starts */
|
|
3339
3871
|
onRequestStart?: (data: {
|
|
3340
3872
|
functionName: string;
|
|
@@ -3457,7 +3989,9 @@ export declare function validateVoiceV1Request(body: unknown): {
|
|
|
3457
3989
|
* attachVoiceClient} goes on last, once the finished context exists.
|
|
3458
3990
|
* @internal
|
|
3459
3991
|
*/
|
|
3460
|
-
export declare function buildBaseContext(req: Request, config?: Partial<
|
|
3992
|
+
export declare function buildBaseContext(req: Request, config?: Partial<FunctionConfigData>): Omit<FunctionContext, "voice" | "config"> & {
|
|
3993
|
+
config: FunctionConfigData;
|
|
3994
|
+
};
|
|
3461
3995
|
/**
|
|
3462
3996
|
* Handle voice callback execution
|
|
3463
3997
|
* @internal
|
|
@@ -3474,7 +4008,7 @@ export declare function handleVoiceV1Callback(functionName: string, userFunction
|
|
|
3474
4008
|
* export, which turns on Basic auth for it like any other handler.
|
|
3475
4009
|
*
|
|
3476
4010
|
* The plan-to-wire mapping belongs to the v2 client, so the handler's result is routed back
|
|
3477
|
-
* through `Client.onCall` rather than re-implementing `
|
|
4011
|
+
* through `Client.onCall` rather than re-implementing `toWebhookBody` over `resolveFlow`
|
|
3478
4012
|
* here. A handler that returns a full `{ statusCode, body }` response instead — what
|
|
3479
4013
|
* `@sinch/agents` does — is emitted untouched.
|
|
3480
4014
|
* @internal
|
|
@@ -4001,6 +4535,550 @@ declare class ElevenLabsStateManager {
|
|
|
4001
4535
|
* Singleton instance of ElevenLabs state
|
|
4002
4536
|
*/
|
|
4003
4537
|
export declare const ElevenLabsState: ElevenLabsStateManager;
|
|
4538
|
+
/** Path the agent media WebSocket is registered on — `createAgent()` and `realtimeAgent()` both use it. */
|
|
4539
|
+
export declare const AGENT_STREAM_PATH = "/stream";
|
|
4540
|
+
/**
|
|
4541
|
+
* Correlation token header, planted in `callHeaders` by whoever dials the STREAM leg.
|
|
4542
|
+
*
|
|
4543
|
+
* A v2 STREAM leg's `callId` is allocated when the platform dials the leg, so there is no id to
|
|
4544
|
+
* pre-register a session under the way v1's ICE callback allows. Every `callHeaders` pair arrives
|
|
4545
|
+
* twice — as an HTTP header on the WebSocket upgrade and inside the `connect` message — so a token
|
|
4546
|
+
* planted at dial time is readable the moment the socket opens.
|
|
4547
|
+
*/
|
|
4548
|
+
export declare const AGENT_HEADER_TOKEN = "x-sinch-agent-token";
|
|
4549
|
+
/**
|
|
4550
|
+
* Resolve the WebSocket URL Sinch should dial to reach this function's own media socket.
|
|
4551
|
+
*
|
|
4552
|
+
* Same order `connectAgent()` uses on v1: an explicit override, then the host the runtime reports
|
|
4553
|
+
* for this function, then `STREAM_URL`, then derivation from the deploy env vars.
|
|
4554
|
+
*
|
|
4555
|
+
* @param context - Function context; `context.host` is only populated on a request-scoped one
|
|
4556
|
+
* @param override - Explicit `wss://` URL, wins over everything
|
|
4557
|
+
* @throws If no source yields a URL, or if a deployed agent resolves a local-dev one
|
|
4558
|
+
*/
|
|
4559
|
+
export declare function resolveAgentStreamUrl(context?: FunctionContext, override?: string): string;
|
|
4560
|
+
/**
|
|
4561
|
+
* A STREAM endpoint, as `dial.stream` builds one.
|
|
4562
|
+
*
|
|
4563
|
+
* Derived from the helper rather than imported by name: the runtime keeps the raw endpoint union
|
|
4564
|
+
* internal now that `dial.stream` is the way to construct one.
|
|
4565
|
+
*/
|
|
4566
|
+
export type AgentStreamEndpoint = ReturnType<typeof dial.stream>;
|
|
4567
|
+
/** Everything a STREAM leg pointed at this function's own media socket needs. */
|
|
4568
|
+
export interface AgentStreamEndpointOptions {
|
|
4569
|
+
/** Resolved `wss://` URL of this function's media socket */
|
|
4570
|
+
endpoint: string;
|
|
4571
|
+
/** Correlation token planted in `callHeaders` */
|
|
4572
|
+
token: string;
|
|
4573
|
+
/** Extra headers the caller wants delivered to the socket */
|
|
4574
|
+
headers?: Record<string, string>;
|
|
4575
|
+
/**
|
|
4576
|
+
* Override the negotiated sample rate. Defaults to 16kHz, which is
|
|
4577
|
+
* what `@sinch/agents`' own media pipeline is built for. `realtimeAgent` passes 8000 or 16000
|
|
4578
|
+
* here per its `audio` option — see the design spec's "Audio format" section: the platform's
|
|
4579
|
+
* own `connectStream` docs default this field to 8000, documented as "standard for PSTN calls".
|
|
4580
|
+
*/
|
|
4581
|
+
sampleRate?: SampleRate;
|
|
4582
|
+
}
|
|
4583
|
+
/**
|
|
4584
|
+
* Build the `to` endpoint for a STREAM leg that terminates on this function's own `/stream`.
|
|
4585
|
+
*
|
|
4586
|
+
* `streamOptions` is always sent in full: omitting it entirely makes the platform default to
|
|
4587
|
+
* 44100 Hz, and supplying it partially makes it default to 8000 Hz. Neither is what the pipeline
|
|
4588
|
+
* is built for. `version` is `1` because that is what the gateway does — binary frames are
|
|
4589
|
+
* un-prefixed raw PCM either way.
|
|
4590
|
+
*
|
|
4591
|
+
* @param options - Endpoint URL, correlation token, extra headers, optional sample-rate override
|
|
4592
|
+
*/
|
|
4593
|
+
export declare function buildAgentStreamEndpoint(options: AgentStreamEndpointOptions): AgentStreamEndpoint;
|
|
4594
|
+
/**
|
|
4595
|
+
* Install `context.voice` on a context object, in place — and the `UniversalConfig` methods on
|
|
4596
|
+
* `context.config` (see `attachConfigAccessors`).
|
|
4597
|
+
*
|
|
4598
|
+
* @param context - Context under construction, without its `voice` member
|
|
4599
|
+
* @param v1 - The v1 SDK client to expose as `context.voice.v1`, if credentials produced one
|
|
4600
|
+
* @returns The same object, now carrying `voice` and a `config` with its accessors
|
|
4601
|
+
* @internal
|
|
4602
|
+
*/
|
|
4603
|
+
export declare function attachVoiceClient<T extends object>(context: T, v1?: VoiceService): T & {
|
|
4604
|
+
voice: VoiceClient;
|
|
4605
|
+
config: FunctionConfig;
|
|
4606
|
+
};
|
|
4607
|
+
/**
|
|
4608
|
+
* A single `onCall` handler slot.
|
|
4609
|
+
*
|
|
4610
|
+
* Same as `@sinch/voice-v2-preview`'s `WebhookHandler` — the webhook, then a builder primed
|
|
4611
|
+
* with the call it is for — followed by the function context and the raw `FunctionRequest`,
|
|
4612
|
+
* since a v2 handler that wants `context.cache`, `context.messaging`, `context.storage`, etc.
|
|
4613
|
+
* needs them like every other runtime handler. A one-argument `(call) => ...` still compiles.
|
|
4614
|
+
*/
|
|
4615
|
+
export type VoiceCallHandler<C extends CallEvent = CallEvent> = (call: C, builder: CommandBuilder, context: FunctionContext, request?: FunctionRequest) => ReturnType<WebhookHandler>;
|
|
4616
|
+
/**
|
|
4617
|
+
* Handlers keyed by call lifecycle stage — the shape `onCall()` takes.
|
|
4618
|
+
*
|
|
4619
|
+
* Same slots as `@sinch/voice-v2-preview`'s `CallHandlers`, widened so each handler also
|
|
4620
|
+
* receives the function context (and the raw request) the way every other runtime handler
|
|
4621
|
+
* does. Named separately from `CallHandlers` — re-exported from this package as-is for anyone
|
|
4622
|
+
* calling `context.voice.onCall` directly — so the two shapes don't collide.
|
|
4623
|
+
*/
|
|
4624
|
+
export interface VoiceCallHandlers {
|
|
4625
|
+
/** `call.incoming` — an inbound call arrived (the v1 ICE callback) */
|
|
4626
|
+
incoming?: VoiceCallHandler<IncomingCall>;
|
|
4627
|
+
/** `call.answered` — an outbound call was answered (the v1 ACE callback) */
|
|
4628
|
+
answered?: VoiceCallHandler<AnsweredCall>;
|
|
4629
|
+
/** `call.menu` and `call.webhook.*` — a mid-call decision point (the v1 PIE callback) */
|
|
4630
|
+
manage?: VoiceCallHandler<MenuCall>;
|
|
4631
|
+
/** `call.hangup` and `call.failed` — the call ended (the v1 DICE callback) */
|
|
4632
|
+
completed?: VoiceCallHandler<CompletedCall>;
|
|
4633
|
+
/** Handlers for `webhook` commands, keyed by the `webhookName` they were raised under. */
|
|
4634
|
+
webhooks?: Record<string, VoiceCallHandler<WebhookCall>>;
|
|
4635
|
+
/** Any event none of the above claims */
|
|
4636
|
+
fallback?: VoiceCallHandler;
|
|
4637
|
+
}
|
|
4638
|
+
/**
|
|
4639
|
+
* Build a `voiceWebhook` export from handlers keyed by call lifecycle stage.
|
|
4640
|
+
*
|
|
4641
|
+
* ```typescript
|
|
4642
|
+
* export const voiceWebhook = onCall({
|
|
4643
|
+
* incoming: (call, builder) => builder.answer().say('Thanks for calling').hangup(),
|
|
4644
|
+
* completed: (call) => console.log('call ended', call.callId),
|
|
4645
|
+
* });
|
|
4646
|
+
* ```
|
|
4647
|
+
*
|
|
4648
|
+
* The events reaching these handlers are signed by the Voice Platform, and the host verifies
|
|
4649
|
+
* that signature once `VOICE_SERVICE_SECRET` is set. While it is unset — Sinch does not expose
|
|
4650
|
+
* a service's secret yet — the host logs one warning and delivers the event anyway.
|
|
4651
|
+
*
|
|
4652
|
+
* Each handler is bound to `context` (and the raw `request`, if the host passed one) before
|
|
4653
|
+
* being handed to `context.voice.onCall`, which only knows the narrower, context-free
|
|
4654
|
+
* `WebhookHandler` shape.
|
|
4655
|
+
*
|
|
4656
|
+
* The dispatch is `context.voice.onCall(handlers)`. That returns a wire `WebhookBody`
|
|
4657
|
+
* and the host emits the wire body itself, so `events.onHangup` is unwrapped back onto the
|
|
4658
|
+
* plan here — left as-is the host's second mapping would drop it.
|
|
4659
|
+
*
|
|
4660
|
+
* @param handlers - Handlers keyed by lifecycle stage
|
|
4661
|
+
*/
|
|
4662
|
+
export declare function onCall(handlers: VoiceCallHandlers): VoiceWebhookHandler;
|
|
4663
|
+
/**
|
|
4664
|
+
* A value an author can give directly, or resolve per call. Resolved once per call, before the
|
|
4665
|
+
* vendor session opens — see `RealtimeAgentOptions.prompt`/`greeting`/`voice`. `call` is the
|
|
4666
|
+
* inbound `call.incoming` event's own `Call`, so a lookup keyed on `call.from` can personalise
|
|
4667
|
+
* the prompt or greeting ("Hello Maria") before the vendor ever hears the line ring.
|
|
4668
|
+
*/
|
|
4669
|
+
export type PerCallValue<T> = T | ((call: Call, context: FunctionContext) => T | Promise<T>);
|
|
4670
|
+
/**
|
|
4671
|
+
* JSON Schema, loosely typed. The runtime does not validate against it — the vendor does, after
|
|
4672
|
+
* an adapter translates it to that vendor's declaration format — so this stays a plain object
|
|
4673
|
+
* rather than pulling in a schema-validation dependency. A `zod` schema's `.shape` or a
|
|
4674
|
+
* hand-written object both satisfy this structurally; the runtime adds no dependency on zod.
|
|
4675
|
+
*/
|
|
4676
|
+
export type JsonSchema = Record<string, unknown>;
|
|
4677
|
+
/** One turn of transcript, from either party, normalised the same way for every vendor. */
|
|
4678
|
+
export interface RealtimeTurn {
|
|
4679
|
+
role: "user" | "agent";
|
|
4680
|
+
text: string;
|
|
4681
|
+
/** ISO 8601 */
|
|
4682
|
+
timestamp: string;
|
|
4683
|
+
}
|
|
4684
|
+
/**
|
|
4685
|
+
* One entry of `ctx.transcript` — a turn from either party, or a completed tool call, in the
|
|
4686
|
+
* order they happened. This is what `onTranscript` fires with and what `ctx.transcript` holds
|
|
4687
|
+
* for the whole call; `onTurn`/`onToolCall` are gone because every event either one reported is
|
|
4688
|
+
* an entry here, tagged by `role`.
|
|
4689
|
+
*/
|
|
4690
|
+
export interface TranscriptEntry {
|
|
4691
|
+
/** `'tool'` is a completed tool call, not spoken turn. */
|
|
4692
|
+
role: "user" | "agent" | "tool";
|
|
4693
|
+
/** Spoken/written text for `'user'`/`'agent'`; the tool's name for `'tool'`. */
|
|
4694
|
+
text: string;
|
|
4695
|
+
/** ISO 8601 */
|
|
4696
|
+
timestamp: string;
|
|
4697
|
+
/** Present only when `role` is `'tool'`. */
|
|
4698
|
+
tool?: string;
|
|
4699
|
+
args?: unknown;
|
|
4700
|
+
/** The handler's resolved value. Absent when the handler threw. */
|
|
4701
|
+
result?: unknown;
|
|
4702
|
+
/** The handler's thrown value, if it threw. */
|
|
4703
|
+
error?: unknown;
|
|
4704
|
+
latencyMs?: number;
|
|
4705
|
+
}
|
|
4706
|
+
/** Fired after a tool's handler resolves or throws — independent of the tool's own return value. */
|
|
4707
|
+
export interface RealtimeToolCallEvent {
|
|
4708
|
+
name: string;
|
|
4709
|
+
args: unknown;
|
|
4710
|
+
/** The handler's resolved value. Absent when the handler threw. */
|
|
4711
|
+
result?: unknown;
|
|
4712
|
+
/** The handler's thrown value, if it threw. */
|
|
4713
|
+
error?: unknown;
|
|
4714
|
+
latencyMs: number;
|
|
4715
|
+
}
|
|
4716
|
+
/** A vendor-side error — session, transport, or a malformed frame. */
|
|
4717
|
+
export interface RealtimeError {
|
|
4718
|
+
message: string;
|
|
4719
|
+
/** A machine-readable error code, when the vendor or transport provides one (e.g. `ECONNRESET`). */
|
|
4720
|
+
code?: string;
|
|
4721
|
+
/**
|
|
4722
|
+
* The vendor's own error payload, if any, for logging. For a connection-level `ws` error this is
|
|
4723
|
+
* always the sanitised `{ message, code? }` from `sanitizeVendorError` — never the raw `Error`
|
|
4724
|
+
* instance, which can carry the connection URL or headers (an API key, for a vendor that puts one
|
|
4725
|
+
* there). A vendor-sent JSON error frame is passed through as-is; that payload is the vendor's own
|
|
4726
|
+
* message body, not connection metadata.
|
|
4727
|
+
*/
|
|
4728
|
+
raw?: unknown;
|
|
4729
|
+
}
|
|
4730
|
+
/**
|
|
4731
|
+
* Call control reachable from inside a tool handler.
|
|
4732
|
+
*
|
|
4733
|
+
* Normalises what all three current realtime templates hand-roll today as a magic
|
|
4734
|
+
* `{ action: 'hangup' | 'transfer', ... }` value a tool returns and the relay loop inspects
|
|
4735
|
+
* after the fact. Calling `ctx.hangup()` / `ctx.transfer()` directly, mid-handler, replaces that
|
|
4736
|
+
* convention: the handler still returns whatever payload the model should see (a confirmation,
|
|
4737
|
+
* an error), and ending or transferring the call is a side effect declared at the point it
|
|
4738
|
+
* happens.
|
|
4739
|
+
*/
|
|
4740
|
+
export interface RealtimeSessionContext {
|
|
4741
|
+
/** The caller's leg's callId — the one `call.hangup` will report. */
|
|
4742
|
+
callId: string;
|
|
4743
|
+
storage: IFunctionStorage;
|
|
4744
|
+
config: UniversalConfig;
|
|
4745
|
+
/**
|
|
4746
|
+
* Aborted the moment this call's session ends, from whichever side (hangup, Sinch closing the
|
|
4747
|
+
* STREAM leg, a fatal vendor error). A tool `handler` that supports cancellation can watch this
|
|
4748
|
+
* to stop early instead of running a side effect for a call that is already over — see the
|
|
4749
|
+
* Deepgram adapter's `FunctionCallCancelled` handling.
|
|
4750
|
+
*/
|
|
4751
|
+
signal: AbortSignal;
|
|
4752
|
+
/**
|
|
4753
|
+
* This call's transcript so far, in order — every entry `onTranscript` has already fired
|
|
4754
|
+
* with. Read from `onEnd` or a tool `handler`; appended to by the relay, never by an author.
|
|
4755
|
+
*/
|
|
4756
|
+
readonly transcript: readonly TranscriptEntry[];
|
|
4757
|
+
/**
|
|
4758
|
+
* End the call. Closes the vendor session and the STREAM leg; `endOnFailure` on the caller's
|
|
4759
|
+
* leg (set by `realtimeAgent`'s own call plan) ends the caller's leg in turn.
|
|
4760
|
+
*/
|
|
4761
|
+
hangup(): void;
|
|
4762
|
+
/**
|
|
4763
|
+
* Move the caller to a human number. Same move-the-live-leg mechanism as the voice builder's
|
|
4764
|
+
* `transferTo*`/`voiceRelay`'s `call.transferToPhone`: the caller's leg leaves this call's
|
|
4765
|
+
* bridge for a new one with `number`, and if that dial is busy, unanswered, or fails, the
|
|
4766
|
+
* caller's leg is dropped rather than returned here — this is a cold transfer, not a warm
|
|
4767
|
+
* one. This agent's own STREAM leg has nobody left to relay to once the caller moves, so it
|
|
4768
|
+
* ends right after the move, whether or not the destination ever answers.
|
|
4769
|
+
*/
|
|
4770
|
+
transfer(number: string): Promise<void>;
|
|
4771
|
+
}
|
|
4772
|
+
export interface RealtimeTool<Args = unknown> {
|
|
4773
|
+
name: string;
|
|
4774
|
+
description: string;
|
|
4775
|
+
/** JSON Schema, vendor-agnostic — the adapter translates it to that vendor's declaration format. */
|
|
4776
|
+
parameters: JsonSchema;
|
|
4777
|
+
/**
|
|
4778
|
+
* Method shorthand, not an arrow-typed property: under `--strict`, a property typed as a
|
|
4779
|
+
* function is checked contravariantly on its parameters, so `RealtimeTool<{ date: string }>`
|
|
4780
|
+
* would not be assignable to `RealtimeTool<unknown>` and `tools: [bookTable]` (a typed
|
|
4781
|
+
* `tool<Args>()` result) would fail to typecheck. A method signature is checked bivariantly
|
|
4782
|
+
* instead, which is what makes a heterogeneous `RealtimeTool[]` possible at all — every tool
|
|
4783
|
+
* here has a different `Args`.
|
|
4784
|
+
*/
|
|
4785
|
+
handler(args: Args, ctx: RealtimeSessionContext): Promise<unknown>;
|
|
4786
|
+
}
|
|
4787
|
+
/** Identity helper — checks a tool's shape against `RealtimeTool` at declaration, not just at `tools: [...]`. */
|
|
4788
|
+
export declare function tool<Args = unknown>(def: RealtimeTool<Args>): RealtimeTool<Args>;
|
|
4789
|
+
/** A vendor whose realtime audio session an adapter drives directly — the {@link getRealtimeAdapter} registry keys. */
|
|
4790
|
+
export type RealtimeAudioProvider = "openai" | "gemini" | "deepgram" | "grok";
|
|
4791
|
+
/**
|
|
4792
|
+
* `'voice-relay'` runs no adapter at all: Sinch does speech-to-text and text-to-speech over Voice
|
|
4793
|
+
* Relay, and `realtimeAgent` drives the LLM loop in text over that same connection — see
|
|
4794
|
+
* `adapters/relay.ts`. Every other value is a `RealtimeAudioProvider`.
|
|
4795
|
+
*/
|
|
4796
|
+
export type RealtimeAgentProvider = RealtimeAudioProvider | "voice-relay";
|
|
4797
|
+
export interface RealtimeAgentOptions {
|
|
4798
|
+
/** Which vendor drives the call. `'voice-relay'` runs the model in text over Voice Relay instead of a vendor's own realtime audio session. */
|
|
4799
|
+
provider: RealtimeAgentProvider;
|
|
4800
|
+
/** System prompt / instructions. A value, or `(call, context) => value`, resolved once per call. */
|
|
4801
|
+
prompt: PerCallValue<string>;
|
|
4802
|
+
/**
|
|
4803
|
+
* Spoken first, before the caller says anything. Adapter sends it as the vendor's greeting
|
|
4804
|
+
* field. A value, or `(call, context) => value`, resolved once per call.
|
|
4805
|
+
*/
|
|
4806
|
+
greeting?: PerCallValue<string>;
|
|
4807
|
+
/**
|
|
4808
|
+
* Portable voice id. Adapter-specific beyond the small portable set — falls through unchanged.
|
|
4809
|
+
* Unset means no voice is sent to the vendor at all, not a runtime-chosen default — each
|
|
4810
|
+
* adapter omits the field and lets the vendor apply its own. A value, or `(call, context) =>
|
|
4811
|
+
* value`, resolved once per call.
|
|
4812
|
+
*/
|
|
4813
|
+
voice?: PerCallValue<string>;
|
|
4814
|
+
/**
|
|
4815
|
+
* The model id, sent straight through. Only `provider: 'voice-relay'` reads this — it names any
|
|
4816
|
+
* model served by an OpenAI Responses-compatible endpoint (e.g. `'gpt-4o-mini'`); see
|
|
4817
|
+
* `adapters/relay.ts`. The other providers pick their model via `providerOptions`.
|
|
4818
|
+
*/
|
|
4819
|
+
model?: string;
|
|
4820
|
+
/**
|
|
4821
|
+
* `provider: 'voice-relay'` only. The Responses-compatible server to call. Defaults to
|
|
4822
|
+
* `https://api.openai.com/v1`, or the `OPENAI_BASE_URL` function variable when set — this
|
|
4823
|
+
* option wins over that variable. Points a customer's own key at Azure OpenAI or a gateway
|
|
4824
|
+
* such as OpenRouter or LiteLLM instead of OpenAI directly.
|
|
4825
|
+
*/
|
|
4826
|
+
baseUrl?: string;
|
|
4827
|
+
/**
|
|
4828
|
+
* `provider: 'voice-relay'` only. OpenAI's Responses API `service_tier` — `'fast'` is the low-latency
|
|
4829
|
+
* default (see `DEFAULT_SERVICE_TIER` in `adapters/relay-llm.ts`): it must be sent on every
|
|
4830
|
+
* request, since a project's own Service Tier setting is not applied to these calls. Overrides
|
|
4831
|
+
* the `LLM_SERVICE_TIER` function variable, which overrides the default.
|
|
4832
|
+
*/
|
|
4833
|
+
serviceTier?: "auto" | "default" | "flex" | "priority" | "fast";
|
|
4834
|
+
/**
|
|
4835
|
+
* `provider: 'voice-relay'` only. OpenAI's Responses API `reasoning.effort` — omitted from the
|
|
4836
|
+
* request only when resolved to `undefined`, which does not happen by default (`'low'`, see
|
|
4837
|
+
* `DEFAULT_REASONING_EFFORT`). Overrides `LLM_REASONING_EFFORT`, which overrides the default.
|
|
4838
|
+
* Sending `reasoning` at all disables `temperature` on the request — see `temperatureParam`.
|
|
4839
|
+
*/
|
|
4840
|
+
reasoningEffort?: "none" | "minimal" | "low" | "medium" | "high";
|
|
4841
|
+
/**
|
|
4842
|
+
* `provider: 'voice-relay'` only. OpenAI's Responses API `text.verbosity`. Overrides
|
|
4843
|
+
* `LLM_VERBOSITY`, which overrides the default (`'low'`).
|
|
4844
|
+
*/
|
|
4845
|
+
verbosity?: "low" | "medium" | "high";
|
|
4846
|
+
/**
|
|
4847
|
+
* The only audio-format choice an author makes. `'telephony'` (default) is 8kHz — what the
|
|
4848
|
+
* Voice v2 platform documents as standard for PSTN calls. `'wideband'` is 16kHz, for a media
|
|
4849
|
+
* path that never touches the PSTN. No raw sample rate, no codec: everything else about wire
|
|
4850
|
+
* audio format is adapter-internal — see the design spec's "Audio format" section.
|
|
4851
|
+
*/
|
|
4852
|
+
audio?: "telephony" | "wideband";
|
|
4853
|
+
/** Tools the model may call. Dispatched in-process by the adapter — see the spec's "Tool calling". */
|
|
4854
|
+
tools?: RealtimeTool[];
|
|
4855
|
+
/**
|
|
4856
|
+
* Inject a standard `hangup_call` tool ("End the call after saying goodbye") so a template
|
|
4857
|
+
* does not have to declare its own. Defaults to `true`. An author tool named `hangup_call`
|
|
4858
|
+
* wins over this one.
|
|
4859
|
+
*/
|
|
4860
|
+
hangup?: boolean;
|
|
4861
|
+
/**
|
|
4862
|
+
* Inject a standard `transfer_to_human` tool (args: `reason`, `summary`) that moves the
|
|
4863
|
+
* caller to this number — see `RealtimeSessionContext.transfer` for the transfer semantics.
|
|
4864
|
+
* A value, or `(call, context) => value`, resolved once per call, same as `prompt`/
|
|
4865
|
+
* `greeting`/`voice`. Absent, or a per-call resolver that itself resolves to `undefined`,
|
|
4866
|
+
* means no transfer tool is injected for that call — `builtInTools` treats both the same. An
|
|
4867
|
+
* author tool named `transfer_to_human` wins over this one.
|
|
4868
|
+
*/
|
|
4869
|
+
transferTo?: PerCallValue<string | undefined>;
|
|
4870
|
+
/**
|
|
4871
|
+
* Fires as each `ctx.transcript` entry is appended — a turn from either party, or a
|
|
4872
|
+
* completed tool call — so an author can stream the transcript live (a websocket, storage)
|
|
4873
|
+
* instead of only reading it back at `onEnd`.
|
|
4874
|
+
*/
|
|
4875
|
+
onTranscript?: (entry: TranscriptEntry, ctx: RealtimeSessionContext) => void | Promise<void>;
|
|
4876
|
+
/** Fires when the caller starts talking over the agent, after the adapter has cleared buffered audio. */
|
|
4877
|
+
onBargeIn?: (ctx: RealtimeSessionContext) => void | Promise<void>;
|
|
4878
|
+
/** Fires on a vendor-side error. Non-fatal unless the adapter also closes the session. */
|
|
4879
|
+
onError?: (err: RealtimeError, ctx: RealtimeSessionContext) => void | Promise<void>;
|
|
4880
|
+
/** Fires once when the session ends. */
|
|
4881
|
+
onEnd?: (ctx: RealtimeSessionContext) => void | Promise<void>;
|
|
4882
|
+
/**
|
|
4883
|
+
* Raw passthrough for what does not normalise, keyed by provider so one options object can
|
|
4884
|
+
* carry config for a provider not currently selected. `providerOptions.deepgram` reaches only
|
|
4885
|
+
* the Deepgram adapter.
|
|
4886
|
+
*/
|
|
4887
|
+
providerOptions?: Record<string, unknown>;
|
|
4888
|
+
/** Override the derived stream URL — same escape hatch `resolveAgentStreamUrl` gives. */
|
|
4889
|
+
streamUrl?: string;
|
|
4890
|
+
}
|
|
4891
|
+
/**
|
|
4892
|
+
* What an adapter actually receives: `prompt`/`greeting`/`voice` already resolved to plain values
|
|
4893
|
+
* by the relay (`agent.ts`), once per call, before `RealtimeAdapter.connect` is called — an
|
|
4894
|
+
* adapter never sees a `PerCallValue` function. `tools` already includes the injected
|
|
4895
|
+
* `hangup_call`/`transfer_to_human` tools, merged with author tools (author wins on a name
|
|
4896
|
+
* collision) — an adapter does not know which tools are built in. `transferTo` itself is
|
|
4897
|
+
* dropped: an adapter dispatches tools, not transfers, and the resolved phone number is already
|
|
4898
|
+
* closed over by the injected tool's handler. Everything else is unchanged from
|
|
4899
|
+
* `RealtimeAgentOptions`.
|
|
4900
|
+
*/
|
|
4901
|
+
export type ResolvedRealtimeAgentOptions = Omit<RealtimeAgentOptions, "prompt" | "greeting" | "voice" | "transferTo"> & {
|
|
4902
|
+
prompt: string;
|
|
4903
|
+
greeting?: string;
|
|
4904
|
+
voice?: string;
|
|
4905
|
+
};
|
|
4906
|
+
/**
|
|
4907
|
+
* Normalised events an adapter reports back to the relay loop as they happen. An adapter never
|
|
4908
|
+
* calls the author's `RealtimeAgentOptions` hooks directly — the relay owns turning these into
|
|
4909
|
+
* `onTurn`/`onToolCall`/`onBargeIn`/`onError` and applying `ctx.hangup()`/`ctx.transfer()`
|
|
4910
|
+
* side effects.
|
|
4911
|
+
*
|
|
4912
|
+
* This callback shape is a deliberate refinement of the design spec's original per-frame-method
|
|
4913
|
+
* sketch (`decodeAudioOut(frame)`, `handleToolCall(event, tools)`, `decodeTurn(event)`): that
|
|
4914
|
+
* sketch assumes the relay owns the vendor socket and pulls frames off it one at a time, which
|
|
4915
|
+
* fits Deepgram's raw `ws` but not an SDK-mediated vendor where the SDK owns the socket and only
|
|
4916
|
+
* exposes callbacks (OpenAI's `@openai/agents`, Google's `ai.live.connect()`). Handing the
|
|
4917
|
+
* adapter a callback bag and letting it drive its own event loop — vendor SDK or raw socket —
|
|
4918
|
+
* fits both; Deepgram is the only adapter built so far, but the shape carries over cleanly.
|
|
4919
|
+
*/
|
|
4920
|
+
export interface RealtimeAdapterCallbacks {
|
|
4921
|
+
/**
|
|
4922
|
+
* PCM16 at the negotiated `RealtimeAgentOptions.audio` rate (8kHz telephony by default, 16kHz
|
|
4923
|
+
* for `'wideband'`), ready to forward to the Sinch STREAM leg unchanged.
|
|
4924
|
+
*/
|
|
4925
|
+
onAudioOut(pcm: Buffer): void;
|
|
4926
|
+
onToolCall(event: RealtimeToolCallEvent): void;
|
|
4927
|
+
onTurn(turn: RealtimeTurn): void;
|
|
4928
|
+
/** Caller barge-in. The adapter has already stopped vendor generation and cleared its own buffers. */
|
|
4929
|
+
onBargeIn(): void;
|
|
4930
|
+
onError(err: RealtimeError): void;
|
|
4931
|
+
/** The vendor session closed, on either side. */
|
|
4932
|
+
onClose(): void;
|
|
4933
|
+
}
|
|
4934
|
+
/** Opaque per-call handle an adapter defines for itself and hands back to `sendAudio`/`clear`/`close`. */
|
|
4935
|
+
export type VendorSession = unknown;
|
|
4936
|
+
export interface RealtimeAdapter {
|
|
4937
|
+
/**
|
|
4938
|
+
* Open the vendor session and start relaying; call `callbacks` as vendor events arrive.
|
|
4939
|
+
* `options.prompt`/`greeting`/`voice` are already resolved plain values — see
|
|
4940
|
+
* `ResolvedRealtimeAgentOptions`.
|
|
4941
|
+
*/
|
|
4942
|
+
/**
|
|
4943
|
+
* @param signal - Aborted if the Sinch STREAM leg ends before this resolves (finding #4) — an
|
|
4944
|
+
* adapter should abort/terminate its own in-flight socket rather than let it connect into a
|
|
4945
|
+
* session nothing will ever use.
|
|
4946
|
+
*/
|
|
4947
|
+
connect(options: ResolvedRealtimeAgentOptions, ctx: RealtimeSessionContext, callbacks: RealtimeAdapterCallbacks, signal: AbortSignal): Promise<VendorSession>;
|
|
4948
|
+
/**
|
|
4949
|
+
* Caller audio (PCM16 at the negotiated `RealtimeAgentOptions.audio` rate — see
|
|
4950
|
+
* `RealtimeAdapterCallbacks.onAudioOut`) -> forward to the vendor in its own wire format.
|
|
4951
|
+
*/
|
|
4952
|
+
sendAudio(session: VendorSession, pcm: Buffer): void;
|
|
4953
|
+
/** Caller barge-in: stop vendor generation and clear anything already buffered for the STREAM leg. */
|
|
4954
|
+
clear(session: VendorSession): void;
|
|
4955
|
+
/** Tear down the vendor session. */
|
|
4956
|
+
close(session: VendorSession): void;
|
|
4957
|
+
}
|
|
4958
|
+
/**
|
|
4959
|
+
* A `realtimeAgent()` result, widened with `connect` — the plan-building half of the default
|
|
4960
|
+
* `voiceWebhook.incoming` handler, exposed so an author can wrap it instead of only using it
|
|
4961
|
+
* as-is. `voiceWebhook` still works standalone (the one-liner path in the design spec's
|
|
4962
|
+
* example); `connect` exists for an author who needs their own `incoming` logic (business
|
|
4963
|
+
* hours, a pre-call lookup, routing to a different plan) and wants to fall through to this
|
|
4964
|
+
* agent's dial-the-STREAM-leg plan rather than reimplementing it:
|
|
4965
|
+
*
|
|
4966
|
+
* ```typescript
|
|
4967
|
+
* const agent = realtimeAgent({ provider: 'deepgram', prompt: '...' });
|
|
4968
|
+
* export const voiceWebhook = onCall({
|
|
4969
|
+
* incoming: async (call, builder, context) => {
|
|
4970
|
+
* if (isAfterHours()) return builder.say('Sorry, we are closed.').hangup();
|
|
4971
|
+
* return agent.connect(call, builder, context);
|
|
4972
|
+
* },
|
|
4973
|
+
* });
|
|
4974
|
+
* ```
|
|
4975
|
+
*
|
|
4976
|
+
* It is also something `dialAgent` can dial, which is the form that works anywhere a flow does —
|
|
4977
|
+
* one option of a menu, a `call.menu` response — not only as the whole `call.incoming` answer:
|
|
4978
|
+
*
|
|
4979
|
+
* ```typescript
|
|
4980
|
+
* incoming: (call, builder) => builder.answer().menu('main', (m) =>
|
|
4981
|
+
* m.prompt('Press 1 for sales, 2 for our assistant.')
|
|
4982
|
+
* .option('1', dialPhone(sales))
|
|
4983
|
+
* .option('2', dialAgent(agent))),
|
|
4984
|
+
* ```
|
|
4985
|
+
*/
|
|
4986
|
+
export type RealtimeAgentHandle = VoiceFunction & {
|
|
4987
|
+
connect: VoiceCallHandler;
|
|
4988
|
+
} & v2.DialableAgent;
|
|
4989
|
+
/**
|
|
4990
|
+
* Build a `RealtimeAgentOptions` into a `RealtimeAgentHandle` (a `VoiceFunction` plus `connect`).
|
|
4991
|
+
*
|
|
4992
|
+
* @param options - Provider, prompt, tools and lifecycle hooks — see the design spec's
|
|
4993
|
+
* "Author-facing API".
|
|
4994
|
+
*/
|
|
4995
|
+
export declare function realtimeAgent(options: RealtimeAgentOptions): RealtimeAgentHandle;
|
|
4996
|
+
/**
|
|
4997
|
+
* A value, or `(call, context) => value` resolved once per call — realtimeAgent's
|
|
4998
|
+
* {@link PerCallValue} without the promise. The voice and language go into the dial command,
|
|
4999
|
+
* which the webhook response carries, so they are settled while the response is built and
|
|
5000
|
+
* cannot wait on a lookup; do that lookup in the handler and pass the result.
|
|
5001
|
+
*/
|
|
5002
|
+
export type PerCallSetting = string | ((call: v2.Call, context: FunctionContext) => string);
|
|
5003
|
+
/** Options for {@link voiceRelay}. */
|
|
5004
|
+
export interface VoiceRelayOptions {
|
|
5005
|
+
/** Platform TTS voice. Defaults to `Emma`. A value, or `(call, context) => value`. */
|
|
5006
|
+
voice?: PerCallSetting;
|
|
5007
|
+
/** BCP-47 speech-to-text language. Defaults to `en-US`. A value, or `(call, context) => value`. */
|
|
5008
|
+
language?: PerCallSetting;
|
|
5009
|
+
/** Let the caller talk over replies. The platform defaults this to `true`. */
|
|
5010
|
+
interruptions?: boolean;
|
|
5011
|
+
/**
|
|
5012
|
+
* Said as soon as the relay connects. A value, or `(call, context) => value` — which may be
|
|
5013
|
+
* async, since it runs once the relay is up — resolved once per call, as realtimeAgent does.
|
|
5014
|
+
*/
|
|
5015
|
+
greeting?: PerCallValue<string>;
|
|
5016
|
+
/** Path the relay socket is registered on. Defaults to `/relay`. */
|
|
5017
|
+
path?: string;
|
|
5018
|
+
/** Called once per connected call — register the call's handlers here. */
|
|
5019
|
+
onConnected(call: RelayCall): void | Promise<void>;
|
|
5020
|
+
}
|
|
5021
|
+
/** Options for {@link RelayCall.send}. */
|
|
5022
|
+
export interface RelaySendOptions {
|
|
5023
|
+
/** Whether the caller may talk over this reply. Defaults to `true`. */
|
|
5024
|
+
interruptible?: boolean;
|
|
5025
|
+
/** Whether this is the last chunk of the reply. Defaults to `true`. */
|
|
5026
|
+
last?: boolean;
|
|
5027
|
+
}
|
|
5028
|
+
/** Transfer options a {@link RelayCall} fills in the call for. */
|
|
5029
|
+
export type RelayTransferOptions = Omit<v2.TransferToOptions, "call">;
|
|
5030
|
+
/** One connected relay call. */
|
|
5031
|
+
export interface RelayCall {
|
|
5032
|
+
/** The caller's call id */
|
|
5033
|
+
readonly id: string;
|
|
5034
|
+
/** Headers the relay leg was dialled with, as the `connect` message reported them */
|
|
5035
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
5036
|
+
/** The function context of the webhook that dialled this relay */
|
|
5037
|
+
readonly context: FunctionContext;
|
|
5038
|
+
/** Speak a reply */
|
|
5039
|
+
send(text: string, options?: RelaySendOptions): void;
|
|
5040
|
+
/** End the call after a short grace for the last reply, then close the relay. */
|
|
5041
|
+
hangup(): void;
|
|
5042
|
+
/** What the caller said — a full utterance, or a prompt the platform assembled */
|
|
5043
|
+
onSpeech(handler: (text: string) => void | Promise<void>): void;
|
|
5044
|
+
/** Keypresses */
|
|
5045
|
+
onDigits(handler: (digits: string) => void | Promise<void>): void;
|
|
5046
|
+
/** The caller talked over a reply */
|
|
5047
|
+
onInterrupted(handler: () => void): void;
|
|
5048
|
+
/** The relay socket closed */
|
|
5049
|
+
onEnded(handler: () => void): void;
|
|
5050
|
+
/** Move the caller to a phone number. See the voice client's `transferToPhone`. */
|
|
5051
|
+
transferToPhone(number: string, options?: RelayTransferOptions): Promise<void>;
|
|
5052
|
+
/** Move the caller to a SIP endpoint */
|
|
5053
|
+
transferToSip(address: string, options?: RelayTransferOptions & {
|
|
5054
|
+
transport?: "UDP" | "TCP" | "TLS";
|
|
5055
|
+
headers?: v2.Headers;
|
|
5056
|
+
}): Promise<void>;
|
|
5057
|
+
/** Move the caller to a media stream */
|
|
5058
|
+
transferToStream(endpoint: string, options?: RelayTransferOptions & {
|
|
5059
|
+
sampleRate?: v2.SampleRate;
|
|
5060
|
+
headers?: v2.Headers;
|
|
5061
|
+
}): Promise<void>;
|
|
5062
|
+
/** Move the caller to another relay socket */
|
|
5063
|
+
transferToRelay(endpoint: string, options?: RelayTransferOptions & {
|
|
5064
|
+
ttsVoice?: string;
|
|
5065
|
+
sttLanguage?: string;
|
|
5066
|
+
}): Promise<void>;
|
|
5067
|
+
/** Move the caller to an AI voice agent: a SIP provider by number, or a realtime agent */
|
|
5068
|
+
transferToAgent(agent: string | v2.DialableAgent, numberOrOptions?: string | RelayTransferOptions, options?: RelayTransferOptions & v2.SipAgentOptions): Promise<void>;
|
|
5069
|
+
}
|
|
5070
|
+
/** What {@link voiceRelay} returns: the socket's `setup`, and something `dialRelay` can dial. */
|
|
5071
|
+
export interface VoiceRelayHandle extends v2.DialableAgent {
|
|
5072
|
+
/** Register the relay socket. Export it as the function's `setup`. */
|
|
5073
|
+
setup(runtime: SinchRuntime): void;
|
|
5074
|
+
}
|
|
5075
|
+
/**
|
|
5076
|
+
* Build a Voice Relay conversation: register its socket with `setup`, dial it with
|
|
5077
|
+
* `builder.dialRelay(relay)`, and handle each call in `onConnected`.
|
|
5078
|
+
*
|
|
5079
|
+
* @param options - Voice, language, greeting, path, and the per-call handler
|
|
5080
|
+
*/
|
|
5081
|
+
export declare function voiceRelay(options: VoiceRelayOptions): VoiceRelayHandle;
|
|
4004
5082
|
/**
|
|
4005
5083
|
* Message inbound event from Conversation API
|
|
4006
5084
|
*/
|
|
@@ -4086,29 +5164,12 @@ export declare function createMessageHelper(event: MessageInboundEvent): {
|
|
|
4086
5164
|
isPostback: () => boolean;
|
|
4087
5165
|
};
|
|
4088
5166
|
/**
|
|
4089
|
-
*
|
|
4090
|
-
|
|
4091
|
-
|
|
4092
|
-
|
|
4093
|
-
* Simplified send message request type that works with SDK
|
|
5167
|
+
* Text-message send request, typed directly against the `@sinch/conversation` SDK so it's
|
|
5168
|
+
* assignable straight into `context.conversation.messages.send({ sendMessageRequestBody })`
|
|
5169
|
+
* without a cast. `IdentifiedBy` (not the broader `Recipient` union) because every helper here
|
|
5170
|
+
* addresses a channel identity, never a `contact_id`.
|
|
4094
5171
|
*/
|
|
4095
|
-
export
|
|
4096
|
-
app_id: string;
|
|
4097
|
-
message: {
|
|
4098
|
-
text_message?: {
|
|
4099
|
-
text: string;
|
|
4100
|
-
};
|
|
4101
|
-
};
|
|
4102
|
-
recipient: {
|
|
4103
|
-
identified_by: {
|
|
4104
|
-
channel_identities: Array<{
|
|
4105
|
-
channel: ConversationChannel;
|
|
4106
|
-
identity: string;
|
|
4107
|
-
}>;
|
|
4108
|
-
};
|
|
4109
|
-
};
|
|
4110
|
-
channel_properties?: Record<string, string>;
|
|
4111
|
-
}
|
|
5172
|
+
export type SendMessageRequest = Conversation.SendMessageRequest<Conversation.IdentifiedBy>;
|
|
4112
5173
|
/**
|
|
4113
5174
|
* Create a text reply to an inbound message (replies on same channel).
|
|
4114
5175
|
* Automatically sets SMS_SENDER channel property if sending to SMS.
|
|
@@ -4337,6 +5398,40 @@ export declare abstract class ConversationController {
|
|
|
4337
5398
|
*/
|
|
4338
5399
|
getWebhookHandler(): (req: Request, res: Response) => Promise<void>;
|
|
4339
5400
|
}
|
|
5401
|
+
export interface LoginRouteOptions {
|
|
5402
|
+
credentials: AuthCredentialPair[];
|
|
5403
|
+
functionName: string;
|
|
5404
|
+
}
|
|
5405
|
+
export declare function handleLoginPageRequest(req: Request, res: Response, opts: LoginRouteOptions): void;
|
|
5406
|
+
export declare function handleLoginPostRequest(req: Request, res: Response, opts: LoginRouteOptions): void;
|
|
5407
|
+
export declare function handleLogoutPostRequest(_req: Request, res: Response): void;
|
|
5408
|
+
/**
|
|
5409
|
+
* Login page for the `auth` gate.
|
|
5410
|
+
*
|
|
5411
|
+
* Separate page rather than the browser's Basic Auth dialog: that dialog cannot be branded, and
|
|
5412
|
+
* to a customer looks indistinguishable from a fault. Credentials still work over
|
|
5413
|
+
* `Authorization: Basic` for scripts — this is only the human path. No function-specific content
|
|
5414
|
+
* lives here; the only thing named is the function itself.
|
|
5415
|
+
*/
|
|
5416
|
+
export declare function renderLoginPage(functionName: string, next: string, error?: string): string;
|
|
5417
|
+
/**
|
|
5418
|
+
* Browser session for the `auth` gate.
|
|
5419
|
+
*
|
|
5420
|
+
* The cookie is an HMAC of a fixed message, keyed by the password. That makes it a stable,
|
|
5421
|
+
* verifiable token with no session store to keep — the pod hosting a function can be replaced at
|
|
5422
|
+
* any moment, so there is nowhere durable to keep one anyway — and it means changing the password
|
|
5423
|
+
* invalidates every session already handed out, without a revocation list.
|
|
5424
|
+
*/
|
|
5425
|
+
/** Neutral name: this cookie is not tied to any one function's identity. */
|
|
5426
|
+
export declare const SESSION_COOKIE_NAME = "sinch_session";
|
|
5427
|
+
/** Session value for a credential pair. Stable, and reveals nothing about the password. */
|
|
5428
|
+
export declare function sessionToken(user: string, password: string): string;
|
|
5429
|
+
/** `Set-Cookie` value for a successful login. Session-scoped — closing the browser signs you out. */
|
|
5430
|
+
export declare function sessionCookieHeader(user: string, password: string): string;
|
|
5431
|
+
/** `Set-Cookie` value that clears the session. */
|
|
5432
|
+
export declare function clearedSessionCookieHeader(): string;
|
|
5433
|
+
/** Whether the `Cookie` header carries a valid session for this credential pair. */
|
|
5434
|
+
export declare function hasValidSessionCookie(cookieHeader: string | undefined, user: string, password: string): boolean;
|
|
4340
5435
|
/**
|
|
4341
5436
|
* Converts a phone number to local/national format.
|
|
4342
5437
|
*
|
|
@@ -4417,74 +5512,6 @@ export declare function formatDuration(seconds: number): string;
|
|
|
4417
5512
|
* @returns Normalized phone number
|
|
4418
5513
|
*/
|
|
4419
5514
|
export declare function extractCallerNumber(cli: string | undefined): string | undefined;
|
|
4420
|
-
/**
|
|
4421
|
-
* Install `context.voice` on a context object, in place.
|
|
4422
|
-
*
|
|
4423
|
-
* @param context - Context under construction, without its `voice` member
|
|
4424
|
-
* @param v1 - The v1 SDK client to expose as `context.voice.v1`, if credentials produced one
|
|
4425
|
-
* @returns The same object, now carrying `voice`
|
|
4426
|
-
* @internal
|
|
4427
|
-
*/
|
|
4428
|
-
export declare function attachVoiceClient<T extends object>(context: T, v1?: VoiceService): T & {
|
|
4429
|
-
voice: VoiceClient;
|
|
4430
|
-
};
|
|
4431
|
-
/**
|
|
4432
|
-
* A single `onCall` handler slot.
|
|
4433
|
-
*
|
|
4434
|
-
* Same as `@sinch/voice-v2-preview`'s `WebhookHandler`, but the event is followed by the
|
|
4435
|
-
* function context and the raw `FunctionRequest` — every other runtime handler gets both, and
|
|
4436
|
-
* a v2 handler that wants `context.cache`, `context.messaging`, `context.storage`, etc. needs
|
|
4437
|
-
* them too. Event stays first so a handler written as `(event) => ...` before this widening
|
|
4438
|
-
* still compiles.
|
|
4439
|
-
*/
|
|
4440
|
-
export type VoiceCallHandler = (event: WebhookRequest, context: FunctionContext, request?: FunctionRequest) => ReturnType<WebhookHandler>;
|
|
4441
|
-
/**
|
|
4442
|
-
* Handlers keyed by call lifecycle stage — the shape `onCall()` takes.
|
|
4443
|
-
*
|
|
4444
|
-
* Same slots as `@sinch/voice-v2-preview`'s `CallHandlers`, widened so each handler also
|
|
4445
|
-
* receives the function context (and the raw request) the way every other runtime handler
|
|
4446
|
-
* does. Named separately from `CallHandlers` — re-exported from this package as-is for anyone
|
|
4447
|
-
* calling `context.voice.onCall` directly — so the two shapes don't collide.
|
|
4448
|
-
*/
|
|
4449
|
-
export interface VoiceCallHandlers {
|
|
4450
|
-
/** `call.incoming` — an inbound call arrived (the v1 ICE callback) */
|
|
4451
|
-
incoming?: VoiceCallHandler;
|
|
4452
|
-
/** `call.answered` — an outbound call was answered (the v1 ACE callback) */
|
|
4453
|
-
answered?: VoiceCallHandler;
|
|
4454
|
-
/** `call.menu` and `call.webhook.*` — a mid-call decision point (the v1 PIE callback) */
|
|
4455
|
-
manage?: VoiceCallHandler;
|
|
4456
|
-
/** `call.hangup` and `call.failed` — the call ended (the v1 DICE callback) */
|
|
4457
|
-
completed?: VoiceCallHandler;
|
|
4458
|
-
/** Handlers for `webhook` commands, keyed by the `webhookName` they were raised under. */
|
|
4459
|
-
webhooks?: Record<string, VoiceCallHandler>;
|
|
4460
|
-
/** Any event none of the above claims */
|
|
4461
|
-
fallback?: VoiceCallHandler;
|
|
4462
|
-
}
|
|
4463
|
-
/**
|
|
4464
|
-
* Build a `voiceWebhook` export from handlers keyed by call lifecycle stage.
|
|
4465
|
-
*
|
|
4466
|
-
* ```typescript
|
|
4467
|
-
* export const voiceWebhook = onCall({
|
|
4468
|
-
* incoming: (event, context) => commands().answer().say('Thanks for calling').hangup(),
|
|
4469
|
-
* completed: (event, context) => console.log('call ended', event.call.callId),
|
|
4470
|
-
* });
|
|
4471
|
-
* ```
|
|
4472
|
-
*
|
|
4473
|
-
* The events reaching these handlers are signed by the Voice Platform, and the host verifies
|
|
4474
|
-
* that signature once `VOICE_SERVICE_SECRET` is set. While it is unset — Sinch does not expose
|
|
4475
|
-
* a service's secret yet — the host logs one warning and delivers the event anyway.
|
|
4476
|
-
*
|
|
4477
|
-
* Each handler is bound to `context` (and the raw `request`, if the host passed one) before
|
|
4478
|
-
* being handed to `context.voice.onCall`, which only knows the narrower, context-free
|
|
4479
|
-
* `WebhookHandler` shape.
|
|
4480
|
-
*
|
|
4481
|
-
* The dispatch is `context.voice.onCall(handlers)`. That returns a wire `WebhookResponse`
|
|
4482
|
-
* and the host emits the wire body itself, so `events.onHangup` is unwrapped back onto the
|
|
4483
|
-
* plan here — left as-is the host's second mapping would drop it.
|
|
4484
|
-
*
|
|
4485
|
-
* @param handlers - Handlers keyed by lifecycle stage
|
|
4486
|
-
*/
|
|
4487
|
-
export declare function onCall(handlers: VoiceCallHandlers): VoiceWebhookHandler;
|
|
4488
5515
|
/**
|
|
4489
5516
|
* Simple template renderer for HTML files
|
|
4490
5517
|
* Replaces {{variableName}} placeholders with actual values
|
|
@@ -4725,6 +5752,10 @@ export declare class SecretsLoader {
|
|
|
4725
5752
|
}
|
|
4726
5753
|
export declare const secretsLoader: SecretsLoader;
|
|
4727
5754
|
|
|
5755
|
+
declare namespace v2 {
|
|
5756
|
+
export { AmdEventOptions, AnsweredCall, BridgeOptions, BridgeToOptions, Call, CallDirection, CallEvent, CallFlow, CallHandlers, CallOptions, CallReason, CallResponse, CallResult, CallType, Client, ClientFlows, Command, CommandBuilder, CompletedCall, ConnectAgentOptions$1 as ConnectAgentOptions, DEFAULT_BRIDGE_NAME, DEFAULT_HOST, DEFAULT_SAMPLE_RATE, DEFAULT_STT_LANGUAGE, DEFAULT_TRANSFER_LEG, DEFAULT_VOICE, Destination, DialAgentOptions, DialEvents, DialOptions, DialRelayOptions, DialSipOptions, DialStreamOptions, DialableAgent, EventType, Flow, HandlerKey, HandlerResult, Headers$1 as Headers, IncomingCall, MenuCall, MenuDefinition, MenuInput, MenuItemBuilder, Money, Options, Origin, OriginationType, PatchTarget, PlaceCallOptions, PromptBuilder, PromptFlow, REDACTED, RecordingCredentials, RecordingDestination, RecordingFormat, RecordingType, RelayCallOptions, SampleRate, SayOptions, SipAgentOptions, SipAgentProvider, StartRecordingOptions, StopMessagesFlags, StreamCallOptions, TransferOptions, TransferToOptions, WebhookBody, WebhookCall, WebhookHandler, WebhookOptions, WebhookRequest, bridgeTo, buildTransferCommands, commands, connectAgent, createClient, dial, dialAgent, dialPhone, dialRelay, dialSip, dialStream, endpointNumber, menu, play, redactCredentials, resolveHandlerKey, resolveWebhookName, say, stringify as stringifyOrdered, toCallBody, toCallEvent, toWebhookBody, toWebhookRequest };
|
|
5757
|
+
}
|
|
5758
|
+
|
|
4728
5759
|
export {
|
|
4729
5760
|
CallResult$1 as CallResult,
|
|
4730
5761
|
CamelCaseOptions as ParserCamelCaseOptions,
|