@sinch/functions-runtime 0.7.1 → 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-5K5FDUEL.js → chunk-KGCIUPCT.js} +1229 -429
- package/dist/chunk-KGCIUPCT.js.map +1 -0
- package/dist/index.d.ts +178 -35
- package/dist/index.js +11 -1
- package/dist/voice/v2.d.ts +92 -14
- package/dist/voice/v2.js +5 -1
- package/package.json +1 -1
- package/dist/chunk-5K5FDUEL.js.map +0 -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,52 +60186,6 @@ function toCallHeaders(headers) {
|
|
|
60180
60186
|
return list.length > 0 ? list : void 0;
|
|
60181
60187
|
}
|
|
60182
60188
|
|
|
60183
|
-
// ../voice-v2-preview/dist/core/agent-endpoint.js
|
|
60184
|
-
var DEFAULT_AGENT_MAX_DURATION = 1800;
|
|
60185
|
-
function agentMaxDuration(context) {
|
|
60186
|
-
const raw = (context?.env ?? process.env)["MAX_CALL_DURATION"];
|
|
60187
|
-
return raw ? Number(raw) : DEFAULT_AGENT_MAX_DURATION;
|
|
60188
|
-
}
|
|
60189
|
-
var PROVIDER_ENDPOINTS = {
|
|
60190
|
-
elevenlabs: { host: "sip.rtc.elevenlabs.io", port: 5060, transport: "TCP" },
|
|
60191
|
-
grok: { host: "sip.voice.x.ai", port: 5061, transport: "TLS" }
|
|
60192
|
-
};
|
|
60193
|
-
var UNSAFE_HOST_CHAR = /[\x00-\x1f\x7f@;\s]/;
|
|
60194
|
-
function sipAgentAddress(provider, number, options) {
|
|
60195
|
-
const endpoint = PROVIDER_ENDPOINTS[provider];
|
|
60196
|
-
if (!endpoint) {
|
|
60197
|
-
throw new Error(`Voice v2 agent: unsupported provider '${provider}'. 'elevenlabs' and 'grok' are SIP-based and supported here. 'sinch' (the agents SDK's media stream), and any other stream-based provider such as OpenAI or Deepgram, need a different call shape \u2014 see @sinch/agents.`);
|
|
60198
|
-
}
|
|
60199
|
-
if (!E164.test(number)) {
|
|
60200
|
-
throw new Error(`Voice v2 agent: '${number}' is not an E.164 phone number. This must be the provider's SIP number (e.g. '+15551234567') \u2014 the Direct SIP number registered with xAI, or the number attached to the ElevenLabs agent's phone integration \u2014 never an agent id, and never a value taken from a caller-controlled webhook field: it is interpolated straight into a SIP URI. (Looking for an agent id instead? That's @sinch/agents' connectAgent(provider, agentId), a different function.)`);
|
|
60201
|
-
}
|
|
60202
|
-
const host = options.host ?? endpoint.host;
|
|
60203
|
-
if (UNSAFE_HOST_CHAR.test(host)) {
|
|
60204
|
-
throw new Error(`Voice v2 agent: options.host '${host}' contains a character a SIP host cannot ('@', ';', whitespace or a control character) \u2014 refusing rather than building a URI that means something other than what it looks like.`);
|
|
60205
|
-
}
|
|
60206
|
-
const port = options.port ?? endpoint.port;
|
|
60207
|
-
const transport = options.transport ?? endpoint.transport;
|
|
60208
|
-
const sipUri = `sip:${number}@${host}:${port};transport=${transport.toLowerCase()}`;
|
|
60209
|
-
return (event) => {
|
|
60210
|
-
const call = event?.call;
|
|
60211
|
-
const perCall = call ? {
|
|
60212
|
-
"X-Sinch-Call-Id": call.callId ?? "",
|
|
60213
|
-
"X-Caller-Number": endpointNumber(call.from),
|
|
60214
|
-
"X-Dialed-Number": endpointNumber(call.to)
|
|
60215
|
-
} : {};
|
|
60216
|
-
const headers = { ...perCall, ...toHeaderMap(options.headers) };
|
|
60217
|
-
return dial.sip(sipUri, { transport, headers });
|
|
60218
|
-
};
|
|
60219
|
-
}
|
|
60220
|
-
function toHeaderMap(headers) {
|
|
60221
|
-
if (!headers)
|
|
60222
|
-
return {};
|
|
60223
|
-
if (Array.isArray(headers)) {
|
|
60224
|
-
return Object.fromEntries(headers.map((h) => [h.key, h.value ?? ""]));
|
|
60225
|
-
}
|
|
60226
|
-
return { ...headers };
|
|
60227
|
-
}
|
|
60228
|
-
|
|
60229
60189
|
// ../voice-v2-preview/dist/core/say-limit.js
|
|
60230
60190
|
var MAX_SAY_CHARS = 600;
|
|
60231
60191
|
var MAX_MESSAGES = 10;
|
|
@@ -60287,6 +60247,52 @@ function sentenceSpans(text) {
|
|
|
60287
60247
|
return spans;
|
|
60288
60248
|
}
|
|
60289
60249
|
|
|
60250
|
+
// ../voice-v2-preview/dist/core/agent-endpoint.js
|
|
60251
|
+
var DEFAULT_AGENT_MAX_DURATION = 1800;
|
|
60252
|
+
function agentMaxDuration(context) {
|
|
60253
|
+
const raw = (context?.env ?? process.env)["MAX_CALL_DURATION"];
|
|
60254
|
+
return raw ? Number(raw) : DEFAULT_AGENT_MAX_DURATION;
|
|
60255
|
+
}
|
|
60256
|
+
var PROVIDER_ENDPOINTS = {
|
|
60257
|
+
elevenlabs: { host: "sip.rtc.elevenlabs.io", port: 5060, transport: "TCP" },
|
|
60258
|
+
grok: { host: "sip.voice.x.ai", port: 5061, transport: "TLS" }
|
|
60259
|
+
};
|
|
60260
|
+
var UNSAFE_HOST_CHAR = /[\x00-\x1f\x7f@;\s]/;
|
|
60261
|
+
function sipAgentAddress(provider, number, options) {
|
|
60262
|
+
const endpoint = PROVIDER_ENDPOINTS[provider];
|
|
60263
|
+
if (!endpoint) {
|
|
60264
|
+
throw new Error(`Voice v2 agent: unsupported provider '${provider}'. 'elevenlabs' and 'grok' are SIP-based and supported here. 'sinch' (the agents SDK's media stream), and any other stream-based provider such as OpenAI or Deepgram, need a different call shape \u2014 see @sinch/agents.`);
|
|
60265
|
+
}
|
|
60266
|
+
if (!E164.test(number)) {
|
|
60267
|
+
throw new Error(`Voice v2 agent: '${number}' is not an E.164 phone number. This must be the provider's SIP number (e.g. '+15551234567') \u2014 the Direct SIP number registered with xAI, or the number attached to the ElevenLabs agent's phone integration \u2014 never an agent id, and never a value taken from a caller-controlled webhook field: it is interpolated straight into a SIP URI. (Looking for an agent id instead? That's @sinch/agents' connectAgent(provider, agentId), a different function.)`);
|
|
60268
|
+
}
|
|
60269
|
+
const host = options.host ?? endpoint.host;
|
|
60270
|
+
if (UNSAFE_HOST_CHAR.test(host)) {
|
|
60271
|
+
throw new Error(`Voice v2 agent: options.host '${host}' contains a character a SIP host cannot ('@', ';', whitespace or a control character) \u2014 refusing rather than building a URI that means something other than what it looks like.`);
|
|
60272
|
+
}
|
|
60273
|
+
const port = options.port ?? endpoint.port;
|
|
60274
|
+
const transport = options.transport ?? endpoint.transport;
|
|
60275
|
+
const sipUri = `sip:${number}@${host}:${port};transport=${transport.toLowerCase()}`;
|
|
60276
|
+
return (event) => {
|
|
60277
|
+
const call = event?.call;
|
|
60278
|
+
const perCall = call ? {
|
|
60279
|
+
"X-Sinch-Call-Id": call.callId ?? "",
|
|
60280
|
+
"X-Caller-Number": endpointNumber(call.from),
|
|
60281
|
+
"X-Dialed-Number": endpointNumber(call.to)
|
|
60282
|
+
} : {};
|
|
60283
|
+
const headers = { ...perCall, ...toHeaderMap(options.headers) };
|
|
60284
|
+
return dial.sip(sipUri, { transport, headers });
|
|
60285
|
+
};
|
|
60286
|
+
}
|
|
60287
|
+
function toHeaderMap(headers) {
|
|
60288
|
+
if (!headers)
|
|
60289
|
+
return {};
|
|
60290
|
+
if (Array.isArray(headers)) {
|
|
60291
|
+
return Object.fromEntries(headers.map((h) => [h.key, h.value ?? ""]));
|
|
60292
|
+
}
|
|
60293
|
+
return { ...headers };
|
|
60294
|
+
}
|
|
60295
|
+
|
|
60290
60296
|
// ../voice-v2-preview/dist/core/commands.js
|
|
60291
60297
|
function internals(builder) {
|
|
60292
60298
|
return builder;
|
|
@@ -60465,6 +60471,10 @@ function bridgeStep(to, options, leg) {
|
|
|
60465
60471
|
];
|
|
60466
60472
|
};
|
|
60467
60473
|
}
|
|
60474
|
+
var RECORD_TO_FUNCTIONS_SENTINEL = "@functions";
|
|
60475
|
+
function isPresignedDestination(url2) {
|
|
60476
|
+
return url2 === RECORD_TO_FUNCTIONS_SENTINEL || /^https:\/\//i.test(url2);
|
|
60477
|
+
}
|
|
60468
60478
|
function toCredentials(credentials) {
|
|
60469
60479
|
if (typeof credentials === "string") {
|
|
60470
60480
|
return credentials;
|
|
@@ -60476,13 +60486,16 @@ function toCredentials(credentials) {
|
|
|
60476
60486
|
return parts.join(":");
|
|
60477
60487
|
}
|
|
60478
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
|
+
}
|
|
60479
60492
|
const transcribing = options.transcribe !== void 0 || options.transcriptionLocale !== void 0;
|
|
60480
60493
|
return {
|
|
60481
60494
|
...options.format && { format: options.format },
|
|
60482
60495
|
...options.recordingType && { recordingType: options.recordingType },
|
|
60483
60496
|
destination: options.destination ?? "AWS",
|
|
60484
60497
|
destinationUrl: options.destinationUrl,
|
|
60485
|
-
credentials: toCredentials(options.credentials),
|
|
60498
|
+
...options.credentials !== void 0 && { credentials: toCredentials(options.credentials) },
|
|
60486
60499
|
...transcribing && {
|
|
60487
60500
|
transcriptionOptions: {
|
|
60488
60501
|
isEnabled: options.transcribe ?? true,
|
|
@@ -60870,6 +60883,10 @@ var CommandBuilder = class {
|
|
|
60870
60883
|
dialAgent(target, numberOrOptions, sipOptions = {}) {
|
|
60871
60884
|
if (typeof target !== "string") {
|
|
60872
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
|
+
}
|
|
60873
60890
|
return this.push(bridgeStep(agentEndpoint(target), options2, STREAM_AGENT_LEG));
|
|
60874
60891
|
}
|
|
60875
60892
|
const { headers, transport, host, port, ...options } = sipOptions;
|
|
@@ -61068,6 +61085,31 @@ var CommandBuilder = class {
|
|
|
61068
61085
|
...Object.keys(events).length > 0 && { events }
|
|
61069
61086
|
});
|
|
61070
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
|
+
}
|
|
61071
61113
|
/**
|
|
61072
61114
|
* Stop a named recording. Non-blocking.
|
|
61073
61115
|
*
|
|
@@ -61776,7 +61818,8 @@ var Client = class {
|
|
|
61776
61818
|
if (!this.publicUrl) {
|
|
61777
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).`);
|
|
61778
61820
|
}
|
|
61779
|
-
|
|
61821
|
+
const query = this.publicUrl.indexOf("?");
|
|
61822
|
+
return query < 0 ? `${this.publicUrl}${stream5}` : `${this.publicUrl.slice(0, query)}${stream5}${this.publicUrl.slice(query)}`;
|
|
61780
61823
|
}
|
|
61781
61824
|
};
|
|
61782
61825
|
function createClient(context, options) {
|
|
@@ -61844,6 +61887,141 @@ function connectAgent(provider, number, options = {}) {
|
|
|
61844
61887
|
};
|
|
61845
61888
|
}
|
|
61846
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
|
+
|
|
61847
62025
|
// ../runtime-shared/dist/security/context-secrets.js
|
|
61848
62026
|
import { inspect } from "util";
|
|
61849
62027
|
var HIDDEN_ENV_KEYS = [
|
|
@@ -62106,7 +62284,8 @@ function attachVoiceClient(context, v1) {
|
|
|
62106
62284
|
enumerable: true,
|
|
62107
62285
|
get() {
|
|
62108
62286
|
if (!client) {
|
|
62109
|
-
|
|
62287
|
+
const publicUrl = process.env[TUNNEL_PUBLIC_URL_ENV];
|
|
62288
|
+
client = Object.assign(createClient(context, publicUrl ? { publicUrl } : void 0), { v1 });
|
|
62110
62289
|
}
|
|
62111
62290
|
return client;
|
|
62112
62291
|
}
|
|
@@ -62855,7 +63034,7 @@ function installStdioRedaction() {
|
|
|
62855
63034
|
// ../runtime-shared/dist/security/voice-signature.js
|
|
62856
63035
|
import { createHash, createHmac as createHmac2, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
62857
63036
|
var VOICE_TIMESTAMP_SKEW_MS = 5 * 60 * 1e3;
|
|
62858
|
-
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";
|
|
62859
63038
|
var AUTHORIZATION_PATTERN = /^service\s+([^:\s]+):(\S+)$/i;
|
|
62860
63039
|
function fail(reason) {
|
|
62861
63040
|
return { valid: false, reason };
|
|
@@ -63012,67 +63191,30 @@ function resetSinchClients() {
|
|
|
63012
63191
|
// ../runtime-shared/dist/host/app.js
|
|
63013
63192
|
var import_express2 = __toESM(require_express2(), 1);
|
|
63014
63193
|
|
|
63015
|
-
// ../runtime-shared/dist/
|
|
63016
|
-
|
|
63017
|
-
|
|
63018
|
-
|
|
63194
|
+
// ../runtime-shared/dist/host/exports.js
|
|
63195
|
+
import { types } from "util";
|
|
63196
|
+
var fnToString = Function.prototype.toString;
|
|
63197
|
+
var fnBind = Function.prototype.bind;
|
|
63198
|
+
var OBJECT_PROTOTYPE_NAMES = new Set(Object.getOwnPropertyNames(Object.prototype));
|
|
63199
|
+
function isAuthorClassPrototype(proto) {
|
|
63200
|
+
if (types.isProxy(proto))
|
|
63201
|
+
return false;
|
|
63202
|
+
const ctor = Object.getOwnPropertyDescriptor(proto, "constructor")?.value;
|
|
63203
|
+
if (typeof ctor !== "function" || types.isProxy(ctor))
|
|
63204
|
+
return false;
|
|
63205
|
+
if (Object.getOwnPropertyDescriptor(ctor, "prototype")?.value !== proto)
|
|
63206
|
+
return false;
|
|
63207
|
+
if (!/^class\b/.test(fnToString.call(ctor)))
|
|
63208
|
+
return false;
|
|
63209
|
+
const name = Object.getOwnPropertyDescriptor(ctor, "name")?.value;
|
|
63210
|
+
return !(typeof name === "string" && Object.getOwnPropertyDescriptor(globalThis, name)?.value === ctor);
|
|
63019
63211
|
}
|
|
63020
|
-
|
|
63021
|
-
|
|
63022
|
-
if (typeof value !== "string")
|
|
63023
|
-
return void 0;
|
|
63024
|
-
if (value.length > 0 && !BASE64_RE.test(value))
|
|
63025
|
-
return void 0;
|
|
63026
|
-
try {
|
|
63027
|
-
return Buffer.from(value, "base64");
|
|
63028
|
-
} catch {
|
|
63212
|
+
function findExport(target, name) {
|
|
63213
|
+
if (OBJECT_PROTOTYPE_NAMES.has(name))
|
|
63029
63214
|
return void 0;
|
|
63030
|
-
|
|
63031
|
-
|
|
63032
|
-
function
|
|
63033
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
63034
|
-
}
|
|
63035
|
-
function parseVendorFrame(raw) {
|
|
63036
|
-
let parsed;
|
|
63037
|
-
try {
|
|
63038
|
-
parsed = JSON.parse(raw.toString());
|
|
63039
|
-
} catch {
|
|
63040
|
-
return void 0;
|
|
63041
|
-
}
|
|
63042
|
-
return isPlainObject(parsed) ? parsed : void 0;
|
|
63043
|
-
}
|
|
63044
|
-
function safeToolOutput(value) {
|
|
63045
|
-
try {
|
|
63046
|
-
return JSON.stringify(value ?? {});
|
|
63047
|
-
} catch {
|
|
63048
|
-
return JSON.stringify({ error: "realtimeAgent: tool result could not be serialized" });
|
|
63049
|
-
}
|
|
63050
|
-
}
|
|
63051
|
-
|
|
63052
|
-
// ../runtime-shared/dist/host/exports.js
|
|
63053
|
-
import { types } from "util";
|
|
63054
|
-
var fnToString = Function.prototype.toString;
|
|
63055
|
-
var fnBind = Function.prototype.bind;
|
|
63056
|
-
var OBJECT_PROTOTYPE_NAMES = new Set(Object.getOwnPropertyNames(Object.prototype));
|
|
63057
|
-
function isAuthorClassPrototype(proto) {
|
|
63058
|
-
if (types.isProxy(proto))
|
|
63059
|
-
return false;
|
|
63060
|
-
const ctor = Object.getOwnPropertyDescriptor(proto, "constructor")?.value;
|
|
63061
|
-
if (typeof ctor !== "function" || types.isProxy(ctor))
|
|
63062
|
-
return false;
|
|
63063
|
-
if (Object.getOwnPropertyDescriptor(ctor, "prototype")?.value !== proto)
|
|
63064
|
-
return false;
|
|
63065
|
-
if (!/^class\b/.test(fnToString.call(ctor)))
|
|
63066
|
-
return false;
|
|
63067
|
-
const name = Object.getOwnPropertyDescriptor(ctor, "name")?.value;
|
|
63068
|
-
return !(typeof name === "string" && Object.getOwnPropertyDescriptor(globalThis, name)?.value === ctor);
|
|
63069
|
-
}
|
|
63070
|
-
function findExport(target, name) {
|
|
63071
|
-
if (OBJECT_PROTOTYPE_NAMES.has(name))
|
|
63072
|
-
return void 0;
|
|
63073
|
-
if (Object.hasOwn(target, name)) {
|
|
63074
|
-
const value = target[name];
|
|
63075
|
-
return typeof value === "function" ? fnBind.call(value, target) : void 0;
|
|
63215
|
+
if (Object.hasOwn(target, name)) {
|
|
63216
|
+
const value = target[name];
|
|
63217
|
+
return typeof value === "function" ? fnBind.call(value, target) : void 0;
|
|
63076
63218
|
}
|
|
63077
63219
|
if (types.isProxy(target))
|
|
63078
63220
|
return void 0;
|
|
@@ -63404,12 +63546,52 @@ async function handleVoiceWebhook(userFunction, context, event, request, logger)
|
|
|
63404
63546
|
return formatCustomResponse(result2);
|
|
63405
63547
|
}
|
|
63406
63548
|
const body = await context.voice.onCall({ fallback: () => result2 })(event);
|
|
63549
|
+
await rewriteRecordingSentinels(body, event.call?.callId, context.storage);
|
|
63407
63550
|
return body === void 0 ? { statusCode: 204 } : {
|
|
63408
63551
|
statusCode: 200,
|
|
63409
63552
|
headers: { "Content-Type": "application/json" },
|
|
63410
63553
|
body: stringify(body)
|
|
63411
63554
|
};
|
|
63412
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
|
+
}
|
|
63413
63595
|
function isVoiceResult(result2) {
|
|
63414
63596
|
return Array.isArray(result2) || result2 instanceof CommandBuilder || typeof result2 === "object" && Array.isArray(result2.commands);
|
|
63415
63597
|
}
|
|
@@ -63452,7 +63634,8 @@ function createApp(options = {}) {
|
|
|
63452
63634
|
}
|
|
63453
63635
|
};
|
|
63454
63636
|
setupJsonParsing(app, jsonOptions);
|
|
63455
|
-
|
|
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));
|
|
63456
63639
|
return app;
|
|
63457
63640
|
}
|
|
63458
63641
|
function createSinchRuntime() {
|
|
@@ -64154,74 +64337,6 @@ var ElevenLabsAutoConfigurator = class {
|
|
|
64154
64337
|
static tryAutoConfigureAsync = tryAutoConfigureAsync;
|
|
64155
64338
|
};
|
|
64156
64339
|
|
|
64157
|
-
// ../runtime-shared/dist/ai/agent-stream.js
|
|
64158
|
-
var AGENT_SAMPLE_RATE = 16e3;
|
|
64159
|
-
var AGENT_STREAM_PATH = "/stream";
|
|
64160
|
-
var AGENT_HEADER_TOKEN = "x-sinch-agent-token";
|
|
64161
|
-
function deriveSocketUrl(path7) {
|
|
64162
|
-
const fnName = process.env["FUNCTION_NAME"];
|
|
64163
|
-
const apiUrl = process.env["API_URL"];
|
|
64164
|
-
if (!fnName || !apiUrl)
|
|
64165
|
-
return "";
|
|
64166
|
-
if (!/^[a-z0-9][a-z0-9-]{0,51}$/.test(fnName))
|
|
64167
|
-
return "";
|
|
64168
|
-
const match = apiUrl.match(/api\.functions\.(\w+)\.sinchvoice\.org/);
|
|
64169
|
-
if (!match)
|
|
64170
|
-
return "";
|
|
64171
|
-
return `wss://${fnName}.fn-${match[1]}.sinch.com${path7}`;
|
|
64172
|
-
}
|
|
64173
|
-
function isLocalDevUrl(url2) {
|
|
64174
|
-
let hostname;
|
|
64175
|
-
try {
|
|
64176
|
-
hostname = new URL(url2).hostname.toLowerCase();
|
|
64177
|
-
} catch {
|
|
64178
|
-
return false;
|
|
64179
|
-
}
|
|
64180
|
-
if (["localhost", "127.0.0.1", "0.0.0.0", "[::1]", "::1"].includes(hostname))
|
|
64181
|
-
return true;
|
|
64182
|
-
if (hostname.endsWith(".localhost"))
|
|
64183
|
-
return true;
|
|
64184
|
-
return /(^|\.)(trycloudflare\.com|loca\.lt)$/.test(hostname) || /(^|\.)ngrok[.-]/.test(hostname);
|
|
64185
|
-
}
|
|
64186
|
-
function isDeployed(context) {
|
|
64187
|
-
return context?.config?.environment === "production" && process.env["SINCH_LOCAL_DEV"] !== "true";
|
|
64188
|
-
}
|
|
64189
|
-
function resolveAgentStreamUrl(context, override) {
|
|
64190
|
-
return resolveSelfSocketUrl(AGENT_STREAM_PATH, "STREAM_URL", context, override);
|
|
64191
|
-
}
|
|
64192
|
-
function resolveSelfSocketUrl(path7, envVar, context, override) {
|
|
64193
|
-
const url2 = override || (context?.host ? `wss://${context.host}${path7}` : "") || process.env[envVar] || deriveSocketUrl(path7);
|
|
64194
|
-
if (!url2) {
|
|
64195
|
-
throw new Error(`WebSocket URL for ${path7} cannot be determined \u2014 set ${envVar}, or ensure FUNCTION_NAME and API_URL are present.`);
|
|
64196
|
-
}
|
|
64197
|
-
if (isDeployed(context) && isLocalDevUrl(url2)) {
|
|
64198
|
-
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.`);
|
|
64199
|
-
}
|
|
64200
|
-
return url2;
|
|
64201
|
-
}
|
|
64202
|
-
function buildAgentStreamEndpoint(options) {
|
|
64203
|
-
return dial.stream(options.endpoint, {
|
|
64204
|
-
sampleRate: options.sampleRate ?? AGENT_SAMPLE_RATE,
|
|
64205
|
-
headers: { ...options.headers, [AGENT_HEADER_TOKEN]: options.token }
|
|
64206
|
-
});
|
|
64207
|
-
}
|
|
64208
|
-
function upgradeHeader(req, name) {
|
|
64209
|
-
const raw = req?.headers?.[name] ?? req?.headers?.[name.toLowerCase()];
|
|
64210
|
-
return Array.isArray(raw) ? raw[0] ?? "" : raw ?? "";
|
|
64211
|
-
}
|
|
64212
|
-
function readCallHeader(connectMsg, name) {
|
|
64213
|
-
const raw = connectMsg["callHeaders"] ?? connectMsg["callheaders"] ?? connectMsg["headers"];
|
|
64214
|
-
if (Array.isArray(raw)) {
|
|
64215
|
-
const hit = raw.find((e) => isPlainObject(e) && typeof e["key"] === "string" && typeof e["value"] === "string" && e.key.toLowerCase() === name);
|
|
64216
|
-
return hit?.value ?? "";
|
|
64217
|
-
}
|
|
64218
|
-
if (isPlainObject(raw)) {
|
|
64219
|
-
const hit = Object.entries(raw).find(([k]) => k.toLowerCase() === name);
|
|
64220
|
-
return hit ? String(hit[1] ?? "") : "";
|
|
64221
|
-
}
|
|
64222
|
-
return "";
|
|
64223
|
-
}
|
|
64224
|
-
|
|
64225
64340
|
// ../runtime-shared/dist/ai/realtime/types.js
|
|
64226
64341
|
function tool(def) {
|
|
64227
64342
|
return def;
|
|
@@ -64837,6 +64952,61 @@ function createDeepgramAdapter(webSocketClient) {
|
|
|
64837
64952
|
}
|
|
64838
64953
|
var deepgramAdapter = createDeepgramAdapter();
|
|
64839
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
|
+
|
|
64840
65010
|
// ../runtime-shared/dist/ai/realtime/audio.js
|
|
64841
65011
|
var MULAW_BIAS = 132;
|
|
64842
65012
|
var MULAW_CLIP = 32635;
|
|
@@ -64987,14 +65157,14 @@ var TRANSFER_TOOL_NAME = "transfer_to_human";
|
|
|
64987
65157
|
function offersHangup(tools) {
|
|
64988
65158
|
return tools.some((t) => t.name === HANGUP_TOOL_NAME);
|
|
64989
65159
|
}
|
|
64990
|
-
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.';
|
|
64991
65161
|
var DELEGATED_CALL_TERMINATION_INSTRUCTIONS = `
|
|
64992
65162
|
|
|
64993
65163
|
CALL TERMINATION
|
|
64994
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.`;
|
|
64995
65165
|
var GPT_LIVE_BACKEND_CALL_TERMINATION_RULE = "\n\nIf the request is to end the call, call hangup_call immediately.";
|
|
64996
|
-
async function resolvePerCallValue(value, call, context) {
|
|
64997
|
-
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;
|
|
64998
65168
|
}
|
|
64999
65169
|
function builtInTools(hangupEnabled, transferNumber, ctx) {
|
|
65000
65170
|
const tools = [];
|
|
@@ -65045,31 +65215,17 @@ var DEFAULT_BACKEND_MODEL = "gpt-5.6-luna";
|
|
|
65045
65215
|
var VENDOR_RATE = 8e3;
|
|
65046
65216
|
var TURN_SILENCE_MS = 1500;
|
|
65047
65217
|
var TRANSCRIPT_FALLBACK_MS = 300;
|
|
65048
|
-
var SILENCE_DBFS_THRESHOLD = -50;
|
|
65049
|
-
var SILENCE_RMS_THRESHOLD = 32768 * 10 ** (SILENCE_DBFS_THRESHOLD / 20);
|
|
65050
65218
|
var AGENT_TURN_HARD_CAP_MS = 3e4;
|
|
65051
|
-
function pcm16Rms(pcm) {
|
|
65052
|
-
const samples = pcm.length >> 1;
|
|
65053
|
-
if (samples === 0)
|
|
65054
|
-
return 0;
|
|
65055
|
-
let sumSquares = 0;
|
|
65056
|
-
for (let i = 0; i < samples; i++) {
|
|
65057
|
-
const sample = pcm.readInt16LE(i * 2);
|
|
65058
|
-
sumSquares += sample * sample;
|
|
65059
|
-
}
|
|
65060
|
-
return Math.sqrt(sumSquares / samples);
|
|
65061
|
-
}
|
|
65062
|
-
function isSpeechFrame(pcm) {
|
|
65063
|
-
return pcm16Rms(pcm) > SILENCE_RMS_THRESHOLD;
|
|
65064
|
-
}
|
|
65065
|
-
function toAnchoredIso(session, offsetMs) {
|
|
65066
|
-
if (offsetMs === void 0 || session.sessionStartedAtMs === void 0)
|
|
65067
|
-
return void 0;
|
|
65068
|
-
return new Date(session.sessionStartedAtMs + offsetMs).toISOString();
|
|
65069
|
-
}
|
|
65070
65219
|
function buildGreetingDirective(greeting) {
|
|
65071
65220
|
return `Greet the caller now by saying exactly: "${greeting}"`;
|
|
65072
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
|
+
}
|
|
65073
65229
|
var CLOSE_ACK_TIMEOUT_MS = 1e3;
|
|
65074
65230
|
var USER_TURN_ARRIVAL_FALLBACK_MS = TURN_SILENCE_MS * 2;
|
|
65075
65231
|
var DEFAULT_BACKEND_SERVICE_TIER = "priority";
|
|
@@ -65209,10 +65365,6 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65209
65365
|
sessionSeconds: void 0,
|
|
65210
65366
|
backendInputTokens: 0,
|
|
65211
65367
|
backendOutputTokens: 0,
|
|
65212
|
-
pendingUserTurnStartMs: void 0,
|
|
65213
|
-
pendingAgentTurnStartMs: void 0,
|
|
65214
|
-
pendingAgentTurnEndMs: void 0,
|
|
65215
|
-
sessionStartedAtMs: void 0,
|
|
65216
65368
|
delegationCreatedAtMs: /* @__PURE__ */ new Map(),
|
|
65217
65369
|
delegationFirstOutputMs: /* @__PURE__ */ new Map(),
|
|
65218
65370
|
delegationToolMs: /* @__PURE__ */ new Map(),
|
|
@@ -65275,10 +65427,6 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65275
65427
|
session.agentTurnStartedAt = void 0;
|
|
65276
65428
|
const text = session.pendingAgentTurnText;
|
|
65277
65429
|
session.pendingAgentTurnText = "";
|
|
65278
|
-
const playbackStartAt = toAnchoredIso(session, session.pendingAgentTurnStartMs);
|
|
65279
|
-
const playbackEndAt = toAnchoredIso(session, session.pendingAgentTurnEndMs);
|
|
65280
|
-
session.pendingAgentTurnStartMs = void 0;
|
|
65281
|
-
session.pendingAgentTurnEndMs = void 0;
|
|
65282
65430
|
let delegationMs;
|
|
65283
65431
|
if (session.lastDelegationId !== void 0) {
|
|
65284
65432
|
const firstOutputMs = session.delegationFirstOutputMs.get(session.lastDelegationId);
|
|
@@ -65295,8 +65443,6 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65295
65443
|
role: "agent",
|
|
65296
65444
|
text,
|
|
65297
65445
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
65298
|
-
playbackStartAt,
|
|
65299
|
-
playbackEndAt,
|
|
65300
65446
|
delegationMs
|
|
65301
65447
|
});
|
|
65302
65448
|
};
|
|
@@ -65310,19 +65456,14 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65310
65456
|
clearTimeout(session.userTurnTimer);
|
|
65311
65457
|
session.userTurnTimer = void 0;
|
|
65312
65458
|
}
|
|
65313
|
-
const speechStartAt = toAnchoredIso(session, session.pendingUserTurnStartMs);
|
|
65314
|
-
const speechEndAt = toAnchoredIso(session, session.pendingUserTurnEndMs);
|
|
65315
65459
|
session.pendingUserTurnEndMs = void 0;
|
|
65316
|
-
session.pendingUserTurnStartMs = void 0;
|
|
65317
65460
|
const text = session.pendingUserTurnText;
|
|
65318
65461
|
session.pendingUserTurnText = "";
|
|
65319
65462
|
if (text)
|
|
65320
65463
|
callbacks.onTurn({
|
|
65321
65464
|
role: "user",
|
|
65322
65465
|
text,
|
|
65323
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
65324
|
-
speechStartAt,
|
|
65325
|
-
speechEndAt
|
|
65466
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
65326
65467
|
});
|
|
65327
65468
|
};
|
|
65328
65469
|
const scheduleUserTurnFlush = () => {
|
|
@@ -65384,15 +65525,10 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65384
65525
|
case "session.started": {
|
|
65385
65526
|
const started = msg["session"];
|
|
65386
65527
|
session.expiresAt = started?.expires_at;
|
|
65387
|
-
session.sessionStartedAtMs = Date.now();
|
|
65388
65528
|
session.ready = true;
|
|
65389
65529
|
settle2(() => resolve(session));
|
|
65390
65530
|
if (options.greeting) {
|
|
65391
|
-
vendorWs.
|
|
65392
|
-
type: "session.instructions.append",
|
|
65393
|
-
content: buildGreetingDirective(options.greeting),
|
|
65394
|
-
delegation_id: null
|
|
65395
|
-
}));
|
|
65531
|
+
sendGreeting(vendorWs, options.greeting);
|
|
65396
65532
|
}
|
|
65397
65533
|
break;
|
|
65398
65534
|
}
|
|
@@ -65424,9 +65560,6 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65424
65560
|
if (hasRealGap)
|
|
65425
65561
|
flushUserTurnNow();
|
|
65426
65562
|
if (delta) {
|
|
65427
|
-
if (session.pendingUserTurnText === "" && startMs !== void 0) {
|
|
65428
|
-
session.pendingUserTurnStartMs = startMs;
|
|
65429
|
-
}
|
|
65430
65563
|
session.pendingUserTurnText += delta;
|
|
65431
65564
|
}
|
|
65432
65565
|
if (endMs !== void 0)
|
|
@@ -65436,20 +65569,14 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65436
65569
|
}
|
|
65437
65570
|
case "session.output_transcript.delta": {
|
|
65438
65571
|
const delta = msg["delta"];
|
|
65439
|
-
const startMs = typeof msg["start_ms"] === "number" ? msg["start_ms"] : void 0;
|
|
65440
|
-
const endMs = typeof msg["end_ms"] === "number" ? msg["end_ms"] : void 0;
|
|
65441
65572
|
if (delta) {
|
|
65442
65573
|
if (session.pendingAgentTurnText === "") {
|
|
65443
65574
|
session.agentTurnStartedAt = Date.now();
|
|
65444
65575
|
if (session.agentTurnHardCapTimer !== void 0)
|
|
65445
65576
|
clearTimeout(session.agentTurnHardCapTimer);
|
|
65446
65577
|
session.agentTurnHardCapTimer = setTimeout(flushAgentTurnNow, AGENT_TURN_HARD_CAP_MS);
|
|
65447
|
-
if (startMs !== void 0)
|
|
65448
|
-
session.pendingAgentTurnStartMs = startMs;
|
|
65449
65578
|
}
|
|
65450
65579
|
session.pendingAgentTurnText += delta;
|
|
65451
|
-
if (endMs !== void 0)
|
|
65452
|
-
session.pendingAgentTurnEndMs = endMs;
|
|
65453
65580
|
}
|
|
65454
65581
|
const audioQuiet = session.lastSpeechAudioAt !== void 0 && Date.now() - session.lastSpeechAudioAt > TURN_SILENCE_MS;
|
|
65455
65582
|
if (audioQuiet) {
|
|
@@ -65573,6 +65700,11 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
65573
65700
|
const mulaw = pcm16ToMulaw(pcm8k);
|
|
65574
65701
|
s.ws.send(JSON.stringify({ type: "session.input_audio.append", audio: mulaw.toString("base64") }));
|
|
65575
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
|
+
},
|
|
65576
65708
|
clear() {
|
|
65577
65709
|
},
|
|
65578
65710
|
close(session) {
|
|
@@ -66337,127 +66469,505 @@ function createGeminiAdapter(webSocketClient) {
|
|
|
66337
66469
|
flushPendingTurns(session, callbacks);
|
|
66338
66470
|
}
|
|
66339
66471
|
}
|
|
66340
|
-
const toolCallRaw = msg["toolCall"];
|
|
66341
|
-
const functionCalls = isPlainObject(toolCallRaw) ? toolCallRaw["functionCalls"] : void 0;
|
|
66342
|
-
if (Array.isArray(functionCalls)) {
|
|
66343
|
-
for (const fc of functionCalls) {
|
|
66344
|
-
if (!isPlainObject(fc) || typeof fc["id"] !== "string" || typeof fc["name"] !== "string") {
|
|
66345
|
-
callbacks.onError({
|
|
66346
|
-
message: "Received a malformed function call from Gemini Live"
|
|
66347
|
-
});
|
|
66348
|
-
continue;
|
|
66349
|
-
}
|
|
66350
|
-
void dispatchToolCall4({ id: fc["id"], name: fc["name"], args: fc["args"] }, tools, ctx, session, callbacks).catch((err) => {
|
|
66351
|
-
const sanitized = sanitizeVendorError(err);
|
|
66352
|
-
callbacks.onError({
|
|
66353
|
-
message: sanitized.message,
|
|
66354
|
-
code: sanitized.code,
|
|
66355
|
-
raw: sanitized
|
|
66356
|
-
});
|
|
66357
|
-
});
|
|
66358
|
-
}
|
|
66359
|
-
} else if (functionCalls !== void 0) {
|
|
66360
|
-
callbacks.onError({
|
|
66361
|
-
message: "Received a malformed toolCall from Gemini Live \u2014 functionCalls was not an array"
|
|
66362
|
-
});
|
|
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;
|
|
66363
66859
|
}
|
|
66364
|
-
|
|
66365
|
-
|
|
66366
|
-
|
|
66367
|
-
|
|
66368
|
-
|
|
66369
|
-
|
|
66860
|
+
case "agent_response": {
|
|
66861
|
+
if (hangingUp) {
|
|
66862
|
+
if (repliesAllowed <= 0) {
|
|
66863
|
+
muted = true;
|
|
66864
|
+
break;
|
|
66865
|
+
}
|
|
66866
|
+
repliesAllowed--;
|
|
66370
66867
|
}
|
|
66371
|
-
|
|
66372
|
-
|
|
66373
|
-
|
|
66374
|
-
});
|
|
66375
|
-
}
|
|
66376
|
-
if (msg["goAway"] !== void 0) {
|
|
66377
|
-
callbacks.onError({
|
|
66378
|
-
message: "Gemini Live sent goAway \u2014 session will close soon",
|
|
66379
|
-
raw: msg["goAway"]
|
|
66380
|
-
});
|
|
66868
|
+
flushAgent();
|
|
66869
|
+
session.pendingAgentText = msg["agent_response_event"]?.agent_response;
|
|
66870
|
+
break;
|
|
66381
66871
|
}
|
|
66382
|
-
|
|
66383
|
-
|
|
66384
|
-
|
|
66385
|
-
|
|
66386
|
-
|
|
66387
|
-
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;
|
|
66388
66877
|
}
|
|
66389
|
-
|
|
66390
|
-
|
|
66391
|
-
|
|
66392
|
-
|
|
66393
|
-
|
|
66394
|
-
if (
|
|
66395
|
-
|
|
66396
|
-
|
|
66397
|
-
|
|
66398
|
-
|
|
66399
|
-
|
|
66400
|
-
|
|
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;
|
|
66401
66891
|
}
|
|
66402
|
-
|
|
66403
|
-
|
|
66404
|
-
|
|
66405
|
-
|
|
66406
|
-
|
|
66407
|
-
if (!session.closingIntentionally)
|
|
66408
|
-
openSocket();
|
|
66409
|
-
}, delayMs);
|
|
66410
|
-
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;
|
|
66411
66897
|
}
|
|
66412
|
-
|
|
66413
|
-
|
|
66414
|
-
|
|
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;
|
|
66415
66910
|
}
|
|
66416
|
-
|
|
66911
|
+
case "client_error": {
|
|
66417
66912
|
callbacks.onError({
|
|
66418
|
-
message: "
|
|
66913
|
+
message: "elevenlabs agent error",
|
|
66914
|
+
raw: msg["error_event"] ?? msg
|
|
66419
66915
|
});
|
|
66916
|
+
settle2(() => reject(new Error("realtimeAgent: elevenlabs error before the session was ready")));
|
|
66917
|
+
closeAnyState(ws);
|
|
66918
|
+
break;
|
|
66420
66919
|
}
|
|
66421
|
-
|
|
66422
|
-
|
|
66423
|
-
|
|
66424
|
-
|
|
66425
|
-
|
|
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
|
+
});
|
|
66426
66938
|
});
|
|
66427
66939
|
},
|
|
66428
66940
|
sendAudio(session, pcm) {
|
|
66429
66941
|
const s = session;
|
|
66430
|
-
if (!s.ready || s.ws.readyState !== s.ws.OPEN)
|
|
66431
|
-
if (!s.closingIntentionally && s.audioBufferBytes + pcm.length <= MAX_BUFFERED_AUDIO_BYTES) {
|
|
66432
|
-
s.audioBuffer.push(pcm);
|
|
66433
|
-
s.audioBufferBytes += pcm.length;
|
|
66434
|
-
}
|
|
66942
|
+
if (!s.ready || !s.resamplerIn || s.ws.readyState !== s.ws.OPEN)
|
|
66435
66943
|
return;
|
|
66436
|
-
|
|
66437
|
-
const
|
|
66438
|
-
s.ws.send(JSON.stringify({
|
|
66439
|
-
realtimeInput: {
|
|
66440
|
-
audio: { data: pcm16k.toString("base64"), mimeType: "audio/pcm;rate=16000" }
|
|
66441
|
-
}
|
|
66442
|
-
}));
|
|
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") }));
|
|
66443
66947
|
},
|
|
66444
|
-
|
|
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;
|
|
66445
66956
|
},
|
|
66446
66957
|
close(session) {
|
|
66447
|
-
|
|
66448
|
-
s.closingIntentionally = true;
|
|
66449
|
-
closeAnyState(s.ws);
|
|
66958
|
+
closeAnyState(session.ws);
|
|
66450
66959
|
}
|
|
66451
66960
|
};
|
|
66452
66961
|
}
|
|
66453
|
-
var
|
|
66962
|
+
var elevenlabsAdapter = createElevenLabsAdapter();
|
|
66454
66963
|
|
|
66455
66964
|
// ../runtime-shared/dist/ai/realtime/registry.js
|
|
66456
66965
|
var adapters = {
|
|
66457
66966
|
deepgram: deepgramAdapter,
|
|
66458
66967
|
openai: openaiAdapter,
|
|
66459
66968
|
grok: grokAdapter,
|
|
66460
|
-
gemini: geminiAdapter
|
|
66969
|
+
gemini: geminiAdapter,
|
|
66970
|
+
elevenlabs: elevenlabsAdapter
|
|
66461
66971
|
};
|
|
66462
66972
|
function getRealtimeAdapter(provider) {
|
|
66463
66973
|
const adapter2 = adapters[provider];
|
|
@@ -66945,6 +67455,59 @@ function audioMs(playbackStartAtIso, playbackEndAtIso) {
|
|
|
66945
67455
|
function logValue(ms) {
|
|
66946
67456
|
return ms ?? -1;
|
|
66947
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
|
+
}
|
|
66948
67511
|
|
|
66949
67512
|
// ../runtime-shared/dist/ai/realtime/adapters/relay.js
|
|
66950
67513
|
var DEFAULT_MAX_CALL_DURATION = 1800;
|
|
@@ -67023,6 +67586,7 @@ function createRelayAgent(options) {
|
|
|
67023
67586
|
setup: relay2.setup,
|
|
67024
67587
|
voiceWebhook: onCall({ incoming: connect, completed: handleCallCompleted }),
|
|
67025
67588
|
connect,
|
|
67589
|
+
call: () => Promise.reject(new Error("realtimeAgent.call() does not support provider 'voice-relay' yet.")),
|
|
67026
67590
|
endpointFor: relay2.endpointFor
|
|
67027
67591
|
};
|
|
67028
67592
|
}
|
|
@@ -67281,55 +67845,103 @@ function attach(options, pendingByCallId, transferredCallIds, call) {
|
|
|
67281
67845
|
});
|
|
67282
67846
|
}
|
|
67283
67847
|
|
|
67284
|
-
// ../runtime-shared/dist/ai/realtime/
|
|
67285
|
-
|
|
67286
|
-
|
|
67287
|
-
|
|
67288
|
-
|
|
67289
|
-
|
|
67290
|
-
|
|
67291
|
-
|
|
67292
|
-
|
|
67293
|
-
|
|
67294
|
-
|
|
67295
|
-
|
|
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;
|
|
67296
67895
|
}
|
|
67297
|
-
|
|
67298
|
-
|
|
67299
|
-
|
|
67300
|
-
|
|
67301
|
-
|
|
67302
|
-
|
|
67303
|
-
|
|
67304
|
-
|
|
67305
|
-
|
|
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));
|
|
67306
67915
|
return {
|
|
67307
|
-
get
|
|
67308
|
-
return
|
|
67916
|
+
get truncated() {
|
|
67917
|
+
return truncated;
|
|
67309
67918
|
},
|
|
67310
|
-
|
|
67311
|
-
|
|
67312
|
-
|
|
67313
|
-
|
|
67314
|
-
|
|
67315
|
-
|
|
67316
|
-
|
|
67317
|
-
|
|
67318
|
-
|
|
67319
|
-
|
|
67320
|
-
|
|
67321
|
-
|
|
67322
|
-
}
|
|
67323
|
-
if (speaking && !loud && quietRun >= hangoverFrames) {
|
|
67324
|
-
speaking = false;
|
|
67325
|
-
return "end";
|
|
67326
|
-
}
|
|
67327
|
-
return void 0;
|
|
67328
|
-
}
|
|
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)
|
|
67329
67931
|
};
|
|
67330
67932
|
}
|
|
67331
67933
|
|
|
67332
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;
|
|
67333
67945
|
var BRIDGE = "bridge";
|
|
67334
67946
|
var CALLER_LEG2 = "caller";
|
|
67335
67947
|
var STREAM_LEG2 = "stream";
|
|
@@ -67340,7 +67952,11 @@ function sendStreamControl(ws, command) {
|
|
|
67340
67952
|
if (ws.readyState === ws.OPEN)
|
|
67341
67953
|
ws.send(JSON.stringify({ command }));
|
|
67342
67954
|
}
|
|
67343
|
-
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;
|
|
67344
67960
|
var HEARTBEAT_INTERVAL_MS = 2e4;
|
|
67345
67961
|
var PENDING_SESSION_TTL_MS = 3e4;
|
|
67346
67962
|
var MAX_PENDING_SESSIONS = 1e3;
|
|
@@ -67350,22 +67966,23 @@ function resolveMaxDuration(context) {
|
|
|
67350
67966
|
}
|
|
67351
67967
|
var FIRST_FRAME_DEADLINE_MS = 2e3;
|
|
67352
67968
|
var MAX_UNAUTHENTICATED_SOCKETS2 = 32;
|
|
67353
|
-
async function resolvePerCallOptions(options, call, context, ctx) {
|
|
67969
|
+
async function resolvePerCallOptions(options, call, context, ctx, data, provider = options.provider) {
|
|
67354
67970
|
const [prompt, greeting, voice, transferTo, language] = await Promise.all([
|
|
67355
|
-
resolvePerCallValue(options.prompt, call, context),
|
|
67356
|
-
resolvePerCallValue(options.greeting, call, context),
|
|
67357
|
-
resolvePerCallValue(options.voice, call, context),
|
|
67358
|
-
resolvePerCallValue(options.transferTo, call, context),
|
|
67359
|
-
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)
|
|
67360
67976
|
]);
|
|
67361
67977
|
const { transferTo: _transferTo, tools: authorTools, ...rest } = options;
|
|
67362
67978
|
const tools = mergeTools(authorTools ?? [], builtInTools(options.hangup ?? true, nonBlank(transferTo), ctx));
|
|
67363
67979
|
let resolvedPrompt = currentDateTimePreamble(options.timezone) + prompt;
|
|
67364
67980
|
if (offersHangup(tools)) {
|
|
67365
|
-
resolvedPrompt +=
|
|
67981
|
+
resolvedPrompt += provider === "openai" ? DELEGATED_CALL_TERMINATION_INSTRUCTIONS : CALL_TERMINATION_INSTRUCTIONS;
|
|
67366
67982
|
}
|
|
67367
67983
|
return {
|
|
67368
67984
|
...rest,
|
|
67985
|
+
provider,
|
|
67369
67986
|
prompt: resolvedPrompt,
|
|
67370
67987
|
greeting,
|
|
67371
67988
|
voice,
|
|
@@ -67383,10 +68000,11 @@ function realtimeAgent(options) {
|
|
|
67383
68000
|
if (options.provider === "voice-relay") {
|
|
67384
68001
|
return createRelayAgent(options);
|
|
67385
68002
|
}
|
|
67386
|
-
const
|
|
68003
|
+
const defaultAdapter = getRealtimeAdapter(options.provider);
|
|
67387
68004
|
let savedContext;
|
|
67388
68005
|
const pendingSessions = /* @__PURE__ */ new Map();
|
|
67389
68006
|
const transferredCallIds = /* @__PURE__ */ new Set();
|
|
68007
|
+
const liveSessions = /* @__PURE__ */ new Map();
|
|
67390
68008
|
function deletePendingSession(token) {
|
|
67391
68009
|
const session = pendingSessions.get(token);
|
|
67392
68010
|
if (!session)
|
|
@@ -67420,10 +68038,12 @@ function realtimeAgent(options) {
|
|
|
67420
68038
|
const req = rawReq;
|
|
67421
68039
|
const headerToken = upgradeHeader(req, AGENT_HEADER_TOKEN);
|
|
67422
68040
|
const startSession = (pending, connectMsg) => {
|
|
67423
|
-
const
|
|
68041
|
+
const call2 = pending.call;
|
|
67424
68042
|
const context = pending.requestContext;
|
|
67425
68043
|
const config = createUniversalConfig(context);
|
|
67426
|
-
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;
|
|
67427
68047
|
const expectedRate = AUDIO_SAMPLE_RATES[options.audio ?? "telephony"];
|
|
67428
68048
|
const reportedRate = connectMsg["sampleRate"];
|
|
67429
68049
|
if (reportedRate !== void 0 && reportedRate !== expectedRate) {
|
|
@@ -67436,15 +68056,20 @@ function realtimeAgent(options) {
|
|
|
67436
68056
|
let ended = false;
|
|
67437
68057
|
let transferred = false;
|
|
67438
68058
|
let heartbeat;
|
|
68059
|
+
let greetingTimer;
|
|
68060
|
+
let hangupTimer;
|
|
68061
|
+
let lastSpeechOutAt = 0;
|
|
67439
68062
|
const lifecycle = new AbortController();
|
|
67440
68063
|
const transcript = [];
|
|
67441
68064
|
const usage = {};
|
|
67442
68065
|
const callConnectedAtMs = Date.now();
|
|
67443
68066
|
let lastUserTurnAt;
|
|
67444
68067
|
let firstAudioAtMs;
|
|
67445
|
-
|
|
68068
|
+
const playout = createPlayoutTracker(PLAYOUT_GAP_MS);
|
|
68069
|
+
const untimedAgentEntries = [];
|
|
67446
68070
|
let bytesPerMs = 8e3 * 2 / 1e3;
|
|
67447
68071
|
const vad = createEnergyVad();
|
|
68072
|
+
const recorder = recordsStream(options.record) ? createStereoRecorder(expectedRate, resolveMaxDuration(context)) : void 0;
|
|
67448
68073
|
let pendingSpeechStartAt;
|
|
67449
68074
|
let pendingSpeechEndAt;
|
|
67450
68075
|
let speechEndFromProvider = false;
|
|
@@ -67457,16 +68082,20 @@ function realtimeAgent(options) {
|
|
|
67457
68082
|
return `[realtimeAgent] turn latency totalMs=${logValue(totalMs)} playbackDelayMs=${logValue(delay)} audioMs=${logValue(audio)} delegationMs=${logValue(entry.delegationMs)}`;
|
|
67458
68083
|
};
|
|
67459
68084
|
const applySelfPlaybackFallback = (entry, cutShort) => {
|
|
67460
|
-
|
|
68085
|
+
const played = playout.take(cutShort ? Infinity : Date.parse(entry.timestamp));
|
|
68086
|
+
if (!played)
|
|
67461
68087
|
return;
|
|
67462
|
-
entry.playbackStartAt ??= new Date(
|
|
68088
|
+
entry.playbackStartAt ??= new Date(played.startMs).toISOString();
|
|
67463
68089
|
if (entry.playbackEndAt === void 0) {
|
|
67464
|
-
|
|
67465
|
-
entry.playbackEndAt = new Date(endMs).toISOString();
|
|
68090
|
+
entry.playbackEndAt = new Date(played.endMs).toISOString();
|
|
67466
68091
|
if (cutShort)
|
|
67467
68092
|
entry.interrupted = true;
|
|
67468
68093
|
}
|
|
67469
68094
|
};
|
|
68095
|
+
const timeUntimedAgentEntries = () => {
|
|
68096
|
+
for (const entry of untimedAgentEntries.splice(0))
|
|
68097
|
+
applySelfPlaybackFallback(entry, false);
|
|
68098
|
+
};
|
|
67470
68099
|
const flushPendingStreamLog = () => {
|
|
67471
68100
|
if (!pendingStreamLog)
|
|
67472
68101
|
return;
|
|
@@ -67484,10 +68113,22 @@ function realtimeAgent(options) {
|
|
|
67484
68113
|
transcript,
|
|
67485
68114
|
usage,
|
|
67486
68115
|
hangup() {
|
|
67487
|
-
|
|
67488
|
-
|
|
67489
|
-
|
|
67490
|
-
|
|
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);
|
|
67491
68132
|
},
|
|
67492
68133
|
async transfer(number) {
|
|
67493
68134
|
if (!E1642.test(number)) {
|
|
@@ -67496,7 +68137,7 @@ function realtimeAgent(options) {
|
|
|
67496
68137
|
await context.voice.transferToPhone(callId, number, {
|
|
67497
68138
|
liveLeg: CALLER_LEG2,
|
|
67498
68139
|
legName: TRANSFER_LEG2,
|
|
67499
|
-
call: { call }
|
|
68140
|
+
call: { call: call2 }
|
|
67500
68141
|
});
|
|
67501
68142
|
transferred = true;
|
|
67502
68143
|
if (callId)
|
|
@@ -67515,9 +68156,17 @@ function realtimeAgent(options) {
|
|
|
67515
68156
|
return;
|
|
67516
68157
|
ended = true;
|
|
67517
68158
|
flushPendingStreamLog();
|
|
68159
|
+
timeUntimedAgentEntries();
|
|
67518
68160
|
lifecycle.abort();
|
|
67519
68161
|
if (heartbeat !== void 0)
|
|
67520
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
|
+
}
|
|
67521
68170
|
if (vendorSession !== void 0)
|
|
67522
68171
|
adapter2.close(vendorSession);
|
|
67523
68172
|
if (ws.readyState === ws.OPEN)
|
|
@@ -67527,18 +68176,44 @@ function realtimeAgent(options) {
|
|
|
67527
68176
|
}
|
|
67528
68177
|
usage.audioSeconds ??= (Date.now() - callConnectedAtMs) / 1e3;
|
|
67529
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
|
+
}
|
|
67530
68191
|
try {
|
|
67531
68192
|
await options.onEnd?.(ctx);
|
|
67532
68193
|
} catch (err) {
|
|
67533
68194
|
console.error("[realtimeAgent] onEnd handler threw:", err.message);
|
|
67534
68195
|
}
|
|
67535
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);
|
|
67536
68207
|
const callbacks = {
|
|
67537
68208
|
onAudioOut(pcm) {
|
|
67538
68209
|
if (firstAudioAtMs === void 0 && lastUserTurnAt !== void 0)
|
|
67539
68210
|
firstAudioAtMs = Date.now();
|
|
67540
|
-
|
|
67541
|
-
|
|
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);
|
|
67542
68217
|
if (ws.readyState === ws.OPEN)
|
|
67543
68218
|
ws.send(pcm);
|
|
67544
68219
|
},
|
|
@@ -67562,10 +68237,11 @@ function realtimeAgent(options) {
|
|
|
67562
68237
|
};
|
|
67563
68238
|
if (turn.role === "user") {
|
|
67564
68239
|
flushPendingStreamLog();
|
|
68240
|
+
timeUntimedAgentEntries();
|
|
67565
68241
|
lastUserTurnAt = Date.now();
|
|
67566
68242
|
firstAudioAtMs = void 0;
|
|
67567
|
-
entry.speechStartAt =
|
|
67568
|
-
entry.speechEndAt =
|
|
68243
|
+
entry.speechStartAt = pendingSpeechStartAt;
|
|
68244
|
+
entry.speechEndAt = pendingSpeechEndAt;
|
|
67569
68245
|
pendingSpeechStartAt = void 0;
|
|
67570
68246
|
pendingSpeechEndAt = void 0;
|
|
67571
68247
|
speechEndFromProvider = false;
|
|
@@ -67573,10 +68249,8 @@ function realtimeAgent(options) {
|
|
|
67573
68249
|
entry.totalMs = Date.now() - lastUserTurnAt;
|
|
67574
68250
|
lastUserTurnAt = void 0;
|
|
67575
68251
|
entry.delegationMs = turn.delegationMs;
|
|
67576
|
-
entry.playbackStartAt =
|
|
67577
|
-
if (
|
|
67578
|
-
entry.playbackEndAt = turn.playbackEndAt;
|
|
67579
|
-
} else if (pendingAgentPlayback.endAt) {
|
|
68252
|
+
entry.playbackStartAt = pendingAgentPlayback.startAt;
|
|
68253
|
+
if (pendingAgentPlayback.endAt) {
|
|
67580
68254
|
entry.playbackEndAt = pendingAgentPlayback.endAt;
|
|
67581
68255
|
if (pendingAgentPlayback.interrupted)
|
|
67582
68256
|
entry.interrupted = true;
|
|
@@ -67589,7 +68263,8 @@ function realtimeAgent(options) {
|
|
|
67589
68263
|
currentAgentEntry = entry;
|
|
67590
68264
|
pendingStreamLog = { entry, totalMs: entry.totalMs, firstAudioAtMs };
|
|
67591
68265
|
}
|
|
67592
|
-
}
|
|
68266
|
+
} else if (turn.role === "agent")
|
|
68267
|
+
untimedAgentEntries.push(entry);
|
|
67593
68268
|
appendTranscript(entry);
|
|
67594
68269
|
},
|
|
67595
68270
|
onSpeechStart() {
|
|
@@ -67621,8 +68296,10 @@ function realtimeAgent(options) {
|
|
|
67621
68296
|
},
|
|
67622
68297
|
onBargeIn() {
|
|
67623
68298
|
sendStreamControl(ws, "clear");
|
|
68299
|
+
recorder?.clearAgent();
|
|
67624
68300
|
if (vendorSession !== void 0)
|
|
67625
68301
|
adapter2.clear(vendorSession);
|
|
68302
|
+
playout.clear(Date.now());
|
|
67626
68303
|
if (currentAgentEntry) {
|
|
67627
68304
|
applySelfPlaybackFallback(currentAgentEntry, true);
|
|
67628
68305
|
flushPendingStreamLog();
|
|
@@ -67643,10 +68320,53 @@ function realtimeAgent(options) {
|
|
|
67643
68320
|
void end();
|
|
67644
68321
|
}
|
|
67645
68322
|
};
|
|
67646
|
-
|
|
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) => {
|
|
67647
68363
|
if (ended || lifecycle.signal.aborted)
|
|
67648
68364
|
return void 0;
|
|
67649
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
|
+
}
|
|
67650
68370
|
return adapter2.connect(resolved, ctx, callbacks, lifecycle.signal);
|
|
67651
68371
|
}).then((session) => {
|
|
67652
68372
|
if (session === void 0)
|
|
@@ -67656,25 +68376,26 @@ function realtimeAgent(options) {
|
|
|
67656
68376
|
return;
|
|
67657
68377
|
}
|
|
67658
68378
|
vendorSession = session;
|
|
67659
|
-
|
|
67660
|
-
|
|
67661
|
-
|
|
67662
|
-
|
|
67663
|
-
|
|
67664
|
-
|
|
67665
|
-
if (
|
|
67666
|
-
|
|
67667
|
-
else
|
|
67668
|
-
|
|
67669
|
-
|
|
67670
|
-
}
|
|
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
|
+
}
|
|
67671
68391
|
}).catch((err) => {
|
|
67672
68392
|
if (ended)
|
|
67673
68393
|
return;
|
|
67674
68394
|
const sanitized = sanitizeVendorError(err);
|
|
67675
68395
|
console.error("[realtimeAgent] adapter connect failed:", sanitized.message);
|
|
67676
68396
|
invokeHook("onError", () => options.onError?.({ message: sanitized.message, code: sanitized.code, raw: sanitized }, ctx));
|
|
67677
|
-
|
|
68397
|
+
if (!answeredEarly)
|
|
68398
|
+
ws.send(JSON.stringify({ command: "reject" }));
|
|
67678
68399
|
if (ws.readyState === ws.OPEN)
|
|
67679
68400
|
ws.close(1011, "Vendor connect failed");
|
|
67680
68401
|
});
|
|
@@ -67753,13 +68474,17 @@ function realtimeAgent(options) {
|
|
|
67753
68474
|
}
|
|
67754
68475
|
const endpointFor = (event, clientContext) => {
|
|
67755
68476
|
const context = clientContext;
|
|
67756
|
-
const
|
|
67757
|
-
const callId = String(
|
|
68477
|
+
const call2 = event.call;
|
|
68478
|
+
const callId = String(call2?.callId ?? "");
|
|
67758
68479
|
const token = randomUUID2();
|
|
68480
|
+
const placed = placedCalls.get(String(call2?.sessionId ?? ""));
|
|
67759
68481
|
if (callId) {
|
|
67760
68482
|
pendingSessions.set(token, {
|
|
67761
|
-
call,
|
|
68483
|
+
call: call2,
|
|
67762
68484
|
requestContext: context,
|
|
68485
|
+
outbound: placed !== void 0,
|
|
68486
|
+
data: placed?.data,
|
|
68487
|
+
provider: placed?.provider,
|
|
67763
68488
|
expiresAt: Date.now() + PENDING_SESSION_TTL_MS,
|
|
67764
68489
|
expiryTimer: schedulePendingSessionExpiry(token)
|
|
67765
68490
|
});
|
|
@@ -67781,11 +68506,23 @@ function realtimeAgent(options) {
|
|
|
67781
68506
|
}
|
|
67782
68507
|
return streamEndpoint;
|
|
67783
68508
|
};
|
|
67784
|
-
const
|
|
67785
|
-
|
|
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();
|
|
67786
68523
|
return {
|
|
67787
|
-
callName: CALLER_LEG2,
|
|
67788
|
-
commands:
|
|
68524
|
+
...inbound && { callName: CALLER_LEG2 },
|
|
68525
|
+
commands: builder.bridgeCall(BRIDGE).dial(streamEndpoint, {
|
|
67789
68526
|
callName: STREAM_LEG2,
|
|
67790
68527
|
maxDuration: resolveMaxDuration(context),
|
|
67791
68528
|
onAnswer: (c) => c.bridgeCall(BRIDGE),
|
|
@@ -67799,9 +68536,26 @@ function realtimeAgent(options) {
|
|
|
67799
68536
|
onHangup: [{ command: "hangup", callName: STREAM_LEG2 }]
|
|
67800
68537
|
};
|
|
67801
68538
|
};
|
|
67802
|
-
const
|
|
67803
|
-
|
|
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 ?? "");
|
|
67804
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
|
+
}
|
|
67805
68559
|
for (const [token, pending] of pendingSessions) {
|
|
67806
68560
|
if (String(pending.call.callId ?? "") === callId)
|
|
67807
68561
|
deletePendingSession(token);
|
|
@@ -67811,7 +68565,27 @@ function realtimeAgent(options) {
|
|
|
67811
68565
|
}
|
|
67812
68566
|
}
|
|
67813
68567
|
};
|
|
67814
|
-
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
|
+
}
|
|
67815
68589
|
return {
|
|
67816
68590
|
setup(runtime) {
|
|
67817
68591
|
runtime.onStartup(async (context) => {
|
|
@@ -67821,7 +68595,9 @@ function realtimeAgent(options) {
|
|
|
67821
68595
|
},
|
|
67822
68596
|
voiceWebhook,
|
|
67823
68597
|
connect,
|
|
67824
|
-
|
|
68598
|
+
call,
|
|
68599
|
+
endpointFor,
|
|
68600
|
+
commandsBefore: () => recordsViaSinch(options.record) ? commands().recordToFunctions().build() : []
|
|
67825
68601
|
};
|
|
67826
68602
|
}
|
|
67827
68603
|
|
|
@@ -70844,6 +71620,20 @@ var LocalStorage = class {
|
|
|
70844
71620
|
const sanitized = key.replace(/^\/+/, "").replace(/\.\./g, "_");
|
|
70845
71621
|
return path4.join(this.baseDir, sanitized);
|
|
70846
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
|
+
}
|
|
70847
71637
|
async write(key, data) {
|
|
70848
71638
|
const filePath = this.resolvePath(key);
|
|
70849
71639
|
await fs3.mkdir(path4.dirname(filePath), { recursive: true });
|
|
@@ -76014,6 +76804,7 @@ var TunnelClient = class {
|
|
|
76014
76804
|
this.tunnelId = message.tunnelId || null;
|
|
76015
76805
|
this.tunnelUrl = message.publicUrl || null;
|
|
76016
76806
|
console.log(`Received welcome: tunnelId=${this.tunnelId}`);
|
|
76807
|
+
if (this.tunnelId && this.tunnelUrl) process.env[TUNNEL_PUBLIC_URL_ENV] = this.buildTunnelUrl();
|
|
76017
76808
|
if (this.welcomeResolver) {
|
|
76018
76809
|
this.welcomeResolver(true);
|
|
76019
76810
|
this.welcomeResolver = null;
|
|
@@ -76224,6 +77015,7 @@ var TunnelClient = class {
|
|
|
76224
77015
|
*/
|
|
76225
77016
|
async disconnect() {
|
|
76226
77017
|
this.shuttingDown = true;
|
|
77018
|
+
delete process.env[TUNNEL_PUBLIC_URL_ENV];
|
|
76227
77019
|
this.stopHeartbeat();
|
|
76228
77020
|
this.streams.closeAll("Tunnel client shutting down");
|
|
76229
77021
|
if (this.ws) {
|
|
@@ -76784,9 +77576,12 @@ export {
|
|
|
76784
77576
|
createMenu,
|
|
76785
77577
|
createSimpleMenu,
|
|
76786
77578
|
MenuTemplates,
|
|
77579
|
+
RECORDING_RECEIVER_PATH,
|
|
77580
|
+
recordingKey,
|
|
76787
77581
|
UniversalConfig,
|
|
76788
77582
|
createConfig,
|
|
76789
77583
|
createUniversalConfig,
|
|
77584
|
+
require_express2 as require_express,
|
|
76790
77585
|
REDACTED,
|
|
76791
77586
|
redactCredentials,
|
|
76792
77587
|
stringify,
|
|
@@ -76796,7 +77591,9 @@ export {
|
|
|
76796
77591
|
DEFAULT_STT_LANGUAGE,
|
|
76797
77592
|
dial,
|
|
76798
77593
|
endpointNumber,
|
|
77594
|
+
MAX_SAY_CHARS,
|
|
76799
77595
|
DEFAULT_BRIDGE_NAME,
|
|
77596
|
+
RECORD_TO_FUNCTIONS_SENTINEL,
|
|
76800
77597
|
PromptBuilder,
|
|
76801
77598
|
MenuItemBuilder,
|
|
76802
77599
|
CommandBuilder,
|
|
@@ -76820,6 +77617,12 @@ export {
|
|
|
76820
77617
|
Client,
|
|
76821
77618
|
createClient,
|
|
76822
77619
|
connectAgent,
|
|
77620
|
+
AGENT_STREAM_PATH,
|
|
77621
|
+
AGENT_HEADER_TOKEN,
|
|
77622
|
+
TUNNEL_PUBLIC_URL_ENV,
|
|
77623
|
+
tunnelPublicUrl,
|
|
77624
|
+
resolveAgentStreamUrl,
|
|
77625
|
+
buildAgentStreamEndpoint,
|
|
76823
77626
|
attachVoiceClient,
|
|
76824
77627
|
onCall,
|
|
76825
77628
|
toCamelCase,
|
|
@@ -76879,6 +77682,7 @@ export {
|
|
|
76879
77682
|
buildBaseContext,
|
|
76880
77683
|
handleVoiceV1Callback,
|
|
76881
77684
|
handleVoiceWebhook,
|
|
77685
|
+
rewriteRecordingSentinels,
|
|
76882
77686
|
handleCustomEndpoint,
|
|
76883
77687
|
createApp,
|
|
76884
77688
|
createSinchRuntime,
|
|
@@ -76890,10 +77694,6 @@ export {
|
|
|
76890
77694
|
ElevenLabsController,
|
|
76891
77695
|
tryAutoConfigureAsync,
|
|
76892
77696
|
ElevenLabsAutoConfigurator,
|
|
76893
|
-
AGENT_STREAM_PATH,
|
|
76894
|
-
AGENT_HEADER_TOKEN,
|
|
76895
|
-
resolveAgentStreamUrl,
|
|
76896
|
-
buildAgentStreamEndpoint,
|
|
76897
77697
|
tool,
|
|
76898
77698
|
voiceRelay,
|
|
76899
77699
|
realtimeAgent,
|
|
@@ -77230,4 +78030,4 @@ serve-static/index.js:
|
|
|
77230
78030
|
* MIT Licensed
|
|
77231
78031
|
*)
|
|
77232
78032
|
*/
|
|
77233
|
-
//# sourceMappingURL=chunk-
|
|
78033
|
+
//# sourceMappingURL=chunk-KGCIUPCT.js.map
|