@sinch/functions-runtime 0.6.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -5
- package/dist/bin/sinch-runtime.js +1 -1
- package/dist/{chunk-TOTJB6SW.js → chunk-DHM4MH2A.js} +584 -60
- package/dist/chunk-DHM4MH2A.js.map +1 -0
- package/dist/index.d.ts +200 -8
- package/dist/index.js +1 -1
- package/dist/voice/v2.d.ts +97 -8
- package/dist/voice/v2.js +1 -3
- package/package.json +1 -1
- package/dist/chunk-TOTJB6SW.js.map +0 -1
|
@@ -60324,6 +60324,14 @@ function defaultLeg(to) {
|
|
|
60324
60324
|
return { name: "relay" };
|
|
60325
60325
|
return { name: "destination" };
|
|
60326
60326
|
}
|
|
60327
|
+
function nextLegName(base, used) {
|
|
60328
|
+
if (!used.has(base))
|
|
60329
|
+
return base;
|
|
60330
|
+
let n = 2;
|
|
60331
|
+
while (used.has(`${base}-${n}`))
|
|
60332
|
+
n++;
|
|
60333
|
+
return `${base}-${n}`;
|
|
60334
|
+
}
|
|
60327
60335
|
function defaultFrom(to, event) {
|
|
60328
60336
|
const call = event?.call;
|
|
60329
60337
|
if (!call)
|
|
@@ -60345,10 +60353,15 @@ function bridgeStep(to, options, leg) {
|
|
|
60345
60353
|
}
|
|
60346
60354
|
const endpoint = typeof to === "function" ? to(scope) : to;
|
|
60347
60355
|
const defaults2 = typeof leg === "function" ? leg(endpoint) : leg;
|
|
60348
|
-
const
|
|
60349
|
-
if (legName
|
|
60356
|
+
const usedNames = scope?.usedNames ?? /* @__PURE__ */ new Set();
|
|
60357
|
+
if (options.legName !== void 0 && usedNames.has(options.legName)) {
|
|
60358
|
+
throw new Error(`Voice v2 dial: the leg name '${options.legName}' is already used earlier in this response \u2014 callName must be unique. Pass a different legName.`);
|
|
60359
|
+
}
|
|
60360
|
+
const legName = options.legName ?? nextLegName(defaults2.name === liveLeg ? defaults2.fallback ?? defaults2.name : defaults2.name, usedNames);
|
|
60361
|
+
if (legName === liveLeg) {
|
|
60350
60362
|
throw new Error(`Voice v2 dial: the dialled leg cannot share the live leg's name '${liveLeg}' \u2014 callName must be unique among live legs. Pass a different legName.`);
|
|
60351
60363
|
}
|
|
60364
|
+
usedNames.add(legName);
|
|
60352
60365
|
const namesLiveLeg = options.liveLeg === void 0 && scope?.namesLiveLeg === true;
|
|
60353
60366
|
if (namesLiveLeg)
|
|
60354
60367
|
scope.dialled.add(legName);
|
|
@@ -60358,7 +60371,8 @@ function bridgeStep(to, options, leg) {
|
|
|
60358
60371
|
liveLeg,
|
|
60359
60372
|
namesLiveLeg,
|
|
60360
60373
|
joined: bridgeName,
|
|
60361
|
-
dialled: scope?.dialled ?? /* @__PURE__ */ new Set()
|
|
60374
|
+
dialled: scope?.dialled ?? /* @__PURE__ */ new Set(),
|
|
60375
|
+
usedNames
|
|
60362
60376
|
};
|
|
60363
60377
|
const noAnswer = options.onNoAnswer && resolveFlow(options.onNoAnswer, inner);
|
|
60364
60378
|
const outcomes = {};
|
|
@@ -60716,6 +60730,13 @@ var CommandBuilder = class {
|
|
|
60716
60730
|
* Never answers the live leg: answering commits billing and forfeits ringback, so an inbound
|
|
60717
60731
|
* call that should be answered first says so with {@link answer}.
|
|
60718
60732
|
*
|
|
60733
|
+
* Voice v2 requires `callName` to be unique over the call's whole lifetime, not just within
|
|
60734
|
+
* this response. Leaving `legName` unset is safe within one response — a repeat of the same
|
|
60735
|
+
* default here, including a fallback dial nested in `onBusy`/`onTimeout`/etc., is numbered
|
|
60736
|
+
* (`destination-2`, `destination-3`, ...) instead of colliding — but dialling again on a
|
|
60737
|
+
* call that a previous response or `PATCH` already gave that default name needs an explicit
|
|
60738
|
+
* `legName`, or the platform returns a 500 with the leg stuck `QUEUED`.
|
|
60739
|
+
*
|
|
60719
60740
|
* @param destination - Who to connect
|
|
60720
60741
|
* @param options - Leg and bridge names, `from`, timeouts, and what happens on no answer
|
|
60721
60742
|
*/
|
|
@@ -60725,6 +60746,9 @@ var CommandBuilder = class {
|
|
|
60725
60746
|
/**
|
|
60726
60747
|
* Connect the caller to a phone number. `from` defaults to the Sinch number the call is on.
|
|
60727
60748
|
*
|
|
60749
|
+
* See {@link bridgeTo} for how `legName` is defaulted and numbered on a repeat, and when it
|
|
60750
|
+
* needs to be passed explicitly.
|
|
60751
|
+
*
|
|
60728
60752
|
* @param number - E.164 number
|
|
60729
60753
|
* @param options - See {@link BridgeToOptions}
|
|
60730
60754
|
*
|
|
@@ -60892,6 +60916,10 @@ var CommandBuilder = class {
|
|
|
60892
60916
|
* arrives as `'call.webhook.escalate'`. `Client.onCall` routes those by name to a handler
|
|
60893
60917
|
* registered under `webhooks`, and to `manage` when no name matches.
|
|
60894
60918
|
*
|
|
60919
|
+
* Like a dial's `callName` and `startRecording`'s `recordingName`, `webhookName` must be
|
|
60920
|
+
* unique for the session's whole lifetime — a flow that repeats across requests (a retry, a
|
|
60921
|
+
* second pass through the same command builder) needs a different name each time it does.
|
|
60922
|
+
*
|
|
60895
60923
|
* @param webhookName - Name for this event (1-64 chars, no whitespace)
|
|
60896
60924
|
* @param url - URL to call. The platform allows it 5 seconds to answer.
|
|
60897
60925
|
* @param options - Fallback URL
|
|
@@ -60920,6 +60948,10 @@ var CommandBuilder = class {
|
|
|
60920
60948
|
* schema requires it and offers no short-lived alternative. See {@link RecordingCredentials}
|
|
60921
60949
|
* before logging anything a `startRecording` is part of.
|
|
60922
60950
|
*
|
|
60951
|
+
* Like a dial's `callName` and `webhook`'s `webhookName`, `recordingName` must be unique for
|
|
60952
|
+
* the session's whole lifetime — a flow that repeats across requests (a retry, a second pass
|
|
60953
|
+
* through the same command builder) needs a different name each time it does.
|
|
60954
|
+
*
|
|
60923
60955
|
* @param options - Destination, credentials, encoding, transcription and outcome events
|
|
60924
60956
|
* @throws If a structured credential component contains a colon
|
|
60925
60957
|
*
|
|
@@ -61093,12 +61125,11 @@ function assertCommands(plan) {
|
|
|
61093
61125
|
}
|
|
61094
61126
|
|
|
61095
61127
|
// ../voice-v2-preview/dist/core/transfer.js
|
|
61096
|
-
var DEFAULT_TRANSFER_LEG = "transfer";
|
|
61097
61128
|
var DEFAULT_TRANSFER_TIMEOUT = 30;
|
|
61098
61129
|
function buildTransferCommands(to, options = {}) {
|
|
61099
61130
|
const bridgeName = options.bridgeName ?? DEFAULT_BRIDGE_NAME;
|
|
61100
61131
|
return commands().dial(to, {
|
|
61101
|
-
callName: options.callName
|
|
61132
|
+
...options.callName !== void 0 && { callName: options.callName },
|
|
61102
61133
|
...options.from !== void 0 && { from: options.from },
|
|
61103
61134
|
timeout: options.timeout ?? DEFAULT_TRANSFER_TIMEOUT,
|
|
61104
61135
|
onAnswer: (c) => c.bridgeCall(bridgeName),
|
|
@@ -61120,7 +61151,7 @@ function buildTransferToCommands(to, target, options = {}, maxDuration) {
|
|
|
61120
61151
|
return [
|
|
61121
61152
|
{ command: "bridgeCall", bridgeName },
|
|
61122
61153
|
buildDial(endpoint, {
|
|
61123
|
-
callName: options.legName
|
|
61154
|
+
...options.legName !== void 0 && { callName: options.legName },
|
|
61124
61155
|
...from !== void 0 && { from },
|
|
61125
61156
|
timeout: options.timeout ?? DEFAULT_TRANSFER_TIMEOUT,
|
|
61126
61157
|
...cap !== void 0 && { maxDuration: cap },
|
|
@@ -61612,7 +61643,8 @@ var Client = class {
|
|
|
61612
61643
|
...this.context && { context: this.context },
|
|
61613
61644
|
liveLeg: !namesLiveLeg && outbound ? ORIGIN_LEG : CALLER_LEG,
|
|
61614
61645
|
namesLiveLeg,
|
|
61615
|
-
dialled: /* @__PURE__ */ new Set()
|
|
61646
|
+
dialled: /* @__PURE__ */ new Set(),
|
|
61647
|
+
usedNames: /* @__PURE__ */ new Set()
|
|
61616
61648
|
};
|
|
61617
61649
|
}
|
|
61618
61650
|
/**
|
|
@@ -62548,14 +62580,19 @@ function buildVoiceSignedRequest(req) {
|
|
|
62548
62580
|
body: req.rawBody
|
|
62549
62581
|
};
|
|
62550
62582
|
}
|
|
62583
|
+
function isVoiceWebhookPath(pathname) {
|
|
62584
|
+
return pathname === "/" || pathname === "/webhook/voice";
|
|
62585
|
+
}
|
|
62551
62586
|
function extractFunctionName(path6, body) {
|
|
62552
|
-
if (body?.event && isVoiceV1Callback(body.event)) {
|
|
62553
|
-
return body.event;
|
|
62554
|
-
}
|
|
62555
|
-
if (isVoiceEvent(body?.event)) {
|
|
62556
|
-
return VOICE_WEBHOOK_HANDLER;
|
|
62557
|
-
}
|
|
62558
62587
|
const pathname = path6.split("?")[0];
|
|
62588
|
+
if (isVoiceWebhookPath(pathname)) {
|
|
62589
|
+
if (body?.event && isVoiceV1Callback(body.event)) {
|
|
62590
|
+
return body.event;
|
|
62591
|
+
}
|
|
62592
|
+
if (isVoiceEvent(body?.event)) {
|
|
62593
|
+
return VOICE_WEBHOOK_HANDLER;
|
|
62594
|
+
}
|
|
62595
|
+
}
|
|
62559
62596
|
const segments = pathname.split("/").filter((s) => s && s !== "*");
|
|
62560
62597
|
if (segments.length === 1 && isVoiceV1Callback(segments[0])) {
|
|
62561
62598
|
return segments[0];
|
|
@@ -63550,6 +63587,7 @@ function readCallHeader(connectMsg, name) {
|
|
|
63550
63587
|
function tool(def) {
|
|
63551
63588
|
return def;
|
|
63552
63589
|
}
|
|
63590
|
+
var DEFAULT_LANGUAGE = "en-US";
|
|
63553
63591
|
function sinchRate(options) {
|
|
63554
63592
|
return options.audio === "wideband" ? 16e3 : 8e3;
|
|
63555
63593
|
}
|
|
@@ -63652,6 +63690,8 @@ function voiceRelay(options) {
|
|
|
63652
63690
|
const speech = [];
|
|
63653
63691
|
const digits = [];
|
|
63654
63692
|
const interrupted = [];
|
|
63693
|
+
const playbackStart = [];
|
|
63694
|
+
const playbackStop = [];
|
|
63655
63695
|
const ended = [];
|
|
63656
63696
|
let over = false;
|
|
63657
63697
|
const write = (message) => {
|
|
@@ -63697,6 +63737,8 @@ function voiceRelay(options) {
|
|
|
63697
63737
|
onSpeech: (handler) => void speech.push(handler),
|
|
63698
63738
|
onDigits: (handler) => void digits.push(handler),
|
|
63699
63739
|
onInterrupted: (handler) => void interrupted.push(handler),
|
|
63740
|
+
onPlaybackStart: (handler) => void playbackStart.push(handler),
|
|
63741
|
+
onPlaybackStop: (handler) => void playbackStop.push(handler),
|
|
63700
63742
|
onEnded: (handler) => void ended.push(handler),
|
|
63701
63743
|
transferToPhone: (number, opts) => move(() => voice.transferToPhone(id, number, withCall(opts))),
|
|
63702
63744
|
transferToSip: (address, opts) => move(() => voice.transferToSip(id, address, withCall(opts))),
|
|
@@ -63733,6 +63775,18 @@ function voiceRelay(options) {
|
|
|
63733
63775
|
for (const handler of interrupted)
|
|
63734
63776
|
run(handler);
|
|
63735
63777
|
break;
|
|
63778
|
+
case "textPlaybackStart":
|
|
63779
|
+
for (const handler of playbackStart)
|
|
63780
|
+
run(handler);
|
|
63781
|
+
break;
|
|
63782
|
+
case "textPlaybackStop":
|
|
63783
|
+
for (const handler of playbackStop)
|
|
63784
|
+
run(() => handler({ cancelled: false }));
|
|
63785
|
+
break;
|
|
63786
|
+
case "textPlaybackCancel":
|
|
63787
|
+
for (const handler of playbackStop)
|
|
63788
|
+
run(() => handler({ cancelled: true }));
|
|
63789
|
+
break;
|
|
63736
63790
|
default:
|
|
63737
63791
|
break;
|
|
63738
63792
|
}
|
|
@@ -63811,7 +63865,7 @@ function redactSecrets(message) {
|
|
|
63811
63865
|
var DEEPGRAM_URL = "wss://agent.deepgram.com/v1/agent/converse";
|
|
63812
63866
|
var DEFAULT_STT_MODEL = "flux-general-en";
|
|
63813
63867
|
var DEFAULT_LLM_PROVIDER = "open_ai";
|
|
63814
|
-
var DEFAULT_LLM_MODEL = "gpt-5.
|
|
63868
|
+
var DEFAULT_LLM_MODEL = "gpt-5.4-nano";
|
|
63815
63869
|
var KEEP_ALIVE_INTERVAL_MS = 8e3;
|
|
63816
63870
|
var KEEP_ALIVE_CHECK_INTERVAL_MS = 2e3;
|
|
63817
63871
|
var HANDSHAKE_TIMEOUT_MS = 1e4;
|
|
@@ -63885,7 +63939,13 @@ function buildSettingsFrame(options) {
|
|
|
63885
63939
|
provider: {
|
|
63886
63940
|
type: "deepgram",
|
|
63887
63941
|
model: sttModel,
|
|
63888
|
-
version: sttModel.startsWith("flux") ? "v2" : "v1"
|
|
63942
|
+
version: sttModel.startsWith("flux") ? "v2" : "v1",
|
|
63943
|
+
// Deepgram's `listen.provider.language` — pins recognition to `options.language`
|
|
63944
|
+
// (defaults to `'en-US'`, see `resolvePerCallOptions`) rather than letting the model
|
|
63945
|
+
// auto-detect and drift onto a misheard phrase, the way it did on a live Gemini call
|
|
63946
|
+
// (see `gemini.ts`'s own `speechConfig.languageCode` comment for that incident; not yet
|
|
63947
|
+
// reproduced against Deepgram specifically, wired here for the same reason).
|
|
63948
|
+
language: options.language ?? DEFAULT_LANGUAGE
|
|
63889
63949
|
}
|
|
63890
63950
|
},
|
|
63891
63951
|
think: {
|
|
@@ -63925,7 +63985,8 @@ function createDeepgramAdapter(webSocketClient) {
|
|
|
63925
63985
|
itemAudioStartedAt: void 0,
|
|
63926
63986
|
bytesSentForItem: 0,
|
|
63927
63987
|
generating: false,
|
|
63928
|
-
interruptedThisResponse: false
|
|
63988
|
+
interruptedThisResponse: false,
|
|
63989
|
+
playbackStopReported: false
|
|
63929
63990
|
};
|
|
63930
63991
|
const tools = options.tools ?? [];
|
|
63931
63992
|
session.keepAliveTimer = setInterval(() => {
|
|
@@ -63969,6 +64030,8 @@ function createDeepgramAdapter(webSocketClient) {
|
|
|
63969
64030
|
session.itemAudioStartedAt = Date.now();
|
|
63970
64031
|
session.bytesSentForItem = 0;
|
|
63971
64032
|
session.interruptedThisResponse = false;
|
|
64033
|
+
session.playbackStopReported = false;
|
|
64034
|
+
callbacks.onPlaybackStart?.();
|
|
63972
64035
|
}
|
|
63973
64036
|
session.bytesSentForItem += raw.length;
|
|
63974
64037
|
callbacks.onAudioOut(raw);
|
|
@@ -64022,15 +64085,26 @@ function createDeepgramAdapter(webSocketClient) {
|
|
|
64022
64085
|
}
|
|
64023
64086
|
break;
|
|
64024
64087
|
}
|
|
64025
|
-
case "AgentAudioDone":
|
|
64088
|
+
case "AgentAudioDone": {
|
|
64089
|
+
const hadAudio = session.generating;
|
|
64026
64090
|
session.generating = false;
|
|
64091
|
+
if (hadAudio && !session.playbackStopReported) {
|
|
64092
|
+
session.playbackStopReported = true;
|
|
64093
|
+
callbacks.onPlaybackStop?.({ cancelled: false });
|
|
64094
|
+
}
|
|
64027
64095
|
break;
|
|
64096
|
+
}
|
|
64028
64097
|
case "UserStartedSpeaking": {
|
|
64098
|
+
callbacks.onSpeechStart?.();
|
|
64029
64099
|
const remainingMs = session.itemAudioStartedAt !== void 0 ? session.bytesSentForItem / session.bytesPerMs - (Date.now() - session.itemAudioStartedAt) : 0;
|
|
64030
64100
|
const stillPlaying = remainingMs > 0;
|
|
64031
64101
|
const shouldBargeIn = stillPlaying || session.generating;
|
|
64032
64102
|
if (shouldBargeIn && !session.interruptedThisResponse) {
|
|
64033
64103
|
session.interruptedThisResponse = true;
|
|
64104
|
+
if (!session.playbackStopReported) {
|
|
64105
|
+
session.playbackStopReported = true;
|
|
64106
|
+
callbacks.onPlaybackStop?.({ cancelled: true });
|
|
64107
|
+
}
|
|
64034
64108
|
callbacks.onBargeIn();
|
|
64035
64109
|
}
|
|
64036
64110
|
break;
|
|
@@ -64054,6 +64128,9 @@ function createDeepgramAdapter(webSocketClient) {
|
|
|
64054
64128
|
}
|
|
64055
64129
|
closeAnyState(dgWs);
|
|
64056
64130
|
break;
|
|
64131
|
+
case "Warning":
|
|
64132
|
+
console.warn("[realtimeAgent] Deepgram Agent API warning:", msg);
|
|
64133
|
+
break;
|
|
64057
64134
|
}
|
|
64058
64135
|
});
|
|
64059
64136
|
dgWs.on("error", (err) => {
|
|
@@ -64209,6 +64286,31 @@ var StreamingResampler = class {
|
|
|
64209
64286
|
};
|
|
64210
64287
|
|
|
64211
64288
|
// ../runtime-shared/dist/ai/realtime/tool-injection.js
|
|
64289
|
+
var DEFAULT_TIMEZONE = "America/Chicago";
|
|
64290
|
+
function currentDateTimePreamble(timezone = DEFAULT_TIMEZONE, now = /* @__PURE__ */ new Date()) {
|
|
64291
|
+
const parts = new Intl.DateTimeFormat("en-GB", {
|
|
64292
|
+
weekday: "long",
|
|
64293
|
+
day: "numeric",
|
|
64294
|
+
month: "long",
|
|
64295
|
+
year: "numeric",
|
|
64296
|
+
hour: "2-digit",
|
|
64297
|
+
minute: "2-digit",
|
|
64298
|
+
hour12: false,
|
|
64299
|
+
timeZone: timezone
|
|
64300
|
+
}).formatToParts(now);
|
|
64301
|
+
const get = (type) => parts.find((p) => p.type === type)?.value ?? "";
|
|
64302
|
+
const zoneName = new Intl.DateTimeFormat("en-US", { timeZone: timezone, timeZoneName: "long" }).formatToParts(now).find((p) => p.type === "timeZoneName")?.value ?? timezone;
|
|
64303
|
+
return `Current date and time: ${get("weekday")}, ${get("day")} ${get("month")} ${get("year")}, ${get("hour")}:${get("minute")} (${zoneName})
|
|
64304
|
+
|
|
64305
|
+
`;
|
|
64306
|
+
}
|
|
64307
|
+
function verbatimGreetingDirective(greeting) {
|
|
64308
|
+
return `Say this exact greeting, word for word, with no changes or additions: "${greeting}"`;
|
|
64309
|
+
}
|
|
64310
|
+
function nonBlank(value) {
|
|
64311
|
+
const trimmed = value?.trim();
|
|
64312
|
+
return trimmed ? trimmed : void 0;
|
|
64313
|
+
}
|
|
64212
64314
|
var E1642 = /^\+\d{6,15}$/;
|
|
64213
64315
|
function invokeHook(name, fn) {
|
|
64214
64316
|
try {
|
|
@@ -64294,6 +64396,11 @@ function pcm16Rms(pcm) {
|
|
|
64294
64396
|
function isSpeechFrame(pcm) {
|
|
64295
64397
|
return pcm16Rms(pcm) > SILENCE_RMS_THRESHOLD;
|
|
64296
64398
|
}
|
|
64399
|
+
function toAnchoredIso(session, offsetMs) {
|
|
64400
|
+
if (offsetMs === void 0 || session.sessionStartedAtMs === void 0)
|
|
64401
|
+
return void 0;
|
|
64402
|
+
return new Date(session.sessionStartedAtMs + offsetMs).toISOString();
|
|
64403
|
+
}
|
|
64297
64404
|
function buildGreetingDirective(greeting) {
|
|
64298
64405
|
return `Greet the caller now by saying exactly: "${greeting}"`;
|
|
64299
64406
|
}
|
|
@@ -64424,7 +64531,18 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64424
64531
|
pendingUserTurnText: "",
|
|
64425
64532
|
userTurnTimer: void 0,
|
|
64426
64533
|
pendingUserTurnEndMs: void 0,
|
|
64427
|
-
closeAckTimer: void 0
|
|
64534
|
+
closeAckTimer: void 0,
|
|
64535
|
+
sessionSeconds: void 0,
|
|
64536
|
+
backendInputTokens: 0,
|
|
64537
|
+
backendOutputTokens: 0,
|
|
64538
|
+
pendingUserTurnStartMs: void 0,
|
|
64539
|
+
pendingAgentTurnStartMs: void 0,
|
|
64540
|
+
pendingAgentTurnEndMs: void 0,
|
|
64541
|
+
sessionStartedAtMs: void 0,
|
|
64542
|
+
delegationCreatedAtMs: /* @__PURE__ */ new Map(),
|
|
64543
|
+
delegationFirstOutputMs: /* @__PURE__ */ new Map(),
|
|
64544
|
+
delegationToolMs: /* @__PURE__ */ new Map(),
|
|
64545
|
+
lastDelegationId: void 0
|
|
64428
64546
|
};
|
|
64429
64547
|
const tools = options.tools ?? [];
|
|
64430
64548
|
vendorWs.on("open", () => {
|
|
@@ -64457,10 +64575,12 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64457
64575
|
const key = stateKey(delegationId);
|
|
64458
64576
|
const deleg = getOrCreateDelegation(key);
|
|
64459
64577
|
deleg.callIds.add(callId);
|
|
64578
|
+
const toolStart = Date.now();
|
|
64460
64579
|
void dispatchToolCall2(callId, name, rawArgs ?? "", tools, ctx, vendorWs, callbacks).catch((err) => {
|
|
64461
64580
|
const sanitized = sanitizeVendorError(err);
|
|
64462
64581
|
callbacks.onError({ message: sanitized.message, code: sanitized.code, raw: sanitized });
|
|
64463
64582
|
}).finally(() => {
|
|
64583
|
+
session.delegationToolMs.set(delegationId, (session.delegationToolMs.get(delegationId) ?? 0) + (Date.now() - toolStart));
|
|
64464
64584
|
session.delegations.get(key)?.callIdsCompleted.add(callId);
|
|
64465
64585
|
maybeFinishResponse(key);
|
|
64466
64586
|
});
|
|
@@ -64481,8 +64601,23 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64481
64601
|
session.agentTurnStartedAt = void 0;
|
|
64482
64602
|
const text = session.pendingAgentTurnText;
|
|
64483
64603
|
session.pendingAgentTurnText = "";
|
|
64604
|
+
const playbackStartAt = toAnchoredIso(session, session.pendingAgentTurnStartMs);
|
|
64605
|
+
const playbackEndAt = toAnchoredIso(session, session.pendingAgentTurnEndMs);
|
|
64606
|
+
session.pendingAgentTurnStartMs = void 0;
|
|
64607
|
+
session.pendingAgentTurnEndMs = void 0;
|
|
64608
|
+
let delegationMs;
|
|
64609
|
+
if (session.lastDelegationId !== void 0) {
|
|
64610
|
+
const firstOutputMs = session.delegationFirstOutputMs.get(session.lastDelegationId);
|
|
64611
|
+
const toolMs = session.delegationToolMs.get(session.lastDelegationId) ?? 0;
|
|
64612
|
+
if (firstOutputMs !== void 0)
|
|
64613
|
+
delegationMs = firstOutputMs + toolMs;
|
|
64614
|
+
session.delegationFirstOutputMs.delete(session.lastDelegationId);
|
|
64615
|
+
session.delegationToolMs.delete(session.lastDelegationId);
|
|
64616
|
+
session.delegationCreatedAtMs.delete(session.lastDelegationId);
|
|
64617
|
+
session.lastDelegationId = void 0;
|
|
64618
|
+
}
|
|
64484
64619
|
if (text)
|
|
64485
|
-
callbacks.onTurn({ role: "agent", text, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
64620
|
+
callbacks.onTurn({ role: "agent", text, timestamp: (/* @__PURE__ */ new Date()).toISOString(), playbackStartAt, playbackEndAt, delegationMs });
|
|
64486
64621
|
};
|
|
64487
64622
|
const scheduleAgentTurnFlush = () => {
|
|
64488
64623
|
if (session.agentTurnTimer !== void 0)
|
|
@@ -64494,11 +64629,14 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64494
64629
|
clearTimeout(session.userTurnTimer);
|
|
64495
64630
|
session.userTurnTimer = void 0;
|
|
64496
64631
|
}
|
|
64632
|
+
const speechStartAt = toAnchoredIso(session, session.pendingUserTurnStartMs);
|
|
64633
|
+
const speechEndAt = toAnchoredIso(session, session.pendingUserTurnEndMs);
|
|
64497
64634
|
session.pendingUserTurnEndMs = void 0;
|
|
64635
|
+
session.pendingUserTurnStartMs = void 0;
|
|
64498
64636
|
const text = session.pendingUserTurnText;
|
|
64499
64637
|
session.pendingUserTurnText = "";
|
|
64500
64638
|
if (text)
|
|
64501
|
-
callbacks.onTurn({ role: "user", text, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
64639
|
+
callbacks.onTurn({ role: "user", text, timestamp: (/* @__PURE__ */ new Date()).toISOString(), speechStartAt, speechEndAt });
|
|
64502
64640
|
};
|
|
64503
64641
|
const scheduleUserTurnFlush = () => {
|
|
64504
64642
|
if (session.userTurnTimer !== void 0)
|
|
@@ -64536,6 +64674,13 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64536
64674
|
signal.removeEventListener("abort", onAbort);
|
|
64537
64675
|
fn();
|
|
64538
64676
|
};
|
|
64677
|
+
const reportUsage = () => {
|
|
64678
|
+
callbacks.onUsage?.({
|
|
64679
|
+
inputTokens: session.backendInputTokens || void 0,
|
|
64680
|
+
outputTokens: session.backendOutputTokens || void 0,
|
|
64681
|
+
audioSeconds: session.sessionSeconds
|
|
64682
|
+
});
|
|
64683
|
+
};
|
|
64539
64684
|
vendorWs.on("message", (raw) => {
|
|
64540
64685
|
if (isOversizedFrame(raw)) {
|
|
64541
64686
|
callbacks.onError({ message: "Received an oversized frame from OpenAI GPT-Live \u2014 dropped" });
|
|
@@ -64550,6 +64695,7 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64550
64695
|
case "session.started": {
|
|
64551
64696
|
const started = msg["session"];
|
|
64552
64697
|
session.expiresAt = started?.expires_at;
|
|
64698
|
+
session.sessionStartedAtMs = Date.now();
|
|
64553
64699
|
session.ready = true;
|
|
64554
64700
|
settle2(() => resolve(session));
|
|
64555
64701
|
if (options.greeting) {
|
|
@@ -64586,8 +64732,12 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64586
64732
|
const hasRealGap = startMs !== void 0 && session.pendingUserTurnEndMs !== void 0 && startMs - session.pendingUserTurnEndMs > TURN_SILENCE_MS;
|
|
64587
64733
|
if (hasRealGap)
|
|
64588
64734
|
flushUserTurnNow();
|
|
64589
|
-
if (delta)
|
|
64735
|
+
if (delta) {
|
|
64736
|
+
if (session.pendingUserTurnText === "" && startMs !== void 0) {
|
|
64737
|
+
session.pendingUserTurnStartMs = startMs;
|
|
64738
|
+
}
|
|
64590
64739
|
session.pendingUserTurnText += delta;
|
|
64740
|
+
}
|
|
64591
64741
|
if (endMs !== void 0)
|
|
64592
64742
|
session.pendingUserTurnEndMs = endMs;
|
|
64593
64743
|
scheduleUserTurnFlush();
|
|
@@ -64595,14 +64745,20 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64595
64745
|
}
|
|
64596
64746
|
case "session.output_transcript.delta": {
|
|
64597
64747
|
const delta = msg["delta"];
|
|
64748
|
+
const startMs = typeof msg["start_ms"] === "number" ? msg["start_ms"] : void 0;
|
|
64749
|
+
const endMs = typeof msg["end_ms"] === "number" ? msg["end_ms"] : void 0;
|
|
64598
64750
|
if (delta) {
|
|
64599
64751
|
if (session.pendingAgentTurnText === "") {
|
|
64600
64752
|
session.agentTurnStartedAt = Date.now();
|
|
64601
64753
|
if (session.agentTurnHardCapTimer !== void 0)
|
|
64602
64754
|
clearTimeout(session.agentTurnHardCapTimer);
|
|
64603
64755
|
session.agentTurnHardCapTimer = setTimeout(flushAgentTurnNow, AGENT_TURN_HARD_CAP_MS);
|
|
64756
|
+
if (startMs !== void 0)
|
|
64757
|
+
session.pendingAgentTurnStartMs = startMs;
|
|
64604
64758
|
}
|
|
64605
64759
|
session.pendingAgentTurnText += delta;
|
|
64760
|
+
if (endMs !== void 0)
|
|
64761
|
+
session.pendingAgentTurnEndMs = endMs;
|
|
64606
64762
|
}
|
|
64607
64763
|
const audioQuiet = session.lastSpeechAudioAt !== void 0 && Date.now() - session.lastSpeechAudioAt > TURN_SILENCE_MS;
|
|
64608
64764
|
if (audioQuiet) {
|
|
@@ -64617,6 +64773,13 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64617
64773
|
const inner = msg["event"];
|
|
64618
64774
|
if (!inner || !delegationId)
|
|
64619
64775
|
break;
|
|
64776
|
+
session.lastDelegationId = delegationId;
|
|
64777
|
+
const isBackendOutput = inner.type === "response.output_item.added" || inner.type === "response.output_item.done" || inner.type === "response.output_text.delta";
|
|
64778
|
+
if (isBackendOutput && !session.delegationFirstOutputMs.has(delegationId)) {
|
|
64779
|
+
const createdAt = session.delegationCreatedAtMs.get(delegationId);
|
|
64780
|
+
if (createdAt !== void 0)
|
|
64781
|
+
session.delegationFirstOutputMs.set(delegationId, Date.now() - createdAt);
|
|
64782
|
+
}
|
|
64620
64783
|
switch (inner.type) {
|
|
64621
64784
|
case "response.created": {
|
|
64622
64785
|
const responseId = inner.response?.id;
|
|
@@ -64636,11 +64799,31 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64636
64799
|
const deleg = getOrCreateDelegation(key);
|
|
64637
64800
|
deleg.responseDone = true;
|
|
64638
64801
|
maybeFinishResponse(key);
|
|
64802
|
+
const backendUsage = inner.response?.usage;
|
|
64803
|
+
if (backendUsage) {
|
|
64804
|
+
session.backendInputTokens += backendUsage.input_tokens ?? 0;
|
|
64805
|
+
session.backendOutputTokens += backendUsage.output_tokens ?? 0;
|
|
64806
|
+
reportUsage();
|
|
64807
|
+
}
|
|
64639
64808
|
break;
|
|
64640
64809
|
}
|
|
64641
64810
|
}
|
|
64642
64811
|
break;
|
|
64643
64812
|
}
|
|
64813
|
+
case "session.delegation.created": {
|
|
64814
|
+
const delegationId = msg["delegation_id"];
|
|
64815
|
+
if (delegationId)
|
|
64816
|
+
session.delegationCreatedAtMs.set(delegationId, Date.now());
|
|
64817
|
+
break;
|
|
64818
|
+
}
|
|
64819
|
+
case "session.usage.updated": {
|
|
64820
|
+
const usage = msg["usage"];
|
|
64821
|
+
if (usage?.seconds !== void 0) {
|
|
64822
|
+
session.sessionSeconds = usage.seconds;
|
|
64823
|
+
reportUsage();
|
|
64824
|
+
}
|
|
64825
|
+
break;
|
|
64826
|
+
}
|
|
64644
64827
|
case "session.closed": {
|
|
64645
64828
|
if (session.closeAckTimer !== void 0) {
|
|
64646
64829
|
clearTimeout(session.closeAckTimer);
|
|
@@ -64799,7 +64982,9 @@ function createOpenAiCompatibleAdapter(config, webSocketClient) {
|
|
|
64799
64982
|
responseCallIds: /* @__PURE__ */ new Set(),
|
|
64800
64983
|
responseCallIdsCompleted: /* @__PURE__ */ new Set(),
|
|
64801
64984
|
responseDone: false,
|
|
64802
|
-
pendingUserTurnText: /* @__PURE__ */ new Map()
|
|
64985
|
+
pendingUserTurnText: /* @__PURE__ */ new Map(),
|
|
64986
|
+
totalInputTokens: 0,
|
|
64987
|
+
totalOutputTokens: 0
|
|
64803
64988
|
};
|
|
64804
64989
|
const tools = options.tools ?? [];
|
|
64805
64990
|
vendorWs.on("open", () => {
|
|
@@ -64892,7 +65077,10 @@ function createOpenAiCompatibleAdapter(config, webSocketClient) {
|
|
|
64892
65077
|
session.ready = true;
|
|
64893
65078
|
settle2(() => resolve(session));
|
|
64894
65079
|
if (options.greeting) {
|
|
64895
|
-
vendorWs.send(JSON.stringify({
|
|
65080
|
+
vendorWs.send(JSON.stringify({
|
|
65081
|
+
type: "response.create",
|
|
65082
|
+
response: { instructions: verbatimGreetingDirective(options.greeting) }
|
|
65083
|
+
}));
|
|
64896
65084
|
}
|
|
64897
65085
|
break;
|
|
64898
65086
|
case "response.created":
|
|
@@ -64905,6 +65093,7 @@ function createOpenAiCompatibleAdapter(config, webSocketClient) {
|
|
|
64905
65093
|
session.currentItemId = itemId;
|
|
64906
65094
|
session.itemAudioStartedAt = Date.now();
|
|
64907
65095
|
session.bytesSentForItem = 0;
|
|
65096
|
+
callbacks.onPlaybackStart?.();
|
|
64908
65097
|
}
|
|
64909
65098
|
const mulaw = safeBase64ToBuffer(msg["delta"]);
|
|
64910
65099
|
if (!mulaw) {
|
|
@@ -64937,16 +65126,27 @@ function createOpenAiCompatibleAdapter(config, webSocketClient) {
|
|
|
64937
65126
|
case "response.function_call_arguments.done":
|
|
64938
65127
|
maybeDispatch(msg["call_id"], msg["name"], msg["arguments"]);
|
|
64939
65128
|
break;
|
|
64940
|
-
case "response.done":
|
|
65129
|
+
case "response.done": {
|
|
65130
|
+
if (session.currentItemId !== void 0)
|
|
65131
|
+
callbacks.onPlaybackStop?.({ cancelled: false });
|
|
65132
|
+
const usage = msg["response"]?.usage;
|
|
65133
|
+
if (usage) {
|
|
65134
|
+
session.totalInputTokens += usage.input_tokens ?? 0;
|
|
65135
|
+
session.totalOutputTokens += usage.output_tokens ?? 0;
|
|
65136
|
+
callbacks.onUsage?.({ inputTokens: session.totalInputTokens, outputTokens: session.totalOutputTokens });
|
|
65137
|
+
}
|
|
64941
65138
|
closeResponse();
|
|
64942
65139
|
break;
|
|
65140
|
+
}
|
|
64943
65141
|
case "input_audio_buffer.speech_started": {
|
|
65142
|
+
callbacks.onSpeechStart?.();
|
|
64944
65143
|
flushPendingUserTurns();
|
|
64945
65144
|
const remainingMs = session.itemAudioStartedAt !== void 0 ? session.bytesSentForItem / MULAW_BYTES_PER_MS - (Date.now() - session.itemAudioStartedAt) : 0;
|
|
64946
65145
|
const stillPlaying = remainingMs > 0;
|
|
64947
65146
|
const shouldBargeIn = stillPlaying || session.responseOpen;
|
|
64948
65147
|
if (shouldBargeIn && !session.interruptedThisResponse) {
|
|
64949
65148
|
session.interruptedThisResponse = true;
|
|
65149
|
+
const hadAudio = session.currentItemId !== void 0;
|
|
64950
65150
|
if (session.responseOpen) {
|
|
64951
65151
|
if (config.serverCancelsOnSpeechStarted) {
|
|
64952
65152
|
closeResponse();
|
|
@@ -64962,10 +65162,15 @@ function createOpenAiCompatibleAdapter(config, webSocketClient) {
|
|
|
64962
65162
|
vendorWs.send(JSON.stringify({ type: "response.cancel" }));
|
|
64963
65163
|
}
|
|
64964
65164
|
}
|
|
65165
|
+
if (hadAudio)
|
|
65166
|
+
callbacks.onPlaybackStop?.({ cancelled: true });
|
|
64965
65167
|
callbacks.onBargeIn();
|
|
64966
65168
|
}
|
|
64967
65169
|
break;
|
|
64968
65170
|
}
|
|
65171
|
+
case "input_audio_buffer.speech_stopped":
|
|
65172
|
+
callbacks.onSpeechEnd?.();
|
|
65173
|
+
break;
|
|
64969
65174
|
case "response.output_audio_transcript.done": {
|
|
64970
65175
|
const text = msg["transcript"];
|
|
64971
65176
|
if (text)
|
|
@@ -65048,7 +65253,14 @@ function buildGrokSession(options, tools) {
|
|
|
65048
65253
|
// `grok-transcribe` is required for xAI to emit
|
|
65049
65254
|
// `conversation.item.input_audio_transcription.updated` at all — see the file header's
|
|
65050
65255
|
// "Input transcription" note (finding #8).
|
|
65051
|
-
|
|
65256
|
+
// `language_hint` biases recognition toward `options.language` (defaults to `'en-US'`,
|
|
65257
|
+
// see `resolvePerCallOptions`) — previously left unset per this file's own header note
|
|
65258
|
+
// ("no author-facing field maps onto [it] yet"); `RealtimeAgentOptions.language` is now
|
|
65259
|
+
// that field.
|
|
65260
|
+
input: {
|
|
65261
|
+
format: { type: "audio/pcmu" },
|
|
65262
|
+
transcription: { model: "grok-transcribe", language_hint: options.language ?? DEFAULT_LANGUAGE }
|
|
65263
|
+
},
|
|
65052
65264
|
output: { format: { type: "audio/pcmu" } }
|
|
65053
65265
|
},
|
|
65054
65266
|
tools: encodeTools2(tools)
|
|
@@ -65078,9 +65290,15 @@ function providerOptionsFor3(options) {
|
|
|
65078
65290
|
}
|
|
65079
65291
|
function flushPendingTurns(session, callbacks) {
|
|
65080
65292
|
if (session.pendingUserText) {
|
|
65081
|
-
callbacks.onTurn({
|
|
65293
|
+
callbacks.onTurn({
|
|
65294
|
+
role: "user",
|
|
65295
|
+
text: session.pendingUserText,
|
|
65296
|
+
timestamp: session.pendingUserTextAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
65297
|
+
});
|
|
65082
65298
|
session.pendingUserText = "";
|
|
65299
|
+
session.pendingUserTextAt = void 0;
|
|
65083
65300
|
}
|
|
65301
|
+
session.speechStartReported = false;
|
|
65084
65302
|
flushPendingAgentTurn(session, callbacks);
|
|
65085
65303
|
}
|
|
65086
65304
|
function flushPendingAgentTurn(session, callbacks) {
|
|
@@ -65131,10 +65349,16 @@ function buildSetupMessage(options, model, tools, resumptionHandle) {
|
|
|
65131
65349
|
model: model.startsWith("models/") ? model : `models/${model}`,
|
|
65132
65350
|
generationConfig: {
|
|
65133
65351
|
responseModalities: ["AUDIO"],
|
|
65134
|
-
//
|
|
65135
|
-
//
|
|
65136
|
-
|
|
65137
|
-
|
|
65352
|
+
// `languageCode` is always sent (`options.language` defaults to `'en-US'` — see
|
|
65353
|
+
// `resolvePerCallOptions`): a live prd call had the caller's speech misheard as Spanish
|
|
65354
|
+
// ("¿Cómo te") and Gemini — a single model doing both recognition and reply, not a
|
|
65355
|
+
// separate STT/TTS pair — answered in Spanish for that turn. Pinning `languageCode`
|
|
65356
|
+
// constrains the session to the configured language regardless of what the audio sounds
|
|
65357
|
+
// like. `voiceConfig` stays conditional on an author voice — unset, Gemini applies its
|
|
65358
|
+
// own default voice.
|
|
65359
|
+
speechConfig: {
|
|
65360
|
+
languageCode: options.language ?? DEFAULT_LANGUAGE,
|
|
65361
|
+
...options.voice && { voiceConfig: { prebuiltVoiceConfig: { voiceName: options.voice } } }
|
|
65138
65362
|
}
|
|
65139
65363
|
},
|
|
65140
65364
|
systemInstruction: { parts: [{ text: options.prompt }] },
|
|
@@ -65222,7 +65446,9 @@ function createGeminiAdapter(webSocketClient) {
|
|
|
65222
65446
|
resamplerIn: new StreamingResampler(rate, VENDOR_IN_RATE),
|
|
65223
65447
|
resamplerOut: new StreamingResampler(VENDOR_OUT_RATE, rate),
|
|
65224
65448
|
pendingUserText: "",
|
|
65225
|
-
pendingAgentText: ""
|
|
65449
|
+
pendingAgentText: "",
|
|
65450
|
+
pendingUserTextAt: void 0,
|
|
65451
|
+
speechStartReported: false
|
|
65226
65452
|
};
|
|
65227
65453
|
let greeted = false;
|
|
65228
65454
|
const sendRealtimeAudio = (pcm) => {
|
|
@@ -65309,6 +65535,13 @@ function createGeminiAdapter(webSocketClient) {
|
|
|
65309
65535
|
}
|
|
65310
65536
|
return;
|
|
65311
65537
|
}
|
|
65538
|
+
const usageMetadata = msg["usageMetadata"];
|
|
65539
|
+
if (usageMetadata) {
|
|
65540
|
+
callbacks.onUsage?.({
|
|
65541
|
+
inputTokens: usageMetadata.promptTokenCount,
|
|
65542
|
+
outputTokens: usageMetadata.responseTokenCount
|
|
65543
|
+
});
|
|
65544
|
+
}
|
|
65312
65545
|
const resumptionUpdate = msg["sessionResumptionUpdate"];
|
|
65313
65546
|
if (resumptionUpdate) {
|
|
65314
65547
|
if (resumptionUpdate.resumable === false) {
|
|
@@ -65339,8 +65572,13 @@ function createGeminiAdapter(webSocketClient) {
|
|
|
65339
65572
|
} else if (parts !== void 0) {
|
|
65340
65573
|
callbacks.onError({ message: "Received a malformed modelTurn from Gemini Live \u2014 parts was not an array" });
|
|
65341
65574
|
}
|
|
65575
|
+
if (content.interimInputTranscription?.text && !session.speechStartReported) {
|
|
65576
|
+
session.speechStartReported = true;
|
|
65577
|
+
callbacks.onSpeechStart?.();
|
|
65578
|
+
}
|
|
65342
65579
|
if (content.inputTranscription?.text) {
|
|
65343
65580
|
session.pendingUserText += content.inputTranscription.text;
|
|
65581
|
+
session.pendingUserTextAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
65344
65582
|
}
|
|
65345
65583
|
if (content.outputTranscription?.text) {
|
|
65346
65584
|
session.pendingAgentText += content.outputTranscription.text;
|
|
@@ -65472,6 +65710,18 @@ function getRealtimeAdapter(provider) {
|
|
|
65472
65710
|
|
|
65473
65711
|
// ../runtime-shared/dist/ai/realtime/adapters/relay-llm.js
|
|
65474
65712
|
var DEFAULT_RESPONSES_BASE_URL = "https://api.openai.com/v1";
|
|
65713
|
+
function resolveBaseUrl(value) {
|
|
65714
|
+
const trimmed = value?.trim();
|
|
65715
|
+
if (!trimmed)
|
|
65716
|
+
return void 0;
|
|
65717
|
+
try {
|
|
65718
|
+
const { protocol } = new URL(trimmed);
|
|
65719
|
+
if (protocol === "http:" || protocol === "https:")
|
|
65720
|
+
return trimmed;
|
|
65721
|
+
} catch {
|
|
65722
|
+
}
|
|
65723
|
+
return void 0;
|
|
65724
|
+
}
|
|
65475
65725
|
var DEFAULT_SERVICE_TIER = "fast";
|
|
65476
65726
|
var DEFAULT_REASONING_EFFORT = "none";
|
|
65477
65727
|
var DEFAULT_VERBOSITY = "low";
|
|
@@ -65669,7 +65919,8 @@ function createResponsesEventState(callbacks) {
|
|
|
65669
65919
|
const flushed = sentences.flush();
|
|
65670
65920
|
if (flushed)
|
|
65671
65921
|
callbacks.onSentence(flushed);
|
|
65672
|
-
|
|
65922
|
+
const usage = response?.usage ? { inputTokens: response.usage.input_tokens, outputTokens: response.usage.output_tokens } : void 0;
|
|
65923
|
+
return { text, responseId, usage };
|
|
65673
65924
|
}
|
|
65674
65925
|
case "response.failed": {
|
|
65675
65926
|
const response = event["response"];
|
|
@@ -65695,7 +65946,7 @@ function createResponsesEventState(callbacks) {
|
|
|
65695
65946
|
};
|
|
65696
65947
|
}
|
|
65697
65948
|
async function streamResponses(options, callbacks) {
|
|
65698
|
-
const baseUrl = (options.baseUrl ?? DEFAULT_RESPONSES_BASE_URL).replace(/\/$/, "");
|
|
65949
|
+
const baseUrl = (resolveBaseUrl(options.baseUrl) ?? DEFAULT_RESPONSES_BASE_URL).replace(/\/$/, "");
|
|
65699
65950
|
let res;
|
|
65700
65951
|
try {
|
|
65701
65952
|
res = await fetch(`${baseUrl}/responses`, {
|
|
@@ -65740,7 +65991,7 @@ async function streamResponses(options, callbacks) {
|
|
|
65740
65991
|
var FIRST_OUTPUT_TIMEOUT_MS = 3e3;
|
|
65741
65992
|
var RESPONSE_TIMEOUT_MS = 15e3;
|
|
65742
65993
|
function buildResponsesWsUrl(baseUrl) {
|
|
65743
|
-
const base = baseUrl ??
|
|
65994
|
+
const base = resolveBaseUrl(baseUrl) ?? DEFAULT_RESPONSES_BASE_URL;
|
|
65744
65995
|
const path6 = "/responses";
|
|
65745
65996
|
const url2 = new URL(base + (base.endsWith("/") ? path6.slice(1) : path6));
|
|
65746
65997
|
url2.protocol = url2.protocol === "http:" ? "ws:" : "wss:";
|
|
@@ -65900,8 +66151,24 @@ function createResponsesWsSession(apiKey, baseUrl, factory2 = (key, url2) => new
|
|
|
65900
66151
|
};
|
|
65901
66152
|
}
|
|
65902
66153
|
|
|
66154
|
+
// ../runtime-shared/dist/ai/realtime/turn-timing.js
|
|
66155
|
+
function playbackDelayMs(firstAgentChunkAtMs, playbackStartAtIso) {
|
|
66156
|
+
if (firstAgentChunkAtMs === void 0 || !playbackStartAtIso)
|
|
66157
|
+
return void 0;
|
|
66158
|
+
return Date.parse(playbackStartAtIso) - firstAgentChunkAtMs;
|
|
66159
|
+
}
|
|
66160
|
+
function audioMs(playbackStartAtIso, playbackEndAtIso) {
|
|
66161
|
+
if (!playbackStartAtIso || !playbackEndAtIso)
|
|
66162
|
+
return void 0;
|
|
66163
|
+
return Date.parse(playbackEndAtIso) - Date.parse(playbackStartAtIso);
|
|
66164
|
+
}
|
|
66165
|
+
function logValue(ms) {
|
|
66166
|
+
return ms ?? -1;
|
|
66167
|
+
}
|
|
66168
|
+
|
|
65903
66169
|
// ../runtime-shared/dist/ai/realtime/adapters/relay.js
|
|
65904
66170
|
var DEFAULT_MAX_CALL_DURATION = 1800;
|
|
66171
|
+
var TRANSFER_LEG = "transfer-1";
|
|
65905
66172
|
function acceptsReasoningTuning(modelId) {
|
|
65906
66173
|
const model = (modelId ?? "").toLowerCase();
|
|
65907
66174
|
return model.startsWith("gpt-5") || isOSeriesModel(model);
|
|
@@ -65932,9 +66199,9 @@ function supportsChaining(baseUrl) {
|
|
|
65932
66199
|
function resolveTuning(options, config, baseUrl) {
|
|
65933
66200
|
const modelAcceptsReasoning = acceptsReasoningTuning(options.model);
|
|
65934
66201
|
return {
|
|
65935
|
-
serviceTier: options.serviceTier ?? (config.getVariable("LLM_SERVICE_TIER")
|
|
65936
|
-
reasoningEffort: options.reasoningEffort ?? (config.getVariable("LLM_REASONING_EFFORT")
|
|
65937
|
-
verbosity: options.verbosity ?? (config.getVariable("LLM_VERBOSITY")
|
|
66202
|
+
serviceTier: nonBlank(options.serviceTier) ?? nonBlank(config.getVariable("LLM_SERVICE_TIER")) ?? (isOpenAiHost(baseUrl) ? DEFAULT_SERVICE_TIER : void 0),
|
|
66203
|
+
reasoningEffort: nonBlank(options.reasoningEffort) ?? nonBlank(config.getVariable("LLM_REASONING_EFFORT")) ?? (modelAcceptsReasoning && !isOSeriesModel(options.model) ? DEFAULT_REASONING_EFFORT : void 0),
|
|
66204
|
+
verbosity: nonBlank(options.verbosity) ?? nonBlank(config.getVariable("LLM_VERBOSITY")) ?? (modelAcceptsReasoning ? DEFAULT_VERBOSITY : void 0)
|
|
65938
66205
|
};
|
|
65939
66206
|
}
|
|
65940
66207
|
function createRelayAgent(options) {
|
|
@@ -65942,10 +66209,14 @@ function createRelayAgent(options) {
|
|
|
65942
66209
|
throw new Error("realtimeAgent: provider 'voice-relay' requires options.model.");
|
|
65943
66210
|
}
|
|
65944
66211
|
const pendingByCallId = /* @__PURE__ */ new Map();
|
|
66212
|
+
const transferredCallIds = /* @__PURE__ */ new Set();
|
|
65945
66213
|
const relay2 = voiceRelay({
|
|
65946
66214
|
voice: options.voice,
|
|
66215
|
+
// voiceRelay's own `language` already defaults to 'en-US' when unset — see its own doc
|
|
66216
|
+
// comment — so no `?? DEFAULT_LANGUAGE` needed here, unlike the STREAM adapters.
|
|
66217
|
+
language: options.language,
|
|
65947
66218
|
greeting: options.greeting,
|
|
65948
|
-
onConnected: (call) => attach(options, pendingByCallId, call)
|
|
66219
|
+
onConnected: (call) => attach(options, pendingByCallId, transferredCallIds, call)
|
|
65949
66220
|
});
|
|
65950
66221
|
const connect = async (call, builder, context) => {
|
|
65951
66222
|
const [prompt, transferTo] = await Promise.all([
|
|
@@ -65953,19 +66224,29 @@ function createRelayAgent(options) {
|
|
|
65953
66224
|
resolvePerCallValue(options.transferTo, call, context)
|
|
65954
66225
|
]);
|
|
65955
66226
|
const callId = String(call.callId ?? "");
|
|
65956
|
-
if (callId)
|
|
65957
|
-
pendingByCallId.set(callId, {
|
|
66227
|
+
if (callId) {
|
|
66228
|
+
pendingByCallId.set(callId, {
|
|
66229
|
+
prompt: currentDateTimePreamble(options.timezone) + prompt,
|
|
66230
|
+
transferTo: nonBlank(transferTo)
|
|
66231
|
+
});
|
|
66232
|
+
}
|
|
65958
66233
|
const maxDuration = Number(createUniversalConfig(context).getVariable("MAX_CALL_DURATION", String(DEFAULT_MAX_CALL_DURATION)));
|
|
65959
66234
|
return builder.answer().dialRelay(relay2, { maxDuration });
|
|
65960
66235
|
};
|
|
66236
|
+
const handleCallCompleted = (call, _builder, context) => {
|
|
66237
|
+
const callId = String(call.callId ?? "");
|
|
66238
|
+
if (callId && transferredCallIds.delete(callId)) {
|
|
66239
|
+
context.voice.hangup({ callId }, TRANSFER_LEG).catch((err) => console.error("[realtimeAgent] ending the transfer leg after the caller hung up failed (may already be gone):", err.message));
|
|
66240
|
+
}
|
|
66241
|
+
};
|
|
65961
66242
|
return {
|
|
65962
66243
|
setup: relay2.setup,
|
|
65963
|
-
voiceWebhook: onCall({ incoming: connect }),
|
|
66244
|
+
voiceWebhook: onCall({ incoming: connect, completed: handleCallCompleted }),
|
|
65964
66245
|
connect,
|
|
65965
66246
|
endpointFor: relay2.endpointFor
|
|
65966
66247
|
};
|
|
65967
66248
|
}
|
|
65968
|
-
function attach(options, pendingByCallId, call) {
|
|
66249
|
+
function attach(options, pendingByCallId, transferredCallIds, call) {
|
|
65969
66250
|
const pending = pendingByCallId.get(call.id);
|
|
65970
66251
|
pendingByCallId.delete(call.id);
|
|
65971
66252
|
const context = call.context;
|
|
@@ -65977,12 +66258,14 @@ function attach(options, pendingByCallId, call) {
|
|
|
65977
66258
|
return;
|
|
65978
66259
|
}
|
|
65979
66260
|
const apiKey = secret;
|
|
65980
|
-
const baseUrl = options.baseUrl ?? config.getVariable("OPENAI_BASE_URL")
|
|
66261
|
+
const baseUrl = resolveBaseUrl(options.baseUrl) ?? resolveBaseUrl(config.getVariable("OPENAI_BASE_URL"));
|
|
65981
66262
|
const tuning = resolveTuning(options, config, baseUrl);
|
|
65982
66263
|
const chainingEnabled = supportsChaining(baseUrl);
|
|
65983
66264
|
const transcript = [];
|
|
66265
|
+
const usage = {};
|
|
65984
66266
|
const ended = new AbortController();
|
|
65985
66267
|
let turnController = null;
|
|
66268
|
+
let pendingPlaybackTurn;
|
|
65986
66269
|
function openWs() {
|
|
65987
66270
|
try {
|
|
65988
66271
|
return createResponsesWsSession(apiKey, baseUrl);
|
|
@@ -66002,6 +66285,7 @@ function attach(options, pendingByCallId, call) {
|
|
|
66002
66285
|
config,
|
|
66003
66286
|
signal: ended.signal,
|
|
66004
66287
|
transcript,
|
|
66288
|
+
usage,
|
|
66005
66289
|
hangup() {
|
|
66006
66290
|
call.hangup();
|
|
66007
66291
|
},
|
|
@@ -66009,7 +66293,8 @@ function attach(options, pendingByCallId, call) {
|
|
|
66009
66293
|
if (!E1642.test(number)) {
|
|
66010
66294
|
throw new Error(`realtimeAgent: ctx.transfer('${number}') is not an E.164 phone number (e.g. '+15551234567').`);
|
|
66011
66295
|
}
|
|
66012
|
-
await call.transferToPhone(number);
|
|
66296
|
+
await call.transferToPhone(number, { legName: TRANSFER_LEG });
|
|
66297
|
+
transferredCallIds.add(call.id);
|
|
66013
66298
|
}
|
|
66014
66299
|
};
|
|
66015
66300
|
const appendTranscript = (entry) => {
|
|
@@ -66021,6 +66306,8 @@ function attach(options, pendingByCallId, call) {
|
|
|
66021
66306
|
call.onEnded(() => {
|
|
66022
66307
|
ended.abort();
|
|
66023
66308
|
wsSession?.close();
|
|
66309
|
+
flushPendingPlaybackTurn();
|
|
66310
|
+
console.log(`[realtimeAgent] call usage inputTokens=${logValue(usage.inputTokens)} outputTokens=${logValue(usage.outputTokens)} audioSeconds=${logValue(usage.audioSeconds)}`);
|
|
66024
66311
|
invokeHook("onEnd", () => options.onEnd?.(ctx));
|
|
66025
66312
|
});
|
|
66026
66313
|
call.onInterrupted(() => {
|
|
@@ -66028,6 +66315,19 @@ function attach(options, pendingByCallId, call) {
|
|
|
66028
66315
|
wsSession?.cancel();
|
|
66029
66316
|
invokeHook("onBargeIn", () => options.onBargeIn?.(ctx));
|
|
66030
66317
|
});
|
|
66318
|
+
call.onPlaybackStart(() => {
|
|
66319
|
+
if (pendingPlaybackTurn && pendingPlaybackTurn.entry.playbackStartAt === void 0) {
|
|
66320
|
+
pendingPlaybackTurn.entry.playbackStartAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
66321
|
+
}
|
|
66322
|
+
});
|
|
66323
|
+
call.onPlaybackStop(({ cancelled }) => {
|
|
66324
|
+
if (!pendingPlaybackTurn)
|
|
66325
|
+
return;
|
|
66326
|
+
pendingPlaybackTurn.entry.playbackEndAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
66327
|
+
if (cancelled)
|
|
66328
|
+
pendingPlaybackTurn.entry.interrupted = true;
|
|
66329
|
+
flushPendingPlaybackTurn();
|
|
66330
|
+
});
|
|
66031
66331
|
async function callLlm(requestOptions, callbacks) {
|
|
66032
66332
|
if (wsUnavailable || wsFailed)
|
|
66033
66333
|
return streamResponses(requestOptions, callbacks);
|
|
@@ -66068,6 +66368,7 @@ function attach(options, pendingByCallId, call) {
|
|
|
66068
66368
|
error = err instanceof Error ? err.message : String(err);
|
|
66069
66369
|
}
|
|
66070
66370
|
}
|
|
66371
|
+
const latencyMs = Date.now() - start;
|
|
66071
66372
|
appendTranscript({
|
|
66072
66373
|
role: "tool",
|
|
66073
66374
|
text: toolCall.name,
|
|
@@ -66076,11 +66377,12 @@ function attach(options, pendingByCallId, call) {
|
|
|
66076
66377
|
args: toolCall.arguments,
|
|
66077
66378
|
result: result2,
|
|
66078
66379
|
error,
|
|
66079
|
-
latencyMs
|
|
66380
|
+
latencyMs
|
|
66080
66381
|
});
|
|
66081
|
-
return { result: result2, error };
|
|
66382
|
+
return { result: result2, error, latencyMs };
|
|
66082
66383
|
}
|
|
66083
|
-
async function converse(newInput, pendingCommit = []) {
|
|
66384
|
+
async function converse(newInput, pendingCommit = [], metrics = { turnStart: Date.now(), rounds: 0, toolMs: 0 }) {
|
|
66385
|
+
metrics.rounds += 1;
|
|
66084
66386
|
const controller = new AbortController();
|
|
66085
66387
|
turnController = controller;
|
|
66086
66388
|
const inFlight = [];
|
|
@@ -66100,7 +66402,11 @@ function attach(options, pendingByCallId, call) {
|
|
|
66100
66402
|
reasoningEffort: tuning.reasoningEffort,
|
|
66101
66403
|
verbosity: tuning.verbosity
|
|
66102
66404
|
}, {
|
|
66103
|
-
onSentence: (sentence) =>
|
|
66405
|
+
onSentence: (sentence) => {
|
|
66406
|
+
if (metrics.firstSentenceMs === void 0)
|
|
66407
|
+
metrics.firstSentenceMs = Date.now() - metrics.turnStart;
|
|
66408
|
+
call.send(sentence, { last: false });
|
|
66409
|
+
},
|
|
66104
66410
|
onToolCall: (toolCall) => {
|
|
66105
66411
|
inFlight.push({ call: toolCall, promise: runTool(toolCall) });
|
|
66106
66412
|
}
|
|
@@ -66109,16 +66415,22 @@ function attach(options, pendingByCallId, call) {
|
|
|
66109
66415
|
if (err instanceof StreamAbortedError) {
|
|
66110
66416
|
return;
|
|
66111
66417
|
}
|
|
66418
|
+
console.error("[realtimeAgent] voice-relay provider LLM turn failed:", err.message);
|
|
66112
66419
|
invokeHook("onError", () => options.onError?.({ message: err.message }, ctx));
|
|
66113
66420
|
return;
|
|
66114
66421
|
} finally {
|
|
66115
66422
|
if (turnController === controller)
|
|
66116
66423
|
turnController = null;
|
|
66117
66424
|
}
|
|
66425
|
+
if (result2.usage) {
|
|
66426
|
+
usage.inputTokens = (usage.inputTokens ?? 0) + (result2.usage.inputTokens ?? 0);
|
|
66427
|
+
usage.outputTokens = (usage.outputTokens ?? 0) + (result2.usage.outputTokens ?? 0);
|
|
66428
|
+
}
|
|
66118
66429
|
call.send("", { last: true });
|
|
66119
66430
|
const roundItems = [...newInput];
|
|
66431
|
+
let agentEntry;
|
|
66120
66432
|
if (result2.text) {
|
|
66121
|
-
|
|
66433
|
+
agentEntry = { role: "agent", text: result2.text, timestamp: (/* @__PURE__ */ new Date()).toISOString() };
|
|
66122
66434
|
roundItems.push({ role: "assistant", content: result2.text });
|
|
66123
66435
|
}
|
|
66124
66436
|
if (inFlight.length === 0) {
|
|
@@ -66126,9 +66438,14 @@ function attach(options, pendingByCallId, call) {
|
|
|
66126
66438
|
previousResponseId = result2.responseId ?? previousResponseId;
|
|
66127
66439
|
else
|
|
66128
66440
|
statelessHistory.push(...pendingCommit, ...roundItems);
|
|
66441
|
+
logTurnLatency(metrics, agentEntry);
|
|
66129
66442
|
return;
|
|
66130
66443
|
}
|
|
66444
|
+
if (agentEntry)
|
|
66445
|
+
appendTranscript(agentEntry);
|
|
66131
66446
|
const outcomes = await Promise.all(inFlight.map((f) => f.promise));
|
|
66447
|
+
for (const outcome of outcomes)
|
|
66448
|
+
metrics.toolMs += outcome.latencyMs;
|
|
66132
66449
|
if (controller.signal.aborted) {
|
|
66133
66450
|
return;
|
|
66134
66451
|
}
|
|
@@ -66145,7 +66462,31 @@ function attach(options, pendingByCallId, call) {
|
|
|
66145
66462
|
output: JSON.stringify(outcome.error ? { error: outcome.error } : outcome.result ?? {})
|
|
66146
66463
|
};
|
|
66147
66464
|
});
|
|
66148
|
-
await converse(nextInput, chainingEnabled ? [] : [...pendingCommit, ...roundItems]);
|
|
66465
|
+
await converse(nextInput, chainingEnabled ? [] : [...pendingCommit, ...roundItems], metrics);
|
|
66466
|
+
}
|
|
66467
|
+
function logTurnLatency(metrics, agentEntry) {
|
|
66468
|
+
const totalMs = Date.now() - metrics.turnStart;
|
|
66469
|
+
if (agentEntry) {
|
|
66470
|
+
agentEntry.latencyMs = metrics.firstSentenceMs;
|
|
66471
|
+
agentEntry.totalMs = totalMs;
|
|
66472
|
+
appendTranscript(agentEntry);
|
|
66473
|
+
pendingPlaybackTurn = { entry: agentEntry, metrics, totalMs };
|
|
66474
|
+
return;
|
|
66475
|
+
}
|
|
66476
|
+
console.log(turnLatencyLine(metrics, totalMs, void 0));
|
|
66477
|
+
}
|
|
66478
|
+
function flushPendingPlaybackTurn() {
|
|
66479
|
+
if (!pendingPlaybackTurn)
|
|
66480
|
+
return;
|
|
66481
|
+
const { entry, metrics, totalMs } = pendingPlaybackTurn;
|
|
66482
|
+
pendingPlaybackTurn = void 0;
|
|
66483
|
+
console.log(turnLatencyLine(metrics, totalMs, entry));
|
|
66484
|
+
}
|
|
66485
|
+
function turnLatencyLine(metrics, totalMs, entry) {
|
|
66486
|
+
const firstAgentChunkAtMs = metrics.firstSentenceMs !== void 0 ? metrics.turnStart + metrics.firstSentenceMs : void 0;
|
|
66487
|
+
const delay = playbackDelayMs(firstAgentChunkAtMs, entry?.playbackStartAt);
|
|
66488
|
+
const audio = audioMs(entry?.playbackStartAt, entry?.playbackEndAt);
|
|
66489
|
+
return `[realtimeAgent] turn latency firstSentenceMs=${logValue(metrics.firstSentenceMs)} totalMs=${totalMs} modelRounds=${metrics.rounds} toolMs=${metrics.toolMs} playbackDelayMs=${logValue(delay)} audioMs=${logValue(audio)}`;
|
|
66149
66490
|
}
|
|
66150
66491
|
call.onSpeech((text) => {
|
|
66151
66492
|
appendTranscript({ role: "user", text, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
@@ -66153,10 +66494,59 @@ function attach(options, pendingByCallId, call) {
|
|
|
66153
66494
|
});
|
|
66154
66495
|
}
|
|
66155
66496
|
|
|
66497
|
+
// ../runtime-shared/dist/ai/realtime/vad.js
|
|
66498
|
+
var DEFAULT_THRESHOLD = 500;
|
|
66499
|
+
var DEFAULT_ATTACK_FRAMES = 2;
|
|
66500
|
+
var DEFAULT_HANGOVER_FRAMES = 20;
|
|
66501
|
+
function pcm16Rms2(pcm) {
|
|
66502
|
+
if (pcm.length < 2)
|
|
66503
|
+
return 0;
|
|
66504
|
+
let sumSquares = 0;
|
|
66505
|
+
const samples = pcm.length >> 1;
|
|
66506
|
+
for (let i = 0; i < samples; i++) {
|
|
66507
|
+
const sample = pcm.readInt16LE(i * 2);
|
|
66508
|
+
sumSquares += sample * sample;
|
|
66509
|
+
}
|
|
66510
|
+
return Math.sqrt(sumSquares / samples);
|
|
66511
|
+
}
|
|
66512
|
+
function createEnergyVad(options = {}) {
|
|
66513
|
+
const threshold = options.threshold ?? DEFAULT_THRESHOLD;
|
|
66514
|
+
const attackFrames = options.attackFrames ?? DEFAULT_ATTACK_FRAMES;
|
|
66515
|
+
const hangoverFrames = options.hangoverFrames ?? DEFAULT_HANGOVER_FRAMES;
|
|
66516
|
+
let speaking = false;
|
|
66517
|
+
let loudRun = 0;
|
|
66518
|
+
let quietRun = 0;
|
|
66519
|
+
return {
|
|
66520
|
+
get speaking() {
|
|
66521
|
+
return speaking;
|
|
66522
|
+
},
|
|
66523
|
+
push(pcm) {
|
|
66524
|
+
const loud = pcm16Rms2(pcm) >= threshold;
|
|
66525
|
+
if (loud) {
|
|
66526
|
+
loudRun++;
|
|
66527
|
+
quietRun = 0;
|
|
66528
|
+
} else {
|
|
66529
|
+
quietRun++;
|
|
66530
|
+
loudRun = 0;
|
|
66531
|
+
}
|
|
66532
|
+
if (!speaking && loud && loudRun >= attackFrames) {
|
|
66533
|
+
speaking = true;
|
|
66534
|
+
return "start";
|
|
66535
|
+
}
|
|
66536
|
+
if (speaking && !loud && quietRun >= hangoverFrames) {
|
|
66537
|
+
speaking = false;
|
|
66538
|
+
return "end";
|
|
66539
|
+
}
|
|
66540
|
+
return void 0;
|
|
66541
|
+
}
|
|
66542
|
+
};
|
|
66543
|
+
}
|
|
66544
|
+
|
|
66156
66545
|
// ../runtime-shared/dist/ai/realtime/agent.js
|
|
66157
66546
|
var BRIDGE = "bridge";
|
|
66158
66547
|
var CALLER_LEG2 = "caller";
|
|
66159
66548
|
var STREAM_LEG2 = "stream";
|
|
66549
|
+
var TRANSFER_LEG2 = "transfer-1";
|
|
66160
66550
|
var CALL_ID_HEADER = "x-realtime-agent-call-id";
|
|
66161
66551
|
var AUDIO_SAMPLE_RATES = { telephony: 8e3, wideband: 16e3 };
|
|
66162
66552
|
function sendStreamControl(ws, command) {
|
|
@@ -66174,19 +66564,20 @@ function resolveMaxDuration(context) {
|
|
|
66174
66564
|
var FIRST_FRAME_DEADLINE_MS = 2e3;
|
|
66175
66565
|
var MAX_UNAUTHENTICATED_SOCKETS2 = 32;
|
|
66176
66566
|
async function resolvePerCallOptions(options, call, context, ctx) {
|
|
66177
|
-
const [prompt, greeting, voice, transferTo] = await Promise.all([
|
|
66567
|
+
const [prompt, greeting, voice, transferTo, language] = await Promise.all([
|
|
66178
66568
|
resolvePerCallValue(options.prompt, call, context),
|
|
66179
66569
|
resolvePerCallValue(options.greeting, call, context),
|
|
66180
66570
|
resolvePerCallValue(options.voice, call, context),
|
|
66181
|
-
resolvePerCallValue(options.transferTo, call, context)
|
|
66571
|
+
resolvePerCallValue(options.transferTo, call, context),
|
|
66572
|
+
resolvePerCallValue(options.language, call, context)
|
|
66182
66573
|
]);
|
|
66183
66574
|
const { transferTo: _transferTo, tools: authorTools, ...rest } = options;
|
|
66184
|
-
const tools = mergeTools(authorTools ?? [], builtInTools(options.hangup ?? true, transferTo, ctx));
|
|
66185
|
-
let resolvedPrompt = prompt;
|
|
66575
|
+
const tools = mergeTools(authorTools ?? [], builtInTools(options.hangup ?? true, nonBlank(transferTo), ctx));
|
|
66576
|
+
let resolvedPrompt = currentDateTimePreamble(options.timezone) + prompt;
|
|
66186
66577
|
if (offersHangup(tools)) {
|
|
66187
66578
|
resolvedPrompt += options.provider === "openai" ? DELEGATED_CALL_TERMINATION_INSTRUCTIONS : CALL_TERMINATION_INSTRUCTIONS;
|
|
66188
66579
|
}
|
|
66189
|
-
return { ...rest, prompt: resolvedPrompt, greeting, voice, tools };
|
|
66580
|
+
return { ...rest, prompt: resolvedPrompt, greeting, voice, tools, language: language ?? DEFAULT_LANGUAGE };
|
|
66190
66581
|
}
|
|
66191
66582
|
function realtimeAgent(options) {
|
|
66192
66583
|
if (!options.provider) {
|
|
@@ -66201,6 +66592,7 @@ function realtimeAgent(options) {
|
|
|
66201
66592
|
const adapter2 = getRealtimeAdapter(options.provider);
|
|
66202
66593
|
let savedContext;
|
|
66203
66594
|
const pendingSessions = /* @__PURE__ */ new Map();
|
|
66595
|
+
const transferredCallIds = /* @__PURE__ */ new Set();
|
|
66204
66596
|
function deletePendingSession(token) {
|
|
66205
66597
|
const session = pendingSessions.get(token);
|
|
66206
66598
|
if (!session)
|
|
@@ -66248,15 +66640,55 @@ function realtimeAgent(options) {
|
|
|
66248
66640
|
}
|
|
66249
66641
|
let vendorSession;
|
|
66250
66642
|
let ended = false;
|
|
66643
|
+
let transferred = false;
|
|
66251
66644
|
let heartbeat;
|
|
66252
66645
|
const lifecycle = new AbortController();
|
|
66253
66646
|
const transcript = [];
|
|
66647
|
+
const usage = {};
|
|
66648
|
+
const callConnectedAtMs = Date.now();
|
|
66649
|
+
let lastUserTurnAt;
|
|
66650
|
+
let firstAudioAtMs;
|
|
66651
|
+
let selfBytesSentForTurn = 0;
|
|
66652
|
+
let bytesPerMs = 8e3 * 2 / 1e3;
|
|
66653
|
+
const vad = createEnergyVad();
|
|
66654
|
+
let pendingSpeechStartAt;
|
|
66655
|
+
let pendingSpeechEndAt;
|
|
66656
|
+
let speechEndFromProvider = false;
|
|
66657
|
+
let currentAgentEntry;
|
|
66658
|
+
let pendingAgentPlayback = {};
|
|
66659
|
+
let pendingStreamLog;
|
|
66660
|
+
const streamTurnLine = (totalMs, firstAudioAtMs_, entry) => {
|
|
66661
|
+
const delay = playbackDelayMs(firstAudioAtMs_, entry.playbackStartAt);
|
|
66662
|
+
const audio = audioMs(entry.playbackStartAt, entry.playbackEndAt);
|
|
66663
|
+
return `[realtimeAgent] turn latency totalMs=${logValue(totalMs)} playbackDelayMs=${logValue(delay)} audioMs=${logValue(audio)} delegationMs=${logValue(entry.delegationMs)}`;
|
|
66664
|
+
};
|
|
66665
|
+
const applySelfPlaybackFallback = (entry, cutShort) => {
|
|
66666
|
+
if (firstAudioAtMs === void 0)
|
|
66667
|
+
return;
|
|
66668
|
+
entry.playbackStartAt ??= new Date(firstAudioAtMs).toISOString();
|
|
66669
|
+
if (entry.playbackEndAt === void 0) {
|
|
66670
|
+
const endMs = cutShort ? Date.now() : firstAudioAtMs + selfBytesSentForTurn / bytesPerMs;
|
|
66671
|
+
entry.playbackEndAt = new Date(endMs).toISOString();
|
|
66672
|
+
if (cutShort)
|
|
66673
|
+
entry.interrupted = true;
|
|
66674
|
+
}
|
|
66675
|
+
};
|
|
66676
|
+
const flushPendingStreamLog = () => {
|
|
66677
|
+
if (!pendingStreamLog)
|
|
66678
|
+
return;
|
|
66679
|
+
const { entry, totalMs, firstAudioAtMs: firstAudioAtMs_ } = pendingStreamLog;
|
|
66680
|
+
pendingStreamLog = void 0;
|
|
66681
|
+
currentAgentEntry = void 0;
|
|
66682
|
+
applySelfPlaybackFallback(entry, false);
|
|
66683
|
+
console.log(streamTurnLine(totalMs, firstAudioAtMs_, entry));
|
|
66684
|
+
};
|
|
66254
66685
|
const ctx = {
|
|
66255
66686
|
callId,
|
|
66256
66687
|
storage: context.storage,
|
|
66257
66688
|
config,
|
|
66258
66689
|
signal: lifecycle.signal,
|
|
66259
66690
|
transcript,
|
|
66691
|
+
usage,
|
|
66260
66692
|
hangup() {
|
|
66261
66693
|
setTimeout(() => {
|
|
66262
66694
|
if (ws.readyState === ws.OPEN)
|
|
@@ -66269,8 +66701,12 @@ function realtimeAgent(options) {
|
|
|
66269
66701
|
}
|
|
66270
66702
|
await context.voice.transferToPhone(callId, number, {
|
|
66271
66703
|
liveLeg: CALLER_LEG2,
|
|
66704
|
+
legName: TRANSFER_LEG2,
|
|
66272
66705
|
call: { call }
|
|
66273
66706
|
});
|
|
66707
|
+
transferred = true;
|
|
66708
|
+
if (callId)
|
|
66709
|
+
transferredCallIds.add(callId);
|
|
66274
66710
|
await context.voice.hangup({ callId }, STREAM_LEG2).catch((err) => console.error("[realtimeAgent] ending the STREAM leg after transfer failed:", err.message));
|
|
66275
66711
|
if (ws.readyState === ws.OPEN)
|
|
66276
66712
|
ws.close(1e3, "Transferred");
|
|
@@ -66284,6 +66720,7 @@ function realtimeAgent(options) {
|
|
|
66284
66720
|
if (ended)
|
|
66285
66721
|
return;
|
|
66286
66722
|
ended = true;
|
|
66723
|
+
flushPendingStreamLog();
|
|
66287
66724
|
lifecycle.abort();
|
|
66288
66725
|
if (heartbeat !== void 0)
|
|
66289
66726
|
clearInterval(heartbeat);
|
|
@@ -66291,6 +66728,11 @@ function realtimeAgent(options) {
|
|
|
66291
66728
|
adapter2.close(vendorSession);
|
|
66292
66729
|
if (ws.readyState === ws.OPEN)
|
|
66293
66730
|
ws.close();
|
|
66731
|
+
if (!transferred) {
|
|
66732
|
+
await context.voice?.hangup({ callId }, CALLER_LEG2).catch((err) => console.error("[realtimeAgent] ending the caller leg failed (may already be gone):", err.message));
|
|
66733
|
+
}
|
|
66734
|
+
usage.audioSeconds ??= (Date.now() - callConnectedAtMs) / 1e3;
|
|
66735
|
+
console.log(`[realtimeAgent] call usage inputTokens=${logValue(usage.inputTokens)} outputTokens=${logValue(usage.outputTokens)} audioSeconds=${logValue(usage.audioSeconds)}`);
|
|
66294
66736
|
try {
|
|
66295
66737
|
await options.onEnd?.(ctx);
|
|
66296
66738
|
} catch (err) {
|
|
@@ -66299,6 +66741,10 @@ function realtimeAgent(options) {
|
|
|
66299
66741
|
};
|
|
66300
66742
|
const callbacks = {
|
|
66301
66743
|
onAudioOut(pcm) {
|
|
66744
|
+
if (firstAudioAtMs === void 0 && lastUserTurnAt !== void 0)
|
|
66745
|
+
firstAudioAtMs = Date.now();
|
|
66746
|
+
if (firstAudioAtMs !== void 0)
|
|
66747
|
+
selfBytesSentForTurn += pcm.length;
|
|
66302
66748
|
if (ws.readyState === ws.OPEN)
|
|
66303
66749
|
ws.send(pcm);
|
|
66304
66750
|
},
|
|
@@ -66315,15 +66761,81 @@ function realtimeAgent(options) {
|
|
|
66315
66761
|
});
|
|
66316
66762
|
},
|
|
66317
66763
|
onTurn(turn) {
|
|
66318
|
-
|
|
66764
|
+
const entry = { role: turn.role, text: turn.text, timestamp: turn.timestamp };
|
|
66765
|
+
if (turn.role === "user") {
|
|
66766
|
+
flushPendingStreamLog();
|
|
66767
|
+
lastUserTurnAt = Date.now();
|
|
66768
|
+
firstAudioAtMs = void 0;
|
|
66769
|
+
entry.speechStartAt = turn.speechStartAt ?? pendingSpeechStartAt;
|
|
66770
|
+
entry.speechEndAt = turn.speechEndAt ?? pendingSpeechEndAt;
|
|
66771
|
+
pendingSpeechStartAt = void 0;
|
|
66772
|
+
pendingSpeechEndAt = void 0;
|
|
66773
|
+
speechEndFromProvider = false;
|
|
66774
|
+
} else if (turn.role === "agent" && lastUserTurnAt !== void 0) {
|
|
66775
|
+
entry.totalMs = Date.now() - lastUserTurnAt;
|
|
66776
|
+
lastUserTurnAt = void 0;
|
|
66777
|
+
entry.delegationMs = turn.delegationMs;
|
|
66778
|
+
entry.playbackStartAt = turn.playbackStartAt ?? pendingAgentPlayback.startAt;
|
|
66779
|
+
if (turn.playbackEndAt) {
|
|
66780
|
+
entry.playbackEndAt = turn.playbackEndAt;
|
|
66781
|
+
} else if (pendingAgentPlayback.endAt) {
|
|
66782
|
+
entry.playbackEndAt = pendingAgentPlayback.endAt;
|
|
66783
|
+
if (pendingAgentPlayback.interrupted)
|
|
66784
|
+
entry.interrupted = true;
|
|
66785
|
+
}
|
|
66786
|
+
const alreadyResolved = entry.playbackEndAt !== void 0;
|
|
66787
|
+
pendingAgentPlayback = {};
|
|
66788
|
+
if (alreadyResolved) {
|
|
66789
|
+
console.log(streamTurnLine(entry.totalMs, firstAudioAtMs, entry));
|
|
66790
|
+
} else {
|
|
66791
|
+
currentAgentEntry = entry;
|
|
66792
|
+
pendingStreamLog = { entry, totalMs: entry.totalMs, firstAudioAtMs };
|
|
66793
|
+
}
|
|
66794
|
+
}
|
|
66795
|
+
appendTranscript(entry);
|
|
66796
|
+
},
|
|
66797
|
+
onSpeechStart() {
|
|
66798
|
+
pendingSpeechStartAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
66799
|
+
},
|
|
66800
|
+
onSpeechEnd() {
|
|
66801
|
+
pendingSpeechEndAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
66802
|
+
speechEndFromProvider = true;
|
|
66803
|
+
},
|
|
66804
|
+
onPlaybackStart() {
|
|
66805
|
+
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
66806
|
+
if (currentAgentEntry)
|
|
66807
|
+
currentAgentEntry.playbackStartAt ??= at;
|
|
66808
|
+
else
|
|
66809
|
+
pendingAgentPlayback.startAt ??= at;
|
|
66810
|
+
},
|
|
66811
|
+
onPlaybackStop({ cancelled }) {
|
|
66812
|
+
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
66813
|
+
if (currentAgentEntry) {
|
|
66814
|
+
currentAgentEntry.playbackEndAt = at;
|
|
66815
|
+
if (cancelled)
|
|
66816
|
+
currentAgentEntry.interrupted = true;
|
|
66817
|
+
flushPendingStreamLog();
|
|
66818
|
+
} else {
|
|
66819
|
+
pendingAgentPlayback.endAt = at;
|
|
66820
|
+
if (cancelled)
|
|
66821
|
+
pendingAgentPlayback.interrupted = true;
|
|
66822
|
+
}
|
|
66319
66823
|
},
|
|
66320
66824
|
onBargeIn() {
|
|
66321
66825
|
sendStreamControl(ws, "clear");
|
|
66322
66826
|
if (vendorSession !== void 0)
|
|
66323
66827
|
adapter2.clear(vendorSession);
|
|
66828
|
+
if (currentAgentEntry) {
|
|
66829
|
+
applySelfPlaybackFallback(currentAgentEntry, true);
|
|
66830
|
+
flushPendingStreamLog();
|
|
66831
|
+
}
|
|
66324
66832
|
invokeHook("onBargeIn", () => options.onBargeIn?.(ctx));
|
|
66325
66833
|
},
|
|
66834
|
+
onUsage(reported) {
|
|
66835
|
+
Object.assign(usage, reported);
|
|
66836
|
+
},
|
|
66326
66837
|
onError(error) {
|
|
66838
|
+
console.error("[realtimeAgent] vendor reported an error:", error.message, error.raw ?? "");
|
|
66327
66839
|
invokeHook("onError", () => options.onError?.(error, ctx));
|
|
66328
66840
|
},
|
|
66329
66841
|
onClose() {
|
|
@@ -66336,6 +66848,7 @@ function realtimeAgent(options) {
|
|
|
66336
66848
|
resolvePerCallOptions(options, call, context, ctx).then((resolved) => {
|
|
66337
66849
|
if (ended || lifecycle.signal.aborted)
|
|
66338
66850
|
return void 0;
|
|
66851
|
+
bytesPerMs = sinchRate(resolved) * 2 / 1e3;
|
|
66339
66852
|
return adapter2.connect(resolved, ctx, callbacks, lifecycle.signal);
|
|
66340
66853
|
}).then((session) => {
|
|
66341
66854
|
if (session === void 0)
|
|
@@ -66350,6 +66863,11 @@ function realtimeAgent(options) {
|
|
|
66350
66863
|
ws.on("message", (raw, isBinary) => {
|
|
66351
66864
|
if (!isBinary)
|
|
66352
66865
|
return;
|
|
66866
|
+
const vadEvent = vad.push(raw);
|
|
66867
|
+
if (vadEvent === "start")
|
|
66868
|
+
pendingSpeechStartAt ??= (/* @__PURE__ */ new Date()).toISOString();
|
|
66869
|
+
else if (vadEvent === "end" && !speechEndFromProvider)
|
|
66870
|
+
pendingSpeechEndAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
66353
66871
|
adapter2.sendAudio(session, raw);
|
|
66354
66872
|
});
|
|
66355
66873
|
}).catch((err) => {
|
|
@@ -66473,19 +66991,26 @@ function realtimeAgent(options) {
|
|
|
66473
66991
|
callName: STREAM_LEG2,
|
|
66474
66992
|
maxDuration: resolveMaxDuration(context),
|
|
66475
66993
|
onAnswer: (c) => c.bridgeCall(BRIDGE),
|
|
66476
|
-
endOnHangup
|
|
66994
|
+
// No `endOnHangup`: once the STREAM leg is answered, ending it (agent hangup, vendor
|
|
66995
|
+
// close, transfer) must not cascade into hanging up the caller's own leg — the runtime
|
|
66996
|
+
// ends the caller explicitly from the session-end path instead (see `end()`). Failure
|
|
66997
|
+
// to ever connect (busy/reject/timeout/failure) is unaffected and still ends the caller
|
|
66998
|
+
// via `endOnFailure` — nothing was dialled yet for the caller to be bridged to.
|
|
66477
66999
|
endOnFailure: CALLER_LEG2
|
|
66478
67000
|
}).build(),
|
|
66479
67001
|
onHangup: [{ command: "hangup", callName: STREAM_LEG2 }]
|
|
66480
67002
|
};
|
|
66481
67003
|
};
|
|
66482
|
-
const handleCallCompleted = (call) => {
|
|
67004
|
+
const handleCallCompleted = (call, _builder, context) => {
|
|
66483
67005
|
const callId = String(call.callId ?? "");
|
|
66484
67006
|
if (callId) {
|
|
66485
67007
|
for (const [token, pending] of pendingSessions) {
|
|
66486
67008
|
if (String(pending.call.callId ?? "") === callId)
|
|
66487
67009
|
deletePendingSession(token);
|
|
66488
67010
|
}
|
|
67011
|
+
if (transferredCallIds.delete(callId)) {
|
|
67012
|
+
context.voice.hangup({ callId }, TRANSFER_LEG2).catch((err) => console.error("[realtimeAgent] ending the transfer leg after the caller hung up failed (may already be gone):", err.message));
|
|
67013
|
+
}
|
|
66489
67014
|
}
|
|
66490
67015
|
};
|
|
66491
67016
|
const voiceWebhook = onCall({ incoming: connect, completed: handleCallCompleted });
|
|
@@ -75279,7 +75804,6 @@ export {
|
|
|
75279
75804
|
toWebhookRequest,
|
|
75280
75805
|
toCallBody,
|
|
75281
75806
|
toWebhookBody,
|
|
75282
|
-
DEFAULT_TRANSFER_LEG,
|
|
75283
75807
|
buildTransferCommands,
|
|
75284
75808
|
resolveHandlerKey,
|
|
75285
75809
|
resolveWebhookName,
|
|
@@ -75690,4 +76214,4 @@ serve-static/index.js:
|
|
|
75690
76214
|
* MIT Licensed
|
|
75691
76215
|
*)
|
|
75692
76216
|
*/
|
|
75693
|
-
//# sourceMappingURL=chunk-
|
|
76217
|
+
//# sourceMappingURL=chunk-DHM4MH2A.js.map
|