@sinch/functions-runtime 0.7.0 → 0.7.2
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 +41 -22
- package/dist/bin/sinch-runtime.js +24 -1
- package/dist/bin/sinch-runtime.js.map +1 -1
- package/dist/{chunk-DLBCKZ6X.js → chunk-KGCIUPCT.js} +1247 -371
- package/dist/{chunk-DLBCKZ6X.js.map → chunk-KGCIUPCT.js.map} +1 -1
- package/dist/index.d.ts +188 -36
- package/dist/index.js +11 -1
- package/dist/voice/v2.d.ts +97 -14
- package/dist/voice/v2.js +5 -1
- package/package.json +1 -1
|
@@ -59781,6 +59781,12 @@ var MenuTemplates = {
|
|
|
59781
59781
|
}
|
|
59782
59782
|
};
|
|
59783
59783
|
|
|
59784
|
+
// ../runtime-shared/dist/storage/recording.js
|
|
59785
|
+
var RECORDING_RECEIVER_PATH = "/_sinch/recording/";
|
|
59786
|
+
function recordingKey(callId, format) {
|
|
59787
|
+
return `recordings/${callId.replace(/[^\w-]/g, "_")}.${format}`;
|
|
59788
|
+
}
|
|
59789
|
+
|
|
59784
59790
|
// ../runtime-shared/dist/config/universal.js
|
|
59785
59791
|
var UniversalConfig = class {
|
|
59786
59792
|
context;
|
|
@@ -60180,6 +60186,67 @@ function toCallHeaders(headers) {
|
|
|
60180
60186
|
return list.length > 0 ? list : void 0;
|
|
60181
60187
|
}
|
|
60182
60188
|
|
|
60189
|
+
// ../voice-v2-preview/dist/core/say-limit.js
|
|
60190
|
+
var MAX_SAY_CHARS = 600;
|
|
60191
|
+
var MAX_MESSAGES = 10;
|
|
60192
|
+
var EXCERPT_CHARS = 40;
|
|
60193
|
+
var WHITESPACE = "\\u0009-\\u000D\\u0020\\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000";
|
|
60194
|
+
var SENTENCE_BREAK = new RegExp(`(?<=[.!?]+["'\u201D\u2019)\\]]*)[${WHITESPACE}]+`, "g");
|
|
60195
|
+
var EDGE_WHITESPACE = new RegExp(`^[${WHITESPACE}]+|[${WHITESPACE}]+$`, "g");
|
|
60196
|
+
function sayParts(text, format) {
|
|
60197
|
+
if (text.length <= MAX_SAY_CHARS)
|
|
60198
|
+
return [text];
|
|
60199
|
+
if (format === "SSML") {
|
|
60200
|
+
throw new Error(`Voice v2 limits each SAY message to ${MAX_SAY_CHARS} characters, and SSML is never split. This SSML document is ${text.length} characters. Shorten it, or pass it as several say() calls.`);
|
|
60201
|
+
}
|
|
60202
|
+
return packSentences(text.replace(EDGE_WHITESPACE, ""));
|
|
60203
|
+
}
|
|
60204
|
+
function assertPromptFits(text) {
|
|
60205
|
+
if (text.length > MAX_SAY_CHARS) {
|
|
60206
|
+
throw new Error(`Voice v2 limits each SAY message to ${MAX_SAY_CHARS} characters, and menu prompts are never split. This prompt is ${text.length} characters. Shorten it.`);
|
|
60207
|
+
}
|
|
60208
|
+
}
|
|
60209
|
+
function assertMessageCount(count) {
|
|
60210
|
+
if (count > MAX_MESSAGES) {
|
|
60211
|
+
throw new Error(`Voice v2 limits a messages list to ${MAX_MESSAGES} items, and each SAY message to ${MAX_SAY_CHARS} characters. These say()/play() calls need ${count} items once long text is split. Shorten the text.`);
|
|
60212
|
+
}
|
|
60213
|
+
}
|
|
60214
|
+
function assertPromptMessageCount(count) {
|
|
60215
|
+
if (count > MAX_MESSAGES) {
|
|
60216
|
+
throw new Error(`Voice v2 limits a menu prompt to ${MAX_MESSAGES} messages. This prompt's say()/play() calls need ${count}. Remove some.`);
|
|
60217
|
+
}
|
|
60218
|
+
}
|
|
60219
|
+
function packSentences(text) {
|
|
60220
|
+
const sentences = sentenceSpans(text);
|
|
60221
|
+
for (const { start, end } of sentences) {
|
|
60222
|
+
if (end - start > MAX_SAY_CHARS) {
|
|
60223
|
+
throw new Error(`Voice v2 limits each SAY message to ${MAX_SAY_CHARS} characters. Longer text is split between sentences, but this sentence alone is ${end - start} characters: "${text.slice(start, start + EXCERPT_CHARS)}\u2026". Shorten it.`);
|
|
60224
|
+
}
|
|
60225
|
+
}
|
|
60226
|
+
const parts = [];
|
|
60227
|
+
let first = 0;
|
|
60228
|
+
while (first < sentences.length) {
|
|
60229
|
+
const start = sentences[first].start;
|
|
60230
|
+
let last = first;
|
|
60231
|
+
while (last + 1 < sentences.length && sentences[last + 1].end - start <= MAX_SAY_CHARS) {
|
|
60232
|
+
last++;
|
|
60233
|
+
}
|
|
60234
|
+
parts.push(text.slice(start, sentences[last].end));
|
|
60235
|
+
first = last + 1;
|
|
60236
|
+
}
|
|
60237
|
+
return parts;
|
|
60238
|
+
}
|
|
60239
|
+
function sentenceSpans(text) {
|
|
60240
|
+
const spans = [];
|
|
60241
|
+
let start = 0;
|
|
60242
|
+
for (const separator of text.matchAll(SENTENCE_BREAK)) {
|
|
60243
|
+
spans.push({ start, end: separator.index });
|
|
60244
|
+
start = separator.index + separator[0].length;
|
|
60245
|
+
}
|
|
60246
|
+
spans.push({ start, end: text.length });
|
|
60247
|
+
return spans;
|
|
60248
|
+
}
|
|
60249
|
+
|
|
60183
60250
|
// ../voice-v2-preview/dist/core/agent-endpoint.js
|
|
60184
60251
|
var DEFAULT_AGENT_MAX_DURATION = 1800;
|
|
60185
60252
|
function agentMaxDuration(context) {
|
|
@@ -60404,6 +60471,10 @@ function bridgeStep(to, options, leg) {
|
|
|
60404
60471
|
];
|
|
60405
60472
|
};
|
|
60406
60473
|
}
|
|
60474
|
+
var RECORD_TO_FUNCTIONS_SENTINEL = "@functions";
|
|
60475
|
+
function isPresignedDestination(url2) {
|
|
60476
|
+
return url2 === RECORD_TO_FUNCTIONS_SENTINEL || /^https:\/\//i.test(url2);
|
|
60477
|
+
}
|
|
60407
60478
|
function toCredentials(credentials) {
|
|
60408
60479
|
if (typeof credentials === "string") {
|
|
60409
60480
|
return credentials;
|
|
@@ -60415,13 +60486,16 @@ function toCredentials(credentials) {
|
|
|
60415
60486
|
return parts.join(":");
|
|
60416
60487
|
}
|
|
60417
60488
|
function toRecordingOptions(options) {
|
|
60489
|
+
if (options.credentials === void 0 && !isPresignedDestination(options.destinationUrl)) {
|
|
60490
|
+
throw new Error("Voice v2 startRecording needs credentials unless destinationUrl is an https:// presigned URL.");
|
|
60491
|
+
}
|
|
60418
60492
|
const transcribing = options.transcribe !== void 0 || options.transcriptionLocale !== void 0;
|
|
60419
60493
|
return {
|
|
60420
60494
|
...options.format && { format: options.format },
|
|
60421
60495
|
...options.recordingType && { recordingType: options.recordingType },
|
|
60422
60496
|
destination: options.destination ?? "AWS",
|
|
60423
60497
|
destinationUrl: options.destinationUrl,
|
|
60424
|
-
credentials: toCredentials(options.credentials),
|
|
60498
|
+
...options.credentials !== void 0 && { credentials: toCredentials(options.credentials) },
|
|
60425
60499
|
...transcribing && {
|
|
60426
60500
|
transcriptionOptions: {
|
|
60427
60501
|
isEnabled: options.transcribe ?? true,
|
|
@@ -60438,8 +60512,12 @@ var PromptBuilder = class {
|
|
|
60438
60512
|
*
|
|
60439
60513
|
* @param text - Text to synthesise, or an SSML document when `format` is `SSML`
|
|
60440
60514
|
* @param options - Voice and format overrides
|
|
60515
|
+
* @throws If `text` is over 600 characters (prompts are never split), or the prompt would hold
|
|
60516
|
+
* more than 10 messages
|
|
60441
60517
|
*/
|
|
60442
60518
|
say(text, options = {}) {
|
|
60519
|
+
assertPromptFits(text);
|
|
60520
|
+
assertPromptMessageCount(this.messages.length + 1);
|
|
60443
60521
|
this.messages.push(sayMessage(text, options));
|
|
60444
60522
|
return this;
|
|
60445
60523
|
}
|
|
@@ -60447,8 +60525,10 @@ var PromptBuilder = class {
|
|
|
60447
60525
|
* Play an audio file.
|
|
60448
60526
|
*
|
|
60449
60527
|
* @param url - Publicly reachable URL of the audio file
|
|
60528
|
+
* @throws If the prompt would hold more than 10 messages
|
|
60450
60529
|
*/
|
|
60451
60530
|
play(url2) {
|
|
60531
|
+
assertPromptMessageCount(this.messages.length + 1);
|
|
60452
60532
|
this.messages.push({ type: "PLAY", play: { url: url2 } });
|
|
60453
60533
|
return this;
|
|
60454
60534
|
}
|
|
@@ -60504,6 +60584,7 @@ var MenuItemBuilder = class {
|
|
|
60504
60584
|
* Prompt played when the menu is entered.
|
|
60505
60585
|
*
|
|
60506
60586
|
* @param prompt - Plain text, a {@link PromptBuilder}, or a callback receiving one
|
|
60587
|
+
* @throws If any prompt text is over 600 characters, or a callback queues more than 10 messages
|
|
60507
60588
|
*/
|
|
60508
60589
|
prompt(prompt) {
|
|
60509
60590
|
this.item.prompt = resolvePrompt(prompt);
|
|
@@ -60513,6 +60594,7 @@ var MenuItemBuilder = class {
|
|
|
60513
60594
|
* Prompt played on each retry. Falls back to `prompt` when unset.
|
|
60514
60595
|
*
|
|
60515
60596
|
* @param prompt - Plain text, a {@link PromptBuilder}, or a callback receiving one
|
|
60597
|
+
* @throws If any prompt text is over 600 characters, or a callback queues more than 10 messages
|
|
60516
60598
|
*/
|
|
60517
60599
|
repeatPrompt(prompt) {
|
|
60518
60600
|
this.item.repeatPrompt = resolvePrompt(prompt);
|
|
@@ -60660,21 +60742,28 @@ var CommandBuilder = class {
|
|
|
60660
60742
|
/** Set only on the builder `onCall` injects — see {@link FlowScope} */
|
|
60661
60743
|
scope;
|
|
60662
60744
|
/**
|
|
60663
|
-
* Speak text on the call.
|
|
60745
|
+
* Speak text on the call. `TEXT` over 600 characters is split between sentences into
|
|
60746
|
+
* consecutive messages.
|
|
60664
60747
|
*
|
|
60665
60748
|
* @param text - Text to synthesise, or an SSML document when `format` is `SSML`
|
|
60666
60749
|
* @param options - Voice and format overrides
|
|
60750
|
+
* @throws If a sentence, or any SSML document, is over 600 characters, or the pending
|
|
60751
|
+
* messages would pass 10 items
|
|
60667
60752
|
*/
|
|
60668
60753
|
say(text, options = {}) {
|
|
60669
|
-
|
|
60754
|
+
const messages = sayParts(text, options.format).map((part) => sayMessage(part, options));
|
|
60755
|
+
assertMessageCount(this.pending.length + messages.length);
|
|
60756
|
+
this.pending.push(...messages);
|
|
60670
60757
|
return this;
|
|
60671
60758
|
}
|
|
60672
60759
|
/**
|
|
60673
60760
|
* Play an audio file on the call.
|
|
60674
60761
|
*
|
|
60675
60762
|
* @param url - Publicly reachable URL of the audio file
|
|
60763
|
+
* @throws If the pending messages would pass 10 items
|
|
60676
60764
|
*/
|
|
60677
60765
|
play(url2) {
|
|
60766
|
+
assertMessageCount(this.pending.length + 1);
|
|
60678
60767
|
this.pending.push({ type: "PLAY", play: { url: url2 } });
|
|
60679
60768
|
return this;
|
|
60680
60769
|
}
|
|
@@ -60794,6 +60883,10 @@ var CommandBuilder = class {
|
|
|
60794
60883
|
dialAgent(target, numberOrOptions, sipOptions = {}) {
|
|
60795
60884
|
if (typeof target !== "string") {
|
|
60796
60885
|
const options2 = numberOrOptions ?? {};
|
|
60886
|
+
const before = target.commandsBefore;
|
|
60887
|
+
if (before) {
|
|
60888
|
+
this.push((scope) => scope?.event ? before.call(target, scope.event, scope.context) : []);
|
|
60889
|
+
}
|
|
60797
60890
|
return this.push(bridgeStep(agentEndpoint(target), options2, STREAM_AGENT_LEG));
|
|
60798
60891
|
}
|
|
60799
60892
|
const { headers, transport, host, port, ...options } = sipOptions;
|
|
@@ -60992,6 +61085,31 @@ var CommandBuilder = class {
|
|
|
60992
61085
|
...Object.keys(events).length > 0 && { events }
|
|
60993
61086
|
});
|
|
60994
61087
|
}
|
|
61088
|
+
/**
|
|
61089
|
+
* Record the call into this function's own storage (`recordings/<callId>.mp3`), with no
|
|
61090
|
+
* credentials. Emits a `startRecording` whose destination is a placeholder
|
|
61091
|
+
* ({@link RECORD_TO_FUNCTIONS_SENTINEL}); the runtime host replaces it with a presigned PUT
|
|
61092
|
+
* URL for the exact key just before the response is sent, and drops the command with a warning
|
|
61093
|
+
* when it cannot (no callId, or storage without a recording destination). Needs a runtime
|
|
61094
|
+
* that does the rewrite — sending this builder's output anywhere else delivers the placeholder.
|
|
61095
|
+
*
|
|
61096
|
+
* Transcription is not offered: the transcript URL is derived from the recording URL, which a
|
|
61097
|
+
* presigned URL cannot carry. The recording is named so {@link stopRecording} can end it;
|
|
61098
|
+
* `recordingName` defaults to `functions-recording`. Without an `onFailure` flow a failed
|
|
61099
|
+
* recording is silent — the platform sends no webhook for it.
|
|
61100
|
+
*
|
|
61101
|
+
* @param options - Format (default `MP3`), recording name, streams captured, outcome flows
|
|
61102
|
+
*/
|
|
61103
|
+
recordToFunctions(options = {}) {
|
|
61104
|
+
return this.startRecording({
|
|
61105
|
+
destinationUrl: RECORD_TO_FUNCTIONS_SENTINEL,
|
|
61106
|
+
recordingName: options.recordingName ?? "functions-recording",
|
|
61107
|
+
format: options.format ?? "MP3",
|
|
61108
|
+
...options.recordingType && { recordingType: options.recordingType },
|
|
61109
|
+
...options.onFinish !== void 0 && { onFinish: options.onFinish },
|
|
61110
|
+
...options.onFailure !== void 0 && { onFailure: options.onFailure }
|
|
61111
|
+
});
|
|
61112
|
+
}
|
|
60995
61113
|
/**
|
|
60996
61114
|
* Stop a named recording. Non-blocking.
|
|
60997
61115
|
*
|
|
@@ -61700,7 +61818,8 @@ var Client = class {
|
|
|
61700
61818
|
if (!this.publicUrl) {
|
|
61701
61819
|
throw new Error(`Cannot resolve stream path '${stream5}' \u2014 this function's public URL is unknown. Pass a full wss:// URL, or set the publicUrl option (context.host is only present in production).`);
|
|
61702
61820
|
}
|
|
61703
|
-
|
|
61821
|
+
const query = this.publicUrl.indexOf("?");
|
|
61822
|
+
return query < 0 ? `${this.publicUrl}${stream5}` : `${this.publicUrl.slice(0, query)}${stream5}${this.publicUrl.slice(query)}`;
|
|
61704
61823
|
}
|
|
61705
61824
|
};
|
|
61706
61825
|
function createClient(context, options) {
|
|
@@ -61768,6 +61887,141 @@ function connectAgent(provider, number, options = {}) {
|
|
|
61768
61887
|
};
|
|
61769
61888
|
}
|
|
61770
61889
|
|
|
61890
|
+
// ../runtime-shared/dist/ai/realtime/wire-safety.js
|
|
61891
|
+
var MAX_INBOUND_FRAME_BYTES = 1e6;
|
|
61892
|
+
function isOversizedFrame(raw) {
|
|
61893
|
+
return raw.length > MAX_INBOUND_FRAME_BYTES;
|
|
61894
|
+
}
|
|
61895
|
+
var BASE64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
61896
|
+
function safeBase64ToBuffer(value) {
|
|
61897
|
+
if (typeof value !== "string")
|
|
61898
|
+
return void 0;
|
|
61899
|
+
if (value.length > 0 && !BASE64_RE.test(value))
|
|
61900
|
+
return void 0;
|
|
61901
|
+
try {
|
|
61902
|
+
return Buffer.from(value, "base64");
|
|
61903
|
+
} catch {
|
|
61904
|
+
return void 0;
|
|
61905
|
+
}
|
|
61906
|
+
}
|
|
61907
|
+
function isPlainObject(value) {
|
|
61908
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
61909
|
+
}
|
|
61910
|
+
function parseVendorFrame(raw) {
|
|
61911
|
+
let parsed;
|
|
61912
|
+
try {
|
|
61913
|
+
parsed = JSON.parse(raw.toString());
|
|
61914
|
+
} catch {
|
|
61915
|
+
return void 0;
|
|
61916
|
+
}
|
|
61917
|
+
return isPlainObject(parsed) ? parsed : void 0;
|
|
61918
|
+
}
|
|
61919
|
+
function safeToolOutput(value) {
|
|
61920
|
+
try {
|
|
61921
|
+
return JSON.stringify(value ?? {});
|
|
61922
|
+
} catch {
|
|
61923
|
+
return JSON.stringify({ error: "realtimeAgent: tool result could not be serialized" });
|
|
61924
|
+
}
|
|
61925
|
+
}
|
|
61926
|
+
|
|
61927
|
+
// ../runtime-shared/dist/security/local-dev.js
|
|
61928
|
+
function isLoopbackUrl(url2) {
|
|
61929
|
+
if (!url2)
|
|
61930
|
+
return false;
|
|
61931
|
+
let hostname;
|
|
61932
|
+
try {
|
|
61933
|
+
hostname = new URL(url2).hostname.toLowerCase();
|
|
61934
|
+
} catch {
|
|
61935
|
+
return false;
|
|
61936
|
+
}
|
|
61937
|
+
if (["localhost", "0.0.0.0", "[::1]", "::1"].includes(hostname))
|
|
61938
|
+
return true;
|
|
61939
|
+
if (hostname.endsWith(".localhost"))
|
|
61940
|
+
return true;
|
|
61941
|
+
return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
|
|
61942
|
+
}
|
|
61943
|
+
function isLocalDevMode(env) {
|
|
61944
|
+
return env["SINCH_LOCAL_DEV"] === "true" && isLoopbackUrl(env["API_URL"]);
|
|
61945
|
+
}
|
|
61946
|
+
var LOCAL_DEV_MODE = isLocalDevMode(process.env);
|
|
61947
|
+
|
|
61948
|
+
// ../runtime-shared/dist/ai/agent-stream.js
|
|
61949
|
+
var AGENT_SAMPLE_RATE = 16e3;
|
|
61950
|
+
var AGENT_STREAM_PATH = "/stream";
|
|
61951
|
+
var AGENT_HEADER_TOKEN = "x-sinch-agent-token";
|
|
61952
|
+
function deriveSocketUrl(path7) {
|
|
61953
|
+
const fnName = process.env["FUNCTION_NAME"];
|
|
61954
|
+
const apiUrl = process.env["API_URL"];
|
|
61955
|
+
if (!fnName || !apiUrl)
|
|
61956
|
+
return "";
|
|
61957
|
+
if (!/^[a-z0-9][a-z0-9-]{0,51}$/.test(fnName))
|
|
61958
|
+
return "";
|
|
61959
|
+
const match = apiUrl.match(/api\.functions\.(\w+)\.sinchvoice\.org/);
|
|
61960
|
+
if (!match)
|
|
61961
|
+
return "";
|
|
61962
|
+
return `wss://${fnName}.fn-${match[1]}.sinch.com${path7}`;
|
|
61963
|
+
}
|
|
61964
|
+
function isLocalDevUrl(url2) {
|
|
61965
|
+
if (isLoopbackUrl(url2))
|
|
61966
|
+
return true;
|
|
61967
|
+
let hostname;
|
|
61968
|
+
try {
|
|
61969
|
+
hostname = new URL(url2).hostname.toLowerCase();
|
|
61970
|
+
} catch {
|
|
61971
|
+
return false;
|
|
61972
|
+
}
|
|
61973
|
+
return /(^|\.)(trycloudflare\.com|loca\.lt)$/.test(hostname) || /(^|\.)ngrok[.-]/.test(hostname);
|
|
61974
|
+
}
|
|
61975
|
+
function isDeployed(context) {
|
|
61976
|
+
return context?.config?.environment === "production" && !LOCAL_DEV_MODE;
|
|
61977
|
+
}
|
|
61978
|
+
var TUNNEL_PUBLIC_URL_ENV = "SINCH_TUNNEL_PUBLIC_URL";
|
|
61979
|
+
function tunnelPublicUrl(path7, kind) {
|
|
61980
|
+
const raw = process.env[TUNNEL_PUBLIC_URL_ENV];
|
|
61981
|
+
if (!raw)
|
|
61982
|
+
return void 0;
|
|
61983
|
+
const url2 = new URL(raw);
|
|
61984
|
+
url2.pathname = url2.pathname.replace(/\/+$/, "") + path7;
|
|
61985
|
+
const secure = url2.protocol === "https:" || url2.protocol === "wss:";
|
|
61986
|
+
url2.protocol = kind === "ws" ? secure ? "wss:" : "ws:" : secure ? "https:" : "http:";
|
|
61987
|
+
return url2.toString();
|
|
61988
|
+
}
|
|
61989
|
+
function resolveAgentStreamUrl(context, override) {
|
|
61990
|
+
return resolveSelfSocketUrl(AGENT_STREAM_PATH, "STREAM_URL", context, override);
|
|
61991
|
+
}
|
|
61992
|
+
function resolveSelfSocketUrl(path7, envVar, context, override) {
|
|
61993
|
+
const url2 = override || (isDeployed(context) ? void 0 : tunnelPublicUrl(path7, "ws")) || (context?.host ? `wss://${context.host}${path7}` : "") || process.env[envVar] || deriveSocketUrl(path7);
|
|
61994
|
+
if (!url2) {
|
|
61995
|
+
throw new Error(`WebSocket URL for ${path7} cannot be determined \u2014 set ${envVar}, or ensure FUNCTION_NAME and API_URL are present.`);
|
|
61996
|
+
}
|
|
61997
|
+
if (isDeployed(context) && isLocalDevUrl(url2)) {
|
|
61998
|
+
throw new Error(`Refusing ${url2} as this deployed function's media endpoint \u2014 it is a local development host the platform cannot reach, so the leg would fail instantly. This is almost always a ${envVar} left over from a 'sinch functions dev' tunnel. Unset it in the deployed environment, or pass the request-scoped context or an explicit URL.`);
|
|
61999
|
+
}
|
|
62000
|
+
return url2;
|
|
62001
|
+
}
|
|
62002
|
+
function buildAgentStreamEndpoint(options) {
|
|
62003
|
+
return dial.stream(options.endpoint, {
|
|
62004
|
+
sampleRate: options.sampleRate ?? AGENT_SAMPLE_RATE,
|
|
62005
|
+
headers: { ...options.headers, [AGENT_HEADER_TOKEN]: options.token }
|
|
62006
|
+
});
|
|
62007
|
+
}
|
|
62008
|
+
function upgradeHeader(req, name) {
|
|
62009
|
+
const raw = req?.headers?.[name] ?? req?.headers?.[name.toLowerCase()];
|
|
62010
|
+
return Array.isArray(raw) ? raw[0] ?? "" : raw ?? "";
|
|
62011
|
+
}
|
|
62012
|
+
function readCallHeader(connectMsg, name) {
|
|
62013
|
+
const raw = connectMsg["callHeaders"] ?? connectMsg["callheaders"] ?? connectMsg["headers"];
|
|
62014
|
+
if (Array.isArray(raw)) {
|
|
62015
|
+
const hit = raw.find((e) => isPlainObject(e) && typeof e["key"] === "string" && typeof e["value"] === "string" && e.key.toLowerCase() === name);
|
|
62016
|
+
return hit?.value ?? "";
|
|
62017
|
+
}
|
|
62018
|
+
if (isPlainObject(raw)) {
|
|
62019
|
+
const hit = Object.entries(raw).find(([k]) => k.toLowerCase() === name);
|
|
62020
|
+
return hit ? String(hit[1] ?? "") : "";
|
|
62021
|
+
}
|
|
62022
|
+
return "";
|
|
62023
|
+
}
|
|
62024
|
+
|
|
61771
62025
|
// ../runtime-shared/dist/security/context-secrets.js
|
|
61772
62026
|
import { inspect } from "util";
|
|
61773
62027
|
var HIDDEN_ENV_KEYS = [
|
|
@@ -62030,7 +62284,8 @@ function attachVoiceClient(context, v1) {
|
|
|
62030
62284
|
enumerable: true,
|
|
62031
62285
|
get() {
|
|
62032
62286
|
if (!client) {
|
|
62033
|
-
|
|
62287
|
+
const publicUrl = process.env[TUNNEL_PUBLIC_URL_ENV];
|
|
62288
|
+
client = Object.assign(createClient(context, publicUrl ? { publicUrl } : void 0), { v1 });
|
|
62034
62289
|
}
|
|
62035
62290
|
return client;
|
|
62036
62291
|
}
|
|
@@ -62779,7 +63034,7 @@ function installStdioRedaction() {
|
|
|
62779
63034
|
// ../runtime-shared/dist/security/voice-signature.js
|
|
62780
63035
|
import { createHash, createHmac as createHmac2, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
62781
63036
|
var VOICE_TIMESTAMP_SKEW_MS = 5 * 60 * 1e3;
|
|
62782
|
-
var VOICE_MISSING_SECRET_WARNING = "Voice v2 webhook not verified: VOICE_SERVICE_SECRET is not set
|
|
63037
|
+
var VOICE_MISSING_SECRET_WARNING = "Voice v2 webhook not verified: VOICE_SERVICE_SECRET is not set. Deploying sets it from the voice service; redeploy to turn verification on";
|
|
62783
63038
|
var AUTHORIZATION_PATTERN = /^service\s+([^:\s]+):(\S+)$/i;
|
|
62784
63039
|
function fail(reason) {
|
|
62785
63040
|
return { valid: false, reason };
|
|
@@ -62936,43 +63191,6 @@ function resetSinchClients() {
|
|
|
62936
63191
|
// ../runtime-shared/dist/host/app.js
|
|
62937
63192
|
var import_express2 = __toESM(require_express2(), 1);
|
|
62938
63193
|
|
|
62939
|
-
// ../runtime-shared/dist/ai/realtime/wire-safety.js
|
|
62940
|
-
var MAX_INBOUND_FRAME_BYTES = 1e6;
|
|
62941
|
-
function isOversizedFrame(raw) {
|
|
62942
|
-
return raw.length > MAX_INBOUND_FRAME_BYTES;
|
|
62943
|
-
}
|
|
62944
|
-
var BASE64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
62945
|
-
function safeBase64ToBuffer(value) {
|
|
62946
|
-
if (typeof value !== "string")
|
|
62947
|
-
return void 0;
|
|
62948
|
-
if (value.length > 0 && !BASE64_RE.test(value))
|
|
62949
|
-
return void 0;
|
|
62950
|
-
try {
|
|
62951
|
-
return Buffer.from(value, "base64");
|
|
62952
|
-
} catch {
|
|
62953
|
-
return void 0;
|
|
62954
|
-
}
|
|
62955
|
-
}
|
|
62956
|
-
function isPlainObject(value) {
|
|
62957
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
62958
|
-
}
|
|
62959
|
-
function parseVendorFrame(raw) {
|
|
62960
|
-
let parsed;
|
|
62961
|
-
try {
|
|
62962
|
-
parsed = JSON.parse(raw.toString());
|
|
62963
|
-
} catch {
|
|
62964
|
-
return void 0;
|
|
62965
|
-
}
|
|
62966
|
-
return isPlainObject(parsed) ? parsed : void 0;
|
|
62967
|
-
}
|
|
62968
|
-
function safeToolOutput(value) {
|
|
62969
|
-
try {
|
|
62970
|
-
return JSON.stringify(value ?? {});
|
|
62971
|
-
} catch {
|
|
62972
|
-
return JSON.stringify({ error: "realtimeAgent: tool result could not be serialized" });
|
|
62973
|
-
}
|
|
62974
|
-
}
|
|
62975
|
-
|
|
62976
63194
|
// ../runtime-shared/dist/host/exports.js
|
|
62977
63195
|
import { types } from "util";
|
|
62978
63196
|
var fnToString = Function.prototype.toString;
|
|
@@ -63328,12 +63546,52 @@ async function handleVoiceWebhook(userFunction, context, event, request, logger)
|
|
|
63328
63546
|
return formatCustomResponse(result2);
|
|
63329
63547
|
}
|
|
63330
63548
|
const body = await context.voice.onCall({ fallback: () => result2 })(event);
|
|
63549
|
+
await rewriteRecordingSentinels(body, event.call?.callId, context.storage);
|
|
63331
63550
|
return body === void 0 ? { statusCode: 204 } : {
|
|
63332
63551
|
statusCode: 200,
|
|
63333
63552
|
headers: { "Content-Type": "application/json" },
|
|
63334
63553
|
body: stringify(body)
|
|
63335
63554
|
};
|
|
63336
63555
|
}
|
|
63556
|
+
async function rewriteRecordingSentinels(body, callId, storage) {
|
|
63557
|
+
const resolve = async (options) => {
|
|
63558
|
+
if (!callId || !storage?.getRecordingDestination) {
|
|
63559
|
+
console.warn(`[recording] Dropping the recording command: ${callId ? "this storage cannot presign a recording destination" : "the event has no callId"}.`);
|
|
63560
|
+
return false;
|
|
63561
|
+
}
|
|
63562
|
+
const format = String(options["format"] ?? "MP3").toLowerCase();
|
|
63563
|
+
if (format !== "mp3" && format !== "wav") {
|
|
63564
|
+
console.warn(`[recording] Dropping the recording command: unsupported format "${format}".`);
|
|
63565
|
+
return false;
|
|
63566
|
+
}
|
|
63567
|
+
try {
|
|
63568
|
+
options["destinationUrl"] = await storage.getRecordingDestination(callId, format);
|
|
63569
|
+
return true;
|
|
63570
|
+
} catch (err) {
|
|
63571
|
+
console.warn("[recording] Dropping the recording command, presigning failed:", err);
|
|
63572
|
+
return false;
|
|
63573
|
+
}
|
|
63574
|
+
};
|
|
63575
|
+
const walk = async (node) => {
|
|
63576
|
+
if (Array.isArray(node)) {
|
|
63577
|
+
for (let i = node.length - 1; i >= 0; i--) {
|
|
63578
|
+
const item = node[i];
|
|
63579
|
+
const options = item?.recordingOptions;
|
|
63580
|
+
if (item?.command === "startRecording" && options?.["destinationUrl"] === RECORD_TO_FUNCTIONS_SENTINEL) {
|
|
63581
|
+
if (!await resolve(options)) {
|
|
63582
|
+
node.splice(i, 1);
|
|
63583
|
+
continue;
|
|
63584
|
+
}
|
|
63585
|
+
}
|
|
63586
|
+
await walk(item);
|
|
63587
|
+
}
|
|
63588
|
+
} else if (node !== null && typeof node === "object") {
|
|
63589
|
+
for (const child of Object.values(node))
|
|
63590
|
+
await walk(child);
|
|
63591
|
+
}
|
|
63592
|
+
};
|
|
63593
|
+
await walk(body);
|
|
63594
|
+
}
|
|
63337
63595
|
function isVoiceResult(result2) {
|
|
63338
63596
|
return Array.isArray(result2) || result2 instanceof CommandBuilder || typeof result2 === "object" && Array.isArray(result2.commands);
|
|
63339
63597
|
}
|
|
@@ -63376,7 +63634,8 @@ function createApp(options = {}) {
|
|
|
63376
63634
|
}
|
|
63377
63635
|
};
|
|
63378
63636
|
setupJsonParsing(app, jsonOptions);
|
|
63379
|
-
|
|
63637
|
+
const urlencoded = import_express2.default.urlencoded({ extended: true, limit: "10mb" });
|
|
63638
|
+
app.use((req, res, next) => req.path.startsWith(RECORDING_RECEIVER_PATH) ? next() : urlencoded(req, res, next));
|
|
63380
63639
|
return app;
|
|
63381
63640
|
}
|
|
63382
63641
|
function createSinchRuntime() {
|
|
@@ -64078,81 +64337,13 @@ var ElevenLabsAutoConfigurator = class {
|
|
|
64078
64337
|
static tryAutoConfigureAsync = tryAutoConfigureAsync;
|
|
64079
64338
|
};
|
|
64080
64339
|
|
|
64081
|
-
// ../runtime-shared/dist/ai/
|
|
64082
|
-
|
|
64083
|
-
|
|
64084
|
-
var AGENT_HEADER_TOKEN = "x-sinch-agent-token";
|
|
64085
|
-
function deriveSocketUrl(path7) {
|
|
64086
|
-
const fnName = process.env["FUNCTION_NAME"];
|
|
64087
|
-
const apiUrl = process.env["API_URL"];
|
|
64088
|
-
if (!fnName || !apiUrl)
|
|
64089
|
-
return "";
|
|
64090
|
-
if (!/^[a-z0-9][a-z0-9-]{0,51}$/.test(fnName))
|
|
64091
|
-
return "";
|
|
64092
|
-
const match = apiUrl.match(/api\.functions\.(\w+)\.sinchvoice\.org/);
|
|
64093
|
-
if (!match)
|
|
64094
|
-
return "";
|
|
64095
|
-
return `wss://${fnName}.fn-${match[1]}.sinch.com${path7}`;
|
|
64096
|
-
}
|
|
64097
|
-
function isLocalDevUrl(url2) {
|
|
64098
|
-
let hostname;
|
|
64099
|
-
try {
|
|
64100
|
-
hostname = new URL(url2).hostname.toLowerCase();
|
|
64101
|
-
} catch {
|
|
64102
|
-
return false;
|
|
64103
|
-
}
|
|
64104
|
-
if (["localhost", "127.0.0.1", "0.0.0.0", "[::1]", "::1"].includes(hostname))
|
|
64105
|
-
return true;
|
|
64106
|
-
if (hostname.endsWith(".localhost"))
|
|
64107
|
-
return true;
|
|
64108
|
-
return /(^|\.)(trycloudflare\.com|loca\.lt)$/.test(hostname) || /(^|\.)ngrok[.-]/.test(hostname);
|
|
64109
|
-
}
|
|
64110
|
-
function isDeployed(context) {
|
|
64111
|
-
return context?.config?.environment === "production" && process.env["SINCH_LOCAL_DEV"] !== "true";
|
|
64112
|
-
}
|
|
64113
|
-
function resolveAgentStreamUrl(context, override) {
|
|
64114
|
-
return resolveSelfSocketUrl(AGENT_STREAM_PATH, "STREAM_URL", context, override);
|
|
64115
|
-
}
|
|
64116
|
-
function resolveSelfSocketUrl(path7, envVar, context, override) {
|
|
64117
|
-
const url2 = override || (context?.host ? `wss://${context.host}${path7}` : "") || process.env[envVar] || deriveSocketUrl(path7);
|
|
64118
|
-
if (!url2) {
|
|
64119
|
-
throw new Error(`WebSocket URL for ${path7} cannot be determined \u2014 set ${envVar}, or ensure FUNCTION_NAME and API_URL are present.`);
|
|
64120
|
-
}
|
|
64121
|
-
if (isDeployed(context) && isLocalDevUrl(url2)) {
|
|
64122
|
-
throw new Error(`Refusing ${url2} as this deployed function's media endpoint \u2014 it is a local development host the platform cannot reach, so the leg would fail instantly. This is almost always a ${envVar} left over from a 'sinch functions dev' tunnel. Unset it in the deployed environment, or pass the request-scoped context or an explicit URL.`);
|
|
64123
|
-
}
|
|
64124
|
-
return url2;
|
|
64125
|
-
}
|
|
64126
|
-
function buildAgentStreamEndpoint(options) {
|
|
64127
|
-
return dial.stream(options.endpoint, {
|
|
64128
|
-
sampleRate: options.sampleRate ?? AGENT_SAMPLE_RATE,
|
|
64129
|
-
headers: { ...options.headers, [AGENT_HEADER_TOKEN]: options.token }
|
|
64130
|
-
});
|
|
64340
|
+
// ../runtime-shared/dist/ai/realtime/types.js
|
|
64341
|
+
function tool(def) {
|
|
64342
|
+
return def;
|
|
64131
64343
|
}
|
|
64132
|
-
|
|
64133
|
-
|
|
64134
|
-
return
|
|
64135
|
-
}
|
|
64136
|
-
function readCallHeader(connectMsg, name) {
|
|
64137
|
-
const raw = connectMsg["callHeaders"] ?? connectMsg["callheaders"] ?? connectMsg["headers"];
|
|
64138
|
-
if (Array.isArray(raw)) {
|
|
64139
|
-
const hit = raw.find((e) => isPlainObject(e) && typeof e["key"] === "string" && typeof e["value"] === "string" && e.key.toLowerCase() === name);
|
|
64140
|
-
return hit?.value ?? "";
|
|
64141
|
-
}
|
|
64142
|
-
if (isPlainObject(raw)) {
|
|
64143
|
-
const hit = Object.entries(raw).find(([k]) => k.toLowerCase() === name);
|
|
64144
|
-
return hit ? String(hit[1] ?? "") : "";
|
|
64145
|
-
}
|
|
64146
|
-
return "";
|
|
64147
|
-
}
|
|
64148
|
-
|
|
64149
|
-
// ../runtime-shared/dist/ai/realtime/types.js
|
|
64150
|
-
function tool(def) {
|
|
64151
|
-
return def;
|
|
64152
|
-
}
|
|
64153
|
-
var DEFAULT_LANGUAGE = "en-US";
|
|
64154
|
-
function sinchRate(options) {
|
|
64155
|
-
return options.audio === "wideband" ? 16e3 : 8e3;
|
|
64344
|
+
var DEFAULT_LANGUAGE = "en-US";
|
|
64345
|
+
function sinchRate(options) {
|
|
64346
|
+
return options.audio === "wideband" ? 16e3 : 8e3;
|
|
64156
64347
|
}
|
|
64157
64348
|
|
|
64158
64349
|
// ../runtime-shared/dist/ai/relay.js
|
|
@@ -64761,6 +64952,61 @@ function createDeepgramAdapter(webSocketClient) {
|
|
|
64761
64952
|
}
|
|
64762
64953
|
var deepgramAdapter = createDeepgramAdapter();
|
|
64763
64954
|
|
|
64955
|
+
// ../runtime-shared/dist/ai/realtime/vad.js
|
|
64956
|
+
var DEFAULT_THRESHOLD = 500;
|
|
64957
|
+
var DEFAULT_ATTACK_FRAMES = 2;
|
|
64958
|
+
var DEFAULT_HANGOVER_FRAMES = 20;
|
|
64959
|
+
function pcm16Rms(pcm) {
|
|
64960
|
+
if (pcm.length < 2)
|
|
64961
|
+
return 0;
|
|
64962
|
+
let sumSquares = 0;
|
|
64963
|
+
const samples = pcm.length >> 1;
|
|
64964
|
+
for (let i = 0; i < samples; i++) {
|
|
64965
|
+
const sample = pcm.readInt16LE(i * 2);
|
|
64966
|
+
sumSquares += sample * sample;
|
|
64967
|
+
}
|
|
64968
|
+
return Math.sqrt(sumSquares / samples);
|
|
64969
|
+
}
|
|
64970
|
+
var SILENCE_RMS_THRESHOLD = 32768 * 10 ** (-50 / 20);
|
|
64971
|
+
function isSpeechFrame(pcm) {
|
|
64972
|
+
return pcm16Rms(pcm) > SILENCE_RMS_THRESHOLD;
|
|
64973
|
+
}
|
|
64974
|
+
function createEnergyVad(options = {}) {
|
|
64975
|
+
const threshold = options.threshold ?? DEFAULT_THRESHOLD;
|
|
64976
|
+
const attackFrames = options.attackFrames ?? DEFAULT_ATTACK_FRAMES;
|
|
64977
|
+
const hangoverFrames = options.hangoverFrames ?? DEFAULT_HANGOVER_FRAMES;
|
|
64978
|
+
let speaking = false;
|
|
64979
|
+
let loudRun = 0;
|
|
64980
|
+
let quietRun = 0;
|
|
64981
|
+
return {
|
|
64982
|
+
get speaking() {
|
|
64983
|
+
return speaking;
|
|
64984
|
+
},
|
|
64985
|
+
get quietFrames() {
|
|
64986
|
+
return quietRun;
|
|
64987
|
+
},
|
|
64988
|
+
push(pcm) {
|
|
64989
|
+
const loud = pcm16Rms(pcm) >= threshold;
|
|
64990
|
+
if (loud) {
|
|
64991
|
+
loudRun++;
|
|
64992
|
+
quietRun = 0;
|
|
64993
|
+
} else {
|
|
64994
|
+
quietRun++;
|
|
64995
|
+
loudRun = 0;
|
|
64996
|
+
}
|
|
64997
|
+
if (!speaking && loud && loudRun >= attackFrames) {
|
|
64998
|
+
speaking = true;
|
|
64999
|
+
return "start";
|
|
65000
|
+
}
|
|
65001
|
+
if (speaking && !loud && quietRun >= hangoverFrames) {
|
|
65002
|
+
speaking = false;
|
|
65003
|
+
return "end";
|
|
65004
|
+
}
|
|
65005
|
+
return void 0;
|
|
65006
|
+
}
|
|
65007
|
+
};
|
|
65008
|
+
}
|
|
65009
|
+
|
|
64764
65010
|
// ../runtime-shared/dist/ai/realtime/audio.js
|
|
64765
65011
|
var MULAW_BIAS = 132;
|
|
64766
65012
|
var MULAW_CLIP = 32635;
|
|
@@ -64911,14 +65157,14 @@ var TRANSFER_TOOL_NAME = "transfer_to_human";
|
|
|
64911
65157
|
function offersHangup(tools) {
|
|
64912
65158
|
return tools.some((t) => t.name === HANGUP_TOOL_NAME);
|
|
64913
65159
|
}
|
|
64914
|
-
var CALL_TERMINATION_INSTRUCTIONS = '\n\nCALL TERMINATION\nWhen the caller indicates the conversation is finished ("goodbye", "that\'s all", "thanks bye", etc.), or the task is complete and there is nothing else to discuss:\n1.
|
|
65160
|
+
var CALL_TERMINATION_INSTRUCTIONS = '\n\nCALL TERMINATION\nWhen the caller indicates the conversation is finished ("goodbye", "that\'s all", "thanks bye", etc.), or the task is complete and there is nothing else to discuss:\n1. Say your complete goodbye first, as one short closing statement.\n2. Only then call the `hangup_call` tool.\n3. Say nothing at all after calling it, and do not wait for another user turn.\nYou cannot end the phone call by saying goodbye. The call only ends when you call the `hangup_call` tool.';
|
|
64915
65161
|
var DELEGATED_CALL_TERMINATION_INSTRUCTIONS = `
|
|
64916
65162
|
|
|
64917
65163
|
CALL TERMINATION
|
|
64918
65164
|
When the caller indicates the conversation is finished ("goodbye", "that's all", "thanks bye", etc.), or the task is complete and there is nothing else to discuss: give a brief closing statement, then you MUST delegate so the backend can end the call. Saying goodbye does not end the phone call. Never finish a conversation without delegating call termination. Do not wait for another user turn.`;
|
|
64919
65165
|
var GPT_LIVE_BACKEND_CALL_TERMINATION_RULE = "\n\nIf the request is to end the call, call hangup_call immediately.";
|
|
64920
|
-
async function resolvePerCallValue(value, call, context) {
|
|
64921
|
-
return typeof value === "function" ? await value(call, context) : value;
|
|
65166
|
+
async function resolvePerCallValue(value, call, context, data) {
|
|
65167
|
+
return typeof value === "function" ? await value(call, context, data) : value;
|
|
64922
65168
|
}
|
|
64923
65169
|
function builtInTools(hangupEnabled, transferNumber, ctx) {
|
|
64924
65170
|
const tools = [];
|
|
@@ -64969,31 +65215,17 @@ var DEFAULT_BACKEND_MODEL = "gpt-5.6-luna";
|
|
|
64969
65215
|
var VENDOR_RATE = 8e3;
|
|
64970
65216
|
var TURN_SILENCE_MS = 1500;
|
|
64971
65217
|
var TRANSCRIPT_FALLBACK_MS = 300;
|
|
64972
|
-
var SILENCE_DBFS_THRESHOLD = -50;
|
|
64973
|
-
var SILENCE_RMS_THRESHOLD = 32768 * 10 ** (SILENCE_DBFS_THRESHOLD / 20);
|
|
64974
65218
|
var AGENT_TURN_HARD_CAP_MS = 3e4;
|
|
64975
|
-
function pcm16Rms(pcm) {
|
|
64976
|
-
const samples = pcm.length >> 1;
|
|
64977
|
-
if (samples === 0)
|
|
64978
|
-
return 0;
|
|
64979
|
-
let sumSquares = 0;
|
|
64980
|
-
for (let i = 0; i < samples; i++) {
|
|
64981
|
-
const sample = pcm.readInt16LE(i * 2);
|
|
64982
|
-
sumSquares += sample * sample;
|
|
64983
|
-
}
|
|
64984
|
-
return Math.sqrt(sumSquares / samples);
|
|
64985
|
-
}
|
|
64986
|
-
function isSpeechFrame(pcm) {
|
|
64987
|
-
return pcm16Rms(pcm) > SILENCE_RMS_THRESHOLD;
|
|
64988
|
-
}
|
|
64989
|
-
function toAnchoredIso(session, offsetMs) {
|
|
64990
|
-
if (offsetMs === void 0 || session.sessionStartedAtMs === void 0)
|
|
64991
|
-
return void 0;
|
|
64992
|
-
return new Date(session.sessionStartedAtMs + offsetMs).toISOString();
|
|
64993
|
-
}
|
|
64994
65219
|
function buildGreetingDirective(greeting) {
|
|
64995
65220
|
return `Greet the caller now by saying exactly: "${greeting}"`;
|
|
64996
65221
|
}
|
|
65222
|
+
function sendGreeting(ws, greeting) {
|
|
65223
|
+
ws.send(JSON.stringify({
|
|
65224
|
+
type: "session.instructions.append",
|
|
65225
|
+
content: buildGreetingDirective(greeting),
|
|
65226
|
+
delegation_id: null
|
|
65227
|
+
}));
|
|
65228
|
+
}
|
|
64997
65229
|
var CLOSE_ACK_TIMEOUT_MS = 1e3;
|
|
64998
65230
|
var USER_TURN_ARRIVAL_FALLBACK_MS = TURN_SILENCE_MS * 2;
|
|
64999
65231
|
var DEFAULT_BACKEND_SERVICE_TIER = "priority";
|
|
@@ -65133,10 +65365,6 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65133
65365
|
sessionSeconds: void 0,
|
|
65134
65366
|
backendInputTokens: 0,
|
|
65135
65367
|
backendOutputTokens: 0,
|
|
65136
|
-
pendingUserTurnStartMs: void 0,
|
|
65137
|
-
pendingAgentTurnStartMs: void 0,
|
|
65138
|
-
pendingAgentTurnEndMs: void 0,
|
|
65139
|
-
sessionStartedAtMs: void 0,
|
|
65140
65368
|
delegationCreatedAtMs: /* @__PURE__ */ new Map(),
|
|
65141
65369
|
delegationFirstOutputMs: /* @__PURE__ */ new Map(),
|
|
65142
65370
|
delegationToolMs: /* @__PURE__ */ new Map(),
|
|
@@ -65199,10 +65427,6 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65199
65427
|
session.agentTurnStartedAt = void 0;
|
|
65200
65428
|
const text = session.pendingAgentTurnText;
|
|
65201
65429
|
session.pendingAgentTurnText = "";
|
|
65202
|
-
const playbackStartAt = toAnchoredIso(session, session.pendingAgentTurnStartMs);
|
|
65203
|
-
const playbackEndAt = toAnchoredIso(session, session.pendingAgentTurnEndMs);
|
|
65204
|
-
session.pendingAgentTurnStartMs = void 0;
|
|
65205
|
-
session.pendingAgentTurnEndMs = void 0;
|
|
65206
65430
|
let delegationMs;
|
|
65207
65431
|
if (session.lastDelegationId !== void 0) {
|
|
65208
65432
|
const firstOutputMs = session.delegationFirstOutputMs.get(session.lastDelegationId);
|
|
@@ -65219,8 +65443,6 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65219
65443
|
role: "agent",
|
|
65220
65444
|
text,
|
|
65221
65445
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
65222
|
-
playbackStartAt,
|
|
65223
|
-
playbackEndAt,
|
|
65224
65446
|
delegationMs
|
|
65225
65447
|
});
|
|
65226
65448
|
};
|
|
@@ -65234,19 +65456,14 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65234
65456
|
clearTimeout(session.userTurnTimer);
|
|
65235
65457
|
session.userTurnTimer = void 0;
|
|
65236
65458
|
}
|
|
65237
|
-
const speechStartAt = toAnchoredIso(session, session.pendingUserTurnStartMs);
|
|
65238
|
-
const speechEndAt = toAnchoredIso(session, session.pendingUserTurnEndMs);
|
|
65239
65459
|
session.pendingUserTurnEndMs = void 0;
|
|
65240
|
-
session.pendingUserTurnStartMs = void 0;
|
|
65241
65460
|
const text = session.pendingUserTurnText;
|
|
65242
65461
|
session.pendingUserTurnText = "";
|
|
65243
65462
|
if (text)
|
|
65244
65463
|
callbacks.onTurn({
|
|
65245
65464
|
role: "user",
|
|
65246
65465
|
text,
|
|
65247
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
65248
|
-
speechStartAt,
|
|
65249
|
-
speechEndAt
|
|
65466
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
65250
65467
|
});
|
|
65251
65468
|
};
|
|
65252
65469
|
const scheduleUserTurnFlush = () => {
|
|
@@ -65308,15 +65525,10 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65308
65525
|
case "session.started": {
|
|
65309
65526
|
const started = msg["session"];
|
|
65310
65527
|
session.expiresAt = started?.expires_at;
|
|
65311
|
-
session.sessionStartedAtMs = Date.now();
|
|
65312
65528
|
session.ready = true;
|
|
65313
65529
|
settle2(() => resolve(session));
|
|
65314
65530
|
if (options.greeting) {
|
|
65315
|
-
vendorWs.
|
|
65316
|
-
type: "session.instructions.append",
|
|
65317
|
-
content: buildGreetingDirective(options.greeting),
|
|
65318
|
-
delegation_id: null
|
|
65319
|
-
}));
|
|
65531
|
+
sendGreeting(vendorWs, options.greeting);
|
|
65320
65532
|
}
|
|
65321
65533
|
break;
|
|
65322
65534
|
}
|
|
@@ -65348,9 +65560,6 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65348
65560
|
if (hasRealGap)
|
|
65349
65561
|
flushUserTurnNow();
|
|
65350
65562
|
if (delta) {
|
|
65351
|
-
if (session.pendingUserTurnText === "" && startMs !== void 0) {
|
|
65352
|
-
session.pendingUserTurnStartMs = startMs;
|
|
65353
|
-
}
|
|
65354
65563
|
session.pendingUserTurnText += delta;
|
|
65355
65564
|
}
|
|
65356
65565
|
if (endMs !== void 0)
|
|
@@ -65360,20 +65569,14 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65360
65569
|
}
|
|
65361
65570
|
case "session.output_transcript.delta": {
|
|
65362
65571
|
const delta = msg["delta"];
|
|
65363
|
-
const startMs = typeof msg["start_ms"] === "number" ? msg["start_ms"] : void 0;
|
|
65364
|
-
const endMs = typeof msg["end_ms"] === "number" ? msg["end_ms"] : void 0;
|
|
65365
65572
|
if (delta) {
|
|
65366
65573
|
if (session.pendingAgentTurnText === "") {
|
|
65367
65574
|
session.agentTurnStartedAt = Date.now();
|
|
65368
65575
|
if (session.agentTurnHardCapTimer !== void 0)
|
|
65369
65576
|
clearTimeout(session.agentTurnHardCapTimer);
|
|
65370
65577
|
session.agentTurnHardCapTimer = setTimeout(flushAgentTurnNow, AGENT_TURN_HARD_CAP_MS);
|
|
65371
|
-
if (startMs !== void 0)
|
|
65372
|
-
session.pendingAgentTurnStartMs = startMs;
|
|
65373
65578
|
}
|
|
65374
65579
|
session.pendingAgentTurnText += delta;
|
|
65375
|
-
if (endMs !== void 0)
|
|
65376
|
-
session.pendingAgentTurnEndMs = endMs;
|
|
65377
65580
|
}
|
|
65378
65581
|
const audioQuiet = session.lastSpeechAudioAt !== void 0 && Date.now() - session.lastSpeechAudioAt > TURN_SILENCE_MS;
|
|
65379
65582
|
if (audioQuiet) {
|
|
@@ -65497,6 +65700,11 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65497
65700
|
const mulaw = pcm16ToMulaw(pcm8k);
|
|
65498
65701
|
s.ws.send(JSON.stringify({ type: "session.input_audio.append", audio: mulaw.toString("base64") }));
|
|
65499
65702
|
},
|
|
65703
|
+
speak(session, text) {
|
|
65704
|
+
const s = session;
|
|
65705
|
+
if (s.ready && s.ws.readyState === s.ws.OPEN)
|
|
65706
|
+
sendGreeting(s.ws, text);
|
|
65707
|
+
},
|
|
65500
65708
|
clear() {
|
|
65501
65709
|
},
|
|
65502
65710
|
close(session) {
|
|
@@ -66261,127 +66469,505 @@ function createGeminiAdapter(webSocketClient) {
|
|
|
66261
66469
|
flushPendingTurns(session, callbacks);
|
|
66262
66470
|
}
|
|
66263
66471
|
}
|
|
66264
|
-
const toolCallRaw = msg["toolCall"];
|
|
66265
|
-
const functionCalls = isPlainObject(toolCallRaw) ? toolCallRaw["functionCalls"] : void 0;
|
|
66266
|
-
if (Array.isArray(functionCalls)) {
|
|
66267
|
-
for (const fc of functionCalls) {
|
|
66268
|
-
if (!isPlainObject(fc) || typeof fc["id"] !== "string" || typeof fc["name"] !== "string") {
|
|
66269
|
-
callbacks.onError({
|
|
66270
|
-
message: "Received a malformed function call from Gemini Live"
|
|
66271
|
-
});
|
|
66272
|
-
continue;
|
|
66273
|
-
}
|
|
66274
|
-
void dispatchToolCall4({ id: fc["id"], name: fc["name"], args: fc["args"] }, tools, ctx, session, callbacks).catch((err) => {
|
|
66275
|
-
const sanitized = sanitizeVendorError(err);
|
|
66276
|
-
callbacks.onError({
|
|
66277
|
-
message: sanitized.message,
|
|
66278
|
-
code: sanitized.code,
|
|
66279
|
-
raw: sanitized
|
|
66280
|
-
});
|
|
66281
|
-
});
|
|
66282
|
-
}
|
|
66283
|
-
} else if (functionCalls !== void 0) {
|
|
66284
|
-
callbacks.onError({
|
|
66285
|
-
message: "Received a malformed toolCall from Gemini Live \u2014 functionCalls was not an array"
|
|
66286
|
-
});
|
|
66472
|
+
const toolCallRaw = msg["toolCall"];
|
|
66473
|
+
const functionCalls = isPlainObject(toolCallRaw) ? toolCallRaw["functionCalls"] : void 0;
|
|
66474
|
+
if (Array.isArray(functionCalls)) {
|
|
66475
|
+
for (const fc of functionCalls) {
|
|
66476
|
+
if (!isPlainObject(fc) || typeof fc["id"] !== "string" || typeof fc["name"] !== "string") {
|
|
66477
|
+
callbacks.onError({
|
|
66478
|
+
message: "Received a malformed function call from Gemini Live"
|
|
66479
|
+
});
|
|
66480
|
+
continue;
|
|
66481
|
+
}
|
|
66482
|
+
void dispatchToolCall4({ id: fc["id"], name: fc["name"], args: fc["args"] }, tools, ctx, session, callbacks).catch((err) => {
|
|
66483
|
+
const sanitized = sanitizeVendorError(err);
|
|
66484
|
+
callbacks.onError({
|
|
66485
|
+
message: sanitized.message,
|
|
66486
|
+
code: sanitized.code,
|
|
66487
|
+
raw: sanitized
|
|
66488
|
+
});
|
|
66489
|
+
});
|
|
66490
|
+
}
|
|
66491
|
+
} else if (functionCalls !== void 0) {
|
|
66492
|
+
callbacks.onError({
|
|
66493
|
+
message: "Received a malformed toolCall from Gemini Live \u2014 functionCalls was not an array"
|
|
66494
|
+
});
|
|
66495
|
+
}
|
|
66496
|
+
const cancellationRaw = msg["toolCallCancellation"];
|
|
66497
|
+
const ids = isPlainObject(cancellationRaw) ? cancellationRaw["ids"] : void 0;
|
|
66498
|
+
if (Array.isArray(ids)) {
|
|
66499
|
+
for (const id of ids) {
|
|
66500
|
+
if (typeof id === "string")
|
|
66501
|
+
session.cancelledCallIds.add(id);
|
|
66502
|
+
}
|
|
66503
|
+
} else if (ids !== void 0) {
|
|
66504
|
+
callbacks.onError({
|
|
66505
|
+
message: "Received a malformed toolCallCancellation from Gemini Live \u2014 ids was not an array"
|
|
66506
|
+
});
|
|
66507
|
+
}
|
|
66508
|
+
if (msg["goAway"] !== void 0) {
|
|
66509
|
+
callbacks.onError({
|
|
66510
|
+
message: "Gemini Live sent goAway \u2014 session will close soon",
|
|
66511
|
+
raw: msg["goAway"]
|
|
66512
|
+
});
|
|
66513
|
+
}
|
|
66514
|
+
});
|
|
66515
|
+
liveWs.on("error", (err) => {
|
|
66516
|
+
const sanitized = sanitizeVendorError(err);
|
|
66517
|
+
if (!settled) {
|
|
66518
|
+
settle2(() => reject(new Error(sanitized.message)));
|
|
66519
|
+
return;
|
|
66520
|
+
}
|
|
66521
|
+
callbacks.onError({ message: sanitized.message, code: sanitized.code, raw: sanitized });
|
|
66522
|
+
});
|
|
66523
|
+
liveWs.on("close", () => {
|
|
66524
|
+
clearSetupTimer();
|
|
66525
|
+
if (session.closingIntentionally) {
|
|
66526
|
+
if (!settled) {
|
|
66527
|
+
settle2(() => reject(new Error("realtimeAgent: connect aborted \u2014 the Sinch STREAM leg ended first")));
|
|
66528
|
+
return;
|
|
66529
|
+
}
|
|
66530
|
+
flushPendingTurns(session, callbacks);
|
|
66531
|
+
callbacks.onClose();
|
|
66532
|
+
return;
|
|
66533
|
+
}
|
|
66534
|
+
const canResume = session.resumptionHandle !== void 0;
|
|
66535
|
+
if (canResume && session.reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
|
|
66536
|
+
session.reconnectAttempts += 1;
|
|
66537
|
+
const delayMs = RECONNECT_BASE_DELAY_MS * 2 ** (session.reconnectAttempts - 1);
|
|
66538
|
+
setTimeout(() => {
|
|
66539
|
+
if (!session.closingIntentionally)
|
|
66540
|
+
openSocket();
|
|
66541
|
+
}, delayMs);
|
|
66542
|
+
return;
|
|
66543
|
+
}
|
|
66544
|
+
if (!settled) {
|
|
66545
|
+
settle2(() => reject(new Error("realtimeAgent: Gemini Live closed before setupComplete, with no resumable session")));
|
|
66546
|
+
return;
|
|
66547
|
+
}
|
|
66548
|
+
if (canResume) {
|
|
66549
|
+
callbacks.onError({
|
|
66550
|
+
message: "realtimeAgent: Gemini Live reconnect attempts exhausted \u2014 ending the call."
|
|
66551
|
+
});
|
|
66552
|
+
}
|
|
66553
|
+
flushPendingTurns(session, callbacks);
|
|
66554
|
+
callbacks.onClose();
|
|
66555
|
+
});
|
|
66556
|
+
};
|
|
66557
|
+
openSocket();
|
|
66558
|
+
});
|
|
66559
|
+
},
|
|
66560
|
+
sendAudio(session, pcm) {
|
|
66561
|
+
const s = session;
|
|
66562
|
+
if (!s.ready || s.ws.readyState !== s.ws.OPEN) {
|
|
66563
|
+
if (!s.closingIntentionally && s.audioBufferBytes + pcm.length <= MAX_BUFFERED_AUDIO_BYTES) {
|
|
66564
|
+
s.audioBuffer.push(pcm);
|
|
66565
|
+
s.audioBufferBytes += pcm.length;
|
|
66566
|
+
}
|
|
66567
|
+
return;
|
|
66568
|
+
}
|
|
66569
|
+
const pcm16k = s.resamplerIn.push(pcm);
|
|
66570
|
+
s.ws.send(JSON.stringify({
|
|
66571
|
+
realtimeInput: {
|
|
66572
|
+
audio: { data: pcm16k.toString("base64"), mimeType: "audio/pcm;rate=16000" }
|
|
66573
|
+
}
|
|
66574
|
+
}));
|
|
66575
|
+
},
|
|
66576
|
+
clear() {
|
|
66577
|
+
},
|
|
66578
|
+
close(session) {
|
|
66579
|
+
const s = session;
|
|
66580
|
+
s.closingIntentionally = true;
|
|
66581
|
+
closeAnyState(s.ws);
|
|
66582
|
+
}
|
|
66583
|
+
};
|
|
66584
|
+
}
|
|
66585
|
+
var geminiAdapter = createGeminiAdapter();
|
|
66586
|
+
|
|
66587
|
+
// ../runtime-shared/dist/ai/realtime/adapters/elevenlabs-tools.js
|
|
66588
|
+
var API_BASE = "https://api.elevenlabs.io/v1";
|
|
66589
|
+
var TIMEOUT_MS = 1e4;
|
|
66590
|
+
function differs(have, want) {
|
|
66591
|
+
return have.description !== void 0 && have.description !== want.description || have.expects_response !== void 0 && have.expects_response !== want.expects_response || have.parameters !== void 0 && JSON.stringify(have.parameters) !== JSON.stringify(want.parameters);
|
|
66592
|
+
}
|
|
66593
|
+
async function ensureElevenLabsClientTools(opts) {
|
|
66594
|
+
const f = opts.fetchFn ?? fetch;
|
|
66595
|
+
const headers = { "xi-api-key": opts.apiKey, "Content-Type": "application/json" };
|
|
66596
|
+
const call = async (method, path7, body) => {
|
|
66597
|
+
const res = await f(`${API_BASE}${path7}`, {
|
|
66598
|
+
method,
|
|
66599
|
+
headers,
|
|
66600
|
+
...body !== void 0 && { body: JSON.stringify(body) },
|
|
66601
|
+
signal: AbortSignal.timeout(TIMEOUT_MS)
|
|
66602
|
+
});
|
|
66603
|
+
if (!res.ok) {
|
|
66604
|
+
throw new Error(`ElevenLabs API ${method} ${path7.split("?")[0]} failed: ${res.status}`);
|
|
66605
|
+
}
|
|
66606
|
+
return res.json();
|
|
66607
|
+
};
|
|
66608
|
+
const agent = await call("GET", `/convai/agents/${encodeURIComponent(opts.agentId)}`);
|
|
66609
|
+
const attachedIds = new Set(agent.conversation_config?.agent?.prompt?.tool_ids ?? []);
|
|
66610
|
+
const workspace = /* @__PURE__ */ new Map();
|
|
66611
|
+
let cursor;
|
|
66612
|
+
do {
|
|
66613
|
+
const page = await call("GET", `/convai/tools?types=client&page_size=100${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
|
|
66614
|
+
for (const t of page.tools ?? []) {
|
|
66615
|
+
const name = t.tool_config?.name;
|
|
66616
|
+
if (name && !workspace.has(name))
|
|
66617
|
+
workspace.set(name, { id: t.id, config: t.tool_config });
|
|
66618
|
+
}
|
|
66619
|
+
cursor = page.has_more ? page.next_cursor : null;
|
|
66620
|
+
} while (cursor);
|
|
66621
|
+
const result2 = { created: [], attached: [] };
|
|
66622
|
+
const newIds = [];
|
|
66623
|
+
for (const tool2 of opts.tools) {
|
|
66624
|
+
const desired = {
|
|
66625
|
+
type: "client",
|
|
66626
|
+
name: tool2.name,
|
|
66627
|
+
description: tool2.description,
|
|
66628
|
+
// `hangup_call` is fire-and-forget: a result makes the model speak again ("The call has
|
|
66629
|
+
// ended.") after the goodbye.
|
|
66630
|
+
expects_response: tool2.name !== "hangup_call",
|
|
66631
|
+
parameters: tool2.parameters
|
|
66632
|
+
};
|
|
66633
|
+
const existing = workspace.get(tool2.name);
|
|
66634
|
+
let id = existing?.id;
|
|
66635
|
+
if (existing && differs(existing.config, desired)) {
|
|
66636
|
+
await call("PATCH", `/convai/tools/${encodeURIComponent(existing.id)}`, {
|
|
66637
|
+
tool_config: desired
|
|
66638
|
+
});
|
|
66639
|
+
}
|
|
66640
|
+
if (!id) {
|
|
66641
|
+
const made = await call("POST", "/convai/tools", { tool_config: desired });
|
|
66642
|
+
id = made.id;
|
|
66643
|
+
result2.created.push(tool2.name);
|
|
66644
|
+
}
|
|
66645
|
+
if (!attachedIds.has(id)) {
|
|
66646
|
+
newIds.push(id);
|
|
66647
|
+
result2.attached.push(tool2.name);
|
|
66648
|
+
}
|
|
66649
|
+
}
|
|
66650
|
+
if (newIds.length > 0) {
|
|
66651
|
+
await call("PATCH", `/convai/agents/${encodeURIComponent(opts.agentId)}`, {
|
|
66652
|
+
conversation_config: { agent: { prompt: { tool_ids: [...attachedIds, ...newIds] } } }
|
|
66653
|
+
});
|
|
66654
|
+
}
|
|
66655
|
+
return result2;
|
|
66656
|
+
}
|
|
66657
|
+
|
|
66658
|
+
// ../runtime-shared/dist/ai/realtime/adapters/elevenlabs.js
|
|
66659
|
+
var API_BASE2 = "https://api.elevenlabs.io/v1";
|
|
66660
|
+
var FETCH_TIMEOUT_MS4 = 1e4;
|
|
66661
|
+
var HANDSHAKE_TIMEOUT_MS5 = 1e4;
|
|
66662
|
+
function parseAudioFormat(format) {
|
|
66663
|
+
if (format === "ulaw_8000")
|
|
66664
|
+
return { ulaw: true, rate: 8e3 };
|
|
66665
|
+
const m = typeof format === "string" ? /^pcm_(\d+)$/.exec(format) : null;
|
|
66666
|
+
return m ? { ulaw: false, rate: Number(m[1]) } : { ulaw: true, rate: 8e3 };
|
|
66667
|
+
}
|
|
66668
|
+
function buildInitiation(options, skip) {
|
|
66669
|
+
if (skip)
|
|
66670
|
+
return { type: "conversation_initiation_client_data" };
|
|
66671
|
+
const lang = (options.language ?? DEFAULT_LANGUAGE).split("-")[0].toLowerCase();
|
|
66672
|
+
return {
|
|
66673
|
+
type: "conversation_initiation_client_data",
|
|
66674
|
+
conversation_config_override: {
|
|
66675
|
+
agent: {
|
|
66676
|
+
prompt: { prompt: options.prompt },
|
|
66677
|
+
...options.greeting && { first_message: options.greeting },
|
|
66678
|
+
// Listen-first: an empty first message makes the agent wait; `speak` opens it later.
|
|
66679
|
+
...options.greetingHeld && !options.greeting && { first_message: "" },
|
|
66680
|
+
...options.language && options.language !== DEFAULT_LANGUAGE && { language: lang }
|
|
66681
|
+
},
|
|
66682
|
+
...options.voice && { tts: { voice_id: options.voice } }
|
|
66683
|
+
}
|
|
66684
|
+
};
|
|
66685
|
+
}
|
|
66686
|
+
async function getSignedUrl(apiKey, agentId, fetchFn, signal) {
|
|
66687
|
+
const res = await fetchFn(`${API_BASE2}/convai/conversation/get-signed-url?agent_id=${encodeURIComponent(agentId)}`, {
|
|
66688
|
+
headers: { "xi-api-key": apiKey },
|
|
66689
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(FETCH_TIMEOUT_MS4)])
|
|
66690
|
+
});
|
|
66691
|
+
if (!res.ok) {
|
|
66692
|
+
throw new Error(`realtimeAgent: elevenlabs signed-URL request failed (${res.status})`);
|
|
66693
|
+
}
|
|
66694
|
+
const body = await res.json();
|
|
66695
|
+
if (!body.signed_url)
|
|
66696
|
+
throw new Error("realtimeAgent: elevenlabs returned no signed_url");
|
|
66697
|
+
return body.signed_url;
|
|
66698
|
+
}
|
|
66699
|
+
async function dispatchToolCall5(call, tools, ctx, ws, callbacks, onHangupResult) {
|
|
66700
|
+
const name = call.tool_name ?? "";
|
|
66701
|
+
const start = Date.now();
|
|
66702
|
+
const found = tools.find((t) => t.name === name);
|
|
66703
|
+
const args = call.parameters ?? {};
|
|
66704
|
+
let result2;
|
|
66705
|
+
let error;
|
|
66706
|
+
try {
|
|
66707
|
+
if (!found)
|
|
66708
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
66709
|
+
if (!isPlainObject(args))
|
|
66710
|
+
throw new Error(`malformed parameters for tool '${name}'`);
|
|
66711
|
+
result2 = await found.handler(args, ctx);
|
|
66712
|
+
} catch (err) {
|
|
66713
|
+
error = err instanceof Error ? err.message : String(err);
|
|
66714
|
+
}
|
|
66715
|
+
callbacks.onToolCall({ name, args, result: result2, error, latencyMs: Date.now() - start });
|
|
66716
|
+
if (name === "hangup_call" && error === void 0)
|
|
66717
|
+
onHangupResult?.();
|
|
66718
|
+
if (call.expects_response === false || !call.tool_call_id)
|
|
66719
|
+
return;
|
|
66720
|
+
if (ws.readyState !== ws.OPEN)
|
|
66721
|
+
return;
|
|
66722
|
+
ws.send(JSON.stringify({
|
|
66723
|
+
type: "client_tool_result",
|
|
66724
|
+
tool_call_id: call.tool_call_id,
|
|
66725
|
+
result: safeToolOutput(error ? { error } : result2 ?? {}),
|
|
66726
|
+
is_error: error !== void 0,
|
|
66727
|
+
...error !== void 0 && { error_type: "external_client" }
|
|
66728
|
+
}));
|
|
66729
|
+
}
|
|
66730
|
+
function createElevenLabsAdapter(webSocketClient, fetchFn = (...a) => fetch(...a)) {
|
|
66731
|
+
return {
|
|
66732
|
+
async connect(options, ctx, callbacks, signal) {
|
|
66733
|
+
if (signal.aborted) {
|
|
66734
|
+
throw new Error("realtimeAgent: connect aborted \u2014 the Sinch STREAM leg ended first");
|
|
66735
|
+
}
|
|
66736
|
+
const apiKey = ctx.config.getSecret("ELEVENLABS_API_KEY");
|
|
66737
|
+
if (!apiKey) {
|
|
66738
|
+
throw new Error("realtimeAgent: provider 'elevenlabs' needs ELEVENLABS_API_KEY \u2014 set it as a function secret.");
|
|
66739
|
+
}
|
|
66740
|
+
const po = options.providerOptions?.["elevenlabs"] ?? {};
|
|
66741
|
+
const agentId = po.agentId ?? ctx.config.getVariable("ELEVENLABS_AGENT_ID");
|
|
66742
|
+
if (!agentId) {
|
|
66743
|
+
throw new Error("realtimeAgent: provider 'elevenlabs' needs an agent id \u2014 set providerOptions.elevenlabs.agentId or the ELEVENLABS_AGENT_ID variable.");
|
|
66744
|
+
}
|
|
66745
|
+
if (po.registerTools !== false && options.tools?.length) {
|
|
66746
|
+
await ensureElevenLabsClientTools({ apiKey, agentId, tools: options.tools, fetchFn });
|
|
66747
|
+
}
|
|
66748
|
+
const signedUrl = await getSignedUrl(apiKey, agentId, fetchFn, signal);
|
|
66749
|
+
if (signal.aborted) {
|
|
66750
|
+
throw new Error("realtimeAgent: connect aborted \u2014 the Sinch STREAM leg ended first");
|
|
66751
|
+
}
|
|
66752
|
+
const WebSocketClient = webSocketClient ?? loadWebSocketClient("elevenlabs");
|
|
66753
|
+
const ws = new WebSocketClient(signedUrl);
|
|
66754
|
+
const session = {
|
|
66755
|
+
ws,
|
|
66756
|
+
ready: false,
|
|
66757
|
+
sinchRate: sinchRate(options),
|
|
66758
|
+
inFormat: { ulaw: true, rate: 8e3 },
|
|
66759
|
+
outFormat: { ulaw: true, rate: 8e3 },
|
|
66760
|
+
resamplerIn: void 0,
|
|
66761
|
+
resamplerOut: void 0,
|
|
66762
|
+
agentSpeaking: false,
|
|
66763
|
+
lastInterruptId: -1,
|
|
66764
|
+
pendingAgentText: void 0
|
|
66765
|
+
};
|
|
66766
|
+
const tools = options.tools ?? [];
|
|
66767
|
+
let hangingUp = false;
|
|
66768
|
+
let repliesAllowed = 0;
|
|
66769
|
+
let muted = false;
|
|
66770
|
+
const flushAgent = () => {
|
|
66771
|
+
if (session.pendingAgentText === void 0)
|
|
66772
|
+
return;
|
|
66773
|
+
const text = session.pendingAgentText;
|
|
66774
|
+
session.pendingAgentText = void 0;
|
|
66775
|
+
if (text)
|
|
66776
|
+
callbacks.onTurn({ role: "agent", text, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
66777
|
+
};
|
|
66778
|
+
const stopPlayback = (cancelled) => {
|
|
66779
|
+
if (!session.agentSpeaking)
|
|
66780
|
+
return;
|
|
66781
|
+
session.agentSpeaking = false;
|
|
66782
|
+
callbacks.onPlaybackStop?.({ cancelled });
|
|
66783
|
+
};
|
|
66784
|
+
ws.on("open", () => {
|
|
66785
|
+
ws.send(JSON.stringify(buildInitiation(options, po.skipOverrides === true)));
|
|
66786
|
+
});
|
|
66787
|
+
return await new Promise((resolve, reject) => {
|
|
66788
|
+
let settled = false;
|
|
66789
|
+
const timer = setTimeout(() => {
|
|
66790
|
+
if (settled)
|
|
66791
|
+
return;
|
|
66792
|
+
settled = true;
|
|
66793
|
+
closeAnyState(ws);
|
|
66794
|
+
reject(new Error("realtimeAgent: provider elevenlabs handshake timed out waiting for conversation_initiation_metadata"));
|
|
66795
|
+
}, HANDSHAKE_TIMEOUT_MS5);
|
|
66796
|
+
const onAbort = () => {
|
|
66797
|
+
if (settled)
|
|
66798
|
+
return;
|
|
66799
|
+
settled = true;
|
|
66800
|
+
clearTimeout(timer);
|
|
66801
|
+
closeAnyState(ws);
|
|
66802
|
+
reject(new Error("realtimeAgent: connect aborted \u2014 the Sinch STREAM leg ended first"));
|
|
66803
|
+
};
|
|
66804
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
66805
|
+
const settle2 = (fn) => {
|
|
66806
|
+
if (settled)
|
|
66807
|
+
return;
|
|
66808
|
+
settled = true;
|
|
66809
|
+
clearTimeout(timer);
|
|
66810
|
+
signal.removeEventListener("abort", onAbort);
|
|
66811
|
+
fn();
|
|
66812
|
+
};
|
|
66813
|
+
ws.on("message", (raw) => {
|
|
66814
|
+
if (isOversizedFrame(raw)) {
|
|
66815
|
+
callbacks.onError({ message: "Received an oversized frame from elevenlabs \u2014 dropped" });
|
|
66816
|
+
return;
|
|
66817
|
+
}
|
|
66818
|
+
const msg = parseVendorFrame(raw);
|
|
66819
|
+
if (!msg) {
|
|
66820
|
+
callbacks.onError({ message: "Received a non-JSON frame from elevenlabs" });
|
|
66821
|
+
return;
|
|
66822
|
+
}
|
|
66823
|
+
switch (msg["type"]) {
|
|
66824
|
+
case "conversation_initiation_metadata": {
|
|
66825
|
+
const meta = msg["conversation_initiation_metadata_event"];
|
|
66826
|
+
session.outFormat = parseAudioFormat(meta?.agent_output_audio_format);
|
|
66827
|
+
session.inFormat = parseAudioFormat(meta?.user_input_audio_format);
|
|
66828
|
+
session.resamplerOut = new StreamingResampler(session.outFormat.rate, session.sinchRate);
|
|
66829
|
+
session.resamplerIn = new StreamingResampler(session.sinchRate, session.inFormat.rate);
|
|
66830
|
+
session.ready = true;
|
|
66831
|
+
settle2(() => resolve(session));
|
|
66832
|
+
break;
|
|
66833
|
+
}
|
|
66834
|
+
case "audio": {
|
|
66835
|
+
const ev = msg["audio_event"];
|
|
66836
|
+
if (typeof ev?.event_id === "number" && ev.event_id <= session.lastInterruptId)
|
|
66837
|
+
break;
|
|
66838
|
+
if (muted)
|
|
66839
|
+
break;
|
|
66840
|
+
const chunk = safeBase64ToBuffer(ev?.audio_base_64);
|
|
66841
|
+
if (!chunk || !session.resamplerOut) {
|
|
66842
|
+
callbacks.onError({ message: "Received a malformed audio event from elevenlabs" });
|
|
66843
|
+
break;
|
|
66844
|
+
}
|
|
66845
|
+
if (!session.agentSpeaking) {
|
|
66846
|
+
session.agentSpeaking = true;
|
|
66847
|
+
callbacks.onPlaybackStart?.();
|
|
66848
|
+
}
|
|
66849
|
+
const pcm = session.outFormat.ulaw ? mulawToPcm16(chunk) : chunk;
|
|
66850
|
+
callbacks.onAudioOut(session.resamplerOut.push(pcm));
|
|
66851
|
+
break;
|
|
66852
|
+
}
|
|
66853
|
+
case "user_transcript": {
|
|
66854
|
+
flushAgent();
|
|
66855
|
+
const text = msg["user_transcription_event"]?.user_transcript;
|
|
66856
|
+
if (text)
|
|
66857
|
+
callbacks.onTurn({ role: "user", text, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
66858
|
+
break;
|
|
66287
66859
|
}
|
|
66288
|
-
|
|
66289
|
-
|
|
66290
|
-
|
|
66291
|
-
|
|
66292
|
-
|
|
66293
|
-
|
|
66860
|
+
case "agent_response": {
|
|
66861
|
+
if (hangingUp) {
|
|
66862
|
+
if (repliesAllowed <= 0) {
|
|
66863
|
+
muted = true;
|
|
66864
|
+
break;
|
|
66865
|
+
}
|
|
66866
|
+
repliesAllowed--;
|
|
66294
66867
|
}
|
|
66295
|
-
|
|
66296
|
-
|
|
66297
|
-
|
|
66298
|
-
});
|
|
66299
|
-
}
|
|
66300
|
-
if (msg["goAway"] !== void 0) {
|
|
66301
|
-
callbacks.onError({
|
|
66302
|
-
message: "Gemini Live sent goAway \u2014 session will close soon",
|
|
66303
|
-
raw: msg["goAway"]
|
|
66304
|
-
});
|
|
66868
|
+
flushAgent();
|
|
66869
|
+
session.pendingAgentText = msg["agent_response_event"]?.agent_response;
|
|
66870
|
+
break;
|
|
66305
66871
|
}
|
|
66306
|
-
|
|
66307
|
-
|
|
66308
|
-
|
|
66309
|
-
|
|
66310
|
-
|
|
66311
|
-
return;
|
|
66872
|
+
case "agent_response_correction": {
|
|
66873
|
+
const corrected = msg["agent_response_correction_event"]?.corrected_agent_response;
|
|
66874
|
+
if (corrected !== void 0)
|
|
66875
|
+
session.pendingAgentText = corrected;
|
|
66876
|
+
break;
|
|
66312
66877
|
}
|
|
66313
|
-
|
|
66314
|
-
|
|
66315
|
-
|
|
66316
|
-
|
|
66317
|
-
|
|
66318
|
-
if (
|
|
66319
|
-
|
|
66320
|
-
|
|
66321
|
-
|
|
66322
|
-
|
|
66323
|
-
|
|
66324
|
-
|
|
66878
|
+
case "agent_response_complete":
|
|
66879
|
+
stopPlayback(false);
|
|
66880
|
+
break;
|
|
66881
|
+
case "interruption": {
|
|
66882
|
+
const id = msg["interruption_event"]?.event_id;
|
|
66883
|
+
if (typeof id === "number")
|
|
66884
|
+
session.lastInterruptId = id;
|
|
66885
|
+
const wasSpeaking = session.agentSpeaking;
|
|
66886
|
+
stopPlayback(true);
|
|
66887
|
+
if (wasSpeaking)
|
|
66888
|
+
callbacks.onBargeIn();
|
|
66889
|
+
flushAgent();
|
|
66890
|
+
break;
|
|
66325
66891
|
}
|
|
66326
|
-
|
|
66327
|
-
|
|
66328
|
-
|
|
66329
|
-
|
|
66330
|
-
|
|
66331
|
-
if (!session.closingIntentionally)
|
|
66332
|
-
openSocket();
|
|
66333
|
-
}, delayMs);
|
|
66334
|
-
return;
|
|
66892
|
+
case "ping": {
|
|
66893
|
+
const id = msg["ping_event"]?.event_id;
|
|
66894
|
+
if (ws.readyState === ws.OPEN)
|
|
66895
|
+
ws.send(JSON.stringify({ type: "pong", event_id: id }));
|
|
66896
|
+
break;
|
|
66335
66897
|
}
|
|
66336
|
-
|
|
66337
|
-
|
|
66338
|
-
|
|
66898
|
+
case "client_tool_call": {
|
|
66899
|
+
const call = msg["client_tool_call"];
|
|
66900
|
+
if (!call)
|
|
66901
|
+
break;
|
|
66902
|
+
void dispatchToolCall5(call, tools, ctx, ws, callbacks, () => {
|
|
66903
|
+
hangingUp = true;
|
|
66904
|
+
repliesAllowed = session.agentSpeaking ? 0 : 1;
|
|
66905
|
+
}).catch((err) => {
|
|
66906
|
+
const s = sanitizeVendorError(err);
|
|
66907
|
+
callbacks.onError({ message: s.message, code: s.code, raw: s });
|
|
66908
|
+
});
|
|
66909
|
+
break;
|
|
66339
66910
|
}
|
|
66340
|
-
|
|
66911
|
+
case "client_error": {
|
|
66341
66912
|
callbacks.onError({
|
|
66342
|
-
message: "
|
|
66913
|
+
message: "elevenlabs agent error",
|
|
66914
|
+
raw: msg["error_event"] ?? msg
|
|
66343
66915
|
});
|
|
66916
|
+
settle2(() => reject(new Error("realtimeAgent: elevenlabs error before the session was ready")));
|
|
66917
|
+
closeAnyState(ws);
|
|
66918
|
+
break;
|
|
66344
66919
|
}
|
|
66345
|
-
|
|
66346
|
-
|
|
66347
|
-
|
|
66348
|
-
|
|
66349
|
-
|
|
66920
|
+
}
|
|
66921
|
+
});
|
|
66922
|
+
ws.on("error", (err) => {
|
|
66923
|
+
const s = sanitizeVendorError(err);
|
|
66924
|
+
if (!settled) {
|
|
66925
|
+
settle2(() => reject(new Error(s.message)));
|
|
66926
|
+
return;
|
|
66927
|
+
}
|
|
66928
|
+
callbacks.onError({ message: s.message, code: s.code, raw: s });
|
|
66929
|
+
});
|
|
66930
|
+
ws.on("close", () => {
|
|
66931
|
+
if (!settled) {
|
|
66932
|
+
settle2(() => reject(new Error("realtimeAgent: elevenlabs closed before the session was ready")));
|
|
66933
|
+
return;
|
|
66934
|
+
}
|
|
66935
|
+
flushAgent();
|
|
66936
|
+
callbacks.onClose();
|
|
66937
|
+
});
|
|
66350
66938
|
});
|
|
66351
66939
|
},
|
|
66352
66940
|
sendAudio(session, pcm) {
|
|
66353
66941
|
const s = session;
|
|
66354
|
-
if (!s.ready || s.ws.readyState !== s.ws.OPEN)
|
|
66355
|
-
if (!s.closingIntentionally && s.audioBufferBytes + pcm.length <= MAX_BUFFERED_AUDIO_BYTES) {
|
|
66356
|
-
s.audioBuffer.push(pcm);
|
|
66357
|
-
s.audioBufferBytes += pcm.length;
|
|
66358
|
-
}
|
|
66942
|
+
if (!s.ready || !s.resamplerIn || s.ws.readyState !== s.ws.OPEN)
|
|
66359
66943
|
return;
|
|
66360
|
-
|
|
66361
|
-
const
|
|
66362
|
-
s.ws.send(JSON.stringify({
|
|
66363
|
-
realtimeInput: {
|
|
66364
|
-
audio: { data: pcm16k.toString("base64"), mimeType: "audio/pcm;rate=16000" }
|
|
66365
|
-
}
|
|
66366
|
-
}));
|
|
66944
|
+
const out = s.resamplerIn.push(pcm);
|
|
66945
|
+
const bytes = s.inFormat.ulaw ? pcm16ToMulaw(out) : out;
|
|
66946
|
+
s.ws.send(JSON.stringify({ user_audio_chunk: bytes.toString("base64") }));
|
|
66367
66947
|
},
|
|
66368
|
-
|
|
66948
|
+
speak(session, text) {
|
|
66949
|
+
const s = session;
|
|
66950
|
+
if (s.ws.readyState !== s.ws.OPEN)
|
|
66951
|
+
return;
|
|
66952
|
+
s.ws.send(JSON.stringify({ type: "user_message", text: verbatimGreetingDirective(text) }));
|
|
66953
|
+
},
|
|
66954
|
+
clear(session) {
|
|
66955
|
+
session.agentSpeaking = false;
|
|
66369
66956
|
},
|
|
66370
66957
|
close(session) {
|
|
66371
|
-
|
|
66372
|
-
s.closingIntentionally = true;
|
|
66373
|
-
closeAnyState(s.ws);
|
|
66958
|
+
closeAnyState(session.ws);
|
|
66374
66959
|
}
|
|
66375
66960
|
};
|
|
66376
66961
|
}
|
|
66377
|
-
var
|
|
66962
|
+
var elevenlabsAdapter = createElevenLabsAdapter();
|
|
66378
66963
|
|
|
66379
66964
|
// ../runtime-shared/dist/ai/realtime/registry.js
|
|
66380
66965
|
var adapters = {
|
|
66381
66966
|
deepgram: deepgramAdapter,
|
|
66382
66967
|
openai: openaiAdapter,
|
|
66383
66968
|
grok: grokAdapter,
|
|
66384
|
-
gemini: geminiAdapter
|
|
66969
|
+
gemini: geminiAdapter,
|
|
66970
|
+
elevenlabs: elevenlabsAdapter
|
|
66385
66971
|
};
|
|
66386
66972
|
function getRealtimeAdapter(provider) {
|
|
66387
66973
|
const adapter2 = adapters[provider];
|
|
@@ -66869,6 +67455,59 @@ function audioMs(playbackStartAtIso, playbackEndAtIso) {
|
|
|
66869
67455
|
function logValue(ms) {
|
|
66870
67456
|
return ms ?? -1;
|
|
66871
67457
|
}
|
|
67458
|
+
function createPlayoutTracker(gapMs) {
|
|
67459
|
+
let cursorMs = 0;
|
|
67460
|
+
let speechEndMs = 0;
|
|
67461
|
+
const segments = [];
|
|
67462
|
+
return {
|
|
67463
|
+
/** Places one outbound frame (`durationMs` long) that arrived at `nowMs`. */
|
|
67464
|
+
push(nowMs, durationMs, isSpeech) {
|
|
67465
|
+
const startMs = Math.max(cursorMs, nowMs);
|
|
67466
|
+
cursorMs = startMs + durationMs;
|
|
67467
|
+
if (!isSpeech)
|
|
67468
|
+
return;
|
|
67469
|
+
speechEndMs = cursorMs;
|
|
67470
|
+
const last = segments[segments.length - 1];
|
|
67471
|
+
if (last && startMs - last.endMs <= gapMs) {
|
|
67472
|
+
last.endMs = cursorMs;
|
|
67473
|
+
last.lastArrivalMs = nowMs;
|
|
67474
|
+
} else {
|
|
67475
|
+
segments.push({ startMs, endMs: cursorMs, lastArrivalMs: nowMs });
|
|
67476
|
+
}
|
|
67477
|
+
},
|
|
67478
|
+
/** Wall time (ms since epoch) at which everything pushed so far has finished playing; `0` before any audio. */
|
|
67479
|
+
playsUntil() {
|
|
67480
|
+
return cursorMs;
|
|
67481
|
+
},
|
|
67482
|
+
/** Like `playsUntil`, but for speech only: the continuous silence a vendor streams between
|
|
67483
|
+
* replies does not extend it. `0` before any speech. */
|
|
67484
|
+
speechUntil() {
|
|
67485
|
+
return speechEndMs;
|
|
67486
|
+
},
|
|
67487
|
+
/** Barge-in: audio queued past `nowMs` will not play. */
|
|
67488
|
+
clear(nowMs) {
|
|
67489
|
+
cursorMs = Math.min(cursorMs, nowMs);
|
|
67490
|
+
speechEndMs = Math.min(speechEndMs, nowMs);
|
|
67491
|
+
const last = segments[segments.length - 1];
|
|
67492
|
+
if (last && last.endMs > nowMs)
|
|
67493
|
+
last.endMs = Math.max(last.startMs, nowMs);
|
|
67494
|
+
},
|
|
67495
|
+
/**
|
|
67496
|
+
* Removes and merges the runs whose last frame arrived by `uptoMs` (every run when
|
|
67497
|
+
* `uptoMs` is `Infinity`). `undefined` when there are none.
|
|
67498
|
+
*/
|
|
67499
|
+
take(uptoMs) {
|
|
67500
|
+
let startMs;
|
|
67501
|
+
let endMs = 0;
|
|
67502
|
+
while (segments.length > 0 && segments[0].lastArrivalMs <= uptoMs) {
|
|
67503
|
+
const seg = segments.shift();
|
|
67504
|
+
startMs ??= seg.startMs;
|
|
67505
|
+
endMs = seg.endMs;
|
|
67506
|
+
}
|
|
67507
|
+
return startMs === void 0 ? void 0 : { startMs, endMs };
|
|
67508
|
+
}
|
|
67509
|
+
};
|
|
67510
|
+
}
|
|
66872
67511
|
|
|
66873
67512
|
// ../runtime-shared/dist/ai/realtime/adapters/relay.js
|
|
66874
67513
|
var DEFAULT_MAX_CALL_DURATION = 1800;
|
|
@@ -66947,6 +67586,7 @@ function createRelayAgent(options) {
|
|
|
66947
67586
|
setup: relay2.setup,
|
|
66948
67587
|
voiceWebhook: onCall({ incoming: connect, completed: handleCallCompleted }),
|
|
66949
67588
|
connect,
|
|
67589
|
+
call: () => Promise.reject(new Error("realtimeAgent.call() does not support provider 'voice-relay' yet.")),
|
|
66950
67590
|
endpointFor: relay2.endpointFor
|
|
66951
67591
|
};
|
|
66952
67592
|
}
|
|
@@ -67205,55 +67845,103 @@ function attach(options, pendingByCallId, transferredCallIds, call) {
|
|
|
67205
67845
|
});
|
|
67206
67846
|
}
|
|
67207
67847
|
|
|
67208
|
-
// ../runtime-shared/dist/ai/realtime/
|
|
67209
|
-
|
|
67210
|
-
|
|
67211
|
-
|
|
67212
|
-
|
|
67213
|
-
|
|
67214
|
-
|
|
67215
|
-
|
|
67216
|
-
|
|
67217
|
-
|
|
67218
|
-
|
|
67219
|
-
|
|
67848
|
+
// ../runtime-shared/dist/ai/realtime/recording.js
|
|
67849
|
+
function encodeStereoWav(left, right, sampleRate) {
|
|
67850
|
+
const frames = Math.max(left.length, right.length) >> 1;
|
|
67851
|
+
const dataBytes = frames * 4;
|
|
67852
|
+
const wav = Buffer.alloc(44 + dataBytes);
|
|
67853
|
+
wav.write("RIFF", 0, "ascii");
|
|
67854
|
+
wav.writeUInt32LE(36 + dataBytes, 4);
|
|
67855
|
+
wav.write("WAVEfmt ", 8, "ascii");
|
|
67856
|
+
wav.writeUInt32LE(16, 16);
|
|
67857
|
+
wav.writeUInt16LE(1, 20);
|
|
67858
|
+
wav.writeUInt16LE(2, 22);
|
|
67859
|
+
wav.writeUInt32LE(sampleRate, 24);
|
|
67860
|
+
wav.writeUInt32LE(sampleRate * 4, 28);
|
|
67861
|
+
wav.writeUInt16LE(4, 32);
|
|
67862
|
+
wav.writeUInt16LE(16, 34);
|
|
67863
|
+
wav.write("data", 36, "ascii");
|
|
67864
|
+
wav.writeUInt32LE(dataBytes, 40);
|
|
67865
|
+
const leftSamples = left.length >> 1;
|
|
67866
|
+
const rightSamples = right.length >> 1;
|
|
67867
|
+
for (let i = 0; i < frames; i++) {
|
|
67868
|
+
if (i < leftSamples)
|
|
67869
|
+
wav.writeInt16LE(left.readInt16LE(i * 2), 44 + i * 4);
|
|
67870
|
+
if (i < rightSamples)
|
|
67871
|
+
wav.writeInt16LE(right.readInt16LE(i * 2), 46 + i * 4);
|
|
67872
|
+
}
|
|
67873
|
+
return wav;
|
|
67874
|
+
}
|
|
67875
|
+
var Channel = class {
|
|
67876
|
+
maxSamples;
|
|
67877
|
+
chunks = [];
|
|
67878
|
+
/** Samples written so far, silence included. */
|
|
67879
|
+
samples = 0;
|
|
67880
|
+
constructor(maxSamples) {
|
|
67881
|
+
this.maxSamples = maxSamples;
|
|
67882
|
+
}
|
|
67883
|
+
/** Appends `pcm` no earlier than sample `at`; returns false once the cap is reached. */
|
|
67884
|
+
push(pcm, at) {
|
|
67885
|
+
const start = Math.max(this.samples, at);
|
|
67886
|
+
pcm = pcm.subarray(0, pcm.length & ~1);
|
|
67887
|
+
const incoming = pcm.length >> 1;
|
|
67888
|
+
if (start + incoming > this.maxSamples)
|
|
67889
|
+
return false;
|
|
67890
|
+
if (start > this.samples)
|
|
67891
|
+
this.chunks.push(Buffer.alloc((start - this.samples) * 2));
|
|
67892
|
+
this.chunks.push(pcm);
|
|
67893
|
+
this.samples = start + incoming;
|
|
67894
|
+
return true;
|
|
67220
67895
|
}
|
|
67221
|
-
|
|
67222
|
-
|
|
67223
|
-
|
|
67224
|
-
|
|
67225
|
-
|
|
67226
|
-
|
|
67227
|
-
|
|
67228
|
-
|
|
67229
|
-
|
|
67896
|
+
/** Drops everything past sample `at` — audio queued but not yet played. */
|
|
67897
|
+
truncate(at) {
|
|
67898
|
+
if (this.samples <= at)
|
|
67899
|
+
return;
|
|
67900
|
+
const all3 = Buffer.concat(this.chunks);
|
|
67901
|
+
this.chunks = [all3.subarray(0, at * 2)];
|
|
67902
|
+
this.samples = at;
|
|
67903
|
+
}
|
|
67904
|
+
toBuffer() {
|
|
67905
|
+
return Buffer.concat(this.chunks);
|
|
67906
|
+
}
|
|
67907
|
+
};
|
|
67908
|
+
function createStereoRecorder(sampleRate, maxSeconds) {
|
|
67909
|
+
const startMs = Date.now();
|
|
67910
|
+
const maxSamples = Math.floor(sampleRate * maxSeconds);
|
|
67911
|
+
const caller = new Channel(maxSamples);
|
|
67912
|
+
const agent = new Channel(maxSamples);
|
|
67913
|
+
let truncated = false;
|
|
67914
|
+
const sampleAt = (nowMs) => Math.max(0, Math.floor((nowMs - startMs) * sampleRate / 1e3));
|
|
67230
67915
|
return {
|
|
67231
|
-
get
|
|
67232
|
-
return
|
|
67916
|
+
get truncated() {
|
|
67917
|
+
return truncated;
|
|
67233
67918
|
},
|
|
67234
|
-
|
|
67235
|
-
|
|
67236
|
-
|
|
67237
|
-
|
|
67238
|
-
|
|
67239
|
-
|
|
67240
|
-
|
|
67241
|
-
|
|
67242
|
-
|
|
67243
|
-
|
|
67244
|
-
|
|
67245
|
-
|
|
67246
|
-
}
|
|
67247
|
-
if (speaking && !loud && quietRun >= hangoverFrames) {
|
|
67248
|
-
speaking = false;
|
|
67249
|
-
return "end";
|
|
67250
|
-
}
|
|
67251
|
-
return void 0;
|
|
67252
|
-
}
|
|
67919
|
+
pushCaller(pcm, nowMs = Date.now()) {
|
|
67920
|
+
if (!caller.push(pcm, sampleAt(nowMs)))
|
|
67921
|
+
truncated = true;
|
|
67922
|
+
},
|
|
67923
|
+
pushAgent(pcm, nowMs = Date.now()) {
|
|
67924
|
+
if (!agent.push(pcm, sampleAt(nowMs)))
|
|
67925
|
+
truncated = true;
|
|
67926
|
+
},
|
|
67927
|
+
clearAgent(nowMs = Date.now()) {
|
|
67928
|
+
agent.truncate(sampleAt(nowMs));
|
|
67929
|
+
},
|
|
67930
|
+
toWav: () => encodeStereoWav(caller.toBuffer(), agent.toBuffer(), sampleRate)
|
|
67253
67931
|
};
|
|
67254
67932
|
}
|
|
67255
67933
|
|
|
67256
67934
|
// ../runtime-shared/dist/ai/realtime/agent.js
|
|
67935
|
+
function recordsStream(record) {
|
|
67936
|
+
return record === true || typeof record === "object" && record.stream === true;
|
|
67937
|
+
}
|
|
67938
|
+
function recordsViaSinch(record) {
|
|
67939
|
+
return typeof record === "object" && record.sinch === true;
|
|
67940
|
+
}
|
|
67941
|
+
var DEFAULT_OUTBOUND_GREETING_FALLBACK_MS = 4e3;
|
|
67942
|
+
var MAX_EARLY_AUDIO_MS = 5e3;
|
|
67943
|
+
var PLACED_CALL_TTL_MS = 2 * 60 * 60 * 1e3;
|
|
67944
|
+
var MAX_PLACED_CALLS = 1e3;
|
|
67257
67945
|
var BRIDGE = "bridge";
|
|
67258
67946
|
var CALLER_LEG2 = "caller";
|
|
67259
67947
|
var STREAM_LEG2 = "stream";
|
|
@@ -67264,7 +67952,11 @@ function sendStreamControl(ws, command) {
|
|
|
67264
67952
|
if (ws.readyState === ws.OPEN)
|
|
67265
67953
|
ws.send(JSON.stringify({ command }));
|
|
67266
67954
|
}
|
|
67267
|
-
var
|
|
67955
|
+
var HANGUP_MIN_WAIT_MS = 2e3;
|
|
67956
|
+
var HANGUP_PLAYOUT_MARGIN_MS = 400;
|
|
67957
|
+
var HANGUP_MAX_WAIT_MS = 2e4;
|
|
67958
|
+
var HANGUP_POLL_MS = 100;
|
|
67959
|
+
var PLAYOUT_GAP_MS = 1500;
|
|
67268
67960
|
var HEARTBEAT_INTERVAL_MS = 2e4;
|
|
67269
67961
|
var PENDING_SESSION_TTL_MS = 3e4;
|
|
67270
67962
|
var MAX_PENDING_SESSIONS = 1e3;
|
|
@@ -67274,22 +67966,23 @@ function resolveMaxDuration(context) {
|
|
|
67274
67966
|
}
|
|
67275
67967
|
var FIRST_FRAME_DEADLINE_MS = 2e3;
|
|
67276
67968
|
var MAX_UNAUTHENTICATED_SOCKETS2 = 32;
|
|
67277
|
-
async function resolvePerCallOptions(options, call, context, ctx) {
|
|
67969
|
+
async function resolvePerCallOptions(options, call, context, ctx, data, provider = options.provider) {
|
|
67278
67970
|
const [prompt, greeting, voice, transferTo, language] = await Promise.all([
|
|
67279
|
-
resolvePerCallValue(options.prompt, call, context),
|
|
67280
|
-
resolvePerCallValue(options.greeting, call, context),
|
|
67281
|
-
resolvePerCallValue(options.voice, call, context),
|
|
67282
|
-
resolvePerCallValue(options.transferTo, call, context),
|
|
67283
|
-
resolvePerCallValue(options.language, call, context)
|
|
67971
|
+
resolvePerCallValue(options.prompt, call, context, data),
|
|
67972
|
+
resolvePerCallValue(options.greeting, call, context, data),
|
|
67973
|
+
resolvePerCallValue(options.voice, call, context, data),
|
|
67974
|
+
resolvePerCallValue(options.transferTo, call, context, data),
|
|
67975
|
+
resolvePerCallValue(options.language, call, context, data)
|
|
67284
67976
|
]);
|
|
67285
67977
|
const { transferTo: _transferTo, tools: authorTools, ...rest } = options;
|
|
67286
67978
|
const tools = mergeTools(authorTools ?? [], builtInTools(options.hangup ?? true, nonBlank(transferTo), ctx));
|
|
67287
67979
|
let resolvedPrompt = currentDateTimePreamble(options.timezone) + prompt;
|
|
67288
67980
|
if (offersHangup(tools)) {
|
|
67289
|
-
resolvedPrompt +=
|
|
67981
|
+
resolvedPrompt += provider === "openai" ? DELEGATED_CALL_TERMINATION_INSTRUCTIONS : CALL_TERMINATION_INSTRUCTIONS;
|
|
67290
67982
|
}
|
|
67291
67983
|
return {
|
|
67292
67984
|
...rest,
|
|
67985
|
+
provider,
|
|
67293
67986
|
prompt: resolvedPrompt,
|
|
67294
67987
|
greeting,
|
|
67295
67988
|
voice,
|
|
@@ -67307,10 +68000,11 @@ function realtimeAgent(options) {
|
|
|
67307
68000
|
if (options.provider === "voice-relay") {
|
|
67308
68001
|
return createRelayAgent(options);
|
|
67309
68002
|
}
|
|
67310
|
-
const
|
|
68003
|
+
const defaultAdapter = getRealtimeAdapter(options.provider);
|
|
67311
68004
|
let savedContext;
|
|
67312
68005
|
const pendingSessions = /* @__PURE__ */ new Map();
|
|
67313
68006
|
const transferredCallIds = /* @__PURE__ */ new Set();
|
|
68007
|
+
const liveSessions = /* @__PURE__ */ new Map();
|
|
67314
68008
|
function deletePendingSession(token) {
|
|
67315
68009
|
const session = pendingSessions.get(token);
|
|
67316
68010
|
if (!session)
|
|
@@ -67344,10 +68038,12 @@ function realtimeAgent(options) {
|
|
|
67344
68038
|
const req = rawReq;
|
|
67345
68039
|
const headerToken = upgradeHeader(req, AGENT_HEADER_TOKEN);
|
|
67346
68040
|
const startSession = (pending, connectMsg) => {
|
|
67347
|
-
const
|
|
68041
|
+
const call2 = pending.call;
|
|
67348
68042
|
const context = pending.requestContext;
|
|
67349
68043
|
const config = createUniversalConfig(context);
|
|
67350
|
-
const callId = String(
|
|
68044
|
+
const callId = String(call2.callId ?? "");
|
|
68045
|
+
const provider = pending.provider ?? options.provider;
|
|
68046
|
+
const adapter2 = pending.provider ? getRealtimeAdapter(pending.provider) : defaultAdapter;
|
|
67351
68047
|
const expectedRate = AUDIO_SAMPLE_RATES[options.audio ?? "telephony"];
|
|
67352
68048
|
const reportedRate = connectMsg["sampleRate"];
|
|
67353
68049
|
if (reportedRate !== void 0 && reportedRate !== expectedRate) {
|
|
@@ -67360,15 +68056,20 @@ function realtimeAgent(options) {
|
|
|
67360
68056
|
let ended = false;
|
|
67361
68057
|
let transferred = false;
|
|
67362
68058
|
let heartbeat;
|
|
68059
|
+
let greetingTimer;
|
|
68060
|
+
let hangupTimer;
|
|
68061
|
+
let lastSpeechOutAt = 0;
|
|
67363
68062
|
const lifecycle = new AbortController();
|
|
67364
68063
|
const transcript = [];
|
|
67365
68064
|
const usage = {};
|
|
67366
68065
|
const callConnectedAtMs = Date.now();
|
|
67367
68066
|
let lastUserTurnAt;
|
|
67368
68067
|
let firstAudioAtMs;
|
|
67369
|
-
|
|
68068
|
+
const playout = createPlayoutTracker(PLAYOUT_GAP_MS);
|
|
68069
|
+
const untimedAgentEntries = [];
|
|
67370
68070
|
let bytesPerMs = 8e3 * 2 / 1e3;
|
|
67371
68071
|
const vad = createEnergyVad();
|
|
68072
|
+
const recorder = recordsStream(options.record) ? createStereoRecorder(expectedRate, resolveMaxDuration(context)) : void 0;
|
|
67372
68073
|
let pendingSpeechStartAt;
|
|
67373
68074
|
let pendingSpeechEndAt;
|
|
67374
68075
|
let speechEndFromProvider = false;
|
|
@@ -67381,16 +68082,20 @@ function realtimeAgent(options) {
|
|
|
67381
68082
|
return `[realtimeAgent] turn latency totalMs=${logValue(totalMs)} playbackDelayMs=${logValue(delay)} audioMs=${logValue(audio)} delegationMs=${logValue(entry.delegationMs)}`;
|
|
67382
68083
|
};
|
|
67383
68084
|
const applySelfPlaybackFallback = (entry, cutShort) => {
|
|
67384
|
-
|
|
68085
|
+
const played = playout.take(cutShort ? Infinity : Date.parse(entry.timestamp));
|
|
68086
|
+
if (!played)
|
|
67385
68087
|
return;
|
|
67386
|
-
entry.playbackStartAt ??= new Date(
|
|
68088
|
+
entry.playbackStartAt ??= new Date(played.startMs).toISOString();
|
|
67387
68089
|
if (entry.playbackEndAt === void 0) {
|
|
67388
|
-
|
|
67389
|
-
entry.playbackEndAt = new Date(endMs).toISOString();
|
|
68090
|
+
entry.playbackEndAt = new Date(played.endMs).toISOString();
|
|
67390
68091
|
if (cutShort)
|
|
67391
68092
|
entry.interrupted = true;
|
|
67392
68093
|
}
|
|
67393
68094
|
};
|
|
68095
|
+
const timeUntimedAgentEntries = () => {
|
|
68096
|
+
for (const entry of untimedAgentEntries.splice(0))
|
|
68097
|
+
applySelfPlaybackFallback(entry, false);
|
|
68098
|
+
};
|
|
67394
68099
|
const flushPendingStreamLog = () => {
|
|
67395
68100
|
if (!pendingStreamLog)
|
|
67396
68101
|
return;
|
|
@@ -67408,10 +68113,22 @@ function realtimeAgent(options) {
|
|
|
67408
68113
|
transcript,
|
|
67409
68114
|
usage,
|
|
67410
68115
|
hangup() {
|
|
67411
|
-
|
|
67412
|
-
|
|
67413
|
-
|
|
67414
|
-
|
|
68116
|
+
if (hangupTimer !== void 0 || ended)
|
|
68117
|
+
return;
|
|
68118
|
+
const startedAt = Date.now();
|
|
68119
|
+
const check = () => {
|
|
68120
|
+
const now = Date.now();
|
|
68121
|
+
const elapsed = now - startedAt;
|
|
68122
|
+
const settled = now >= playout.speechUntil() + HANGUP_PLAYOUT_MARGIN_MS && now - lastSpeechOutAt >= HANGUP_PLAYOUT_MARGIN_MS;
|
|
68123
|
+
if (elapsed >= HANGUP_MIN_WAIT_MS && settled || elapsed >= HANGUP_MAX_WAIT_MS) {
|
|
68124
|
+
hangupTimer = void 0;
|
|
68125
|
+
if (ws.readyState === ws.OPEN)
|
|
68126
|
+
ws.close();
|
|
68127
|
+
return;
|
|
68128
|
+
}
|
|
68129
|
+
hangupTimer = setTimeout(check, HANGUP_POLL_MS);
|
|
68130
|
+
};
|
|
68131
|
+
hangupTimer = setTimeout(check, HANGUP_MIN_WAIT_MS);
|
|
67415
68132
|
},
|
|
67416
68133
|
async transfer(number) {
|
|
67417
68134
|
if (!E1642.test(number)) {
|
|
@@ -67420,7 +68137,7 @@ function realtimeAgent(options) {
|
|
|
67420
68137
|
await context.voice.transferToPhone(callId, number, {
|
|
67421
68138
|
liveLeg: CALLER_LEG2,
|
|
67422
68139
|
legName: TRANSFER_LEG2,
|
|
67423
|
-
call: { call }
|
|
68140
|
+
call: { call: call2 }
|
|
67424
68141
|
});
|
|
67425
68142
|
transferred = true;
|
|
67426
68143
|
if (callId)
|
|
@@ -67439,9 +68156,17 @@ function realtimeAgent(options) {
|
|
|
67439
68156
|
return;
|
|
67440
68157
|
ended = true;
|
|
67441
68158
|
flushPendingStreamLog();
|
|
68159
|
+
timeUntimedAgentEntries();
|
|
67442
68160
|
lifecycle.abort();
|
|
67443
68161
|
if (heartbeat !== void 0)
|
|
67444
68162
|
clearInterval(heartbeat);
|
|
68163
|
+
clearTimeout(greetingTimer);
|
|
68164
|
+
clearTimeout(hangupTimer);
|
|
68165
|
+
hangupTimer = void 0;
|
|
68166
|
+
for (const key of sessionKeys) {
|
|
68167
|
+
if (liveSessions.get(key) === closeLive)
|
|
68168
|
+
liveSessions.delete(key);
|
|
68169
|
+
}
|
|
67445
68170
|
if (vendorSession !== void 0)
|
|
67446
68171
|
adapter2.close(vendorSession);
|
|
67447
68172
|
if (ws.readyState === ws.OPEN)
|
|
@@ -67451,18 +68176,44 @@ function realtimeAgent(options) {
|
|
|
67451
68176
|
}
|
|
67452
68177
|
usage.audioSeconds ??= (Date.now() - callConnectedAtMs) / 1e3;
|
|
67453
68178
|
console.log(`[realtimeAgent] call usage inputTokens=${logValue(usage.inputTokens)} outputTokens=${logValue(usage.outputTokens)} audioSeconds=${logValue(usage.audioSeconds)}`);
|
|
68179
|
+
if (recorder) {
|
|
68180
|
+
const storageKey = recordingKey(callId, "wav");
|
|
68181
|
+
try {
|
|
68182
|
+
await context.storage.write(storageKey, recorder.toWav());
|
|
68183
|
+
ctx.recording = { storageKey };
|
|
68184
|
+
if (recorder.truncated) {
|
|
68185
|
+
console.warn(`[realtimeAgent] recording hit its ${resolveMaxDuration(context)}s cap and was cut short`);
|
|
68186
|
+
}
|
|
68187
|
+
} catch (err) {
|
|
68188
|
+
console.error("[realtimeAgent] saving the recording failed:", err.message);
|
|
68189
|
+
}
|
|
68190
|
+
}
|
|
67454
68191
|
try {
|
|
67455
68192
|
await options.onEnd?.(ctx);
|
|
67456
68193
|
} catch (err) {
|
|
67457
68194
|
console.error("[realtimeAgent] onEnd handler threw:", err.message);
|
|
67458
68195
|
}
|
|
67459
68196
|
};
|
|
68197
|
+
const closeLive = () => {
|
|
68198
|
+
if (transferred)
|
|
68199
|
+
return;
|
|
68200
|
+
if (ws.readyState === ws.OPEN)
|
|
68201
|
+
ws.close();
|
|
68202
|
+
void end();
|
|
68203
|
+
};
|
|
68204
|
+
const sessionKeys = [callId, String(call2.sessionId ?? "")].filter((k) => k !== "");
|
|
68205
|
+
for (const key of sessionKeys)
|
|
68206
|
+
liveSessions.set(key, closeLive);
|
|
67460
68207
|
const callbacks = {
|
|
67461
68208
|
onAudioOut(pcm) {
|
|
67462
68209
|
if (firstAudioAtMs === void 0 && lastUserTurnAt !== void 0)
|
|
67463
68210
|
firstAudioAtMs = Date.now();
|
|
67464
|
-
|
|
67465
|
-
|
|
68211
|
+
const nowMs = Date.now();
|
|
68212
|
+
const speech = isSpeechFrame(pcm);
|
|
68213
|
+
if (speech)
|
|
68214
|
+
lastSpeechOutAt = nowMs;
|
|
68215
|
+
playout.push(nowMs, pcm.length / bytesPerMs, speech);
|
|
68216
|
+
recorder?.pushAgent(pcm);
|
|
67466
68217
|
if (ws.readyState === ws.OPEN)
|
|
67467
68218
|
ws.send(pcm);
|
|
67468
68219
|
},
|
|
@@ -67486,10 +68237,11 @@ function realtimeAgent(options) {
|
|
|
67486
68237
|
};
|
|
67487
68238
|
if (turn.role === "user") {
|
|
67488
68239
|
flushPendingStreamLog();
|
|
68240
|
+
timeUntimedAgentEntries();
|
|
67489
68241
|
lastUserTurnAt = Date.now();
|
|
67490
68242
|
firstAudioAtMs = void 0;
|
|
67491
|
-
entry.speechStartAt =
|
|
67492
|
-
entry.speechEndAt =
|
|
68243
|
+
entry.speechStartAt = pendingSpeechStartAt;
|
|
68244
|
+
entry.speechEndAt = pendingSpeechEndAt;
|
|
67493
68245
|
pendingSpeechStartAt = void 0;
|
|
67494
68246
|
pendingSpeechEndAt = void 0;
|
|
67495
68247
|
speechEndFromProvider = false;
|
|
@@ -67497,10 +68249,8 @@ function realtimeAgent(options) {
|
|
|
67497
68249
|
entry.totalMs = Date.now() - lastUserTurnAt;
|
|
67498
68250
|
lastUserTurnAt = void 0;
|
|
67499
68251
|
entry.delegationMs = turn.delegationMs;
|
|
67500
|
-
entry.playbackStartAt =
|
|
67501
|
-
if (
|
|
67502
|
-
entry.playbackEndAt = turn.playbackEndAt;
|
|
67503
|
-
} else if (pendingAgentPlayback.endAt) {
|
|
68252
|
+
entry.playbackStartAt = pendingAgentPlayback.startAt;
|
|
68253
|
+
if (pendingAgentPlayback.endAt) {
|
|
67504
68254
|
entry.playbackEndAt = pendingAgentPlayback.endAt;
|
|
67505
68255
|
if (pendingAgentPlayback.interrupted)
|
|
67506
68256
|
entry.interrupted = true;
|
|
@@ -67513,7 +68263,8 @@ function realtimeAgent(options) {
|
|
|
67513
68263
|
currentAgentEntry = entry;
|
|
67514
68264
|
pendingStreamLog = { entry, totalMs: entry.totalMs, firstAudioAtMs };
|
|
67515
68265
|
}
|
|
67516
|
-
}
|
|
68266
|
+
} else if (turn.role === "agent")
|
|
68267
|
+
untimedAgentEntries.push(entry);
|
|
67517
68268
|
appendTranscript(entry);
|
|
67518
68269
|
},
|
|
67519
68270
|
onSpeechStart() {
|
|
@@ -67545,8 +68296,10 @@ function realtimeAgent(options) {
|
|
|
67545
68296
|
},
|
|
67546
68297
|
onBargeIn() {
|
|
67547
68298
|
sendStreamControl(ws, "clear");
|
|
68299
|
+
recorder?.clearAgent();
|
|
67548
68300
|
if (vendorSession !== void 0)
|
|
67549
68301
|
adapter2.clear(vendorSession);
|
|
68302
|
+
playout.clear(Date.now());
|
|
67550
68303
|
if (currentAgentEntry) {
|
|
67551
68304
|
applySelfPlaybackFallback(currentAgentEntry, true);
|
|
67552
68305
|
flushPendingStreamLog();
|
|
@@ -67567,10 +68320,53 @@ function realtimeAgent(options) {
|
|
|
67567
68320
|
void end();
|
|
67568
68321
|
}
|
|
67569
68322
|
};
|
|
67570
|
-
|
|
68323
|
+
const answeredEarly = pending.outbound;
|
|
68324
|
+
if (answeredEarly) {
|
|
68325
|
+
ws.send(JSON.stringify({ command: "answer" }));
|
|
68326
|
+
heartbeat = setInterval(() => sendStreamControl(ws, "heartbeat"), HEARTBEAT_INTERVAL_MS);
|
|
68327
|
+
}
|
|
68328
|
+
const earlyAudio = [];
|
|
68329
|
+
let earlyBytes = 0;
|
|
68330
|
+
let greetingText;
|
|
68331
|
+
let calleeSpoke = false;
|
|
68332
|
+
const sendGreeting2 = () => {
|
|
68333
|
+
if (greetingText === void 0 || vendorSession === void 0)
|
|
68334
|
+
return;
|
|
68335
|
+
const text = greetingText;
|
|
68336
|
+
greetingText = void 0;
|
|
68337
|
+
clearTimeout(greetingTimer);
|
|
68338
|
+
adapter2.speak(vendorSession, text);
|
|
68339
|
+
};
|
|
68340
|
+
ws.on("message", (raw, isBinary) => {
|
|
68341
|
+
if (!isBinary)
|
|
68342
|
+
return;
|
|
68343
|
+
recorder?.pushCaller(raw);
|
|
68344
|
+
const vadEvent = vad.push(raw);
|
|
68345
|
+
if (vadEvent === "start") {
|
|
68346
|
+
pendingSpeechStartAt ??= (/* @__PURE__ */ new Date()).toISOString();
|
|
68347
|
+
calleeSpoke = true;
|
|
68348
|
+
sendGreeting2();
|
|
68349
|
+
} else if (vadEvent === "end" && !speechEndFromProvider) {
|
|
68350
|
+
pendingSpeechEndAt = new Date(Date.now() - vad.quietFrames * raw.length / bytesPerMs).toISOString();
|
|
68351
|
+
}
|
|
68352
|
+
if (vendorSession !== void 0) {
|
|
68353
|
+
adapter2.sendAudio(vendorSession, raw);
|
|
68354
|
+
return;
|
|
68355
|
+
}
|
|
68356
|
+
earlyAudio.push(raw);
|
|
68357
|
+
earlyBytes += raw.length;
|
|
68358
|
+
while (earlyBytes > MAX_EARLY_AUDIO_MS * bytesPerMs && earlyAudio.length > 1) {
|
|
68359
|
+
earlyBytes -= earlyAudio.shift().length;
|
|
68360
|
+
}
|
|
68361
|
+
});
|
|
68362
|
+
resolvePerCallOptions(options, call2, context, ctx, pending.data, provider).then((resolved) => {
|
|
67571
68363
|
if (ended || lifecycle.signal.aborted)
|
|
67572
68364
|
return void 0;
|
|
67573
68365
|
bytesPerMs = sinchRate(resolved) * 2 / 1e3;
|
|
68366
|
+
if (pending.outbound && resolved.greeting && adapter2.speak) {
|
|
68367
|
+
greetingText = resolved.greeting;
|
|
68368
|
+
return adapter2.connect({ ...resolved, greeting: void 0, greetingHeld: true }, ctx, callbacks, lifecycle.signal);
|
|
68369
|
+
}
|
|
67574
68370
|
return adapter2.connect(resolved, ctx, callbacks, lifecycle.signal);
|
|
67575
68371
|
}).then((session) => {
|
|
67576
68372
|
if (session === void 0)
|
|
@@ -67580,25 +68376,26 @@ function realtimeAgent(options) {
|
|
|
67580
68376
|
return;
|
|
67581
68377
|
}
|
|
67582
68378
|
vendorSession = session;
|
|
67583
|
-
|
|
67584
|
-
|
|
67585
|
-
|
|
67586
|
-
|
|
67587
|
-
|
|
67588
|
-
|
|
67589
|
-
if (
|
|
67590
|
-
|
|
67591
|
-
else
|
|
67592
|
-
|
|
67593
|
-
|
|
67594
|
-
}
|
|
68379
|
+
if (!answeredEarly)
|
|
68380
|
+
ws.send(JSON.stringify({ command: "answer" }));
|
|
68381
|
+
heartbeat ??= setInterval(() => sendStreamControl(ws, "heartbeat"), HEARTBEAT_INTERVAL_MS);
|
|
68382
|
+
for (const frame of earlyAudio.splice(0))
|
|
68383
|
+
adapter2.sendAudio(session, frame);
|
|
68384
|
+
if (greetingText !== void 0) {
|
|
68385
|
+
if (calleeSpoke)
|
|
68386
|
+
sendGreeting2();
|
|
68387
|
+
else {
|
|
68388
|
+
greetingTimer = setTimeout(sendGreeting2, options.outboundGreetingFallbackMs ?? DEFAULT_OUTBOUND_GREETING_FALLBACK_MS);
|
|
68389
|
+
}
|
|
68390
|
+
}
|
|
67595
68391
|
}).catch((err) => {
|
|
67596
68392
|
if (ended)
|
|
67597
68393
|
return;
|
|
67598
68394
|
const sanitized = sanitizeVendorError(err);
|
|
67599
68395
|
console.error("[realtimeAgent] adapter connect failed:", sanitized.message);
|
|
67600
68396
|
invokeHook("onError", () => options.onError?.({ message: sanitized.message, code: sanitized.code, raw: sanitized }, ctx));
|
|
67601
|
-
|
|
68397
|
+
if (!answeredEarly)
|
|
68398
|
+
ws.send(JSON.stringify({ command: "reject" }));
|
|
67602
68399
|
if (ws.readyState === ws.OPEN)
|
|
67603
68400
|
ws.close(1011, "Vendor connect failed");
|
|
67604
68401
|
});
|
|
@@ -67677,13 +68474,17 @@ function realtimeAgent(options) {
|
|
|
67677
68474
|
}
|
|
67678
68475
|
const endpointFor = (event, clientContext) => {
|
|
67679
68476
|
const context = clientContext;
|
|
67680
|
-
const
|
|
67681
|
-
const callId = String(
|
|
68477
|
+
const call2 = event.call;
|
|
68478
|
+
const callId = String(call2?.callId ?? "");
|
|
67682
68479
|
const token = randomUUID2();
|
|
68480
|
+
const placed = placedCalls.get(String(call2?.sessionId ?? ""));
|
|
67683
68481
|
if (callId) {
|
|
67684
68482
|
pendingSessions.set(token, {
|
|
67685
|
-
call,
|
|
68483
|
+
call: call2,
|
|
67686
68484
|
requestContext: context,
|
|
68485
|
+
outbound: placed !== void 0,
|
|
68486
|
+
data: placed?.data,
|
|
68487
|
+
provider: placed?.provider,
|
|
67687
68488
|
expiresAt: Date.now() + PENDING_SESSION_TTL_MS,
|
|
67688
68489
|
expiryTimer: schedulePendingSessionExpiry(token)
|
|
67689
68490
|
});
|
|
@@ -67705,11 +68506,23 @@ function realtimeAgent(options) {
|
|
|
67705
68506
|
}
|
|
67706
68507
|
return streamEndpoint;
|
|
67707
68508
|
};
|
|
67708
|
-
const
|
|
67709
|
-
|
|
68509
|
+
const placedCalls = /* @__PURE__ */ new Map();
|
|
68510
|
+
function rememberPlacedCall(sessionId, data, provider) {
|
|
68511
|
+
const now = Date.now();
|
|
68512
|
+
for (const [id, placed] of placedCalls) {
|
|
68513
|
+
if (placed.expiresAt <= now || placedCalls.size > MAX_PLACED_CALLS)
|
|
68514
|
+
placedCalls.delete(id);
|
|
68515
|
+
}
|
|
68516
|
+
placedCalls.set(sessionId, { data, provider, expiresAt: now + PLACED_CALL_TTL_MS });
|
|
68517
|
+
}
|
|
68518
|
+
const plan = (call2, context, inbound) => {
|
|
68519
|
+
const streamEndpoint = endpointFor(toWebhookRequest(call2), context);
|
|
68520
|
+
const builder = inbound ? commands().answer() : commands();
|
|
68521
|
+
if (recordsViaSinch(options.record))
|
|
68522
|
+
builder.recordToFunctions();
|
|
67710
68523
|
return {
|
|
67711
|
-
callName: CALLER_LEG2,
|
|
67712
|
-
commands:
|
|
68524
|
+
...inbound && { callName: CALLER_LEG2 },
|
|
68525
|
+
commands: builder.bridgeCall(BRIDGE).dial(streamEndpoint, {
|
|
67713
68526
|
callName: STREAM_LEG2,
|
|
67714
68527
|
maxDuration: resolveMaxDuration(context),
|
|
67715
68528
|
onAnswer: (c) => c.bridgeCall(BRIDGE),
|
|
@@ -67723,9 +68536,26 @@ function realtimeAgent(options) {
|
|
|
67723
68536
|
onHangup: [{ command: "hangup", callName: STREAM_LEG2 }]
|
|
67724
68537
|
};
|
|
67725
68538
|
};
|
|
67726
|
-
const
|
|
67727
|
-
|
|
68539
|
+
const connect = (call2, _builder, context) => plan(call2, context, true);
|
|
68540
|
+
const handleAnswered = (call2, _builder, context) => {
|
|
68541
|
+
const placed = placedCalls.get(String(call2.sessionId ?? ""));
|
|
68542
|
+
if (!placed || placed.answered)
|
|
68543
|
+
return void 0;
|
|
68544
|
+
placed.answered = true;
|
|
68545
|
+
return plan(call2, context, false);
|
|
68546
|
+
};
|
|
68547
|
+
const handleCallCompleted = (call2, _builder, context) => {
|
|
68548
|
+
const callId = String(call2.callId ?? "");
|
|
67728
68549
|
if (callId) {
|
|
68550
|
+
const sessionId = String(call2.sessionId ?? "");
|
|
68551
|
+
const placed = placedCalls.get(sessionId);
|
|
68552
|
+
if (placed?.answered && call2.callType !== "STREAM") {
|
|
68553
|
+
context.voice.hangup({ sessionId, callName: STREAM_LEG2 }).catch((err) => console.error("[realtimeAgent] ending the STREAM leg after the callee hung up failed (may already be gone):", err.message));
|
|
68554
|
+
}
|
|
68555
|
+
if (call2.callType !== "STREAM") {
|
|
68556
|
+
placedCalls.delete(sessionId);
|
|
68557
|
+
(liveSessions.get(sessionId) ?? liveSessions.get(callId))?.();
|
|
68558
|
+
}
|
|
67729
68559
|
for (const [token, pending] of pendingSessions) {
|
|
67730
68560
|
if (String(pending.call.callId ?? "") === callId)
|
|
67731
68561
|
deletePendingSession(token);
|
|
@@ -67735,7 +68565,27 @@ function realtimeAgent(options) {
|
|
|
67735
68565
|
}
|
|
67736
68566
|
}
|
|
67737
68567
|
};
|
|
67738
|
-
const voiceWebhook = onCall({
|
|
68568
|
+
const voiceWebhook = onCall({
|
|
68569
|
+
incoming: connect,
|
|
68570
|
+
answered: handleAnswered,
|
|
68571
|
+
completed: handleCallCompleted
|
|
68572
|
+
});
|
|
68573
|
+
async function call(to, callOptions = {}) {
|
|
68574
|
+
const context = callOptions.context ?? savedContext;
|
|
68575
|
+
if (!context) {
|
|
68576
|
+
throw new Error("realtimeAgent.call() needs a FunctionContext. Pass { context }, or call it after the function has started.");
|
|
68577
|
+
}
|
|
68578
|
+
if (callOptions.provider)
|
|
68579
|
+
getRealtimeAdapter(callOptions.provider);
|
|
68580
|
+
const response = await context.voice.call(to, {
|
|
68581
|
+
callName: CALLER_LEG2,
|
|
68582
|
+
...callOptions.from && { from: callOptions.from },
|
|
68583
|
+
...callOptions.timeout !== void 0 && { timeout: callOptions.timeout },
|
|
68584
|
+
...callOptions.maxDuration !== void 0 && { maxDuration: callOptions.maxDuration }
|
|
68585
|
+
});
|
|
68586
|
+
rememberPlacedCall(response.sessionId, callOptions.data, callOptions.provider);
|
|
68587
|
+
return response;
|
|
68588
|
+
}
|
|
67739
68589
|
return {
|
|
67740
68590
|
setup(runtime) {
|
|
67741
68591
|
runtime.onStartup(async (context) => {
|
|
@@ -67745,7 +68595,9 @@ function realtimeAgent(options) {
|
|
|
67745
68595
|
},
|
|
67746
68596
|
voiceWebhook,
|
|
67747
68597
|
connect,
|
|
67748
|
-
|
|
68598
|
+
call,
|
|
68599
|
+
endpointFor,
|
|
68600
|
+
commandsBefore: () => recordsViaSinch(options.record) ? commands().recordToFunctions().build() : []
|
|
67749
68601
|
};
|
|
67750
68602
|
}
|
|
67751
68603
|
|
|
@@ -68977,10 +69829,10 @@ var VALID_DIGITS = "0-9\uFF10-\uFF19\u0660-\u0669\u06F0-\u06F9";
|
|
|
68977
69829
|
var DASHES = "-\u2010-\u2015\u2212\u30FC\uFF0D";
|
|
68978
69830
|
var SLASHES = "\uFF0F/";
|
|
68979
69831
|
var DOTS = "\uFF0E.";
|
|
68980
|
-
var
|
|
69832
|
+
var WHITESPACE2 = " \xA0\xAD\u200B\u2060\u3000";
|
|
68981
69833
|
var BRACKETS = "()\uFF08\uFF09\uFF3B\uFF3D\\[\\]";
|
|
68982
69834
|
var TILDES = "~\u2053\u223C\uFF5E";
|
|
68983
|
-
var VALID_PUNCTUATION = "".concat(DASHES).concat(SLASHES).concat(DOTS).concat(
|
|
69835
|
+
var VALID_PUNCTUATION = "".concat(DASHES).concat(SLASHES).concat(DOTS).concat(WHITESPACE2).concat(BRACKETS).concat(TILDES);
|
|
68984
69836
|
var PLUS_CHARS = "+\uFF0B";
|
|
68985
69837
|
|
|
68986
69838
|
// ../../node_modules/libphonenumber-js/es6/helpers/stripIddPrefix.js
|
|
@@ -70768,6 +71620,20 @@ var LocalStorage = class {
|
|
|
70768
71620
|
const sanitized = key.replace(/^\/+/, "").replace(/\.\./g, "_");
|
|
70769
71621
|
return path4.join(this.baseDir, sanitized);
|
|
70770
71622
|
}
|
|
71623
|
+
/**
|
|
71624
|
+
* Sinch Voice uploads the finished recording itself, so dev points it at the runtime's built-in
|
|
71625
|
+
* `PUT /_sinch/recording/:file` receiver (RECORDING_RECEIVER_PATH) over the tunnel, which writes into `recordings/`.
|
|
71626
|
+
*/
|
|
71627
|
+
async getRecordingDestination(callId, format) {
|
|
71628
|
+
const urlPath = `${RECORDING_RECEIVER_PATH}${path4.posix.basename(recordingKey(callId, format))}`;
|
|
71629
|
+
const url2 = tunnelPublicUrl(urlPath, "http");
|
|
71630
|
+
if (!url2) {
|
|
71631
|
+
throw new Error(
|
|
71632
|
+
"Recording needs a public URL to receive the file in dev. Run `sinch functions dev` with a tunnel."
|
|
71633
|
+
);
|
|
71634
|
+
}
|
|
71635
|
+
return url2;
|
|
71636
|
+
}
|
|
70771
71637
|
async write(key, data) {
|
|
70772
71638
|
const filePath = this.resolvePath(key);
|
|
70773
71639
|
await fs3.mkdir(path4.dirname(filePath), { recursive: true });
|
|
@@ -75938,6 +76804,7 @@ var TunnelClient = class {
|
|
|
75938
76804
|
this.tunnelId = message.tunnelId || null;
|
|
75939
76805
|
this.tunnelUrl = message.publicUrl || null;
|
|
75940
76806
|
console.log(`Received welcome: tunnelId=${this.tunnelId}`);
|
|
76807
|
+
if (this.tunnelId && this.tunnelUrl) process.env[TUNNEL_PUBLIC_URL_ENV] = this.buildTunnelUrl();
|
|
75941
76808
|
if (this.welcomeResolver) {
|
|
75942
76809
|
this.welcomeResolver(true);
|
|
75943
76810
|
this.welcomeResolver = null;
|
|
@@ -76148,6 +77015,7 @@ var TunnelClient = class {
|
|
|
76148
77015
|
*/
|
|
76149
77016
|
async disconnect() {
|
|
76150
77017
|
this.shuttingDown = true;
|
|
77018
|
+
delete process.env[TUNNEL_PUBLIC_URL_ENV];
|
|
76151
77019
|
this.stopHeartbeat();
|
|
76152
77020
|
this.streams.closeAll("Tunnel client shutting down");
|
|
76153
77021
|
if (this.ws) {
|
|
@@ -76708,9 +77576,12 @@ export {
|
|
|
76708
77576
|
createMenu,
|
|
76709
77577
|
createSimpleMenu,
|
|
76710
77578
|
MenuTemplates,
|
|
77579
|
+
RECORDING_RECEIVER_PATH,
|
|
77580
|
+
recordingKey,
|
|
76711
77581
|
UniversalConfig,
|
|
76712
77582
|
createConfig,
|
|
76713
77583
|
createUniversalConfig,
|
|
77584
|
+
require_express2 as require_express,
|
|
76714
77585
|
REDACTED,
|
|
76715
77586
|
redactCredentials,
|
|
76716
77587
|
stringify,
|
|
@@ -76720,7 +77591,9 @@ export {
|
|
|
76720
77591
|
DEFAULT_STT_LANGUAGE,
|
|
76721
77592
|
dial,
|
|
76722
77593
|
endpointNumber,
|
|
77594
|
+
MAX_SAY_CHARS,
|
|
76723
77595
|
DEFAULT_BRIDGE_NAME,
|
|
77596
|
+
RECORD_TO_FUNCTIONS_SENTINEL,
|
|
76724
77597
|
PromptBuilder,
|
|
76725
77598
|
MenuItemBuilder,
|
|
76726
77599
|
CommandBuilder,
|
|
@@ -76744,6 +77617,12 @@ export {
|
|
|
76744
77617
|
Client,
|
|
76745
77618
|
createClient,
|
|
76746
77619
|
connectAgent,
|
|
77620
|
+
AGENT_STREAM_PATH,
|
|
77621
|
+
AGENT_HEADER_TOKEN,
|
|
77622
|
+
TUNNEL_PUBLIC_URL_ENV,
|
|
77623
|
+
tunnelPublicUrl,
|
|
77624
|
+
resolveAgentStreamUrl,
|
|
77625
|
+
buildAgentStreamEndpoint,
|
|
76747
77626
|
attachVoiceClient,
|
|
76748
77627
|
onCall,
|
|
76749
77628
|
toCamelCase,
|
|
@@ -76803,6 +77682,7 @@ export {
|
|
|
76803
77682
|
buildBaseContext,
|
|
76804
77683
|
handleVoiceV1Callback,
|
|
76805
77684
|
handleVoiceWebhook,
|
|
77685
|
+
rewriteRecordingSentinels,
|
|
76806
77686
|
handleCustomEndpoint,
|
|
76807
77687
|
createApp,
|
|
76808
77688
|
createSinchRuntime,
|
|
@@ -76814,10 +77694,6 @@ export {
|
|
|
76814
77694
|
ElevenLabsController,
|
|
76815
77695
|
tryAutoConfigureAsync,
|
|
76816
77696
|
ElevenLabsAutoConfigurator,
|
|
76817
|
-
AGENT_STREAM_PATH,
|
|
76818
|
-
AGENT_HEADER_TOKEN,
|
|
76819
|
-
resolveAgentStreamUrl,
|
|
76820
|
-
buildAgentStreamEndpoint,
|
|
76821
77697
|
tool,
|
|
76822
77698
|
voiceRelay,
|
|
76823
77699
|
realtimeAgent,
|
|
@@ -77154,4 +78030,4 @@ serve-static/index.js:
|
|
|
77154
78030
|
* MIT Licensed
|
|
77155
78031
|
*)
|
|
77156
78032
|
*/
|
|
77157
|
-
//# sourceMappingURL=chunk-
|
|
78033
|
+
//# sourceMappingURL=chunk-KGCIUPCT.js.map
|