@sinch/functions-runtime 0.7.1 → 0.7.3

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.
@@ -59781,6 +59781,18 @@ var MenuTemplates = {
59781
59781
  }
59782
59782
  };
59783
59783
 
59784
+ // ../runtime-shared/dist/storage/recording.js
59785
+ var RECORDING_RECEIVER_PATH = "/_sinch/recording/";
59786
+ function normalizeRecordingFormat(format) {
59787
+ const f = format.toLowerCase();
59788
+ if (f !== "mp3" && f !== "wav")
59789
+ throw new Error(`Unsupported recording format "${format}"`);
59790
+ return f;
59791
+ }
59792
+ function recordingKey(callId, format) {
59793
+ return `recordings/${callId.replace(/[^\w-]/g, "_")}.${format}`;
59794
+ }
59795
+
59784
59796
  // ../runtime-shared/dist/config/universal.js
59785
59797
  var UniversalConfig = class {
59786
59798
  context;
@@ -60180,52 +60192,6 @@ function toCallHeaders(headers) {
60180
60192
  return list.length > 0 ? list : void 0;
60181
60193
  }
60182
60194
 
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
60195
  // ../voice-v2-preview/dist/core/say-limit.js
60230
60196
  var MAX_SAY_CHARS = 600;
60231
60197
  var MAX_MESSAGES = 10;
@@ -60287,6 +60253,52 @@ function sentenceSpans(text) {
60287
60253
  return spans;
60288
60254
  }
60289
60255
 
60256
+ // ../voice-v2-preview/dist/core/agent-endpoint.js
60257
+ var DEFAULT_AGENT_MAX_DURATION = 1800;
60258
+ function agentMaxDuration(context) {
60259
+ const raw = (context?.env ?? process.env)["MAX_CALL_DURATION"];
60260
+ return raw ? Number(raw) : DEFAULT_AGENT_MAX_DURATION;
60261
+ }
60262
+ var PROVIDER_ENDPOINTS = {
60263
+ elevenlabs: { host: "sip.rtc.elevenlabs.io", port: 5060, transport: "TCP" },
60264
+ grok: { host: "sip.voice.x.ai", port: 5061, transport: "TLS" }
60265
+ };
60266
+ var UNSAFE_HOST_CHAR = /[\x00-\x1f\x7f@;\s]/;
60267
+ function sipAgentAddress(provider, number, options) {
60268
+ const endpoint = PROVIDER_ENDPOINTS[provider];
60269
+ if (!endpoint) {
60270
+ 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.`);
60271
+ }
60272
+ if (!E164.test(number)) {
60273
+ 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.)`);
60274
+ }
60275
+ const host = options.host ?? endpoint.host;
60276
+ if (UNSAFE_HOST_CHAR.test(host)) {
60277
+ 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.`);
60278
+ }
60279
+ const port = options.port ?? endpoint.port;
60280
+ const transport = options.transport ?? endpoint.transport;
60281
+ const sipUri = `sip:${number}@${host}:${port};transport=${transport.toLowerCase()}`;
60282
+ return (event) => {
60283
+ const call = event?.call;
60284
+ const perCall = call ? {
60285
+ "X-Sinch-Call-Id": call.callId ?? "",
60286
+ "X-Caller-Number": endpointNumber(call.from),
60287
+ "X-Dialed-Number": endpointNumber(call.to)
60288
+ } : {};
60289
+ const headers = { ...perCall, ...toHeaderMap(options.headers) };
60290
+ return dial.sip(sipUri, { transport, headers });
60291
+ };
60292
+ }
60293
+ function toHeaderMap(headers) {
60294
+ if (!headers)
60295
+ return {};
60296
+ if (Array.isArray(headers)) {
60297
+ return Object.fromEntries(headers.map((h) => [h.key, h.value ?? ""]));
60298
+ }
60299
+ return { ...headers };
60300
+ }
60301
+
60290
60302
  // ../voice-v2-preview/dist/core/commands.js
60291
60303
  function internals(builder) {
60292
60304
  return builder;
@@ -60465,6 +60477,10 @@ function bridgeStep(to, options, leg) {
60465
60477
  ];
60466
60478
  };
60467
60479
  }
60480
+ var RECORD_TO_FUNCTIONS_SENTINEL = "@functions";
60481
+ function isPresignedDestination(url2) {
60482
+ return url2 === RECORD_TO_FUNCTIONS_SENTINEL || /^https:\/\//i.test(url2);
60483
+ }
60468
60484
  function toCredentials(credentials) {
60469
60485
  if (typeof credentials === "string") {
60470
60486
  return credentials;
@@ -60476,13 +60492,16 @@ function toCredentials(credentials) {
60476
60492
  return parts.join(":");
60477
60493
  }
60478
60494
  function toRecordingOptions(options) {
60495
+ if (options.credentials === void 0 && !isPresignedDestination(options.destinationUrl)) {
60496
+ throw new Error("Voice v2 startRecording needs credentials unless destinationUrl is an https:// presigned URL.");
60497
+ }
60479
60498
  const transcribing = options.transcribe !== void 0 || options.transcriptionLocale !== void 0;
60480
60499
  return {
60481
60500
  ...options.format && { format: options.format },
60482
60501
  ...options.recordingType && { recordingType: options.recordingType },
60483
60502
  destination: options.destination ?? "AWS",
60484
60503
  destinationUrl: options.destinationUrl,
60485
- credentials: toCredentials(options.credentials),
60504
+ ...options.credentials !== void 0 && { credentials: toCredentials(options.credentials) },
60486
60505
  ...transcribing && {
60487
60506
  transcriptionOptions: {
60488
60507
  isEnabled: options.transcribe ?? true,
@@ -60870,6 +60889,10 @@ var CommandBuilder = class {
60870
60889
  dialAgent(target, numberOrOptions, sipOptions = {}) {
60871
60890
  if (typeof target !== "string") {
60872
60891
  const options2 = numberOrOptions ?? {};
60892
+ const before = target.commandsBefore;
60893
+ if (before) {
60894
+ this.push((scope) => scope?.event ? before.call(target, scope.event, scope.context) : []);
60895
+ }
60873
60896
  return this.push(bridgeStep(agentEndpoint(target), options2, STREAM_AGENT_LEG));
60874
60897
  }
60875
60898
  const { headers, transport, host, port, ...options } = sipOptions;
@@ -61068,6 +61091,31 @@ var CommandBuilder = class {
61068
61091
  ...Object.keys(events).length > 0 && { events }
61069
61092
  });
61070
61093
  }
61094
+ /**
61095
+ * Record the call into this function's own storage (`recordings/<callId>.mp3`), with no
61096
+ * credentials. Emits a `startRecording` whose destination is a placeholder
61097
+ * ({@link RECORD_TO_FUNCTIONS_SENTINEL}); the runtime host replaces it with a presigned PUT
61098
+ * URL for the exact key just before the response is sent, and drops the command with a warning
61099
+ * when it cannot (no callId, or storage without a recording destination). Needs a runtime
61100
+ * that does the rewrite — sending this builder's output anywhere else delivers the placeholder.
61101
+ *
61102
+ * Transcription is not offered: the transcript URL is derived from the recording URL, which a
61103
+ * presigned URL cannot carry. The recording is named so {@link stopRecording} can end it;
61104
+ * `recordingName` defaults to `functions-recording`. Without an `onFailure` flow a failed
61105
+ * recording is silent — the platform sends no webhook for it.
61106
+ *
61107
+ * @param options - Format (default `MP3`), recording name, streams captured, outcome flows
61108
+ */
61109
+ recordToFunctions(options = {}) {
61110
+ return this.startRecording({
61111
+ destinationUrl: RECORD_TO_FUNCTIONS_SENTINEL,
61112
+ recordingName: options.recordingName ?? "functions-recording",
61113
+ format: options.format ?? "MP3",
61114
+ ...options.recordingType && { recordingType: options.recordingType },
61115
+ ...options.onFinish !== void 0 && { onFinish: options.onFinish },
61116
+ ...options.onFailure !== void 0 && { onFailure: options.onFailure }
61117
+ });
61118
+ }
61071
61119
  /**
61072
61120
  * Stop a named recording. Non-blocking.
61073
61121
  *
@@ -61776,7 +61824,8 @@ var Client = class {
61776
61824
  if (!this.publicUrl) {
61777
61825
  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
61826
  }
61779
- return `${this.publicUrl}${stream5}`;
61827
+ const query = this.publicUrl.indexOf("?");
61828
+ return query < 0 ? `${this.publicUrl}${stream5}` : `${this.publicUrl.slice(0, query)}${stream5}${this.publicUrl.slice(query)}`;
61780
61829
  }
61781
61830
  };
61782
61831
  function createClient(context, options) {
@@ -61844,6 +61893,141 @@ function connectAgent(provider, number, options = {}) {
61844
61893
  };
61845
61894
  }
61846
61895
 
61896
+ // ../runtime-shared/dist/ai/realtime/wire-safety.js
61897
+ var MAX_INBOUND_FRAME_BYTES = 1e6;
61898
+ function isOversizedFrame(raw) {
61899
+ return raw.length > MAX_INBOUND_FRAME_BYTES;
61900
+ }
61901
+ var BASE64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
61902
+ function safeBase64ToBuffer(value) {
61903
+ if (typeof value !== "string")
61904
+ return void 0;
61905
+ if (value.length > 0 && !BASE64_RE.test(value))
61906
+ return void 0;
61907
+ try {
61908
+ return Buffer.from(value, "base64");
61909
+ } catch {
61910
+ return void 0;
61911
+ }
61912
+ }
61913
+ function isPlainObject(value) {
61914
+ return typeof value === "object" && value !== null && !Array.isArray(value);
61915
+ }
61916
+ function parseVendorFrame(raw) {
61917
+ let parsed;
61918
+ try {
61919
+ parsed = JSON.parse(raw.toString());
61920
+ } catch {
61921
+ return void 0;
61922
+ }
61923
+ return isPlainObject(parsed) ? parsed : void 0;
61924
+ }
61925
+ function safeToolOutput(value) {
61926
+ try {
61927
+ return JSON.stringify(value ?? {});
61928
+ } catch {
61929
+ return JSON.stringify({ error: "realtimeAgent: tool result could not be serialized" });
61930
+ }
61931
+ }
61932
+
61933
+ // ../runtime-shared/dist/security/local-dev.js
61934
+ function isLoopbackUrl(url2) {
61935
+ if (!url2)
61936
+ return false;
61937
+ let hostname;
61938
+ try {
61939
+ hostname = new URL(url2).hostname.toLowerCase();
61940
+ } catch {
61941
+ return false;
61942
+ }
61943
+ if (["localhost", "0.0.0.0", "[::1]", "::1"].includes(hostname))
61944
+ return true;
61945
+ if (hostname.endsWith(".localhost"))
61946
+ return true;
61947
+ return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
61948
+ }
61949
+ function isLocalDevMode(env) {
61950
+ return env["SINCH_LOCAL_DEV"] === "true" && isLoopbackUrl(env["API_URL"]);
61951
+ }
61952
+ var LOCAL_DEV_MODE = isLocalDevMode(process.env);
61953
+
61954
+ // ../runtime-shared/dist/ai/agent-stream.js
61955
+ var AGENT_SAMPLE_RATE = 16e3;
61956
+ var AGENT_STREAM_PATH = "/stream";
61957
+ var AGENT_HEADER_TOKEN = "x-sinch-agent-token";
61958
+ function deriveSocketUrl(path7) {
61959
+ const fnName = process.env["FUNCTION_NAME"];
61960
+ const apiUrl = process.env["API_URL"];
61961
+ if (!fnName || !apiUrl)
61962
+ return "";
61963
+ if (!/^[a-z0-9][a-z0-9-]{0,51}$/.test(fnName))
61964
+ return "";
61965
+ const match = apiUrl.match(/api\.functions\.(\w+)\.sinchvoice\.org/);
61966
+ if (!match)
61967
+ return "";
61968
+ return `wss://${fnName}.fn-${match[1]}.sinch.com${path7}`;
61969
+ }
61970
+ function isLocalDevUrl(url2) {
61971
+ if (isLoopbackUrl(url2))
61972
+ return true;
61973
+ let hostname;
61974
+ try {
61975
+ hostname = new URL(url2).hostname.toLowerCase();
61976
+ } catch {
61977
+ return false;
61978
+ }
61979
+ return /(^|\.)(trycloudflare\.com|loca\.lt)$/.test(hostname) || /(^|\.)ngrok[.-]/.test(hostname);
61980
+ }
61981
+ function isDeployed(context) {
61982
+ return context?.config?.environment === "production" && !LOCAL_DEV_MODE;
61983
+ }
61984
+ var TUNNEL_PUBLIC_URL_ENV = "SINCH_TUNNEL_PUBLIC_URL";
61985
+ function tunnelPublicUrl(path7, kind) {
61986
+ const raw = process.env[TUNNEL_PUBLIC_URL_ENV];
61987
+ if (!raw)
61988
+ return void 0;
61989
+ const url2 = new URL(raw);
61990
+ url2.pathname = url2.pathname.replace(/\/+$/, "") + path7;
61991
+ const secure = url2.protocol === "https:" || url2.protocol === "wss:";
61992
+ url2.protocol = kind === "ws" ? secure ? "wss:" : "ws:" : secure ? "https:" : "http:";
61993
+ return url2.toString();
61994
+ }
61995
+ function resolveAgentStreamUrl(context, override) {
61996
+ return resolveSelfSocketUrl(AGENT_STREAM_PATH, "STREAM_URL", context, override);
61997
+ }
61998
+ function resolveSelfSocketUrl(path7, envVar, context, override) {
61999
+ const url2 = override || (isDeployed(context) ? void 0 : tunnelPublicUrl(path7, "ws")) || (context?.host ? `wss://${context.host}${path7}` : "") || process.env[envVar] || deriveSocketUrl(path7);
62000
+ if (!url2) {
62001
+ throw new Error(`WebSocket URL for ${path7} cannot be determined \u2014 set ${envVar}, or ensure FUNCTION_NAME and API_URL are present.`);
62002
+ }
62003
+ if (isDeployed(context) && isLocalDevUrl(url2)) {
62004
+ 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.`);
62005
+ }
62006
+ return url2;
62007
+ }
62008
+ function buildAgentStreamEndpoint(options) {
62009
+ return dial.stream(options.endpoint, {
62010
+ sampleRate: options.sampleRate ?? AGENT_SAMPLE_RATE,
62011
+ headers: { ...options.headers, [AGENT_HEADER_TOKEN]: options.token }
62012
+ });
62013
+ }
62014
+ function upgradeHeader(req, name) {
62015
+ const raw = req?.headers?.[name] ?? req?.headers?.[name.toLowerCase()];
62016
+ return Array.isArray(raw) ? raw[0] ?? "" : raw ?? "";
62017
+ }
62018
+ function readCallHeader(connectMsg, name) {
62019
+ const raw = connectMsg["callHeaders"] ?? connectMsg["callheaders"] ?? connectMsg["headers"];
62020
+ if (Array.isArray(raw)) {
62021
+ const hit = raw.find((e) => isPlainObject(e) && typeof e["key"] === "string" && typeof e["value"] === "string" && e.key.toLowerCase() === name);
62022
+ return hit?.value ?? "";
62023
+ }
62024
+ if (isPlainObject(raw)) {
62025
+ const hit = Object.entries(raw).find(([k]) => k.toLowerCase() === name);
62026
+ return hit ? String(hit[1] ?? "") : "";
62027
+ }
62028
+ return "";
62029
+ }
62030
+
61847
62031
  // ../runtime-shared/dist/security/context-secrets.js
61848
62032
  import { inspect } from "util";
61849
62033
  var HIDDEN_ENV_KEYS = [
@@ -62106,7 +62290,8 @@ function attachVoiceClient(context, v1) {
62106
62290
  enumerable: true,
62107
62291
  get() {
62108
62292
  if (!client) {
62109
- client = Object.assign(createClient(context), { v1 });
62293
+ const publicUrl = process.env[TUNNEL_PUBLIC_URL_ENV];
62294
+ client = Object.assign(createClient(context, publicUrl ? { publicUrl } : void 0), { v1 });
62110
62295
  }
62111
62296
  return client;
62112
62297
  }
@@ -62855,7 +63040,7 @@ function installStdioRedaction() {
62855
63040
  // ../runtime-shared/dist/security/voice-signature.js
62856
63041
  import { createHash, createHmac as createHmac2, timingSafeEqual as timingSafeEqual3 } from "crypto";
62857
63042
  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; Sinch does not expose the service secret yet";
63043
+ 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
63044
  var AUTHORIZATION_PATTERN = /^service\s+([^:\s]+):(\S+)$/i;
62860
63045
  function fail(reason) {
62861
63046
  return { valid: false, reason };
@@ -63012,67 +63197,30 @@ function resetSinchClients() {
63012
63197
  // ../runtime-shared/dist/host/app.js
63013
63198
  var import_express2 = __toESM(require_express2(), 1);
63014
63199
 
63015
- // ../runtime-shared/dist/ai/realtime/wire-safety.js
63016
- var MAX_INBOUND_FRAME_BYTES = 1e6;
63017
- function isOversizedFrame(raw) {
63018
- return raw.length > MAX_INBOUND_FRAME_BYTES;
63200
+ // ../runtime-shared/dist/host/exports.js
63201
+ import { types } from "util";
63202
+ var fnToString = Function.prototype.toString;
63203
+ var fnBind = Function.prototype.bind;
63204
+ var OBJECT_PROTOTYPE_NAMES = new Set(Object.getOwnPropertyNames(Object.prototype));
63205
+ function isAuthorClassPrototype(proto) {
63206
+ if (types.isProxy(proto))
63207
+ return false;
63208
+ const ctor = Object.getOwnPropertyDescriptor(proto, "constructor")?.value;
63209
+ if (typeof ctor !== "function" || types.isProxy(ctor))
63210
+ return false;
63211
+ if (Object.getOwnPropertyDescriptor(ctor, "prototype")?.value !== proto)
63212
+ return false;
63213
+ if (!/^class\b/.test(fnToString.call(ctor)))
63214
+ return false;
63215
+ const name = Object.getOwnPropertyDescriptor(ctor, "name")?.value;
63216
+ return !(typeof name === "string" && Object.getOwnPropertyDescriptor(globalThis, name)?.value === ctor);
63019
63217
  }
63020
- var BASE64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
63021
- function safeBase64ToBuffer(value) {
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 {
63218
+ function findExport(target, name) {
63219
+ if (OBJECT_PROTOTYPE_NAMES.has(name))
63029
63220
  return void 0;
63030
- }
63031
- }
63032
- function isPlainObject(value) {
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;
63221
+ if (Object.hasOwn(target, name)) {
63222
+ const value = target[name];
63223
+ return typeof value === "function" ? fnBind.call(value, target) : void 0;
63076
63224
  }
63077
63225
  if (types.isProxy(target))
63078
63226
  return void 0;
@@ -63404,12 +63552,52 @@ async function handleVoiceWebhook(userFunction, context, event, request, logger)
63404
63552
  return formatCustomResponse(result2);
63405
63553
  }
63406
63554
  const body = await context.voice.onCall({ fallback: () => result2 })(event);
63555
+ await rewriteRecordingSentinels(body, event.call?.callId, context.storage);
63407
63556
  return body === void 0 ? { statusCode: 204 } : {
63408
63557
  statusCode: 200,
63409
63558
  headers: { "Content-Type": "application/json" },
63410
63559
  body: stringify(body)
63411
63560
  };
63412
63561
  }
63562
+ async function rewriteRecordingSentinels(body, callId, storage) {
63563
+ const resolve = async (options) => {
63564
+ if (!callId || !(storage?.recordingUrl ?? storage?.getRecordingDestination)) {
63565
+ console.warn(`[recording] Dropping the recording command: ${callId ? "this storage cannot presign a recording destination" : "the event has no callId"}.`);
63566
+ return false;
63567
+ }
63568
+ const format = String(options["format"] ?? "MP3").toLowerCase();
63569
+ if (format !== "mp3" && format !== "wav") {
63570
+ console.warn(`[recording] Dropping the recording command: unsupported format "${format}".`);
63571
+ return false;
63572
+ }
63573
+ try {
63574
+ options["destinationUrl"] = await (storage.recordingUrl ? storage.recordingUrl(callId, format) : storage.getRecordingDestination(callId, format));
63575
+ return true;
63576
+ } catch (err) {
63577
+ console.warn("[recording] Dropping the recording command, presigning failed:", err);
63578
+ return false;
63579
+ }
63580
+ };
63581
+ const walk = async (node) => {
63582
+ if (Array.isArray(node)) {
63583
+ for (let i = node.length - 1; i >= 0; i--) {
63584
+ const item = node[i];
63585
+ const options = item?.recordingOptions;
63586
+ if (item?.command === "startRecording" && options?.["destinationUrl"] === RECORD_TO_FUNCTIONS_SENTINEL) {
63587
+ if (!await resolve(options)) {
63588
+ node.splice(i, 1);
63589
+ continue;
63590
+ }
63591
+ }
63592
+ await walk(item);
63593
+ }
63594
+ } else if (node !== null && typeof node === "object") {
63595
+ for (const child of Object.values(node))
63596
+ await walk(child);
63597
+ }
63598
+ };
63599
+ await walk(body);
63600
+ }
63413
63601
  function isVoiceResult(result2) {
63414
63602
  return Array.isArray(result2) || result2 instanceof CommandBuilder || typeof result2 === "object" && Array.isArray(result2.commands);
63415
63603
  }
@@ -63452,7 +63640,8 @@ function createApp(options = {}) {
63452
63640
  }
63453
63641
  };
63454
63642
  setupJsonParsing(app, jsonOptions);
63455
- app.use(import_express2.default.urlencoded({ extended: true, limit: "10mb" }));
63643
+ const urlencoded = import_express2.default.urlencoded({ extended: true, limit: "10mb" });
63644
+ app.use((req, res, next) => req.path.startsWith(RECORDING_RECEIVER_PATH) ? next() : urlencoded(req, res, next));
63456
63645
  return app;
63457
63646
  }
63458
63647
  function createSinchRuntime() {
@@ -64154,74 +64343,6 @@ var ElevenLabsAutoConfigurator = class {
64154
64343
  static tryAutoConfigureAsync = tryAutoConfigureAsync;
64155
64344
  };
64156
64345
 
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
64346
  // ../runtime-shared/dist/ai/realtime/types.js
64226
64347
  function tool(def) {
64227
64348
  return def;
@@ -64837,6 +64958,61 @@ function createDeepgramAdapter(webSocketClient) {
64837
64958
  }
64838
64959
  var deepgramAdapter = createDeepgramAdapter();
64839
64960
 
64961
+ // ../runtime-shared/dist/ai/realtime/vad.js
64962
+ var DEFAULT_THRESHOLD = 500;
64963
+ var DEFAULT_ATTACK_FRAMES = 2;
64964
+ var DEFAULT_HANGOVER_FRAMES = 20;
64965
+ function pcm16Rms(pcm) {
64966
+ if (pcm.length < 2)
64967
+ return 0;
64968
+ let sumSquares = 0;
64969
+ const samples = pcm.length >> 1;
64970
+ for (let i = 0; i < samples; i++) {
64971
+ const sample = pcm.readInt16LE(i * 2);
64972
+ sumSquares += sample * sample;
64973
+ }
64974
+ return Math.sqrt(sumSquares / samples);
64975
+ }
64976
+ var SILENCE_RMS_THRESHOLD = 32768 * 10 ** (-50 / 20);
64977
+ function isSpeechFrame(pcm) {
64978
+ return pcm16Rms(pcm) > SILENCE_RMS_THRESHOLD;
64979
+ }
64980
+ function createEnergyVad(options = {}) {
64981
+ const threshold = options.threshold ?? DEFAULT_THRESHOLD;
64982
+ const attackFrames = options.attackFrames ?? DEFAULT_ATTACK_FRAMES;
64983
+ const hangoverFrames = options.hangoverFrames ?? DEFAULT_HANGOVER_FRAMES;
64984
+ let speaking = false;
64985
+ let loudRun = 0;
64986
+ let quietRun = 0;
64987
+ return {
64988
+ get speaking() {
64989
+ return speaking;
64990
+ },
64991
+ get quietFrames() {
64992
+ return quietRun;
64993
+ },
64994
+ push(pcm) {
64995
+ const loud = pcm16Rms(pcm) >= threshold;
64996
+ if (loud) {
64997
+ loudRun++;
64998
+ quietRun = 0;
64999
+ } else {
65000
+ quietRun++;
65001
+ loudRun = 0;
65002
+ }
65003
+ if (!speaking && loud && loudRun >= attackFrames) {
65004
+ speaking = true;
65005
+ return "start";
65006
+ }
65007
+ if (speaking && !loud && quietRun >= hangoverFrames) {
65008
+ speaking = false;
65009
+ return "end";
65010
+ }
65011
+ return void 0;
65012
+ }
65013
+ };
65014
+ }
65015
+
64840
65016
  // ../runtime-shared/dist/ai/realtime/audio.js
64841
65017
  var MULAW_BIAS = 132;
64842
65018
  var MULAW_CLIP = 32635;
@@ -64987,14 +65163,14 @@ var TRANSFER_TOOL_NAME = "transfer_to_human";
64987
65163
  function offersHangup(tools) {
64988
65164
  return tools.some((t) => t.name === HANGUP_TOOL_NAME);
64989
65165
  }
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. Give a brief natural closing statement.\n2. Immediately call the `hangup_call` tool.\n3. Do not wait for another user turn after saying goodbye.\nYou cannot end the phone call by saying goodbye. The call only ends when you call the `hangup_call` tool.';
65166
+ 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
65167
  var DELEGATED_CALL_TERMINATION_INSTRUCTIONS = `
64992
65168
 
64993
65169
  CALL TERMINATION
64994
65170
  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
65171
  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;
65172
+ async function resolvePerCallValue(value, call, context, data) {
65173
+ return typeof value === "function" ? await value(call, context, data) : value;
64998
65174
  }
64999
65175
  function builtInTools(hangupEnabled, transferNumber, ctx) {
65000
65176
  const tools = [];
@@ -65045,31 +65221,17 @@ var DEFAULT_BACKEND_MODEL = "gpt-5.6-luna";
65045
65221
  var VENDOR_RATE = 8e3;
65046
65222
  var TURN_SILENCE_MS = 1500;
65047
65223
  var TRANSCRIPT_FALLBACK_MS = 300;
65048
- var SILENCE_DBFS_THRESHOLD = -50;
65049
- var SILENCE_RMS_THRESHOLD = 32768 * 10 ** (SILENCE_DBFS_THRESHOLD / 20);
65050
65224
  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
65225
  function buildGreetingDirective(greeting) {
65071
65226
  return `Greet the caller now by saying exactly: "${greeting}"`;
65072
65227
  }
65228
+ function sendGreeting(ws, greeting) {
65229
+ ws.send(JSON.stringify({
65230
+ type: "session.instructions.append",
65231
+ content: buildGreetingDirective(greeting),
65232
+ delegation_id: null
65233
+ }));
65234
+ }
65073
65235
  var CLOSE_ACK_TIMEOUT_MS = 1e3;
65074
65236
  var USER_TURN_ARRIVAL_FALLBACK_MS = TURN_SILENCE_MS * 2;
65075
65237
  var DEFAULT_BACKEND_SERVICE_TIER = "priority";
@@ -65209,10 +65371,6 @@ function createOpenAiAdapter(webSocketClient) {
65209
65371
  sessionSeconds: void 0,
65210
65372
  backendInputTokens: 0,
65211
65373
  backendOutputTokens: 0,
65212
- pendingUserTurnStartMs: void 0,
65213
- pendingAgentTurnStartMs: void 0,
65214
- pendingAgentTurnEndMs: void 0,
65215
- sessionStartedAtMs: void 0,
65216
65374
  delegationCreatedAtMs: /* @__PURE__ */ new Map(),
65217
65375
  delegationFirstOutputMs: /* @__PURE__ */ new Map(),
65218
65376
  delegationToolMs: /* @__PURE__ */ new Map(),
@@ -65275,10 +65433,6 @@ function createOpenAiAdapter(webSocketClient) {
65275
65433
  session.agentTurnStartedAt = void 0;
65276
65434
  const text = session.pendingAgentTurnText;
65277
65435
  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
65436
  let delegationMs;
65283
65437
  if (session.lastDelegationId !== void 0) {
65284
65438
  const firstOutputMs = session.delegationFirstOutputMs.get(session.lastDelegationId);
@@ -65295,8 +65449,6 @@ function createOpenAiAdapter(webSocketClient) {
65295
65449
  role: "agent",
65296
65450
  text,
65297
65451
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
65298
- playbackStartAt,
65299
- playbackEndAt,
65300
65452
  delegationMs
65301
65453
  });
65302
65454
  };
@@ -65310,19 +65462,14 @@ function createOpenAiAdapter(webSocketClient) {
65310
65462
  clearTimeout(session.userTurnTimer);
65311
65463
  session.userTurnTimer = void 0;
65312
65464
  }
65313
- const speechStartAt = toAnchoredIso(session, session.pendingUserTurnStartMs);
65314
- const speechEndAt = toAnchoredIso(session, session.pendingUserTurnEndMs);
65315
65465
  session.pendingUserTurnEndMs = void 0;
65316
- session.pendingUserTurnStartMs = void 0;
65317
65466
  const text = session.pendingUserTurnText;
65318
65467
  session.pendingUserTurnText = "";
65319
65468
  if (text)
65320
65469
  callbacks.onTurn({
65321
65470
  role: "user",
65322
65471
  text,
65323
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
65324
- speechStartAt,
65325
- speechEndAt
65472
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
65326
65473
  });
65327
65474
  };
65328
65475
  const scheduleUserTurnFlush = () => {
@@ -65384,15 +65531,10 @@ function createOpenAiAdapter(webSocketClient) {
65384
65531
  case "session.started": {
65385
65532
  const started = msg["session"];
65386
65533
  session.expiresAt = started?.expires_at;
65387
- session.sessionStartedAtMs = Date.now();
65388
65534
  session.ready = true;
65389
65535
  settle2(() => resolve(session));
65390
65536
  if (options.greeting) {
65391
- vendorWs.send(JSON.stringify({
65392
- type: "session.instructions.append",
65393
- content: buildGreetingDirective(options.greeting),
65394
- delegation_id: null
65395
- }));
65537
+ sendGreeting(vendorWs, options.greeting);
65396
65538
  }
65397
65539
  break;
65398
65540
  }
@@ -65424,9 +65566,6 @@ function createOpenAiAdapter(webSocketClient) {
65424
65566
  if (hasRealGap)
65425
65567
  flushUserTurnNow();
65426
65568
  if (delta) {
65427
- if (session.pendingUserTurnText === "" && startMs !== void 0) {
65428
- session.pendingUserTurnStartMs = startMs;
65429
- }
65430
65569
  session.pendingUserTurnText += delta;
65431
65570
  }
65432
65571
  if (endMs !== void 0)
@@ -65436,20 +65575,14 @@ function createOpenAiAdapter(webSocketClient) {
65436
65575
  }
65437
65576
  case "session.output_transcript.delta": {
65438
65577
  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
65578
  if (delta) {
65442
65579
  if (session.pendingAgentTurnText === "") {
65443
65580
  session.agentTurnStartedAt = Date.now();
65444
65581
  if (session.agentTurnHardCapTimer !== void 0)
65445
65582
  clearTimeout(session.agentTurnHardCapTimer);
65446
65583
  session.agentTurnHardCapTimer = setTimeout(flushAgentTurnNow, AGENT_TURN_HARD_CAP_MS);
65447
- if (startMs !== void 0)
65448
- session.pendingAgentTurnStartMs = startMs;
65449
65584
  }
65450
65585
  session.pendingAgentTurnText += delta;
65451
- if (endMs !== void 0)
65452
- session.pendingAgentTurnEndMs = endMs;
65453
65586
  }
65454
65587
  const audioQuiet = session.lastSpeechAudioAt !== void 0 && Date.now() - session.lastSpeechAudioAt > TURN_SILENCE_MS;
65455
65588
  if (audioQuiet) {
@@ -65502,7 +65635,7 @@ function createOpenAiAdapter(webSocketClient) {
65502
65635
  break;
65503
65636
  }
65504
65637
  case "session.delegation.created": {
65505
- const delegationId = msg["delegation_id"];
65638
+ const delegationId = msg["delegation"]?.id ?? msg["delegation_id"];
65506
65639
  if (delegationId)
65507
65640
  session.delegationCreatedAtMs.set(delegationId, Date.now());
65508
65641
  break;
@@ -65573,6 +65706,11 @@ function createOpenAiAdapter(webSocketClient) {
65573
65706
  const mulaw = pcm16ToMulaw(pcm8k);
65574
65707
  s.ws.send(JSON.stringify({ type: "session.input_audio.append", audio: mulaw.toString("base64") }));
65575
65708
  },
65709
+ speak(session, text) {
65710
+ const s = session;
65711
+ if (s.ready && s.ws.readyState === s.ws.OPEN)
65712
+ sendGreeting(s.ws, text);
65713
+ },
65576
65714
  clear() {
65577
65715
  },
65578
65716
  close(session) {
@@ -66337,127 +66475,505 @@ function createGeminiAdapter(webSocketClient) {
66337
66475
  flushPendingTurns(session, callbacks);
66338
66476
  }
66339
66477
  }
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
- });
66478
+ const toolCallRaw = msg["toolCall"];
66479
+ const functionCalls = isPlainObject(toolCallRaw) ? toolCallRaw["functionCalls"] : void 0;
66480
+ if (Array.isArray(functionCalls)) {
66481
+ for (const fc of functionCalls) {
66482
+ if (!isPlainObject(fc) || typeof fc["id"] !== "string" || typeof fc["name"] !== "string") {
66483
+ callbacks.onError({
66484
+ message: "Received a malformed function call from Gemini Live"
66485
+ });
66486
+ continue;
66487
+ }
66488
+ void dispatchToolCall4({ id: fc["id"], name: fc["name"], args: fc["args"] }, tools, ctx, session, callbacks).catch((err) => {
66489
+ const sanitized = sanitizeVendorError(err);
66490
+ callbacks.onError({
66491
+ message: sanitized.message,
66492
+ code: sanitized.code,
66493
+ raw: sanitized
66494
+ });
66495
+ });
66496
+ }
66497
+ } else if (functionCalls !== void 0) {
66498
+ callbacks.onError({
66499
+ message: "Received a malformed toolCall from Gemini Live \u2014 functionCalls was not an array"
66500
+ });
66501
+ }
66502
+ const cancellationRaw = msg["toolCallCancellation"];
66503
+ const ids = isPlainObject(cancellationRaw) ? cancellationRaw["ids"] : void 0;
66504
+ if (Array.isArray(ids)) {
66505
+ for (const id of ids) {
66506
+ if (typeof id === "string")
66507
+ session.cancelledCallIds.add(id);
66508
+ }
66509
+ } else if (ids !== void 0) {
66510
+ callbacks.onError({
66511
+ message: "Received a malformed toolCallCancellation from Gemini Live \u2014 ids was not an array"
66512
+ });
66513
+ }
66514
+ if (msg["goAway"] !== void 0) {
66515
+ callbacks.onError({
66516
+ message: "Gemini Live sent goAway \u2014 session will close soon",
66517
+ raw: msg["goAway"]
66518
+ });
66519
+ }
66520
+ });
66521
+ liveWs.on("error", (err) => {
66522
+ const sanitized = sanitizeVendorError(err);
66523
+ if (!settled) {
66524
+ settle2(() => reject(new Error(sanitized.message)));
66525
+ return;
66526
+ }
66527
+ callbacks.onError({ message: sanitized.message, code: sanitized.code, raw: sanitized });
66528
+ });
66529
+ liveWs.on("close", () => {
66530
+ clearSetupTimer();
66531
+ if (session.closingIntentionally) {
66532
+ if (!settled) {
66533
+ settle2(() => reject(new Error("realtimeAgent: connect aborted \u2014 the Sinch STREAM leg ended first")));
66534
+ return;
66535
+ }
66536
+ flushPendingTurns(session, callbacks);
66537
+ callbacks.onClose();
66538
+ return;
66539
+ }
66540
+ const canResume = session.resumptionHandle !== void 0;
66541
+ if (canResume && session.reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
66542
+ session.reconnectAttempts += 1;
66543
+ const delayMs = RECONNECT_BASE_DELAY_MS * 2 ** (session.reconnectAttempts - 1);
66544
+ setTimeout(() => {
66545
+ if (!session.closingIntentionally)
66546
+ openSocket();
66547
+ }, delayMs);
66548
+ return;
66549
+ }
66550
+ if (!settled) {
66551
+ settle2(() => reject(new Error("realtimeAgent: Gemini Live closed before setupComplete, with no resumable session")));
66552
+ return;
66553
+ }
66554
+ if (canResume) {
66555
+ callbacks.onError({
66556
+ message: "realtimeAgent: Gemini Live reconnect attempts exhausted \u2014 ending the call."
66557
+ });
66558
+ }
66559
+ flushPendingTurns(session, callbacks);
66560
+ callbacks.onClose();
66561
+ });
66562
+ };
66563
+ openSocket();
66564
+ });
66565
+ },
66566
+ sendAudio(session, pcm) {
66567
+ const s = session;
66568
+ if (!s.ready || s.ws.readyState !== s.ws.OPEN) {
66569
+ if (!s.closingIntentionally && s.audioBufferBytes + pcm.length <= MAX_BUFFERED_AUDIO_BYTES) {
66570
+ s.audioBuffer.push(pcm);
66571
+ s.audioBufferBytes += pcm.length;
66572
+ }
66573
+ return;
66574
+ }
66575
+ const pcm16k = s.resamplerIn.push(pcm);
66576
+ s.ws.send(JSON.stringify({
66577
+ realtimeInput: {
66578
+ audio: { data: pcm16k.toString("base64"), mimeType: "audio/pcm;rate=16000" }
66579
+ }
66580
+ }));
66581
+ },
66582
+ clear() {
66583
+ },
66584
+ close(session) {
66585
+ const s = session;
66586
+ s.closingIntentionally = true;
66587
+ closeAnyState(s.ws);
66588
+ }
66589
+ };
66590
+ }
66591
+ var geminiAdapter = createGeminiAdapter();
66592
+
66593
+ // ../runtime-shared/dist/ai/realtime/adapters/elevenlabs-tools.js
66594
+ var API_BASE = "https://api.elevenlabs.io/v1";
66595
+ var TIMEOUT_MS = 1e4;
66596
+ function differs(have, want) {
66597
+ 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);
66598
+ }
66599
+ async function ensureElevenLabsClientTools(opts) {
66600
+ const f = opts.fetchFn ?? fetch;
66601
+ const headers = { "xi-api-key": opts.apiKey, "Content-Type": "application/json" };
66602
+ const call = async (method, path7, body) => {
66603
+ const res = await f(`${API_BASE}${path7}`, {
66604
+ method,
66605
+ headers,
66606
+ ...body !== void 0 && { body: JSON.stringify(body) },
66607
+ signal: AbortSignal.timeout(TIMEOUT_MS)
66608
+ });
66609
+ if (!res.ok) {
66610
+ throw new Error(`ElevenLabs API ${method} ${path7.split("?")[0]} failed: ${res.status}`);
66611
+ }
66612
+ return res.json();
66613
+ };
66614
+ const agent = await call("GET", `/convai/agents/${encodeURIComponent(opts.agentId)}`);
66615
+ const attachedIds = new Set(agent.conversation_config?.agent?.prompt?.tool_ids ?? []);
66616
+ const workspace = /* @__PURE__ */ new Map();
66617
+ let cursor;
66618
+ do {
66619
+ const page = await call("GET", `/convai/tools?types=client&page_size=100${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
66620
+ for (const t of page.tools ?? []) {
66621
+ const name = t.tool_config?.name;
66622
+ if (name && !workspace.has(name))
66623
+ workspace.set(name, { id: t.id, config: t.tool_config });
66624
+ }
66625
+ cursor = page.has_more ? page.next_cursor : null;
66626
+ } while (cursor);
66627
+ const result2 = { created: [], attached: [] };
66628
+ const newIds = [];
66629
+ for (const tool2 of opts.tools) {
66630
+ const desired = {
66631
+ type: "client",
66632
+ name: tool2.name,
66633
+ description: tool2.description,
66634
+ // `hangup_call` is fire-and-forget: a result makes the model speak again ("The call has
66635
+ // ended.") after the goodbye.
66636
+ expects_response: tool2.name !== "hangup_call",
66637
+ parameters: tool2.parameters
66638
+ };
66639
+ const existing = workspace.get(tool2.name);
66640
+ let id = existing?.id;
66641
+ if (existing && differs(existing.config, desired)) {
66642
+ await call("PATCH", `/convai/tools/${encodeURIComponent(existing.id)}`, {
66643
+ tool_config: desired
66644
+ });
66645
+ }
66646
+ if (!id) {
66647
+ const made = await call("POST", "/convai/tools", { tool_config: desired });
66648
+ id = made.id;
66649
+ result2.created.push(tool2.name);
66650
+ }
66651
+ if (!attachedIds.has(id)) {
66652
+ newIds.push(id);
66653
+ result2.attached.push(tool2.name);
66654
+ }
66655
+ }
66656
+ if (newIds.length > 0) {
66657
+ await call("PATCH", `/convai/agents/${encodeURIComponent(opts.agentId)}`, {
66658
+ conversation_config: { agent: { prompt: { tool_ids: [...attachedIds, ...newIds] } } }
66659
+ });
66660
+ }
66661
+ return result2;
66662
+ }
66663
+
66664
+ // ../runtime-shared/dist/ai/realtime/adapters/elevenlabs.js
66665
+ var API_BASE2 = "https://api.elevenlabs.io/v1";
66666
+ var FETCH_TIMEOUT_MS4 = 1e4;
66667
+ var HANDSHAKE_TIMEOUT_MS5 = 1e4;
66668
+ function parseAudioFormat(format) {
66669
+ if (format === "ulaw_8000")
66670
+ return { ulaw: true, rate: 8e3 };
66671
+ const m = typeof format === "string" ? /^pcm_(\d+)$/.exec(format) : null;
66672
+ return m ? { ulaw: false, rate: Number(m[1]) } : { ulaw: true, rate: 8e3 };
66673
+ }
66674
+ function buildInitiation(options, skip) {
66675
+ if (skip)
66676
+ return { type: "conversation_initiation_client_data" };
66677
+ const lang = (options.language ?? DEFAULT_LANGUAGE).split("-")[0].toLowerCase();
66678
+ return {
66679
+ type: "conversation_initiation_client_data",
66680
+ conversation_config_override: {
66681
+ agent: {
66682
+ prompt: { prompt: options.prompt },
66683
+ ...options.greeting && { first_message: options.greeting },
66684
+ // Listen-first: an empty first message makes the agent wait; `speak` opens it later.
66685
+ ...options.greetingHeld && !options.greeting && { first_message: "" },
66686
+ ...options.language && options.language !== DEFAULT_LANGUAGE && { language: lang }
66687
+ },
66688
+ ...options.voice && { tts: { voice_id: options.voice } }
66689
+ }
66690
+ };
66691
+ }
66692
+ async function getSignedUrl(apiKey, agentId, fetchFn, signal) {
66693
+ const res = await fetchFn(`${API_BASE2}/convai/conversation/get-signed-url?agent_id=${encodeURIComponent(agentId)}`, {
66694
+ headers: { "xi-api-key": apiKey },
66695
+ signal: AbortSignal.any([signal, AbortSignal.timeout(FETCH_TIMEOUT_MS4)])
66696
+ });
66697
+ if (!res.ok) {
66698
+ throw new Error(`realtimeAgent: elevenlabs signed-URL request failed (${res.status})`);
66699
+ }
66700
+ const body = await res.json();
66701
+ if (!body.signed_url)
66702
+ throw new Error("realtimeAgent: elevenlabs returned no signed_url");
66703
+ return body.signed_url;
66704
+ }
66705
+ async function dispatchToolCall5(call, tools, ctx, ws, callbacks, onHangupResult) {
66706
+ const name = call.tool_name ?? "";
66707
+ const start = Date.now();
66708
+ const found = tools.find((t) => t.name === name);
66709
+ const args = call.parameters ?? {};
66710
+ let result2;
66711
+ let error;
66712
+ try {
66713
+ if (!found)
66714
+ throw new Error(`Unknown tool: ${name}`);
66715
+ if (!isPlainObject(args))
66716
+ throw new Error(`malformed parameters for tool '${name}'`);
66717
+ result2 = await found.handler(args, ctx);
66718
+ } catch (err) {
66719
+ error = err instanceof Error ? err.message : String(err);
66720
+ }
66721
+ callbacks.onToolCall({ name, args, result: result2, error, latencyMs: Date.now() - start });
66722
+ if (name === "hangup_call" && error === void 0)
66723
+ onHangupResult?.();
66724
+ if (call.expects_response === false || !call.tool_call_id)
66725
+ return;
66726
+ if (ws.readyState !== ws.OPEN)
66727
+ return;
66728
+ ws.send(JSON.stringify({
66729
+ type: "client_tool_result",
66730
+ tool_call_id: call.tool_call_id,
66731
+ result: safeToolOutput(error ? { error } : result2 ?? {}),
66732
+ is_error: error !== void 0,
66733
+ ...error !== void 0 && { error_type: "external_client" }
66734
+ }));
66735
+ }
66736
+ function createElevenLabsAdapter(webSocketClient, fetchFn = (...a) => fetch(...a)) {
66737
+ return {
66738
+ async connect(options, ctx, callbacks, signal) {
66739
+ if (signal.aborted) {
66740
+ throw new Error("realtimeAgent: connect aborted \u2014 the Sinch STREAM leg ended first");
66741
+ }
66742
+ const apiKey = ctx.config.getSecret("ELEVENLABS_API_KEY");
66743
+ if (!apiKey) {
66744
+ throw new Error("realtimeAgent: provider 'elevenlabs' needs ELEVENLABS_API_KEY \u2014 set it as a function secret.");
66745
+ }
66746
+ const po = options.providerOptions?.["elevenlabs"] ?? {};
66747
+ const agentId = po.agentId ?? ctx.config.getVariable("ELEVENLABS_AGENT_ID");
66748
+ if (!agentId) {
66749
+ throw new Error("realtimeAgent: provider 'elevenlabs' needs an agent id \u2014 set providerOptions.elevenlabs.agentId or the ELEVENLABS_AGENT_ID variable.");
66750
+ }
66751
+ if (po.registerTools !== false && options.tools?.length) {
66752
+ await ensureElevenLabsClientTools({ apiKey, agentId, tools: options.tools, fetchFn });
66753
+ }
66754
+ const signedUrl = await getSignedUrl(apiKey, agentId, fetchFn, signal);
66755
+ if (signal.aborted) {
66756
+ throw new Error("realtimeAgent: connect aborted \u2014 the Sinch STREAM leg ended first");
66757
+ }
66758
+ const WebSocketClient = webSocketClient ?? loadWebSocketClient("elevenlabs");
66759
+ const ws = new WebSocketClient(signedUrl);
66760
+ const session = {
66761
+ ws,
66762
+ ready: false,
66763
+ sinchRate: sinchRate(options),
66764
+ inFormat: { ulaw: true, rate: 8e3 },
66765
+ outFormat: { ulaw: true, rate: 8e3 },
66766
+ resamplerIn: void 0,
66767
+ resamplerOut: void 0,
66768
+ agentSpeaking: false,
66769
+ lastInterruptId: -1,
66770
+ pendingAgentText: void 0
66771
+ };
66772
+ const tools = options.tools ?? [];
66773
+ let hangingUp = false;
66774
+ let repliesAllowed = 0;
66775
+ let muted = false;
66776
+ const flushAgent = () => {
66777
+ if (session.pendingAgentText === void 0)
66778
+ return;
66779
+ const text = session.pendingAgentText;
66780
+ session.pendingAgentText = void 0;
66781
+ if (text)
66782
+ callbacks.onTurn({ role: "agent", text, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
66783
+ };
66784
+ const stopPlayback = (cancelled) => {
66785
+ if (!session.agentSpeaking)
66786
+ return;
66787
+ session.agentSpeaking = false;
66788
+ callbacks.onPlaybackStop?.({ cancelled });
66789
+ };
66790
+ ws.on("open", () => {
66791
+ ws.send(JSON.stringify(buildInitiation(options, po.skipOverrides === true)));
66792
+ });
66793
+ return await new Promise((resolve, reject) => {
66794
+ let settled = false;
66795
+ const timer = setTimeout(() => {
66796
+ if (settled)
66797
+ return;
66798
+ settled = true;
66799
+ closeAnyState(ws);
66800
+ reject(new Error("realtimeAgent: provider elevenlabs handshake timed out waiting for conversation_initiation_metadata"));
66801
+ }, HANDSHAKE_TIMEOUT_MS5);
66802
+ const onAbort = () => {
66803
+ if (settled)
66804
+ return;
66805
+ settled = true;
66806
+ clearTimeout(timer);
66807
+ closeAnyState(ws);
66808
+ reject(new Error("realtimeAgent: connect aborted \u2014 the Sinch STREAM leg ended first"));
66809
+ };
66810
+ signal.addEventListener("abort", onAbort, { once: true });
66811
+ const settle2 = (fn) => {
66812
+ if (settled)
66813
+ return;
66814
+ settled = true;
66815
+ clearTimeout(timer);
66816
+ signal.removeEventListener("abort", onAbort);
66817
+ fn();
66818
+ };
66819
+ ws.on("message", (raw) => {
66820
+ if (isOversizedFrame(raw)) {
66821
+ callbacks.onError({ message: "Received an oversized frame from elevenlabs \u2014 dropped" });
66822
+ return;
66823
+ }
66824
+ const msg = parseVendorFrame(raw);
66825
+ if (!msg) {
66826
+ callbacks.onError({ message: "Received a non-JSON frame from elevenlabs" });
66827
+ return;
66828
+ }
66829
+ switch (msg["type"]) {
66830
+ case "conversation_initiation_metadata": {
66831
+ const meta = msg["conversation_initiation_metadata_event"];
66832
+ session.outFormat = parseAudioFormat(meta?.agent_output_audio_format);
66833
+ session.inFormat = parseAudioFormat(meta?.user_input_audio_format);
66834
+ session.resamplerOut = new StreamingResampler(session.outFormat.rate, session.sinchRate);
66835
+ session.resamplerIn = new StreamingResampler(session.sinchRate, session.inFormat.rate);
66836
+ session.ready = true;
66837
+ settle2(() => resolve(session));
66838
+ break;
66839
+ }
66840
+ case "audio": {
66841
+ const ev = msg["audio_event"];
66842
+ if (typeof ev?.event_id === "number" && ev.event_id <= session.lastInterruptId)
66843
+ break;
66844
+ if (muted)
66845
+ break;
66846
+ const chunk = safeBase64ToBuffer(ev?.audio_base_64);
66847
+ if (!chunk || !session.resamplerOut) {
66848
+ callbacks.onError({ message: "Received a malformed audio event from elevenlabs" });
66849
+ break;
66850
+ }
66851
+ if (!session.agentSpeaking) {
66852
+ session.agentSpeaking = true;
66853
+ callbacks.onPlaybackStart?.();
66854
+ }
66855
+ const pcm = session.outFormat.ulaw ? mulawToPcm16(chunk) : chunk;
66856
+ callbacks.onAudioOut(session.resamplerOut.push(pcm));
66857
+ break;
66858
+ }
66859
+ case "user_transcript": {
66860
+ flushAgent();
66861
+ const text = msg["user_transcription_event"]?.user_transcript;
66862
+ if (text)
66863
+ callbacks.onTurn({ role: "user", text, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
66864
+ break;
66363
66865
  }
66364
- const cancellationRaw = msg["toolCallCancellation"];
66365
- const ids = isPlainObject(cancellationRaw) ? cancellationRaw["ids"] : void 0;
66366
- if (Array.isArray(ids)) {
66367
- for (const id of ids) {
66368
- if (typeof id === "string")
66369
- session.cancelledCallIds.add(id);
66866
+ case "agent_response": {
66867
+ if (hangingUp) {
66868
+ if (repliesAllowed <= 0) {
66869
+ muted = true;
66870
+ break;
66871
+ }
66872
+ repliesAllowed--;
66370
66873
  }
66371
- } else if (ids !== void 0) {
66372
- callbacks.onError({
66373
- message: "Received a malformed toolCallCancellation from Gemini Live \u2014 ids was not an array"
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
- });
66874
+ flushAgent();
66875
+ session.pendingAgentText = msg["agent_response_event"]?.agent_response;
66876
+ break;
66381
66877
  }
66382
- });
66383
- liveWs.on("error", (err) => {
66384
- const sanitized = sanitizeVendorError(err);
66385
- if (!settled) {
66386
- settle2(() => reject(new Error(sanitized.message)));
66387
- return;
66878
+ case "agent_response_correction": {
66879
+ const corrected = msg["agent_response_correction_event"]?.corrected_agent_response;
66880
+ if (corrected !== void 0)
66881
+ session.pendingAgentText = corrected;
66882
+ break;
66388
66883
  }
66389
- callbacks.onError({ message: sanitized.message, code: sanitized.code, raw: sanitized });
66390
- });
66391
- liveWs.on("close", () => {
66392
- clearSetupTimer();
66393
- if (session.closingIntentionally) {
66394
- if (!settled) {
66395
- settle2(() => reject(new Error("realtimeAgent: connect aborted \u2014 the Sinch STREAM leg ended first")));
66396
- return;
66397
- }
66398
- flushPendingTurns(session, callbacks);
66399
- callbacks.onClose();
66400
- return;
66884
+ case "agent_response_complete":
66885
+ stopPlayback(false);
66886
+ break;
66887
+ case "interruption": {
66888
+ const id = msg["interruption_event"]?.event_id;
66889
+ if (typeof id === "number")
66890
+ session.lastInterruptId = id;
66891
+ const wasSpeaking = session.agentSpeaking;
66892
+ stopPlayback(true);
66893
+ if (wasSpeaking)
66894
+ callbacks.onBargeIn();
66895
+ flushAgent();
66896
+ break;
66401
66897
  }
66402
- const canResume = session.resumptionHandle !== void 0;
66403
- if (canResume && session.reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
66404
- session.reconnectAttempts += 1;
66405
- const delayMs = RECONNECT_BASE_DELAY_MS * 2 ** (session.reconnectAttempts - 1);
66406
- setTimeout(() => {
66407
- if (!session.closingIntentionally)
66408
- openSocket();
66409
- }, delayMs);
66410
- return;
66898
+ case "ping": {
66899
+ const id = msg["ping_event"]?.event_id;
66900
+ if (ws.readyState === ws.OPEN)
66901
+ ws.send(JSON.stringify({ type: "pong", event_id: id }));
66902
+ break;
66411
66903
  }
66412
- if (!settled) {
66413
- settle2(() => reject(new Error("realtimeAgent: Gemini Live closed before setupComplete, with no resumable session")));
66414
- return;
66904
+ case "client_tool_call": {
66905
+ const call = msg["client_tool_call"];
66906
+ if (!call)
66907
+ break;
66908
+ void dispatchToolCall5(call, tools, ctx, ws, callbacks, () => {
66909
+ hangingUp = true;
66910
+ repliesAllowed = session.agentSpeaking ? 0 : 1;
66911
+ }).catch((err) => {
66912
+ const s = sanitizeVendorError(err);
66913
+ callbacks.onError({ message: s.message, code: s.code, raw: s });
66914
+ });
66915
+ break;
66415
66916
  }
66416
- if (canResume) {
66917
+ case "client_error": {
66417
66918
  callbacks.onError({
66418
- message: "realtimeAgent: Gemini Live reconnect attempts exhausted \u2014 ending the call."
66919
+ message: "elevenlabs agent error",
66920
+ raw: msg["error_event"] ?? msg
66419
66921
  });
66922
+ settle2(() => reject(new Error("realtimeAgent: elevenlabs error before the session was ready")));
66923
+ closeAnyState(ws);
66924
+ break;
66420
66925
  }
66421
- flushPendingTurns(session, callbacks);
66422
- callbacks.onClose();
66423
- });
66424
- };
66425
- openSocket();
66926
+ }
66927
+ });
66928
+ ws.on("error", (err) => {
66929
+ const s = sanitizeVendorError(err);
66930
+ if (!settled) {
66931
+ settle2(() => reject(new Error(s.message)));
66932
+ return;
66933
+ }
66934
+ callbacks.onError({ message: s.message, code: s.code, raw: s });
66935
+ });
66936
+ ws.on("close", () => {
66937
+ if (!settled) {
66938
+ settle2(() => reject(new Error("realtimeAgent: elevenlabs closed before the session was ready")));
66939
+ return;
66940
+ }
66941
+ flushAgent();
66942
+ callbacks.onClose();
66943
+ });
66426
66944
  });
66427
66945
  },
66428
66946
  sendAudio(session, pcm) {
66429
66947
  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
- }
66948
+ if (!s.ready || !s.resamplerIn || s.ws.readyState !== s.ws.OPEN)
66435
66949
  return;
66436
- }
66437
- const pcm16k = s.resamplerIn.push(pcm);
66438
- s.ws.send(JSON.stringify({
66439
- realtimeInput: {
66440
- audio: { data: pcm16k.toString("base64"), mimeType: "audio/pcm;rate=16000" }
66441
- }
66442
- }));
66950
+ const out = s.resamplerIn.push(pcm);
66951
+ const bytes = s.inFormat.ulaw ? pcm16ToMulaw(out) : out;
66952
+ s.ws.send(JSON.stringify({ user_audio_chunk: bytes.toString("base64") }));
66443
66953
  },
66444
- clear() {
66954
+ speak(session, text) {
66955
+ const s = session;
66956
+ if (s.ws.readyState !== s.ws.OPEN)
66957
+ return;
66958
+ s.ws.send(JSON.stringify({ type: "user_message", text: verbatimGreetingDirective(text) }));
66959
+ },
66960
+ clear(session) {
66961
+ session.agentSpeaking = false;
66445
66962
  },
66446
66963
  close(session) {
66447
- const s = session;
66448
- s.closingIntentionally = true;
66449
- closeAnyState(s.ws);
66964
+ closeAnyState(session.ws);
66450
66965
  }
66451
66966
  };
66452
66967
  }
66453
- var geminiAdapter = createGeminiAdapter();
66968
+ var elevenlabsAdapter = createElevenLabsAdapter();
66454
66969
 
66455
66970
  // ../runtime-shared/dist/ai/realtime/registry.js
66456
66971
  var adapters = {
66457
66972
  deepgram: deepgramAdapter,
66458
66973
  openai: openaiAdapter,
66459
66974
  grok: grokAdapter,
66460
- gemini: geminiAdapter
66975
+ gemini: geminiAdapter,
66976
+ elevenlabs: elevenlabsAdapter
66461
66977
  };
66462
66978
  function getRealtimeAdapter(provider) {
66463
66979
  const adapter2 = adapters[provider];
@@ -66945,6 +67461,59 @@ function audioMs(playbackStartAtIso, playbackEndAtIso) {
66945
67461
  function logValue(ms) {
66946
67462
  return ms ?? -1;
66947
67463
  }
67464
+ function createPlayoutTracker(gapMs) {
67465
+ let cursorMs = 0;
67466
+ let speechEndMs = 0;
67467
+ const segments = [];
67468
+ return {
67469
+ /** Places one outbound frame (`durationMs` long) that arrived at `nowMs`. */
67470
+ push(nowMs, durationMs, isSpeech) {
67471
+ const startMs = Math.max(cursorMs, nowMs);
67472
+ cursorMs = startMs + durationMs;
67473
+ if (!isSpeech)
67474
+ return;
67475
+ speechEndMs = cursorMs;
67476
+ const last = segments[segments.length - 1];
67477
+ if (last && startMs - last.endMs <= gapMs) {
67478
+ last.endMs = cursorMs;
67479
+ last.lastArrivalMs = nowMs;
67480
+ } else {
67481
+ segments.push({ startMs, endMs: cursorMs, lastArrivalMs: nowMs });
67482
+ }
67483
+ },
67484
+ /** Wall time (ms since epoch) at which everything pushed so far has finished playing; `0` before any audio. */
67485
+ playsUntil() {
67486
+ return cursorMs;
67487
+ },
67488
+ /** Like `playsUntil`, but for speech only: the continuous silence a vendor streams between
67489
+ * replies does not extend it. `0` before any speech. */
67490
+ speechUntil() {
67491
+ return speechEndMs;
67492
+ },
67493
+ /** Barge-in: audio queued past `nowMs` will not play. */
67494
+ clear(nowMs) {
67495
+ cursorMs = Math.min(cursorMs, nowMs);
67496
+ speechEndMs = Math.min(speechEndMs, nowMs);
67497
+ const last = segments[segments.length - 1];
67498
+ if (last && last.endMs > nowMs)
67499
+ last.endMs = Math.max(last.startMs, nowMs);
67500
+ },
67501
+ /**
67502
+ * Removes and merges the runs whose last frame arrived by `uptoMs` (every run when
67503
+ * `uptoMs` is `Infinity`). `undefined` when there are none.
67504
+ */
67505
+ take(uptoMs) {
67506
+ let startMs;
67507
+ let endMs = 0;
67508
+ while (segments.length > 0 && segments[0].lastArrivalMs <= uptoMs) {
67509
+ const seg = segments.shift();
67510
+ startMs ??= seg.startMs;
67511
+ endMs = seg.endMs;
67512
+ }
67513
+ return startMs === void 0 ? void 0 : { startMs, endMs };
67514
+ }
67515
+ };
67516
+ }
66948
67517
 
66949
67518
  // ../runtime-shared/dist/ai/realtime/adapters/relay.js
66950
67519
  var DEFAULT_MAX_CALL_DURATION = 1800;
@@ -67023,6 +67592,7 @@ function createRelayAgent(options) {
67023
67592
  setup: relay2.setup,
67024
67593
  voiceWebhook: onCall({ incoming: connect, completed: handleCallCompleted }),
67025
67594
  connect,
67595
+ call: () => Promise.reject(new Error("realtimeAgent.call() does not support provider 'voice-relay' yet.")),
67026
67596
  endpointFor: relay2.endpointFor
67027
67597
  };
67028
67598
  }
@@ -67281,55 +67851,103 @@ function attach(options, pendingByCallId, transferredCallIds, call) {
67281
67851
  });
67282
67852
  }
67283
67853
 
67284
- // ../runtime-shared/dist/ai/realtime/vad.js
67285
- var DEFAULT_THRESHOLD = 500;
67286
- var DEFAULT_ATTACK_FRAMES = 2;
67287
- var DEFAULT_HANGOVER_FRAMES = 20;
67288
- function pcm16Rms2(pcm) {
67289
- if (pcm.length < 2)
67290
- return 0;
67291
- let sumSquares = 0;
67292
- const samples = pcm.length >> 1;
67293
- for (let i = 0; i < samples; i++) {
67294
- const sample = pcm.readInt16LE(i * 2);
67295
- sumSquares += sample * sample;
67854
+ // ../runtime-shared/dist/ai/realtime/recording.js
67855
+ function encodeStereoWav(left, right, sampleRate) {
67856
+ const frames = Math.max(left.length, right.length) >> 1;
67857
+ const dataBytes = frames * 4;
67858
+ const wav = Buffer.alloc(44 + dataBytes);
67859
+ wav.write("RIFF", 0, "ascii");
67860
+ wav.writeUInt32LE(36 + dataBytes, 4);
67861
+ wav.write("WAVEfmt ", 8, "ascii");
67862
+ wav.writeUInt32LE(16, 16);
67863
+ wav.writeUInt16LE(1, 20);
67864
+ wav.writeUInt16LE(2, 22);
67865
+ wav.writeUInt32LE(sampleRate, 24);
67866
+ wav.writeUInt32LE(sampleRate * 4, 28);
67867
+ wav.writeUInt16LE(4, 32);
67868
+ wav.writeUInt16LE(16, 34);
67869
+ wav.write("data", 36, "ascii");
67870
+ wav.writeUInt32LE(dataBytes, 40);
67871
+ const leftSamples = left.length >> 1;
67872
+ const rightSamples = right.length >> 1;
67873
+ for (let i = 0; i < frames; i++) {
67874
+ if (i < leftSamples)
67875
+ wav.writeInt16LE(left.readInt16LE(i * 2), 44 + i * 4);
67876
+ if (i < rightSamples)
67877
+ wav.writeInt16LE(right.readInt16LE(i * 2), 46 + i * 4);
67878
+ }
67879
+ return wav;
67880
+ }
67881
+ var Channel = class {
67882
+ maxSamples;
67883
+ chunks = [];
67884
+ /** Samples written so far, silence included. */
67885
+ samples = 0;
67886
+ constructor(maxSamples) {
67887
+ this.maxSamples = maxSamples;
67888
+ }
67889
+ /** Appends `pcm` no earlier than sample `at`; returns false once the cap is reached. */
67890
+ push(pcm, at) {
67891
+ const start = Math.max(this.samples, at);
67892
+ pcm = pcm.subarray(0, pcm.length & ~1);
67893
+ const incoming = pcm.length >> 1;
67894
+ if (start + incoming > this.maxSamples)
67895
+ return false;
67896
+ if (start > this.samples)
67897
+ this.chunks.push(Buffer.alloc((start - this.samples) * 2));
67898
+ this.chunks.push(pcm);
67899
+ this.samples = start + incoming;
67900
+ return true;
67296
67901
  }
67297
- return Math.sqrt(sumSquares / samples);
67298
- }
67299
- function createEnergyVad(options = {}) {
67300
- const threshold = options.threshold ?? DEFAULT_THRESHOLD;
67301
- const attackFrames = options.attackFrames ?? DEFAULT_ATTACK_FRAMES;
67302
- const hangoverFrames = options.hangoverFrames ?? DEFAULT_HANGOVER_FRAMES;
67303
- let speaking = false;
67304
- let loudRun = 0;
67305
- let quietRun = 0;
67902
+ /** Drops everything past sample `at` — audio queued but not yet played. */
67903
+ truncate(at) {
67904
+ if (this.samples <= at)
67905
+ return;
67906
+ const all3 = Buffer.concat(this.chunks);
67907
+ this.chunks = [all3.subarray(0, at * 2)];
67908
+ this.samples = at;
67909
+ }
67910
+ toBuffer() {
67911
+ return Buffer.concat(this.chunks);
67912
+ }
67913
+ };
67914
+ function createStereoRecorder(sampleRate, maxSeconds) {
67915
+ const startMs = Date.now();
67916
+ const maxSamples = Math.floor(sampleRate * maxSeconds);
67917
+ const caller = new Channel(maxSamples);
67918
+ const agent = new Channel(maxSamples);
67919
+ let truncated = false;
67920
+ const sampleAt = (nowMs) => Math.max(0, Math.floor((nowMs - startMs) * sampleRate / 1e3));
67306
67921
  return {
67307
- get speaking() {
67308
- return speaking;
67922
+ get truncated() {
67923
+ return truncated;
67309
67924
  },
67310
- push(pcm) {
67311
- const loud = pcm16Rms2(pcm) >= threshold;
67312
- if (loud) {
67313
- loudRun++;
67314
- quietRun = 0;
67315
- } else {
67316
- quietRun++;
67317
- loudRun = 0;
67318
- }
67319
- if (!speaking && loud && loudRun >= attackFrames) {
67320
- speaking = true;
67321
- return "start";
67322
- }
67323
- if (speaking && !loud && quietRun >= hangoverFrames) {
67324
- speaking = false;
67325
- return "end";
67326
- }
67327
- return void 0;
67328
- }
67925
+ pushCaller(pcm, nowMs = Date.now()) {
67926
+ if (!caller.push(pcm, sampleAt(nowMs)))
67927
+ truncated = true;
67928
+ },
67929
+ pushAgent(pcm, nowMs = Date.now()) {
67930
+ if (!agent.push(pcm, sampleAt(nowMs)))
67931
+ truncated = true;
67932
+ },
67933
+ clearAgent(nowMs = Date.now()) {
67934
+ agent.truncate(sampleAt(nowMs));
67935
+ },
67936
+ toWav: () => encodeStereoWav(caller.toBuffer(), agent.toBuffer(), sampleRate)
67329
67937
  };
67330
67938
  }
67331
67939
 
67332
67940
  // ../runtime-shared/dist/ai/realtime/agent.js
67941
+ function recordsStream(record) {
67942
+ return record === true || typeof record === "object" && record.stream === true;
67943
+ }
67944
+ function recordsViaSinch(record) {
67945
+ return typeof record === "object" && record.sinch === true;
67946
+ }
67947
+ var DEFAULT_OUTBOUND_GREETING_FALLBACK_MS = 4e3;
67948
+ var MAX_EARLY_AUDIO_MS = 5e3;
67949
+ var PLACED_CALL_TTL_MS = 2 * 60 * 60 * 1e3;
67950
+ var MAX_PLACED_CALLS = 1e3;
67333
67951
  var BRIDGE = "bridge";
67334
67952
  var CALLER_LEG2 = "caller";
67335
67953
  var STREAM_LEG2 = "stream";
@@ -67340,7 +67958,11 @@ function sendStreamControl(ws, command) {
67340
67958
  if (ws.readyState === ws.OPEN)
67341
67959
  ws.send(JSON.stringify({ command }));
67342
67960
  }
67343
- var HANGUP_GRACE_MS2 = 2e3;
67961
+ var HANGUP_MIN_WAIT_MS = 2e3;
67962
+ var HANGUP_PLAYOUT_MARGIN_MS = 400;
67963
+ var HANGUP_MAX_WAIT_MS = 2e4;
67964
+ var HANGUP_POLL_MS = 100;
67965
+ var PLAYOUT_GAP_MS = 1500;
67344
67966
  var HEARTBEAT_INTERVAL_MS = 2e4;
67345
67967
  var PENDING_SESSION_TTL_MS = 3e4;
67346
67968
  var MAX_PENDING_SESSIONS = 1e3;
@@ -67350,22 +67972,23 @@ function resolveMaxDuration(context) {
67350
67972
  }
67351
67973
  var FIRST_FRAME_DEADLINE_MS = 2e3;
67352
67974
  var MAX_UNAUTHENTICATED_SOCKETS2 = 32;
67353
- async function resolvePerCallOptions(options, call, context, ctx) {
67975
+ async function resolvePerCallOptions(options, call, context, ctx, data, provider = options.provider) {
67354
67976
  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)
67977
+ resolvePerCallValue(options.prompt, call, context, data),
67978
+ resolvePerCallValue(options.greeting, call, context, data),
67979
+ resolvePerCallValue(options.voice, call, context, data),
67980
+ resolvePerCallValue(options.transferTo, call, context, data),
67981
+ resolvePerCallValue(options.language, call, context, data)
67360
67982
  ]);
67361
67983
  const { transferTo: _transferTo, tools: authorTools, ...rest } = options;
67362
67984
  const tools = mergeTools(authorTools ?? [], builtInTools(options.hangup ?? true, nonBlank(transferTo), ctx));
67363
67985
  let resolvedPrompt = currentDateTimePreamble(options.timezone) + prompt;
67364
67986
  if (offersHangup(tools)) {
67365
- resolvedPrompt += options.provider === "openai" ? DELEGATED_CALL_TERMINATION_INSTRUCTIONS : CALL_TERMINATION_INSTRUCTIONS;
67987
+ resolvedPrompt += provider === "openai" ? DELEGATED_CALL_TERMINATION_INSTRUCTIONS : CALL_TERMINATION_INSTRUCTIONS;
67366
67988
  }
67367
67989
  return {
67368
67990
  ...rest,
67991
+ provider,
67369
67992
  prompt: resolvedPrompt,
67370
67993
  greeting,
67371
67994
  voice,
@@ -67383,10 +68006,11 @@ function realtimeAgent(options) {
67383
68006
  if (options.provider === "voice-relay") {
67384
68007
  return createRelayAgent(options);
67385
68008
  }
67386
- const adapter2 = getRealtimeAdapter(options.provider);
68009
+ const defaultAdapter = getRealtimeAdapter(options.provider);
67387
68010
  let savedContext;
67388
68011
  const pendingSessions = /* @__PURE__ */ new Map();
67389
68012
  const transferredCallIds = /* @__PURE__ */ new Set();
68013
+ const liveSessions = /* @__PURE__ */ new Map();
67390
68014
  function deletePendingSession(token) {
67391
68015
  const session = pendingSessions.get(token);
67392
68016
  if (!session)
@@ -67420,10 +68044,12 @@ function realtimeAgent(options) {
67420
68044
  const req = rawReq;
67421
68045
  const headerToken = upgradeHeader(req, AGENT_HEADER_TOKEN);
67422
68046
  const startSession = (pending, connectMsg) => {
67423
- const call = pending.call;
68047
+ const call2 = pending.call;
67424
68048
  const context = pending.requestContext;
67425
68049
  const config = createUniversalConfig(context);
67426
- const callId = String(call.callId ?? "");
68050
+ const callId = String(call2.callId ?? "");
68051
+ const provider = pending.provider ?? options.provider;
68052
+ const adapter2 = pending.provider ? getRealtimeAdapter(pending.provider) : defaultAdapter;
67427
68053
  const expectedRate = AUDIO_SAMPLE_RATES[options.audio ?? "telephony"];
67428
68054
  const reportedRate = connectMsg["sampleRate"];
67429
68055
  if (reportedRate !== void 0 && reportedRate !== expectedRate) {
@@ -67436,15 +68062,22 @@ function realtimeAgent(options) {
67436
68062
  let ended = false;
67437
68063
  let transferred = false;
67438
68064
  let heartbeat;
68065
+ let greetingTimer;
68066
+ let hangupTimer;
68067
+ let lastSpeechOutAt = 0;
67439
68068
  const lifecycle = new AbortController();
67440
68069
  const transcript = [];
67441
68070
  const usage = {};
67442
68071
  const callConnectedAtMs = Date.now();
67443
68072
  let lastUserTurnAt;
67444
68073
  let firstAudioAtMs;
67445
- let selfBytesSentForTurn = 0;
68074
+ let earlyRunStartAt;
68075
+ let lastAudioAt;
68076
+ const playout = createPlayoutTracker(PLAYOUT_GAP_MS);
68077
+ const untimedAgentEntries = [];
67446
68078
  let bytesPerMs = 8e3 * 2 / 1e3;
67447
68079
  const vad = createEnergyVad();
68080
+ const recorder = recordsStream(options.record) ? createStereoRecorder(expectedRate, resolveMaxDuration(context)) : void 0;
67448
68081
  let pendingSpeechStartAt;
67449
68082
  let pendingSpeechEndAt;
67450
68083
  let speechEndFromProvider = false;
@@ -67457,16 +68090,20 @@ function realtimeAgent(options) {
67457
68090
  return `[realtimeAgent] turn latency totalMs=${logValue(totalMs)} playbackDelayMs=${logValue(delay)} audioMs=${logValue(audio)} delegationMs=${logValue(entry.delegationMs)}`;
67458
68091
  };
67459
68092
  const applySelfPlaybackFallback = (entry, cutShort) => {
67460
- if (firstAudioAtMs === void 0)
68093
+ const played = playout.take(cutShort ? Infinity : Date.parse(entry.timestamp));
68094
+ if (!played)
67461
68095
  return;
67462
- entry.playbackStartAt ??= new Date(firstAudioAtMs).toISOString();
68096
+ entry.playbackStartAt ??= new Date(played.startMs).toISOString();
67463
68097
  if (entry.playbackEndAt === void 0) {
67464
- const endMs = cutShort ? Date.now() : firstAudioAtMs + selfBytesSentForTurn / bytesPerMs;
67465
- entry.playbackEndAt = new Date(endMs).toISOString();
68098
+ entry.playbackEndAt = new Date(played.endMs).toISOString();
67466
68099
  if (cutShort)
67467
68100
  entry.interrupted = true;
67468
68101
  }
67469
68102
  };
68103
+ const timeUntimedAgentEntries = () => {
68104
+ for (const entry of untimedAgentEntries.splice(0))
68105
+ applySelfPlaybackFallback(entry, false);
68106
+ };
67470
68107
  const flushPendingStreamLog = () => {
67471
68108
  if (!pendingStreamLog)
67472
68109
  return;
@@ -67484,10 +68121,22 @@ function realtimeAgent(options) {
67484
68121
  transcript,
67485
68122
  usage,
67486
68123
  hangup() {
67487
- setTimeout(() => {
67488
- if (ws.readyState === ws.OPEN)
67489
- ws.close();
67490
- }, HANGUP_GRACE_MS2);
68124
+ if (hangupTimer !== void 0 || ended)
68125
+ return;
68126
+ const startedAt = Date.now();
68127
+ const check = () => {
68128
+ const now = Date.now();
68129
+ const elapsed = now - startedAt;
68130
+ const settled = now >= playout.speechUntil() + HANGUP_PLAYOUT_MARGIN_MS && now - lastSpeechOutAt >= HANGUP_PLAYOUT_MARGIN_MS;
68131
+ if (elapsed >= HANGUP_MIN_WAIT_MS && settled || elapsed >= HANGUP_MAX_WAIT_MS) {
68132
+ hangupTimer = void 0;
68133
+ if (ws.readyState === ws.OPEN)
68134
+ ws.close();
68135
+ return;
68136
+ }
68137
+ hangupTimer = setTimeout(check, HANGUP_POLL_MS);
68138
+ };
68139
+ hangupTimer = setTimeout(check, HANGUP_MIN_WAIT_MS);
67491
68140
  },
67492
68141
  async transfer(number) {
67493
68142
  if (!E1642.test(number)) {
@@ -67496,7 +68145,7 @@ function realtimeAgent(options) {
67496
68145
  await context.voice.transferToPhone(callId, number, {
67497
68146
  liveLeg: CALLER_LEG2,
67498
68147
  legName: TRANSFER_LEG2,
67499
- call: { call }
68148
+ call: { call: call2 }
67500
68149
  });
67501
68150
  transferred = true;
67502
68151
  if (callId)
@@ -67515,9 +68164,17 @@ function realtimeAgent(options) {
67515
68164
  return;
67516
68165
  ended = true;
67517
68166
  flushPendingStreamLog();
68167
+ timeUntimedAgentEntries();
67518
68168
  lifecycle.abort();
67519
68169
  if (heartbeat !== void 0)
67520
68170
  clearInterval(heartbeat);
68171
+ clearTimeout(greetingTimer);
68172
+ clearTimeout(hangupTimer);
68173
+ hangupTimer = void 0;
68174
+ for (const key of sessionKeys) {
68175
+ if (liveSessions.get(key) === closeLive)
68176
+ liveSessions.delete(key);
68177
+ }
67521
68178
  if (vendorSession !== void 0)
67522
68179
  adapter2.close(vendorSession);
67523
68180
  if (ws.readyState === ws.OPEN)
@@ -67527,18 +68184,48 @@ function realtimeAgent(options) {
67527
68184
  }
67528
68185
  usage.audioSeconds ??= (Date.now() - callConnectedAtMs) / 1e3;
67529
68186
  console.log(`[realtimeAgent] call usage inputTokens=${logValue(usage.inputTokens)} outputTokens=${logValue(usage.outputTokens)} audioSeconds=${logValue(usage.audioSeconds)}`);
68187
+ if (recorder) {
68188
+ const storageKey = recordingKey(callId, "wav");
68189
+ try {
68190
+ await context.storage.write(storageKey, recorder.toWav());
68191
+ ctx.recording = { storageKey };
68192
+ if (recorder.truncated) {
68193
+ console.warn(`[realtimeAgent] recording hit its ${resolveMaxDuration(context)}s cap and was cut short`);
68194
+ }
68195
+ } catch (err) {
68196
+ console.error("[realtimeAgent] saving the recording failed:", err.message);
68197
+ }
68198
+ }
67530
68199
  try {
67531
68200
  await options.onEnd?.(ctx);
67532
68201
  } catch (err) {
67533
68202
  console.error("[realtimeAgent] onEnd handler threw:", err.message);
67534
68203
  }
67535
68204
  };
68205
+ const closeLive = () => {
68206
+ if (transferred)
68207
+ return;
68208
+ if (ws.readyState === ws.OPEN)
68209
+ ws.close();
68210
+ void end();
68211
+ };
68212
+ const sessionKeys = [callId, String(call2.sessionId ?? "")].filter((k) => k !== "");
68213
+ for (const key of sessionKeys)
68214
+ liveSessions.set(key, closeLive);
67536
68215
  const callbacks = {
67537
68216
  onAudioOut(pcm) {
67538
68217
  if (firstAudioAtMs === void 0 && lastUserTurnAt !== void 0)
67539
68218
  firstAudioAtMs = Date.now();
67540
- if (firstAudioAtMs !== void 0)
67541
- selfBytesSentForTurn += pcm.length;
68219
+ const frameAt = Date.now();
68220
+ if (lastUserTurnAt === void 0 && (lastAudioAt === void 0 || frameAt - lastAudioAt > PLAYOUT_GAP_MS))
68221
+ earlyRunStartAt = frameAt;
68222
+ lastAudioAt = frameAt;
68223
+ const nowMs = Date.now();
68224
+ const speech = isSpeechFrame(pcm);
68225
+ if (speech)
68226
+ lastSpeechOutAt = nowMs;
68227
+ playout.push(nowMs, pcm.length / bytesPerMs, speech);
68228
+ recorder?.pushAgent(pcm);
67542
68229
  if (ws.readyState === ws.OPEN)
67543
68230
  ws.send(pcm);
67544
68231
  },
@@ -67562,21 +68249,22 @@ function realtimeAgent(options) {
67562
68249
  };
67563
68250
  if (turn.role === "user") {
67564
68251
  flushPendingStreamLog();
68252
+ timeUntimedAgentEntries();
67565
68253
  lastUserTurnAt = Date.now();
67566
- firstAudioAtMs = void 0;
67567
- entry.speechStartAt = turn.speechStartAt ?? pendingSpeechStartAt;
67568
- entry.speechEndAt = turn.speechEndAt ?? pendingSpeechEndAt;
68254
+ firstAudioAtMs = earlyRunStartAt !== void 0 && lastAudioAt !== void 0 && Date.now() - lastAudioAt <= PLAYOUT_GAP_MS ? earlyRunStartAt : void 0;
68255
+ earlyRunStartAt = void 0;
68256
+ entry.speechStartAt = pendingSpeechStartAt;
68257
+ entry.speechEndAt = pendingSpeechEndAt;
67569
68258
  pendingSpeechStartAt = void 0;
67570
68259
  pendingSpeechEndAt = void 0;
67571
68260
  speechEndFromProvider = false;
67572
68261
  } else if (turn.role === "agent" && lastUserTurnAt !== void 0) {
68262
+ earlyRunStartAt = void 0;
67573
68263
  entry.totalMs = Date.now() - lastUserTurnAt;
67574
68264
  lastUserTurnAt = void 0;
67575
68265
  entry.delegationMs = turn.delegationMs;
67576
- entry.playbackStartAt = turn.playbackStartAt ?? pendingAgentPlayback.startAt;
67577
- if (turn.playbackEndAt) {
67578
- entry.playbackEndAt = turn.playbackEndAt;
67579
- } else if (pendingAgentPlayback.endAt) {
68266
+ entry.playbackStartAt = pendingAgentPlayback.startAt;
68267
+ if (pendingAgentPlayback.endAt) {
67580
68268
  entry.playbackEndAt = pendingAgentPlayback.endAt;
67581
68269
  if (pendingAgentPlayback.interrupted)
67582
68270
  entry.interrupted = true;
@@ -67589,6 +68277,9 @@ function realtimeAgent(options) {
67589
68277
  currentAgentEntry = entry;
67590
68278
  pendingStreamLog = { entry, totalMs: entry.totalMs, firstAudioAtMs };
67591
68279
  }
68280
+ } else if (turn.role === "agent") {
68281
+ earlyRunStartAt = void 0;
68282
+ untimedAgentEntries.push(entry);
67592
68283
  }
67593
68284
  appendTranscript(entry);
67594
68285
  },
@@ -67621,8 +68312,10 @@ function realtimeAgent(options) {
67621
68312
  },
67622
68313
  onBargeIn() {
67623
68314
  sendStreamControl(ws, "clear");
68315
+ recorder?.clearAgent();
67624
68316
  if (vendorSession !== void 0)
67625
68317
  adapter2.clear(vendorSession);
68318
+ playout.clear(Date.now());
67626
68319
  if (currentAgentEntry) {
67627
68320
  applySelfPlaybackFallback(currentAgentEntry, true);
67628
68321
  flushPendingStreamLog();
@@ -67643,10 +68336,53 @@ function realtimeAgent(options) {
67643
68336
  void end();
67644
68337
  }
67645
68338
  };
67646
- resolvePerCallOptions(options, call, context, ctx).then((resolved) => {
68339
+ const answeredEarly = pending.outbound;
68340
+ if (answeredEarly) {
68341
+ ws.send(JSON.stringify({ command: "answer" }));
68342
+ heartbeat = setInterval(() => sendStreamControl(ws, "heartbeat"), HEARTBEAT_INTERVAL_MS);
68343
+ }
68344
+ const earlyAudio = [];
68345
+ let earlyBytes = 0;
68346
+ let greetingText;
68347
+ let calleeSpoke = false;
68348
+ const sendGreeting2 = () => {
68349
+ if (greetingText === void 0 || vendorSession === void 0)
68350
+ return;
68351
+ const text = greetingText;
68352
+ greetingText = void 0;
68353
+ clearTimeout(greetingTimer);
68354
+ adapter2.speak(vendorSession, text);
68355
+ };
68356
+ ws.on("message", (raw, isBinary) => {
68357
+ if (!isBinary)
68358
+ return;
68359
+ recorder?.pushCaller(raw);
68360
+ const vadEvent = vad.push(raw);
68361
+ if (vadEvent === "start") {
68362
+ pendingSpeechStartAt ??= (/* @__PURE__ */ new Date()).toISOString();
68363
+ calleeSpoke = true;
68364
+ sendGreeting2();
68365
+ } else if (vadEvent === "end" && !speechEndFromProvider) {
68366
+ pendingSpeechEndAt = new Date(Date.now() - vad.quietFrames * raw.length / bytesPerMs).toISOString();
68367
+ }
68368
+ if (vendorSession !== void 0) {
68369
+ adapter2.sendAudio(vendorSession, raw);
68370
+ return;
68371
+ }
68372
+ earlyAudio.push(raw);
68373
+ earlyBytes += raw.length;
68374
+ while (earlyBytes > MAX_EARLY_AUDIO_MS * bytesPerMs && earlyAudio.length > 1) {
68375
+ earlyBytes -= earlyAudio.shift().length;
68376
+ }
68377
+ });
68378
+ resolvePerCallOptions(options, call2, context, ctx, pending.data, provider).then((resolved) => {
67647
68379
  if (ended || lifecycle.signal.aborted)
67648
68380
  return void 0;
67649
68381
  bytesPerMs = sinchRate(resolved) * 2 / 1e3;
68382
+ if (pending.outbound && resolved.greeting && adapter2.speak) {
68383
+ greetingText = resolved.greeting;
68384
+ return adapter2.connect({ ...resolved, greeting: void 0, greetingHeld: true }, ctx, callbacks, lifecycle.signal);
68385
+ }
67650
68386
  return adapter2.connect(resolved, ctx, callbacks, lifecycle.signal);
67651
68387
  }).then((session) => {
67652
68388
  if (session === void 0)
@@ -67656,25 +68392,26 @@ function realtimeAgent(options) {
67656
68392
  return;
67657
68393
  }
67658
68394
  vendorSession = session;
67659
- ws.send(JSON.stringify({ command: "answer" }));
67660
- heartbeat = setInterval(() => sendStreamControl(ws, "heartbeat"), HEARTBEAT_INTERVAL_MS);
67661
- ws.on("message", (raw, isBinary) => {
67662
- if (!isBinary)
67663
- return;
67664
- const vadEvent = vad.push(raw);
67665
- if (vadEvent === "start")
67666
- pendingSpeechStartAt ??= (/* @__PURE__ */ new Date()).toISOString();
67667
- else if (vadEvent === "end" && !speechEndFromProvider)
67668
- pendingSpeechEndAt = (/* @__PURE__ */ new Date()).toISOString();
67669
- adapter2.sendAudio(session, raw);
67670
- });
68395
+ if (!answeredEarly)
68396
+ ws.send(JSON.stringify({ command: "answer" }));
68397
+ heartbeat ??= setInterval(() => sendStreamControl(ws, "heartbeat"), HEARTBEAT_INTERVAL_MS);
68398
+ for (const frame of earlyAudio.splice(0))
68399
+ adapter2.sendAudio(session, frame);
68400
+ if (greetingText !== void 0) {
68401
+ if (calleeSpoke)
68402
+ sendGreeting2();
68403
+ else {
68404
+ greetingTimer = setTimeout(sendGreeting2, options.outboundGreetingFallbackMs ?? DEFAULT_OUTBOUND_GREETING_FALLBACK_MS);
68405
+ }
68406
+ }
67671
68407
  }).catch((err) => {
67672
68408
  if (ended)
67673
68409
  return;
67674
68410
  const sanitized = sanitizeVendorError(err);
67675
68411
  console.error("[realtimeAgent] adapter connect failed:", sanitized.message);
67676
68412
  invokeHook("onError", () => options.onError?.({ message: sanitized.message, code: sanitized.code, raw: sanitized }, ctx));
67677
- ws.send(JSON.stringify({ command: "reject" }));
68413
+ if (!answeredEarly)
68414
+ ws.send(JSON.stringify({ command: "reject" }));
67678
68415
  if (ws.readyState === ws.OPEN)
67679
68416
  ws.close(1011, "Vendor connect failed");
67680
68417
  });
@@ -67753,13 +68490,17 @@ function realtimeAgent(options) {
67753
68490
  }
67754
68491
  const endpointFor = (event, clientContext) => {
67755
68492
  const context = clientContext;
67756
- const call = event.call;
67757
- const callId = String(call?.callId ?? "");
68493
+ const call2 = event.call;
68494
+ const callId = String(call2?.callId ?? "");
67758
68495
  const token = randomUUID2();
68496
+ const placed = placedCalls.get(String(call2?.sessionId ?? ""));
67759
68497
  if (callId) {
67760
68498
  pendingSessions.set(token, {
67761
- call,
68499
+ call: call2,
67762
68500
  requestContext: context,
68501
+ outbound: placed !== void 0,
68502
+ data: placed?.data,
68503
+ provider: placed?.provider,
67763
68504
  expiresAt: Date.now() + PENDING_SESSION_TTL_MS,
67764
68505
  expiryTimer: schedulePendingSessionExpiry(token)
67765
68506
  });
@@ -67781,11 +68522,23 @@ function realtimeAgent(options) {
67781
68522
  }
67782
68523
  return streamEndpoint;
67783
68524
  };
67784
- const connect = (call, _builder, context) => {
67785
- const streamEndpoint = endpointFor(toWebhookRequest(call), context);
68525
+ const placedCalls = /* @__PURE__ */ new Map();
68526
+ function rememberPlacedCall(sessionId, data, provider) {
68527
+ const now = Date.now();
68528
+ for (const [id, placed] of placedCalls) {
68529
+ if (placed.expiresAt <= now || placedCalls.size > MAX_PLACED_CALLS)
68530
+ placedCalls.delete(id);
68531
+ }
68532
+ placedCalls.set(sessionId, { data, provider, expiresAt: now + PLACED_CALL_TTL_MS });
68533
+ }
68534
+ const plan = (call2, context, inbound) => {
68535
+ const streamEndpoint = endpointFor(toWebhookRequest(call2), context);
68536
+ const builder = inbound ? commands().answer() : commands();
68537
+ if (recordsViaSinch(options.record))
68538
+ builder.recordToFunctions();
67786
68539
  return {
67787
- callName: CALLER_LEG2,
67788
- commands: commands().answer().bridgeCall(BRIDGE).dial(streamEndpoint, {
68540
+ ...inbound && { callName: CALLER_LEG2 },
68541
+ commands: builder.bridgeCall(BRIDGE).dial(streamEndpoint, {
67789
68542
  callName: STREAM_LEG2,
67790
68543
  maxDuration: resolveMaxDuration(context),
67791
68544
  onAnswer: (c) => c.bridgeCall(BRIDGE),
@@ -67799,9 +68552,26 @@ function realtimeAgent(options) {
67799
68552
  onHangup: [{ command: "hangup", callName: STREAM_LEG2 }]
67800
68553
  };
67801
68554
  };
67802
- const handleCallCompleted = (call, _builder, context) => {
67803
- const callId = String(call.callId ?? "");
68555
+ const connect = (call2, _builder, context) => plan(call2, context, true);
68556
+ const handleAnswered = (call2, _builder, context) => {
68557
+ const placed = placedCalls.get(String(call2.sessionId ?? ""));
68558
+ if (!placed || placed.answered)
68559
+ return void 0;
68560
+ placed.answered = true;
68561
+ return plan(call2, context, false);
68562
+ };
68563
+ const handleCallCompleted = (call2, _builder, context) => {
68564
+ const callId = String(call2.callId ?? "");
67804
68565
  if (callId) {
68566
+ const sessionId = String(call2.sessionId ?? "");
68567
+ const placed = placedCalls.get(sessionId);
68568
+ if (placed?.answered && call2.callType !== "STREAM") {
68569
+ 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));
68570
+ }
68571
+ if (call2.callType !== "STREAM") {
68572
+ placedCalls.delete(sessionId);
68573
+ (liveSessions.get(sessionId) ?? liveSessions.get(callId))?.();
68574
+ }
67805
68575
  for (const [token, pending] of pendingSessions) {
67806
68576
  if (String(pending.call.callId ?? "") === callId)
67807
68577
  deletePendingSession(token);
@@ -67811,7 +68581,27 @@ function realtimeAgent(options) {
67811
68581
  }
67812
68582
  }
67813
68583
  };
67814
- const voiceWebhook = onCall({ incoming: connect, completed: handleCallCompleted });
68584
+ const voiceWebhook = onCall({
68585
+ incoming: connect,
68586
+ answered: handleAnswered,
68587
+ completed: handleCallCompleted
68588
+ });
68589
+ async function call(to, callOptions = {}) {
68590
+ const context = callOptions.context ?? savedContext;
68591
+ if (!context) {
68592
+ throw new Error("realtimeAgent.call() needs a FunctionContext. Pass { context }, or call it after the function has started.");
68593
+ }
68594
+ if (callOptions.provider)
68595
+ getRealtimeAdapter(callOptions.provider);
68596
+ const response = await context.voice.call(to, {
68597
+ callName: CALLER_LEG2,
68598
+ ...callOptions.from && { from: callOptions.from },
68599
+ ...callOptions.timeout !== void 0 && { timeout: callOptions.timeout },
68600
+ ...callOptions.maxDuration !== void 0 && { maxDuration: callOptions.maxDuration }
68601
+ });
68602
+ rememberPlacedCall(response.sessionId, callOptions.data, callOptions.provider);
68603
+ return response;
68604
+ }
67815
68605
  return {
67816
68606
  setup(runtime) {
67817
68607
  runtime.onStartup(async (context) => {
@@ -67821,7 +68611,9 @@ function realtimeAgent(options) {
67821
68611
  },
67822
68612
  voiceWebhook,
67823
68613
  connect,
67824
- endpointFor
68614
+ call,
68615
+ endpointFor,
68616
+ commandsBefore: () => recordsViaSinch(options.record) ? commands().recordToFunctions().build() : []
67825
68617
  };
67826
68618
  }
67827
68619
 
@@ -70844,6 +71636,24 @@ var LocalStorage = class {
70844
71636
  const sanitized = key.replace(/^\/+/, "").replace(/\.\./g, "_");
70845
71637
  return path4.join(this.baseDir, sanitized);
70846
71638
  }
71639
+ /**
71640
+ * Sinch Voice uploads the finished recording itself, so dev points it at the runtime's built-in
71641
+ * `PUT /_sinch/recording/:file` receiver (RECORDING_RECEIVER_PATH) over the tunnel, which writes into `recordings/`.
71642
+ */
71643
+ async getRecordingDestination(callId, format) {
71644
+ const urlPath = `${RECORDING_RECEIVER_PATH}${path4.posix.basename(recordingKey(callId, format))}`;
71645
+ const url2 = tunnelPublicUrl(urlPath, "http");
71646
+ if (!url2) {
71647
+ throw new Error(
71648
+ "Recording needs a public URL to receive the file in dev. Run `sinch functions dev` with a tunnel."
71649
+ );
71650
+ }
71651
+ return url2;
71652
+ }
71653
+ /** The URL `recordToFunctions()` records to; see {@link IFunctionStorage.recordingUrl}. */
71654
+ async recordingUrl(callId, format = "mp3") {
71655
+ return this.getRecordingDestination(callId, normalizeRecordingFormat(format));
71656
+ }
70847
71657
  async write(key, data) {
70848
71658
  const filePath = this.resolvePath(key);
70849
71659
  await fs3.mkdir(path4.dirname(filePath), { recursive: true });
@@ -76014,6 +76824,7 @@ var TunnelClient = class {
76014
76824
  this.tunnelId = message.tunnelId || null;
76015
76825
  this.tunnelUrl = message.publicUrl || null;
76016
76826
  console.log(`Received welcome: tunnelId=${this.tunnelId}`);
76827
+ if (this.tunnelId && this.tunnelUrl) process.env[TUNNEL_PUBLIC_URL_ENV] = this.buildTunnelUrl();
76017
76828
  if (this.welcomeResolver) {
76018
76829
  this.welcomeResolver(true);
76019
76830
  this.welcomeResolver = null;
@@ -76224,6 +77035,7 @@ var TunnelClient = class {
76224
77035
  */
76225
77036
  async disconnect() {
76226
77037
  this.shuttingDown = true;
77038
+ delete process.env[TUNNEL_PUBLIC_URL_ENV];
76227
77039
  this.stopHeartbeat();
76228
77040
  this.streams.closeAll("Tunnel client shutting down");
76229
77041
  if (this.ws) {
@@ -76784,9 +77596,13 @@ export {
76784
77596
  createMenu,
76785
77597
  createSimpleMenu,
76786
77598
  MenuTemplates,
77599
+ RECORDING_RECEIVER_PATH,
77600
+ normalizeRecordingFormat,
77601
+ recordingKey,
76787
77602
  UniversalConfig,
76788
77603
  createConfig,
76789
77604
  createUniversalConfig,
77605
+ require_express2 as require_express,
76790
77606
  REDACTED,
76791
77607
  redactCredentials,
76792
77608
  stringify,
@@ -76796,7 +77612,9 @@ export {
76796
77612
  DEFAULT_STT_LANGUAGE,
76797
77613
  dial,
76798
77614
  endpointNumber,
77615
+ MAX_SAY_CHARS,
76799
77616
  DEFAULT_BRIDGE_NAME,
77617
+ RECORD_TO_FUNCTIONS_SENTINEL,
76800
77618
  PromptBuilder,
76801
77619
  MenuItemBuilder,
76802
77620
  CommandBuilder,
@@ -76820,6 +77638,12 @@ export {
76820
77638
  Client,
76821
77639
  createClient,
76822
77640
  connectAgent,
77641
+ AGENT_STREAM_PATH,
77642
+ AGENT_HEADER_TOKEN,
77643
+ TUNNEL_PUBLIC_URL_ENV,
77644
+ tunnelPublicUrl,
77645
+ resolveAgentStreamUrl,
77646
+ buildAgentStreamEndpoint,
76823
77647
  attachVoiceClient,
76824
77648
  onCall,
76825
77649
  toCamelCase,
@@ -76879,6 +77703,7 @@ export {
76879
77703
  buildBaseContext,
76880
77704
  handleVoiceV1Callback,
76881
77705
  handleVoiceWebhook,
77706
+ rewriteRecordingSentinels,
76882
77707
  handleCustomEndpoint,
76883
77708
  createApp,
76884
77709
  createSinchRuntime,
@@ -76890,10 +77715,6 @@ export {
76890
77715
  ElevenLabsController,
76891
77716
  tryAutoConfigureAsync,
76892
77717
  ElevenLabsAutoConfigurator,
76893
- AGENT_STREAM_PATH,
76894
- AGENT_HEADER_TOKEN,
76895
- resolveAgentStreamUrl,
76896
- buildAgentStreamEndpoint,
76897
77718
  tool,
76898
77719
  voiceRelay,
76899
77720
  realtimeAgent,
@@ -77230,4 +78051,4 @@ serve-static/index.js:
77230
78051
  * MIT Licensed
77231
78052
  *)
77232
78053
  */
77233
- //# sourceMappingURL=chunk-5K5FDUEL.js.map
78054
+ //# sourceMappingURL=chunk-KCLRM3MM.js.map