@sinch/functions-runtime 0.6.0 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -5
- package/dist/bin/sinch-runtime.js +1 -1
- package/dist/{chunk-TOTJB6SW.js → chunk-W3R4GR3E.js} +596 -63
- package/dist/chunk-W3R4GR3E.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;
|
|
@@ -63879,12 +63933,26 @@ function buildSettingsFrame(options) {
|
|
|
63879
63933
|
output: { encoding: "linear16", sample_rate: sampleRate, container: "none" }
|
|
63880
63934
|
},
|
|
63881
63935
|
agent: {
|
|
63936
|
+
// Deepgram's `agent.language` — pins recognition to `options.language` (defaults to
|
|
63937
|
+
// `'en-US'`, see `resolvePerCallOptions`) rather than letting the model auto-detect and
|
|
63938
|
+
// drift onto a misheard phrase, the way it did on a live Gemini call (see `gemini.ts`'s own
|
|
63939
|
+
// `speechConfig.languageCode` comment for that incident). This must live at `agent.language`,
|
|
63940
|
+
// never inside `listen.provider`: a live probe against the current Deepgram API on
|
|
63941
|
+
// 2026-09-26 confirmed a Flux listen model plus `listen.provider.language` is rejected as
|
|
63942
|
+
// `UNPARSABLE_CLIENT_MESSAGE` ("Check the agent.listen.provider field against the API
|
|
63943
|
+
// spec"), while Flux plus `agent.language`, Flux with no language at all, and nova-3 with
|
|
63944
|
+
// `language` at either location are all accepted — matching the shape the C# runtime
|
|
63945
|
+
// already sends. `language_hints` (for `flux-general-multi`) is a separate,
|
|
63946
|
+
// `listen.provider`-only concern this adapter does not yet support.
|
|
63947
|
+
language: options.language ?? DEFAULT_LANGUAGE,
|
|
63882
63948
|
listen: {
|
|
63883
63949
|
// Deepgram's Voice Agent API: Flux models take `version: 'v2'`, every other listen
|
|
63884
63950
|
// model takes `'v1'` — https://developers.deepgram.com/docs/configure-voice-agent.
|
|
63885
63951
|
provider: {
|
|
63886
63952
|
type: "deepgram",
|
|
63887
63953
|
model: sttModel,
|
|
63954
|
+
// Flux listen models (`flux-general-en`, `flux-general-multi`) take `version: 'v2'`;
|
|
63955
|
+
// every other model (Nova, etc.) takes `'v1'`.
|
|
63888
63956
|
version: sttModel.startsWith("flux") ? "v2" : "v1"
|
|
63889
63957
|
}
|
|
63890
63958
|
},
|
|
@@ -63925,7 +63993,8 @@ function createDeepgramAdapter(webSocketClient) {
|
|
|
63925
63993
|
itemAudioStartedAt: void 0,
|
|
63926
63994
|
bytesSentForItem: 0,
|
|
63927
63995
|
generating: false,
|
|
63928
|
-
interruptedThisResponse: false
|
|
63996
|
+
interruptedThisResponse: false,
|
|
63997
|
+
playbackStopReported: false
|
|
63929
63998
|
};
|
|
63930
63999
|
const tools = options.tools ?? [];
|
|
63931
64000
|
session.keepAliveTimer = setInterval(() => {
|
|
@@ -63969,6 +64038,8 @@ function createDeepgramAdapter(webSocketClient) {
|
|
|
63969
64038
|
session.itemAudioStartedAt = Date.now();
|
|
63970
64039
|
session.bytesSentForItem = 0;
|
|
63971
64040
|
session.interruptedThisResponse = false;
|
|
64041
|
+
session.playbackStopReported = false;
|
|
64042
|
+
callbacks.onPlaybackStart?.();
|
|
63972
64043
|
}
|
|
63973
64044
|
session.bytesSentForItem += raw.length;
|
|
63974
64045
|
callbacks.onAudioOut(raw);
|
|
@@ -64022,15 +64093,26 @@ function createDeepgramAdapter(webSocketClient) {
|
|
|
64022
64093
|
}
|
|
64023
64094
|
break;
|
|
64024
64095
|
}
|
|
64025
|
-
case "AgentAudioDone":
|
|
64096
|
+
case "AgentAudioDone": {
|
|
64097
|
+
const hadAudio = session.generating;
|
|
64026
64098
|
session.generating = false;
|
|
64099
|
+
if (hadAudio && !session.playbackStopReported) {
|
|
64100
|
+
session.playbackStopReported = true;
|
|
64101
|
+
callbacks.onPlaybackStop?.({ cancelled: false });
|
|
64102
|
+
}
|
|
64027
64103
|
break;
|
|
64104
|
+
}
|
|
64028
64105
|
case "UserStartedSpeaking": {
|
|
64106
|
+
callbacks.onSpeechStart?.();
|
|
64029
64107
|
const remainingMs = session.itemAudioStartedAt !== void 0 ? session.bytesSentForItem / session.bytesPerMs - (Date.now() - session.itemAudioStartedAt) : 0;
|
|
64030
64108
|
const stillPlaying = remainingMs > 0;
|
|
64031
64109
|
const shouldBargeIn = stillPlaying || session.generating;
|
|
64032
64110
|
if (shouldBargeIn && !session.interruptedThisResponse) {
|
|
64033
64111
|
session.interruptedThisResponse = true;
|
|
64112
|
+
if (!session.playbackStopReported) {
|
|
64113
|
+
session.playbackStopReported = true;
|
|
64114
|
+
callbacks.onPlaybackStop?.({ cancelled: true });
|
|
64115
|
+
}
|
|
64034
64116
|
callbacks.onBargeIn();
|
|
64035
64117
|
}
|
|
64036
64118
|
break;
|
|
@@ -64054,6 +64136,9 @@ function createDeepgramAdapter(webSocketClient) {
|
|
|
64054
64136
|
}
|
|
64055
64137
|
closeAnyState(dgWs);
|
|
64056
64138
|
break;
|
|
64139
|
+
case "Warning":
|
|
64140
|
+
console.warn("[realtimeAgent] Deepgram Agent API warning:", msg);
|
|
64141
|
+
break;
|
|
64057
64142
|
}
|
|
64058
64143
|
});
|
|
64059
64144
|
dgWs.on("error", (err) => {
|
|
@@ -64209,6 +64294,31 @@ var StreamingResampler = class {
|
|
|
64209
64294
|
};
|
|
64210
64295
|
|
|
64211
64296
|
// ../runtime-shared/dist/ai/realtime/tool-injection.js
|
|
64297
|
+
var DEFAULT_TIMEZONE = "America/Chicago";
|
|
64298
|
+
function currentDateTimePreamble(timezone = DEFAULT_TIMEZONE, now = /* @__PURE__ */ new Date()) {
|
|
64299
|
+
const parts = new Intl.DateTimeFormat("en-GB", {
|
|
64300
|
+
weekday: "long",
|
|
64301
|
+
day: "numeric",
|
|
64302
|
+
month: "long",
|
|
64303
|
+
year: "numeric",
|
|
64304
|
+
hour: "2-digit",
|
|
64305
|
+
minute: "2-digit",
|
|
64306
|
+
hour12: false,
|
|
64307
|
+
timeZone: timezone
|
|
64308
|
+
}).formatToParts(now);
|
|
64309
|
+
const get = (type) => parts.find((p) => p.type === type)?.value ?? "";
|
|
64310
|
+
const zoneName = new Intl.DateTimeFormat("en-US", { timeZone: timezone, timeZoneName: "long" }).formatToParts(now).find((p) => p.type === "timeZoneName")?.value ?? timezone;
|
|
64311
|
+
return `Current date and time: ${get("weekday")}, ${get("day")} ${get("month")} ${get("year")}, ${get("hour")}:${get("minute")} (${zoneName})
|
|
64312
|
+
|
|
64313
|
+
`;
|
|
64314
|
+
}
|
|
64315
|
+
function verbatimGreetingDirective(greeting) {
|
|
64316
|
+
return `Say this exact greeting, word for word, with no changes or additions: "${greeting}"`;
|
|
64317
|
+
}
|
|
64318
|
+
function nonBlank(value) {
|
|
64319
|
+
const trimmed = value?.trim();
|
|
64320
|
+
return trimmed ? trimmed : void 0;
|
|
64321
|
+
}
|
|
64212
64322
|
var E1642 = /^\+\d{6,15}$/;
|
|
64213
64323
|
function invokeHook(name, fn) {
|
|
64214
64324
|
try {
|
|
@@ -64294,6 +64404,11 @@ function pcm16Rms(pcm) {
|
|
|
64294
64404
|
function isSpeechFrame(pcm) {
|
|
64295
64405
|
return pcm16Rms(pcm) > SILENCE_RMS_THRESHOLD;
|
|
64296
64406
|
}
|
|
64407
|
+
function toAnchoredIso(session, offsetMs) {
|
|
64408
|
+
if (offsetMs === void 0 || session.sessionStartedAtMs === void 0)
|
|
64409
|
+
return void 0;
|
|
64410
|
+
return new Date(session.sessionStartedAtMs + offsetMs).toISOString();
|
|
64411
|
+
}
|
|
64297
64412
|
function buildGreetingDirective(greeting) {
|
|
64298
64413
|
return `Greet the caller now by saying exactly: "${greeting}"`;
|
|
64299
64414
|
}
|
|
@@ -64317,15 +64432,16 @@ function buildInstructions(options) {
|
|
|
64317
64432
|
|
|
64318
64433
|
Open the call by greeting the caller before waiting for any caller input.`;
|
|
64319
64434
|
}
|
|
64320
|
-
function buildBackendInstructions(po, tools) {
|
|
64435
|
+
function buildBackendInstructions(options, po, tools) {
|
|
64436
|
+
const preamble = currentDateTimePreamble(options.timezone);
|
|
64321
64437
|
if (!offersHangup(tools))
|
|
64322
|
-
return po.backendInstructions;
|
|
64438
|
+
return preamble + (po.backendInstructions ?? "");
|
|
64323
64439
|
const terminationBlock = CALL_TERMINATION_INSTRUCTIONS + GPT_LIVE_BACKEND_CALL_TERMINATION_RULE;
|
|
64324
|
-
return po.backendInstructions ? po.backendInstructions + terminationBlock : terminationBlock.trimStart();
|
|
64440
|
+
return preamble + (po.backendInstructions ? po.backendInstructions + terminationBlock : terminationBlock.trimStart());
|
|
64325
64441
|
}
|
|
64326
64442
|
function buildSessionStart(options, tools) {
|
|
64327
64443
|
const po = providerOptionsFor2(options);
|
|
64328
|
-
const backendInstructions = buildBackendInstructions(po, tools);
|
|
64444
|
+
const backendInstructions = buildBackendInstructions(options, po, tools);
|
|
64329
64445
|
return {
|
|
64330
64446
|
type: "session.start",
|
|
64331
64447
|
session: {
|
|
@@ -64424,7 +64540,18 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64424
64540
|
pendingUserTurnText: "",
|
|
64425
64541
|
userTurnTimer: void 0,
|
|
64426
64542
|
pendingUserTurnEndMs: void 0,
|
|
64427
|
-
closeAckTimer: void 0
|
|
64543
|
+
closeAckTimer: void 0,
|
|
64544
|
+
sessionSeconds: void 0,
|
|
64545
|
+
backendInputTokens: 0,
|
|
64546
|
+
backendOutputTokens: 0,
|
|
64547
|
+
pendingUserTurnStartMs: void 0,
|
|
64548
|
+
pendingAgentTurnStartMs: void 0,
|
|
64549
|
+
pendingAgentTurnEndMs: void 0,
|
|
64550
|
+
sessionStartedAtMs: void 0,
|
|
64551
|
+
delegationCreatedAtMs: /* @__PURE__ */ new Map(),
|
|
64552
|
+
delegationFirstOutputMs: /* @__PURE__ */ new Map(),
|
|
64553
|
+
delegationToolMs: /* @__PURE__ */ new Map(),
|
|
64554
|
+
lastDelegationId: void 0
|
|
64428
64555
|
};
|
|
64429
64556
|
const tools = options.tools ?? [];
|
|
64430
64557
|
vendorWs.on("open", () => {
|
|
@@ -64457,10 +64584,12 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64457
64584
|
const key = stateKey(delegationId);
|
|
64458
64585
|
const deleg = getOrCreateDelegation(key);
|
|
64459
64586
|
deleg.callIds.add(callId);
|
|
64587
|
+
const toolStart = Date.now();
|
|
64460
64588
|
void dispatchToolCall2(callId, name, rawArgs ?? "", tools, ctx, vendorWs, callbacks).catch((err) => {
|
|
64461
64589
|
const sanitized = sanitizeVendorError(err);
|
|
64462
64590
|
callbacks.onError({ message: sanitized.message, code: sanitized.code, raw: sanitized });
|
|
64463
64591
|
}).finally(() => {
|
|
64592
|
+
session.delegationToolMs.set(delegationId, (session.delegationToolMs.get(delegationId) ?? 0) + (Date.now() - toolStart));
|
|
64464
64593
|
session.delegations.get(key)?.callIdsCompleted.add(callId);
|
|
64465
64594
|
maybeFinishResponse(key);
|
|
64466
64595
|
});
|
|
@@ -64481,8 +64610,23 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64481
64610
|
session.agentTurnStartedAt = void 0;
|
|
64482
64611
|
const text = session.pendingAgentTurnText;
|
|
64483
64612
|
session.pendingAgentTurnText = "";
|
|
64613
|
+
const playbackStartAt = toAnchoredIso(session, session.pendingAgentTurnStartMs);
|
|
64614
|
+
const playbackEndAt = toAnchoredIso(session, session.pendingAgentTurnEndMs);
|
|
64615
|
+
session.pendingAgentTurnStartMs = void 0;
|
|
64616
|
+
session.pendingAgentTurnEndMs = void 0;
|
|
64617
|
+
let delegationMs;
|
|
64618
|
+
if (session.lastDelegationId !== void 0) {
|
|
64619
|
+
const firstOutputMs = session.delegationFirstOutputMs.get(session.lastDelegationId);
|
|
64620
|
+
const toolMs = session.delegationToolMs.get(session.lastDelegationId) ?? 0;
|
|
64621
|
+
if (firstOutputMs !== void 0)
|
|
64622
|
+
delegationMs = firstOutputMs + toolMs;
|
|
64623
|
+
session.delegationFirstOutputMs.delete(session.lastDelegationId);
|
|
64624
|
+
session.delegationToolMs.delete(session.lastDelegationId);
|
|
64625
|
+
session.delegationCreatedAtMs.delete(session.lastDelegationId);
|
|
64626
|
+
session.lastDelegationId = void 0;
|
|
64627
|
+
}
|
|
64484
64628
|
if (text)
|
|
64485
|
-
callbacks.onTurn({ role: "agent", text, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
64629
|
+
callbacks.onTurn({ role: "agent", text, timestamp: (/* @__PURE__ */ new Date()).toISOString(), playbackStartAt, playbackEndAt, delegationMs });
|
|
64486
64630
|
};
|
|
64487
64631
|
const scheduleAgentTurnFlush = () => {
|
|
64488
64632
|
if (session.agentTurnTimer !== void 0)
|
|
@@ -64494,11 +64638,14 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64494
64638
|
clearTimeout(session.userTurnTimer);
|
|
64495
64639
|
session.userTurnTimer = void 0;
|
|
64496
64640
|
}
|
|
64641
|
+
const speechStartAt = toAnchoredIso(session, session.pendingUserTurnStartMs);
|
|
64642
|
+
const speechEndAt = toAnchoredIso(session, session.pendingUserTurnEndMs);
|
|
64497
64643
|
session.pendingUserTurnEndMs = void 0;
|
|
64644
|
+
session.pendingUserTurnStartMs = void 0;
|
|
64498
64645
|
const text = session.pendingUserTurnText;
|
|
64499
64646
|
session.pendingUserTurnText = "";
|
|
64500
64647
|
if (text)
|
|
64501
|
-
callbacks.onTurn({ role: "user", text, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
64648
|
+
callbacks.onTurn({ role: "user", text, timestamp: (/* @__PURE__ */ new Date()).toISOString(), speechStartAt, speechEndAt });
|
|
64502
64649
|
};
|
|
64503
64650
|
const scheduleUserTurnFlush = () => {
|
|
64504
64651
|
if (session.userTurnTimer !== void 0)
|
|
@@ -64536,6 +64683,13 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64536
64683
|
signal.removeEventListener("abort", onAbort);
|
|
64537
64684
|
fn();
|
|
64538
64685
|
};
|
|
64686
|
+
const reportUsage = () => {
|
|
64687
|
+
callbacks.onUsage?.({
|
|
64688
|
+
inputTokens: session.backendInputTokens || void 0,
|
|
64689
|
+
outputTokens: session.backendOutputTokens || void 0,
|
|
64690
|
+
audioSeconds: session.sessionSeconds
|
|
64691
|
+
});
|
|
64692
|
+
};
|
|
64539
64693
|
vendorWs.on("message", (raw) => {
|
|
64540
64694
|
if (isOversizedFrame(raw)) {
|
|
64541
64695
|
callbacks.onError({ message: "Received an oversized frame from OpenAI GPT-Live \u2014 dropped" });
|
|
@@ -64550,6 +64704,7 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64550
64704
|
case "session.started": {
|
|
64551
64705
|
const started = msg["session"];
|
|
64552
64706
|
session.expiresAt = started?.expires_at;
|
|
64707
|
+
session.sessionStartedAtMs = Date.now();
|
|
64553
64708
|
session.ready = true;
|
|
64554
64709
|
settle2(() => resolve(session));
|
|
64555
64710
|
if (options.greeting) {
|
|
@@ -64586,8 +64741,12 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64586
64741
|
const hasRealGap = startMs !== void 0 && session.pendingUserTurnEndMs !== void 0 && startMs - session.pendingUserTurnEndMs > TURN_SILENCE_MS;
|
|
64587
64742
|
if (hasRealGap)
|
|
64588
64743
|
flushUserTurnNow();
|
|
64589
|
-
if (delta)
|
|
64744
|
+
if (delta) {
|
|
64745
|
+
if (session.pendingUserTurnText === "" && startMs !== void 0) {
|
|
64746
|
+
session.pendingUserTurnStartMs = startMs;
|
|
64747
|
+
}
|
|
64590
64748
|
session.pendingUserTurnText += delta;
|
|
64749
|
+
}
|
|
64591
64750
|
if (endMs !== void 0)
|
|
64592
64751
|
session.pendingUserTurnEndMs = endMs;
|
|
64593
64752
|
scheduleUserTurnFlush();
|
|
@@ -64595,14 +64754,20 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64595
64754
|
}
|
|
64596
64755
|
case "session.output_transcript.delta": {
|
|
64597
64756
|
const delta = msg["delta"];
|
|
64757
|
+
const startMs = typeof msg["start_ms"] === "number" ? msg["start_ms"] : void 0;
|
|
64758
|
+
const endMs = typeof msg["end_ms"] === "number" ? msg["end_ms"] : void 0;
|
|
64598
64759
|
if (delta) {
|
|
64599
64760
|
if (session.pendingAgentTurnText === "") {
|
|
64600
64761
|
session.agentTurnStartedAt = Date.now();
|
|
64601
64762
|
if (session.agentTurnHardCapTimer !== void 0)
|
|
64602
64763
|
clearTimeout(session.agentTurnHardCapTimer);
|
|
64603
64764
|
session.agentTurnHardCapTimer = setTimeout(flushAgentTurnNow, AGENT_TURN_HARD_CAP_MS);
|
|
64765
|
+
if (startMs !== void 0)
|
|
64766
|
+
session.pendingAgentTurnStartMs = startMs;
|
|
64604
64767
|
}
|
|
64605
64768
|
session.pendingAgentTurnText += delta;
|
|
64769
|
+
if (endMs !== void 0)
|
|
64770
|
+
session.pendingAgentTurnEndMs = endMs;
|
|
64606
64771
|
}
|
|
64607
64772
|
const audioQuiet = session.lastSpeechAudioAt !== void 0 && Date.now() - session.lastSpeechAudioAt > TURN_SILENCE_MS;
|
|
64608
64773
|
if (audioQuiet) {
|
|
@@ -64617,6 +64782,13 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64617
64782
|
const inner = msg["event"];
|
|
64618
64783
|
if (!inner || !delegationId)
|
|
64619
64784
|
break;
|
|
64785
|
+
session.lastDelegationId = delegationId;
|
|
64786
|
+
const isBackendOutput = inner.type === "response.output_item.added" || inner.type === "response.output_item.done" || inner.type === "response.output_text.delta";
|
|
64787
|
+
if (isBackendOutput && !session.delegationFirstOutputMs.has(delegationId)) {
|
|
64788
|
+
const createdAt = session.delegationCreatedAtMs.get(delegationId);
|
|
64789
|
+
if (createdAt !== void 0)
|
|
64790
|
+
session.delegationFirstOutputMs.set(delegationId, Date.now() - createdAt);
|
|
64791
|
+
}
|
|
64620
64792
|
switch (inner.type) {
|
|
64621
64793
|
case "response.created": {
|
|
64622
64794
|
const responseId = inner.response?.id;
|
|
@@ -64636,11 +64808,31 @@ function createOpenAiAdapter(webSocketClient) {
|
|
|
64636
64808
|
const deleg = getOrCreateDelegation(key);
|
|
64637
64809
|
deleg.responseDone = true;
|
|
64638
64810
|
maybeFinishResponse(key);
|
|
64811
|
+
const backendUsage = inner.response?.usage;
|
|
64812
|
+
if (backendUsage) {
|
|
64813
|
+
session.backendInputTokens += backendUsage.input_tokens ?? 0;
|
|
64814
|
+
session.backendOutputTokens += backendUsage.output_tokens ?? 0;
|
|
64815
|
+
reportUsage();
|
|
64816
|
+
}
|
|
64639
64817
|
break;
|
|
64640
64818
|
}
|
|
64641
64819
|
}
|
|
64642
64820
|
break;
|
|
64643
64821
|
}
|
|
64822
|
+
case "session.delegation.created": {
|
|
64823
|
+
const delegationId = msg["delegation_id"];
|
|
64824
|
+
if (delegationId)
|
|
64825
|
+
session.delegationCreatedAtMs.set(delegationId, Date.now());
|
|
64826
|
+
break;
|
|
64827
|
+
}
|
|
64828
|
+
case "session.usage.updated": {
|
|
64829
|
+
const usage = msg["usage"];
|
|
64830
|
+
if (usage?.seconds !== void 0) {
|
|
64831
|
+
session.sessionSeconds = usage.seconds;
|
|
64832
|
+
reportUsage();
|
|
64833
|
+
}
|
|
64834
|
+
break;
|
|
64835
|
+
}
|
|
64644
64836
|
case "session.closed": {
|
|
64645
64837
|
if (session.closeAckTimer !== void 0) {
|
|
64646
64838
|
clearTimeout(session.closeAckTimer);
|
|
@@ -64799,7 +64991,9 @@ function createOpenAiCompatibleAdapter(config, webSocketClient) {
|
|
|
64799
64991
|
responseCallIds: /* @__PURE__ */ new Set(),
|
|
64800
64992
|
responseCallIdsCompleted: /* @__PURE__ */ new Set(),
|
|
64801
64993
|
responseDone: false,
|
|
64802
|
-
pendingUserTurnText: /* @__PURE__ */ new Map()
|
|
64994
|
+
pendingUserTurnText: /* @__PURE__ */ new Map(),
|
|
64995
|
+
totalInputTokens: 0,
|
|
64996
|
+
totalOutputTokens: 0
|
|
64803
64997
|
};
|
|
64804
64998
|
const tools = options.tools ?? [];
|
|
64805
64999
|
vendorWs.on("open", () => {
|
|
@@ -64892,7 +65086,10 @@ function createOpenAiCompatibleAdapter(config, webSocketClient) {
|
|
|
64892
65086
|
session.ready = true;
|
|
64893
65087
|
settle2(() => resolve(session));
|
|
64894
65088
|
if (options.greeting) {
|
|
64895
|
-
vendorWs.send(JSON.stringify({
|
|
65089
|
+
vendorWs.send(JSON.stringify({
|
|
65090
|
+
type: "response.create",
|
|
65091
|
+
response: { instructions: verbatimGreetingDirective(options.greeting) }
|
|
65092
|
+
}));
|
|
64896
65093
|
}
|
|
64897
65094
|
break;
|
|
64898
65095
|
case "response.created":
|
|
@@ -64905,6 +65102,7 @@ function createOpenAiCompatibleAdapter(config, webSocketClient) {
|
|
|
64905
65102
|
session.currentItemId = itemId;
|
|
64906
65103
|
session.itemAudioStartedAt = Date.now();
|
|
64907
65104
|
session.bytesSentForItem = 0;
|
|
65105
|
+
callbacks.onPlaybackStart?.();
|
|
64908
65106
|
}
|
|
64909
65107
|
const mulaw = safeBase64ToBuffer(msg["delta"]);
|
|
64910
65108
|
if (!mulaw) {
|
|
@@ -64937,16 +65135,27 @@ function createOpenAiCompatibleAdapter(config, webSocketClient) {
|
|
|
64937
65135
|
case "response.function_call_arguments.done":
|
|
64938
65136
|
maybeDispatch(msg["call_id"], msg["name"], msg["arguments"]);
|
|
64939
65137
|
break;
|
|
64940
|
-
case "response.done":
|
|
65138
|
+
case "response.done": {
|
|
65139
|
+
if (session.currentItemId !== void 0)
|
|
65140
|
+
callbacks.onPlaybackStop?.({ cancelled: false });
|
|
65141
|
+
const usage = msg["response"]?.usage;
|
|
65142
|
+
if (usage) {
|
|
65143
|
+
session.totalInputTokens += usage.input_tokens ?? 0;
|
|
65144
|
+
session.totalOutputTokens += usage.output_tokens ?? 0;
|
|
65145
|
+
callbacks.onUsage?.({ inputTokens: session.totalInputTokens, outputTokens: session.totalOutputTokens });
|
|
65146
|
+
}
|
|
64941
65147
|
closeResponse();
|
|
64942
65148
|
break;
|
|
65149
|
+
}
|
|
64943
65150
|
case "input_audio_buffer.speech_started": {
|
|
65151
|
+
callbacks.onSpeechStart?.();
|
|
64944
65152
|
flushPendingUserTurns();
|
|
64945
65153
|
const remainingMs = session.itemAudioStartedAt !== void 0 ? session.bytesSentForItem / MULAW_BYTES_PER_MS - (Date.now() - session.itemAudioStartedAt) : 0;
|
|
64946
65154
|
const stillPlaying = remainingMs > 0;
|
|
64947
65155
|
const shouldBargeIn = stillPlaying || session.responseOpen;
|
|
64948
65156
|
if (shouldBargeIn && !session.interruptedThisResponse) {
|
|
64949
65157
|
session.interruptedThisResponse = true;
|
|
65158
|
+
const hadAudio = session.currentItemId !== void 0;
|
|
64950
65159
|
if (session.responseOpen) {
|
|
64951
65160
|
if (config.serverCancelsOnSpeechStarted) {
|
|
64952
65161
|
closeResponse();
|
|
@@ -64962,10 +65171,15 @@ function createOpenAiCompatibleAdapter(config, webSocketClient) {
|
|
|
64962
65171
|
vendorWs.send(JSON.stringify({ type: "response.cancel" }));
|
|
64963
65172
|
}
|
|
64964
65173
|
}
|
|
65174
|
+
if (hadAudio)
|
|
65175
|
+
callbacks.onPlaybackStop?.({ cancelled: true });
|
|
64965
65176
|
callbacks.onBargeIn();
|
|
64966
65177
|
}
|
|
64967
65178
|
break;
|
|
64968
65179
|
}
|
|
65180
|
+
case "input_audio_buffer.speech_stopped":
|
|
65181
|
+
callbacks.onSpeechEnd?.();
|
|
65182
|
+
break;
|
|
64969
65183
|
case "response.output_audio_transcript.done": {
|
|
64970
65184
|
const text = msg["transcript"];
|
|
64971
65185
|
if (text)
|
|
@@ -65048,7 +65262,14 @@ function buildGrokSession(options, tools) {
|
|
|
65048
65262
|
// `grok-transcribe` is required for xAI to emit
|
|
65049
65263
|
// `conversation.item.input_audio_transcription.updated` at all — see the file header's
|
|
65050
65264
|
// "Input transcription" note (finding #8).
|
|
65051
|
-
|
|
65265
|
+
// `language_hint` biases recognition toward `options.language` (defaults to `'en-US'`,
|
|
65266
|
+
// see `resolvePerCallOptions`) — previously left unset per this file's own header note
|
|
65267
|
+
// ("no author-facing field maps onto [it] yet"); `RealtimeAgentOptions.language` is now
|
|
65268
|
+
// that field.
|
|
65269
|
+
input: {
|
|
65270
|
+
format: { type: "audio/pcmu" },
|
|
65271
|
+
transcription: { model: "grok-transcribe", language_hint: options.language ?? DEFAULT_LANGUAGE }
|
|
65272
|
+
},
|
|
65052
65273
|
output: { format: { type: "audio/pcmu" } }
|
|
65053
65274
|
},
|
|
65054
65275
|
tools: encodeTools2(tools)
|
|
@@ -65078,9 +65299,15 @@ function providerOptionsFor3(options) {
|
|
|
65078
65299
|
}
|
|
65079
65300
|
function flushPendingTurns(session, callbacks) {
|
|
65080
65301
|
if (session.pendingUserText) {
|
|
65081
|
-
callbacks.onTurn({
|
|
65302
|
+
callbacks.onTurn({
|
|
65303
|
+
role: "user",
|
|
65304
|
+
text: session.pendingUserText,
|
|
65305
|
+
timestamp: session.pendingUserTextAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
65306
|
+
});
|
|
65082
65307
|
session.pendingUserText = "";
|
|
65308
|
+
session.pendingUserTextAt = void 0;
|
|
65083
65309
|
}
|
|
65310
|
+
session.speechStartReported = false;
|
|
65084
65311
|
flushPendingAgentTurn(session, callbacks);
|
|
65085
65312
|
}
|
|
65086
65313
|
function flushPendingAgentTurn(session, callbacks) {
|
|
@@ -65131,10 +65358,16 @@ function buildSetupMessage(options, model, tools, resumptionHandle) {
|
|
|
65131
65358
|
model: model.startsWith("models/") ? model : `models/${model}`,
|
|
65132
65359
|
generationConfig: {
|
|
65133
65360
|
responseModalities: ["AUDIO"],
|
|
65134
|
-
//
|
|
65135
|
-
//
|
|
65136
|
-
|
|
65137
|
-
|
|
65361
|
+
// `languageCode` is always sent (`options.language` defaults to `'en-US'` — see
|
|
65362
|
+
// `resolvePerCallOptions`): a live prd call had the caller's speech misheard as Spanish
|
|
65363
|
+
// ("¿Cómo te") and Gemini — a single model doing both recognition and reply, not a
|
|
65364
|
+
// separate STT/TTS pair — answered in Spanish for that turn. Pinning `languageCode`
|
|
65365
|
+
// constrains the session to the configured language regardless of what the audio sounds
|
|
65366
|
+
// like. `voiceConfig` stays conditional on an author voice — unset, Gemini applies its
|
|
65367
|
+
// own default voice.
|
|
65368
|
+
speechConfig: {
|
|
65369
|
+
languageCode: options.language ?? DEFAULT_LANGUAGE,
|
|
65370
|
+
...options.voice && { voiceConfig: { prebuiltVoiceConfig: { voiceName: options.voice } } }
|
|
65138
65371
|
}
|
|
65139
65372
|
},
|
|
65140
65373
|
systemInstruction: { parts: [{ text: options.prompt }] },
|
|
@@ -65222,7 +65455,9 @@ function createGeminiAdapter(webSocketClient) {
|
|
|
65222
65455
|
resamplerIn: new StreamingResampler(rate, VENDOR_IN_RATE),
|
|
65223
65456
|
resamplerOut: new StreamingResampler(VENDOR_OUT_RATE, rate),
|
|
65224
65457
|
pendingUserText: "",
|
|
65225
|
-
pendingAgentText: ""
|
|
65458
|
+
pendingAgentText: "",
|
|
65459
|
+
pendingUserTextAt: void 0,
|
|
65460
|
+
speechStartReported: false
|
|
65226
65461
|
};
|
|
65227
65462
|
let greeted = false;
|
|
65228
65463
|
const sendRealtimeAudio = (pcm) => {
|
|
@@ -65309,6 +65544,13 @@ function createGeminiAdapter(webSocketClient) {
|
|
|
65309
65544
|
}
|
|
65310
65545
|
return;
|
|
65311
65546
|
}
|
|
65547
|
+
const usageMetadata = msg["usageMetadata"];
|
|
65548
|
+
if (usageMetadata) {
|
|
65549
|
+
callbacks.onUsage?.({
|
|
65550
|
+
inputTokens: usageMetadata.promptTokenCount,
|
|
65551
|
+
outputTokens: usageMetadata.responseTokenCount
|
|
65552
|
+
});
|
|
65553
|
+
}
|
|
65312
65554
|
const resumptionUpdate = msg["sessionResumptionUpdate"];
|
|
65313
65555
|
if (resumptionUpdate) {
|
|
65314
65556
|
if (resumptionUpdate.resumable === false) {
|
|
@@ -65339,8 +65581,13 @@ function createGeminiAdapter(webSocketClient) {
|
|
|
65339
65581
|
} else if (parts !== void 0) {
|
|
65340
65582
|
callbacks.onError({ message: "Received a malformed modelTurn from Gemini Live \u2014 parts was not an array" });
|
|
65341
65583
|
}
|
|
65584
|
+
if (content.interimInputTranscription?.text && !session.speechStartReported) {
|
|
65585
|
+
session.speechStartReported = true;
|
|
65586
|
+
callbacks.onSpeechStart?.();
|
|
65587
|
+
}
|
|
65342
65588
|
if (content.inputTranscription?.text) {
|
|
65343
65589
|
session.pendingUserText += content.inputTranscription.text;
|
|
65590
|
+
session.pendingUserTextAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
65344
65591
|
}
|
|
65345
65592
|
if (content.outputTranscription?.text) {
|
|
65346
65593
|
session.pendingAgentText += content.outputTranscription.text;
|
|
@@ -65472,6 +65719,18 @@ function getRealtimeAdapter(provider) {
|
|
|
65472
65719
|
|
|
65473
65720
|
// ../runtime-shared/dist/ai/realtime/adapters/relay-llm.js
|
|
65474
65721
|
var DEFAULT_RESPONSES_BASE_URL = "https://api.openai.com/v1";
|
|
65722
|
+
function resolveBaseUrl(value) {
|
|
65723
|
+
const trimmed = value?.trim();
|
|
65724
|
+
if (!trimmed)
|
|
65725
|
+
return void 0;
|
|
65726
|
+
try {
|
|
65727
|
+
const { protocol } = new URL(trimmed);
|
|
65728
|
+
if (protocol === "http:" || protocol === "https:")
|
|
65729
|
+
return trimmed;
|
|
65730
|
+
} catch {
|
|
65731
|
+
}
|
|
65732
|
+
return void 0;
|
|
65733
|
+
}
|
|
65475
65734
|
var DEFAULT_SERVICE_TIER = "fast";
|
|
65476
65735
|
var DEFAULT_REASONING_EFFORT = "none";
|
|
65477
65736
|
var DEFAULT_VERBOSITY = "low";
|
|
@@ -65669,7 +65928,8 @@ function createResponsesEventState(callbacks) {
|
|
|
65669
65928
|
const flushed = sentences.flush();
|
|
65670
65929
|
if (flushed)
|
|
65671
65930
|
callbacks.onSentence(flushed);
|
|
65672
|
-
|
|
65931
|
+
const usage = response?.usage ? { inputTokens: response.usage.input_tokens, outputTokens: response.usage.output_tokens } : void 0;
|
|
65932
|
+
return { text, responseId, usage };
|
|
65673
65933
|
}
|
|
65674
65934
|
case "response.failed": {
|
|
65675
65935
|
const response = event["response"];
|
|
@@ -65695,7 +65955,7 @@ function createResponsesEventState(callbacks) {
|
|
|
65695
65955
|
};
|
|
65696
65956
|
}
|
|
65697
65957
|
async function streamResponses(options, callbacks) {
|
|
65698
|
-
const baseUrl = (options.baseUrl ?? DEFAULT_RESPONSES_BASE_URL).replace(/\/$/, "");
|
|
65958
|
+
const baseUrl = (resolveBaseUrl(options.baseUrl) ?? DEFAULT_RESPONSES_BASE_URL).replace(/\/$/, "");
|
|
65699
65959
|
let res;
|
|
65700
65960
|
try {
|
|
65701
65961
|
res = await fetch(`${baseUrl}/responses`, {
|
|
@@ -65740,7 +66000,7 @@ async function streamResponses(options, callbacks) {
|
|
|
65740
66000
|
var FIRST_OUTPUT_TIMEOUT_MS = 3e3;
|
|
65741
66001
|
var RESPONSE_TIMEOUT_MS = 15e3;
|
|
65742
66002
|
function buildResponsesWsUrl(baseUrl) {
|
|
65743
|
-
const base = baseUrl ??
|
|
66003
|
+
const base = resolveBaseUrl(baseUrl) ?? DEFAULT_RESPONSES_BASE_URL;
|
|
65744
66004
|
const path6 = "/responses";
|
|
65745
66005
|
const url2 = new URL(base + (base.endsWith("/") ? path6.slice(1) : path6));
|
|
65746
66006
|
url2.protocol = url2.protocol === "http:" ? "ws:" : "wss:";
|
|
@@ -65900,8 +66160,24 @@ function createResponsesWsSession(apiKey, baseUrl, factory2 = (key, url2) => new
|
|
|
65900
66160
|
};
|
|
65901
66161
|
}
|
|
65902
66162
|
|
|
66163
|
+
// ../runtime-shared/dist/ai/realtime/turn-timing.js
|
|
66164
|
+
function playbackDelayMs(firstAgentChunkAtMs, playbackStartAtIso) {
|
|
66165
|
+
if (firstAgentChunkAtMs === void 0 || !playbackStartAtIso)
|
|
66166
|
+
return void 0;
|
|
66167
|
+
return Date.parse(playbackStartAtIso) - firstAgentChunkAtMs;
|
|
66168
|
+
}
|
|
66169
|
+
function audioMs(playbackStartAtIso, playbackEndAtIso) {
|
|
66170
|
+
if (!playbackStartAtIso || !playbackEndAtIso)
|
|
66171
|
+
return void 0;
|
|
66172
|
+
return Date.parse(playbackEndAtIso) - Date.parse(playbackStartAtIso);
|
|
66173
|
+
}
|
|
66174
|
+
function logValue(ms) {
|
|
66175
|
+
return ms ?? -1;
|
|
66176
|
+
}
|
|
66177
|
+
|
|
65903
66178
|
// ../runtime-shared/dist/ai/realtime/adapters/relay.js
|
|
65904
66179
|
var DEFAULT_MAX_CALL_DURATION = 1800;
|
|
66180
|
+
var TRANSFER_LEG = "transfer-1";
|
|
65905
66181
|
function acceptsReasoningTuning(modelId) {
|
|
65906
66182
|
const model = (modelId ?? "").toLowerCase();
|
|
65907
66183
|
return model.startsWith("gpt-5") || isOSeriesModel(model);
|
|
@@ -65932,9 +66208,9 @@ function supportsChaining(baseUrl) {
|
|
|
65932
66208
|
function resolveTuning(options, config, baseUrl) {
|
|
65933
66209
|
const modelAcceptsReasoning = acceptsReasoningTuning(options.model);
|
|
65934
66210
|
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")
|
|
66211
|
+
serviceTier: nonBlank(options.serviceTier) ?? nonBlank(config.getVariable("LLM_SERVICE_TIER")) ?? (isOpenAiHost(baseUrl) ? DEFAULT_SERVICE_TIER : void 0),
|
|
66212
|
+
reasoningEffort: nonBlank(options.reasoningEffort) ?? nonBlank(config.getVariable("LLM_REASONING_EFFORT")) ?? (modelAcceptsReasoning && !isOSeriesModel(options.model) ? DEFAULT_REASONING_EFFORT : void 0),
|
|
66213
|
+
verbosity: nonBlank(options.verbosity) ?? nonBlank(config.getVariable("LLM_VERBOSITY")) ?? (modelAcceptsReasoning ? DEFAULT_VERBOSITY : void 0)
|
|
65938
66214
|
};
|
|
65939
66215
|
}
|
|
65940
66216
|
function createRelayAgent(options) {
|
|
@@ -65942,10 +66218,14 @@ function createRelayAgent(options) {
|
|
|
65942
66218
|
throw new Error("realtimeAgent: provider 'voice-relay' requires options.model.");
|
|
65943
66219
|
}
|
|
65944
66220
|
const pendingByCallId = /* @__PURE__ */ new Map();
|
|
66221
|
+
const transferredCallIds = /* @__PURE__ */ new Set();
|
|
65945
66222
|
const relay2 = voiceRelay({
|
|
65946
66223
|
voice: options.voice,
|
|
66224
|
+
// voiceRelay's own `language` already defaults to 'en-US' when unset — see its own doc
|
|
66225
|
+
// comment — so no `?? DEFAULT_LANGUAGE` needed here, unlike the STREAM adapters.
|
|
66226
|
+
language: options.language,
|
|
65947
66227
|
greeting: options.greeting,
|
|
65948
|
-
onConnected: (call) => attach(options, pendingByCallId, call)
|
|
66228
|
+
onConnected: (call) => attach(options, pendingByCallId, transferredCallIds, call)
|
|
65949
66229
|
});
|
|
65950
66230
|
const connect = async (call, builder, context) => {
|
|
65951
66231
|
const [prompt, transferTo] = await Promise.all([
|
|
@@ -65953,19 +66233,29 @@ function createRelayAgent(options) {
|
|
|
65953
66233
|
resolvePerCallValue(options.transferTo, call, context)
|
|
65954
66234
|
]);
|
|
65955
66235
|
const callId = String(call.callId ?? "");
|
|
65956
|
-
if (callId)
|
|
65957
|
-
pendingByCallId.set(callId, {
|
|
66236
|
+
if (callId) {
|
|
66237
|
+
pendingByCallId.set(callId, {
|
|
66238
|
+
prompt: currentDateTimePreamble(options.timezone) + prompt,
|
|
66239
|
+
transferTo: nonBlank(transferTo)
|
|
66240
|
+
});
|
|
66241
|
+
}
|
|
65958
66242
|
const maxDuration = Number(createUniversalConfig(context).getVariable("MAX_CALL_DURATION", String(DEFAULT_MAX_CALL_DURATION)));
|
|
65959
66243
|
return builder.answer().dialRelay(relay2, { maxDuration });
|
|
65960
66244
|
};
|
|
66245
|
+
const handleCallCompleted = (call, _builder, context) => {
|
|
66246
|
+
const callId = String(call.callId ?? "");
|
|
66247
|
+
if (callId && transferredCallIds.delete(callId)) {
|
|
66248
|
+
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));
|
|
66249
|
+
}
|
|
66250
|
+
};
|
|
65961
66251
|
return {
|
|
65962
66252
|
setup: relay2.setup,
|
|
65963
|
-
voiceWebhook: onCall({ incoming: connect }),
|
|
66253
|
+
voiceWebhook: onCall({ incoming: connect, completed: handleCallCompleted }),
|
|
65964
66254
|
connect,
|
|
65965
66255
|
endpointFor: relay2.endpointFor
|
|
65966
66256
|
};
|
|
65967
66257
|
}
|
|
65968
|
-
function attach(options, pendingByCallId, call) {
|
|
66258
|
+
function attach(options, pendingByCallId, transferredCallIds, call) {
|
|
65969
66259
|
const pending = pendingByCallId.get(call.id);
|
|
65970
66260
|
pendingByCallId.delete(call.id);
|
|
65971
66261
|
const context = call.context;
|
|
@@ -65977,12 +66267,14 @@ function attach(options, pendingByCallId, call) {
|
|
|
65977
66267
|
return;
|
|
65978
66268
|
}
|
|
65979
66269
|
const apiKey = secret;
|
|
65980
|
-
const baseUrl = options.baseUrl ?? config.getVariable("OPENAI_BASE_URL")
|
|
66270
|
+
const baseUrl = resolveBaseUrl(options.baseUrl) ?? resolveBaseUrl(config.getVariable("OPENAI_BASE_URL"));
|
|
65981
66271
|
const tuning = resolveTuning(options, config, baseUrl);
|
|
65982
66272
|
const chainingEnabled = supportsChaining(baseUrl);
|
|
65983
66273
|
const transcript = [];
|
|
66274
|
+
const usage = {};
|
|
65984
66275
|
const ended = new AbortController();
|
|
65985
66276
|
let turnController = null;
|
|
66277
|
+
let pendingPlaybackTurn;
|
|
65986
66278
|
function openWs() {
|
|
65987
66279
|
try {
|
|
65988
66280
|
return createResponsesWsSession(apiKey, baseUrl);
|
|
@@ -66002,6 +66294,7 @@ function attach(options, pendingByCallId, call) {
|
|
|
66002
66294
|
config,
|
|
66003
66295
|
signal: ended.signal,
|
|
66004
66296
|
transcript,
|
|
66297
|
+
usage,
|
|
66005
66298
|
hangup() {
|
|
66006
66299
|
call.hangup();
|
|
66007
66300
|
},
|
|
@@ -66009,7 +66302,8 @@ function attach(options, pendingByCallId, call) {
|
|
|
66009
66302
|
if (!E1642.test(number)) {
|
|
66010
66303
|
throw new Error(`realtimeAgent: ctx.transfer('${number}') is not an E.164 phone number (e.g. '+15551234567').`);
|
|
66011
66304
|
}
|
|
66012
|
-
await call.transferToPhone(number);
|
|
66305
|
+
await call.transferToPhone(number, { legName: TRANSFER_LEG });
|
|
66306
|
+
transferredCallIds.add(call.id);
|
|
66013
66307
|
}
|
|
66014
66308
|
};
|
|
66015
66309
|
const appendTranscript = (entry) => {
|
|
@@ -66021,6 +66315,8 @@ function attach(options, pendingByCallId, call) {
|
|
|
66021
66315
|
call.onEnded(() => {
|
|
66022
66316
|
ended.abort();
|
|
66023
66317
|
wsSession?.close();
|
|
66318
|
+
flushPendingPlaybackTurn();
|
|
66319
|
+
console.log(`[realtimeAgent] call usage inputTokens=${logValue(usage.inputTokens)} outputTokens=${logValue(usage.outputTokens)} audioSeconds=${logValue(usage.audioSeconds)}`);
|
|
66024
66320
|
invokeHook("onEnd", () => options.onEnd?.(ctx));
|
|
66025
66321
|
});
|
|
66026
66322
|
call.onInterrupted(() => {
|
|
@@ -66028,6 +66324,19 @@ function attach(options, pendingByCallId, call) {
|
|
|
66028
66324
|
wsSession?.cancel();
|
|
66029
66325
|
invokeHook("onBargeIn", () => options.onBargeIn?.(ctx));
|
|
66030
66326
|
});
|
|
66327
|
+
call.onPlaybackStart(() => {
|
|
66328
|
+
if (pendingPlaybackTurn && pendingPlaybackTurn.entry.playbackStartAt === void 0) {
|
|
66329
|
+
pendingPlaybackTurn.entry.playbackStartAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
66330
|
+
}
|
|
66331
|
+
});
|
|
66332
|
+
call.onPlaybackStop(({ cancelled }) => {
|
|
66333
|
+
if (!pendingPlaybackTurn)
|
|
66334
|
+
return;
|
|
66335
|
+
pendingPlaybackTurn.entry.playbackEndAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
66336
|
+
if (cancelled)
|
|
66337
|
+
pendingPlaybackTurn.entry.interrupted = true;
|
|
66338
|
+
flushPendingPlaybackTurn();
|
|
66339
|
+
});
|
|
66031
66340
|
async function callLlm(requestOptions, callbacks) {
|
|
66032
66341
|
if (wsUnavailable || wsFailed)
|
|
66033
66342
|
return streamResponses(requestOptions, callbacks);
|
|
@@ -66068,6 +66377,7 @@ function attach(options, pendingByCallId, call) {
|
|
|
66068
66377
|
error = err instanceof Error ? err.message : String(err);
|
|
66069
66378
|
}
|
|
66070
66379
|
}
|
|
66380
|
+
const latencyMs = Date.now() - start;
|
|
66071
66381
|
appendTranscript({
|
|
66072
66382
|
role: "tool",
|
|
66073
66383
|
text: toolCall.name,
|
|
@@ -66076,11 +66386,12 @@ function attach(options, pendingByCallId, call) {
|
|
|
66076
66386
|
args: toolCall.arguments,
|
|
66077
66387
|
result: result2,
|
|
66078
66388
|
error,
|
|
66079
|
-
latencyMs
|
|
66389
|
+
latencyMs
|
|
66080
66390
|
});
|
|
66081
|
-
return { result: result2, error };
|
|
66391
|
+
return { result: result2, error, latencyMs };
|
|
66082
66392
|
}
|
|
66083
|
-
async function converse(newInput, pendingCommit = []) {
|
|
66393
|
+
async function converse(newInput, pendingCommit = [], metrics = { turnStart: Date.now(), rounds: 0, toolMs: 0 }) {
|
|
66394
|
+
metrics.rounds += 1;
|
|
66084
66395
|
const controller = new AbortController();
|
|
66085
66396
|
turnController = controller;
|
|
66086
66397
|
const inFlight = [];
|
|
@@ -66100,7 +66411,11 @@ function attach(options, pendingByCallId, call) {
|
|
|
66100
66411
|
reasoningEffort: tuning.reasoningEffort,
|
|
66101
66412
|
verbosity: tuning.verbosity
|
|
66102
66413
|
}, {
|
|
66103
|
-
onSentence: (sentence) =>
|
|
66414
|
+
onSentence: (sentence) => {
|
|
66415
|
+
if (metrics.firstSentenceMs === void 0)
|
|
66416
|
+
metrics.firstSentenceMs = Date.now() - metrics.turnStart;
|
|
66417
|
+
call.send(sentence, { last: false });
|
|
66418
|
+
},
|
|
66104
66419
|
onToolCall: (toolCall) => {
|
|
66105
66420
|
inFlight.push({ call: toolCall, promise: runTool(toolCall) });
|
|
66106
66421
|
}
|
|
@@ -66109,16 +66424,22 @@ function attach(options, pendingByCallId, call) {
|
|
|
66109
66424
|
if (err instanceof StreamAbortedError) {
|
|
66110
66425
|
return;
|
|
66111
66426
|
}
|
|
66427
|
+
console.error("[realtimeAgent] voice-relay provider LLM turn failed:", err.message);
|
|
66112
66428
|
invokeHook("onError", () => options.onError?.({ message: err.message }, ctx));
|
|
66113
66429
|
return;
|
|
66114
66430
|
} finally {
|
|
66115
66431
|
if (turnController === controller)
|
|
66116
66432
|
turnController = null;
|
|
66117
66433
|
}
|
|
66434
|
+
if (result2.usage) {
|
|
66435
|
+
usage.inputTokens = (usage.inputTokens ?? 0) + (result2.usage.inputTokens ?? 0);
|
|
66436
|
+
usage.outputTokens = (usage.outputTokens ?? 0) + (result2.usage.outputTokens ?? 0);
|
|
66437
|
+
}
|
|
66118
66438
|
call.send("", { last: true });
|
|
66119
66439
|
const roundItems = [...newInput];
|
|
66440
|
+
let agentEntry;
|
|
66120
66441
|
if (result2.text) {
|
|
66121
|
-
|
|
66442
|
+
agentEntry = { role: "agent", text: result2.text, timestamp: (/* @__PURE__ */ new Date()).toISOString() };
|
|
66122
66443
|
roundItems.push({ role: "assistant", content: result2.text });
|
|
66123
66444
|
}
|
|
66124
66445
|
if (inFlight.length === 0) {
|
|
@@ -66126,9 +66447,14 @@ function attach(options, pendingByCallId, call) {
|
|
|
66126
66447
|
previousResponseId = result2.responseId ?? previousResponseId;
|
|
66127
66448
|
else
|
|
66128
66449
|
statelessHistory.push(...pendingCommit, ...roundItems);
|
|
66450
|
+
logTurnLatency(metrics, agentEntry);
|
|
66129
66451
|
return;
|
|
66130
66452
|
}
|
|
66453
|
+
if (agentEntry)
|
|
66454
|
+
appendTranscript(agentEntry);
|
|
66131
66455
|
const outcomes = await Promise.all(inFlight.map((f) => f.promise));
|
|
66456
|
+
for (const outcome of outcomes)
|
|
66457
|
+
metrics.toolMs += outcome.latencyMs;
|
|
66132
66458
|
if (controller.signal.aborted) {
|
|
66133
66459
|
return;
|
|
66134
66460
|
}
|
|
@@ -66145,7 +66471,31 @@ function attach(options, pendingByCallId, call) {
|
|
|
66145
66471
|
output: JSON.stringify(outcome.error ? { error: outcome.error } : outcome.result ?? {})
|
|
66146
66472
|
};
|
|
66147
66473
|
});
|
|
66148
|
-
await converse(nextInput, chainingEnabled ? [] : [...pendingCommit, ...roundItems]);
|
|
66474
|
+
await converse(nextInput, chainingEnabled ? [] : [...pendingCommit, ...roundItems], metrics);
|
|
66475
|
+
}
|
|
66476
|
+
function logTurnLatency(metrics, agentEntry) {
|
|
66477
|
+
const totalMs = Date.now() - metrics.turnStart;
|
|
66478
|
+
if (agentEntry) {
|
|
66479
|
+
agentEntry.latencyMs = metrics.firstSentenceMs;
|
|
66480
|
+
agentEntry.totalMs = totalMs;
|
|
66481
|
+
appendTranscript(agentEntry);
|
|
66482
|
+
pendingPlaybackTurn = { entry: agentEntry, metrics, totalMs };
|
|
66483
|
+
return;
|
|
66484
|
+
}
|
|
66485
|
+
console.log(turnLatencyLine(metrics, totalMs, void 0));
|
|
66486
|
+
}
|
|
66487
|
+
function flushPendingPlaybackTurn() {
|
|
66488
|
+
if (!pendingPlaybackTurn)
|
|
66489
|
+
return;
|
|
66490
|
+
const { entry, metrics, totalMs } = pendingPlaybackTurn;
|
|
66491
|
+
pendingPlaybackTurn = void 0;
|
|
66492
|
+
console.log(turnLatencyLine(metrics, totalMs, entry));
|
|
66493
|
+
}
|
|
66494
|
+
function turnLatencyLine(metrics, totalMs, entry) {
|
|
66495
|
+
const firstAgentChunkAtMs = metrics.firstSentenceMs !== void 0 ? metrics.turnStart + metrics.firstSentenceMs : void 0;
|
|
66496
|
+
const delay = playbackDelayMs(firstAgentChunkAtMs, entry?.playbackStartAt);
|
|
66497
|
+
const audio = audioMs(entry?.playbackStartAt, entry?.playbackEndAt);
|
|
66498
|
+
return `[realtimeAgent] turn latency firstSentenceMs=${logValue(metrics.firstSentenceMs)} totalMs=${totalMs} modelRounds=${metrics.rounds} toolMs=${metrics.toolMs} playbackDelayMs=${logValue(delay)} audioMs=${logValue(audio)}`;
|
|
66149
66499
|
}
|
|
66150
66500
|
call.onSpeech((text) => {
|
|
66151
66501
|
appendTranscript({ role: "user", text, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
@@ -66153,10 +66503,59 @@ function attach(options, pendingByCallId, call) {
|
|
|
66153
66503
|
});
|
|
66154
66504
|
}
|
|
66155
66505
|
|
|
66506
|
+
// ../runtime-shared/dist/ai/realtime/vad.js
|
|
66507
|
+
var DEFAULT_THRESHOLD = 500;
|
|
66508
|
+
var DEFAULT_ATTACK_FRAMES = 2;
|
|
66509
|
+
var DEFAULT_HANGOVER_FRAMES = 20;
|
|
66510
|
+
function pcm16Rms2(pcm) {
|
|
66511
|
+
if (pcm.length < 2)
|
|
66512
|
+
return 0;
|
|
66513
|
+
let sumSquares = 0;
|
|
66514
|
+
const samples = pcm.length >> 1;
|
|
66515
|
+
for (let i = 0; i < samples; i++) {
|
|
66516
|
+
const sample = pcm.readInt16LE(i * 2);
|
|
66517
|
+
sumSquares += sample * sample;
|
|
66518
|
+
}
|
|
66519
|
+
return Math.sqrt(sumSquares / samples);
|
|
66520
|
+
}
|
|
66521
|
+
function createEnergyVad(options = {}) {
|
|
66522
|
+
const threshold = options.threshold ?? DEFAULT_THRESHOLD;
|
|
66523
|
+
const attackFrames = options.attackFrames ?? DEFAULT_ATTACK_FRAMES;
|
|
66524
|
+
const hangoverFrames = options.hangoverFrames ?? DEFAULT_HANGOVER_FRAMES;
|
|
66525
|
+
let speaking = false;
|
|
66526
|
+
let loudRun = 0;
|
|
66527
|
+
let quietRun = 0;
|
|
66528
|
+
return {
|
|
66529
|
+
get speaking() {
|
|
66530
|
+
return speaking;
|
|
66531
|
+
},
|
|
66532
|
+
push(pcm) {
|
|
66533
|
+
const loud = pcm16Rms2(pcm) >= threshold;
|
|
66534
|
+
if (loud) {
|
|
66535
|
+
loudRun++;
|
|
66536
|
+
quietRun = 0;
|
|
66537
|
+
} else {
|
|
66538
|
+
quietRun++;
|
|
66539
|
+
loudRun = 0;
|
|
66540
|
+
}
|
|
66541
|
+
if (!speaking && loud && loudRun >= attackFrames) {
|
|
66542
|
+
speaking = true;
|
|
66543
|
+
return "start";
|
|
66544
|
+
}
|
|
66545
|
+
if (speaking && !loud && quietRun >= hangoverFrames) {
|
|
66546
|
+
speaking = false;
|
|
66547
|
+
return "end";
|
|
66548
|
+
}
|
|
66549
|
+
return void 0;
|
|
66550
|
+
}
|
|
66551
|
+
};
|
|
66552
|
+
}
|
|
66553
|
+
|
|
66156
66554
|
// ../runtime-shared/dist/ai/realtime/agent.js
|
|
66157
66555
|
var BRIDGE = "bridge";
|
|
66158
66556
|
var CALLER_LEG2 = "caller";
|
|
66159
66557
|
var STREAM_LEG2 = "stream";
|
|
66558
|
+
var TRANSFER_LEG2 = "transfer-1";
|
|
66160
66559
|
var CALL_ID_HEADER = "x-realtime-agent-call-id";
|
|
66161
66560
|
var AUDIO_SAMPLE_RATES = { telephony: 8e3, wideband: 16e3 };
|
|
66162
66561
|
function sendStreamControl(ws, command) {
|
|
@@ -66174,19 +66573,20 @@ function resolveMaxDuration(context) {
|
|
|
66174
66573
|
var FIRST_FRAME_DEADLINE_MS = 2e3;
|
|
66175
66574
|
var MAX_UNAUTHENTICATED_SOCKETS2 = 32;
|
|
66176
66575
|
async function resolvePerCallOptions(options, call, context, ctx) {
|
|
66177
|
-
const [prompt, greeting, voice, transferTo] = await Promise.all([
|
|
66576
|
+
const [prompt, greeting, voice, transferTo, language] = await Promise.all([
|
|
66178
66577
|
resolvePerCallValue(options.prompt, call, context),
|
|
66179
66578
|
resolvePerCallValue(options.greeting, call, context),
|
|
66180
66579
|
resolvePerCallValue(options.voice, call, context),
|
|
66181
|
-
resolvePerCallValue(options.transferTo, call, context)
|
|
66580
|
+
resolvePerCallValue(options.transferTo, call, context),
|
|
66581
|
+
resolvePerCallValue(options.language, call, context)
|
|
66182
66582
|
]);
|
|
66183
66583
|
const { transferTo: _transferTo, tools: authorTools, ...rest } = options;
|
|
66184
|
-
const tools = mergeTools(authorTools ?? [], builtInTools(options.hangup ?? true, transferTo, ctx));
|
|
66185
|
-
let resolvedPrompt = prompt;
|
|
66584
|
+
const tools = mergeTools(authorTools ?? [], builtInTools(options.hangup ?? true, nonBlank(transferTo), ctx));
|
|
66585
|
+
let resolvedPrompt = currentDateTimePreamble(options.timezone) + prompt;
|
|
66186
66586
|
if (offersHangup(tools)) {
|
|
66187
66587
|
resolvedPrompt += options.provider === "openai" ? DELEGATED_CALL_TERMINATION_INSTRUCTIONS : CALL_TERMINATION_INSTRUCTIONS;
|
|
66188
66588
|
}
|
|
66189
|
-
return { ...rest, prompt: resolvedPrompt, greeting, voice, tools };
|
|
66589
|
+
return { ...rest, prompt: resolvedPrompt, greeting, voice, tools, language: language ?? DEFAULT_LANGUAGE };
|
|
66190
66590
|
}
|
|
66191
66591
|
function realtimeAgent(options) {
|
|
66192
66592
|
if (!options.provider) {
|
|
@@ -66201,6 +66601,7 @@ function realtimeAgent(options) {
|
|
|
66201
66601
|
const adapter2 = getRealtimeAdapter(options.provider);
|
|
66202
66602
|
let savedContext;
|
|
66203
66603
|
const pendingSessions = /* @__PURE__ */ new Map();
|
|
66604
|
+
const transferredCallIds = /* @__PURE__ */ new Set();
|
|
66204
66605
|
function deletePendingSession(token) {
|
|
66205
66606
|
const session = pendingSessions.get(token);
|
|
66206
66607
|
if (!session)
|
|
@@ -66248,15 +66649,55 @@ function realtimeAgent(options) {
|
|
|
66248
66649
|
}
|
|
66249
66650
|
let vendorSession;
|
|
66250
66651
|
let ended = false;
|
|
66652
|
+
let transferred = false;
|
|
66251
66653
|
let heartbeat;
|
|
66252
66654
|
const lifecycle = new AbortController();
|
|
66253
66655
|
const transcript = [];
|
|
66656
|
+
const usage = {};
|
|
66657
|
+
const callConnectedAtMs = Date.now();
|
|
66658
|
+
let lastUserTurnAt;
|
|
66659
|
+
let firstAudioAtMs;
|
|
66660
|
+
let selfBytesSentForTurn = 0;
|
|
66661
|
+
let bytesPerMs = 8e3 * 2 / 1e3;
|
|
66662
|
+
const vad = createEnergyVad();
|
|
66663
|
+
let pendingSpeechStartAt;
|
|
66664
|
+
let pendingSpeechEndAt;
|
|
66665
|
+
let speechEndFromProvider = false;
|
|
66666
|
+
let currentAgentEntry;
|
|
66667
|
+
let pendingAgentPlayback = {};
|
|
66668
|
+
let pendingStreamLog;
|
|
66669
|
+
const streamTurnLine = (totalMs, firstAudioAtMs_, entry) => {
|
|
66670
|
+
const delay = playbackDelayMs(firstAudioAtMs_, entry.playbackStartAt);
|
|
66671
|
+
const audio = audioMs(entry.playbackStartAt, entry.playbackEndAt);
|
|
66672
|
+
return `[realtimeAgent] turn latency totalMs=${logValue(totalMs)} playbackDelayMs=${logValue(delay)} audioMs=${logValue(audio)} delegationMs=${logValue(entry.delegationMs)}`;
|
|
66673
|
+
};
|
|
66674
|
+
const applySelfPlaybackFallback = (entry, cutShort) => {
|
|
66675
|
+
if (firstAudioAtMs === void 0)
|
|
66676
|
+
return;
|
|
66677
|
+
entry.playbackStartAt ??= new Date(firstAudioAtMs).toISOString();
|
|
66678
|
+
if (entry.playbackEndAt === void 0) {
|
|
66679
|
+
const endMs = cutShort ? Date.now() : firstAudioAtMs + selfBytesSentForTurn / bytesPerMs;
|
|
66680
|
+
entry.playbackEndAt = new Date(endMs).toISOString();
|
|
66681
|
+
if (cutShort)
|
|
66682
|
+
entry.interrupted = true;
|
|
66683
|
+
}
|
|
66684
|
+
};
|
|
66685
|
+
const flushPendingStreamLog = () => {
|
|
66686
|
+
if (!pendingStreamLog)
|
|
66687
|
+
return;
|
|
66688
|
+
const { entry, totalMs, firstAudioAtMs: firstAudioAtMs_ } = pendingStreamLog;
|
|
66689
|
+
pendingStreamLog = void 0;
|
|
66690
|
+
currentAgentEntry = void 0;
|
|
66691
|
+
applySelfPlaybackFallback(entry, false);
|
|
66692
|
+
console.log(streamTurnLine(totalMs, firstAudioAtMs_, entry));
|
|
66693
|
+
};
|
|
66254
66694
|
const ctx = {
|
|
66255
66695
|
callId,
|
|
66256
66696
|
storage: context.storage,
|
|
66257
66697
|
config,
|
|
66258
66698
|
signal: lifecycle.signal,
|
|
66259
66699
|
transcript,
|
|
66700
|
+
usage,
|
|
66260
66701
|
hangup() {
|
|
66261
66702
|
setTimeout(() => {
|
|
66262
66703
|
if (ws.readyState === ws.OPEN)
|
|
@@ -66269,8 +66710,12 @@ function realtimeAgent(options) {
|
|
|
66269
66710
|
}
|
|
66270
66711
|
await context.voice.transferToPhone(callId, number, {
|
|
66271
66712
|
liveLeg: CALLER_LEG2,
|
|
66713
|
+
legName: TRANSFER_LEG2,
|
|
66272
66714
|
call: { call }
|
|
66273
66715
|
});
|
|
66716
|
+
transferred = true;
|
|
66717
|
+
if (callId)
|
|
66718
|
+
transferredCallIds.add(callId);
|
|
66274
66719
|
await context.voice.hangup({ callId }, STREAM_LEG2).catch((err) => console.error("[realtimeAgent] ending the STREAM leg after transfer failed:", err.message));
|
|
66275
66720
|
if (ws.readyState === ws.OPEN)
|
|
66276
66721
|
ws.close(1e3, "Transferred");
|
|
@@ -66284,6 +66729,7 @@ function realtimeAgent(options) {
|
|
|
66284
66729
|
if (ended)
|
|
66285
66730
|
return;
|
|
66286
66731
|
ended = true;
|
|
66732
|
+
flushPendingStreamLog();
|
|
66287
66733
|
lifecycle.abort();
|
|
66288
66734
|
if (heartbeat !== void 0)
|
|
66289
66735
|
clearInterval(heartbeat);
|
|
@@ -66291,6 +66737,11 @@ function realtimeAgent(options) {
|
|
|
66291
66737
|
adapter2.close(vendorSession);
|
|
66292
66738
|
if (ws.readyState === ws.OPEN)
|
|
66293
66739
|
ws.close();
|
|
66740
|
+
if (!transferred) {
|
|
66741
|
+
await context.voice?.hangup({ callId }, CALLER_LEG2).catch((err) => console.error("[realtimeAgent] ending the caller leg failed (may already be gone):", err.message));
|
|
66742
|
+
}
|
|
66743
|
+
usage.audioSeconds ??= (Date.now() - callConnectedAtMs) / 1e3;
|
|
66744
|
+
console.log(`[realtimeAgent] call usage inputTokens=${logValue(usage.inputTokens)} outputTokens=${logValue(usage.outputTokens)} audioSeconds=${logValue(usage.audioSeconds)}`);
|
|
66294
66745
|
try {
|
|
66295
66746
|
await options.onEnd?.(ctx);
|
|
66296
66747
|
} catch (err) {
|
|
@@ -66299,6 +66750,10 @@ function realtimeAgent(options) {
|
|
|
66299
66750
|
};
|
|
66300
66751
|
const callbacks = {
|
|
66301
66752
|
onAudioOut(pcm) {
|
|
66753
|
+
if (firstAudioAtMs === void 0 && lastUserTurnAt !== void 0)
|
|
66754
|
+
firstAudioAtMs = Date.now();
|
|
66755
|
+
if (firstAudioAtMs !== void 0)
|
|
66756
|
+
selfBytesSentForTurn += pcm.length;
|
|
66302
66757
|
if (ws.readyState === ws.OPEN)
|
|
66303
66758
|
ws.send(pcm);
|
|
66304
66759
|
},
|
|
@@ -66315,15 +66770,81 @@ function realtimeAgent(options) {
|
|
|
66315
66770
|
});
|
|
66316
66771
|
},
|
|
66317
66772
|
onTurn(turn) {
|
|
66318
|
-
|
|
66773
|
+
const entry = { role: turn.role, text: turn.text, timestamp: turn.timestamp };
|
|
66774
|
+
if (turn.role === "user") {
|
|
66775
|
+
flushPendingStreamLog();
|
|
66776
|
+
lastUserTurnAt = Date.now();
|
|
66777
|
+
firstAudioAtMs = void 0;
|
|
66778
|
+
entry.speechStartAt = turn.speechStartAt ?? pendingSpeechStartAt;
|
|
66779
|
+
entry.speechEndAt = turn.speechEndAt ?? pendingSpeechEndAt;
|
|
66780
|
+
pendingSpeechStartAt = void 0;
|
|
66781
|
+
pendingSpeechEndAt = void 0;
|
|
66782
|
+
speechEndFromProvider = false;
|
|
66783
|
+
} else if (turn.role === "agent" && lastUserTurnAt !== void 0) {
|
|
66784
|
+
entry.totalMs = Date.now() - lastUserTurnAt;
|
|
66785
|
+
lastUserTurnAt = void 0;
|
|
66786
|
+
entry.delegationMs = turn.delegationMs;
|
|
66787
|
+
entry.playbackStartAt = turn.playbackStartAt ?? pendingAgentPlayback.startAt;
|
|
66788
|
+
if (turn.playbackEndAt) {
|
|
66789
|
+
entry.playbackEndAt = turn.playbackEndAt;
|
|
66790
|
+
} else if (pendingAgentPlayback.endAt) {
|
|
66791
|
+
entry.playbackEndAt = pendingAgentPlayback.endAt;
|
|
66792
|
+
if (pendingAgentPlayback.interrupted)
|
|
66793
|
+
entry.interrupted = true;
|
|
66794
|
+
}
|
|
66795
|
+
const alreadyResolved = entry.playbackEndAt !== void 0;
|
|
66796
|
+
pendingAgentPlayback = {};
|
|
66797
|
+
if (alreadyResolved) {
|
|
66798
|
+
console.log(streamTurnLine(entry.totalMs, firstAudioAtMs, entry));
|
|
66799
|
+
} else {
|
|
66800
|
+
currentAgentEntry = entry;
|
|
66801
|
+
pendingStreamLog = { entry, totalMs: entry.totalMs, firstAudioAtMs };
|
|
66802
|
+
}
|
|
66803
|
+
}
|
|
66804
|
+
appendTranscript(entry);
|
|
66805
|
+
},
|
|
66806
|
+
onSpeechStart() {
|
|
66807
|
+
pendingSpeechStartAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
66808
|
+
},
|
|
66809
|
+
onSpeechEnd() {
|
|
66810
|
+
pendingSpeechEndAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
66811
|
+
speechEndFromProvider = true;
|
|
66812
|
+
},
|
|
66813
|
+
onPlaybackStart() {
|
|
66814
|
+
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
66815
|
+
if (currentAgentEntry)
|
|
66816
|
+
currentAgentEntry.playbackStartAt ??= at;
|
|
66817
|
+
else
|
|
66818
|
+
pendingAgentPlayback.startAt ??= at;
|
|
66819
|
+
},
|
|
66820
|
+
onPlaybackStop({ cancelled }) {
|
|
66821
|
+
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
66822
|
+
if (currentAgentEntry) {
|
|
66823
|
+
currentAgentEntry.playbackEndAt = at;
|
|
66824
|
+
if (cancelled)
|
|
66825
|
+
currentAgentEntry.interrupted = true;
|
|
66826
|
+
flushPendingStreamLog();
|
|
66827
|
+
} else {
|
|
66828
|
+
pendingAgentPlayback.endAt = at;
|
|
66829
|
+
if (cancelled)
|
|
66830
|
+
pendingAgentPlayback.interrupted = true;
|
|
66831
|
+
}
|
|
66319
66832
|
},
|
|
66320
66833
|
onBargeIn() {
|
|
66321
66834
|
sendStreamControl(ws, "clear");
|
|
66322
66835
|
if (vendorSession !== void 0)
|
|
66323
66836
|
adapter2.clear(vendorSession);
|
|
66837
|
+
if (currentAgentEntry) {
|
|
66838
|
+
applySelfPlaybackFallback(currentAgentEntry, true);
|
|
66839
|
+
flushPendingStreamLog();
|
|
66840
|
+
}
|
|
66324
66841
|
invokeHook("onBargeIn", () => options.onBargeIn?.(ctx));
|
|
66325
66842
|
},
|
|
66843
|
+
onUsage(reported) {
|
|
66844
|
+
Object.assign(usage, reported);
|
|
66845
|
+
},
|
|
66326
66846
|
onError(error) {
|
|
66847
|
+
console.error("[realtimeAgent] vendor reported an error:", error.message, error.raw ?? "");
|
|
66327
66848
|
invokeHook("onError", () => options.onError?.(error, ctx));
|
|
66328
66849
|
},
|
|
66329
66850
|
onClose() {
|
|
@@ -66336,6 +66857,7 @@ function realtimeAgent(options) {
|
|
|
66336
66857
|
resolvePerCallOptions(options, call, context, ctx).then((resolved) => {
|
|
66337
66858
|
if (ended || lifecycle.signal.aborted)
|
|
66338
66859
|
return void 0;
|
|
66860
|
+
bytesPerMs = sinchRate(resolved) * 2 / 1e3;
|
|
66339
66861
|
return adapter2.connect(resolved, ctx, callbacks, lifecycle.signal);
|
|
66340
66862
|
}).then((session) => {
|
|
66341
66863
|
if (session === void 0)
|
|
@@ -66350,6 +66872,11 @@ function realtimeAgent(options) {
|
|
|
66350
66872
|
ws.on("message", (raw, isBinary) => {
|
|
66351
66873
|
if (!isBinary)
|
|
66352
66874
|
return;
|
|
66875
|
+
const vadEvent = vad.push(raw);
|
|
66876
|
+
if (vadEvent === "start")
|
|
66877
|
+
pendingSpeechStartAt ??= (/* @__PURE__ */ new Date()).toISOString();
|
|
66878
|
+
else if (vadEvent === "end" && !speechEndFromProvider)
|
|
66879
|
+
pendingSpeechEndAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
66353
66880
|
adapter2.sendAudio(session, raw);
|
|
66354
66881
|
});
|
|
66355
66882
|
}).catch((err) => {
|
|
@@ -66473,19 +67000,26 @@ function realtimeAgent(options) {
|
|
|
66473
67000
|
callName: STREAM_LEG2,
|
|
66474
67001
|
maxDuration: resolveMaxDuration(context),
|
|
66475
67002
|
onAnswer: (c) => c.bridgeCall(BRIDGE),
|
|
66476
|
-
endOnHangup
|
|
67003
|
+
// No `endOnHangup`: once the STREAM leg is answered, ending it (agent hangup, vendor
|
|
67004
|
+
// close, transfer) must not cascade into hanging up the caller's own leg — the runtime
|
|
67005
|
+
// ends the caller explicitly from the session-end path instead (see `end()`). Failure
|
|
67006
|
+
// to ever connect (busy/reject/timeout/failure) is unaffected and still ends the caller
|
|
67007
|
+
// via `endOnFailure` — nothing was dialled yet for the caller to be bridged to.
|
|
66477
67008
|
endOnFailure: CALLER_LEG2
|
|
66478
67009
|
}).build(),
|
|
66479
67010
|
onHangup: [{ command: "hangup", callName: STREAM_LEG2 }]
|
|
66480
67011
|
};
|
|
66481
67012
|
};
|
|
66482
|
-
const handleCallCompleted = (call) => {
|
|
67013
|
+
const handleCallCompleted = (call, _builder, context) => {
|
|
66483
67014
|
const callId = String(call.callId ?? "");
|
|
66484
67015
|
if (callId) {
|
|
66485
67016
|
for (const [token, pending] of pendingSessions) {
|
|
66486
67017
|
if (String(pending.call.callId ?? "") === callId)
|
|
66487
67018
|
deletePendingSession(token);
|
|
66488
67019
|
}
|
|
67020
|
+
if (transferredCallIds.delete(callId)) {
|
|
67021
|
+
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));
|
|
67022
|
+
}
|
|
66489
67023
|
}
|
|
66490
67024
|
};
|
|
66491
67025
|
const voiceWebhook = onCall({ incoming: connect, completed: handleCallCompleted });
|
|
@@ -75279,7 +75813,6 @@ export {
|
|
|
75279
75813
|
toWebhookRequest,
|
|
75280
75814
|
toCallBody,
|
|
75281
75815
|
toWebhookBody,
|
|
75282
|
-
DEFAULT_TRANSFER_LEG,
|
|
75283
75816
|
buildTransferCommands,
|
|
75284
75817
|
resolveHandlerKey,
|
|
75285
75818
|
resolveWebhookName,
|
|
@@ -75690,4 +76223,4 @@ serve-static/index.js:
|
|
|
75690
76223
|
* MIT Licensed
|
|
75691
76224
|
*)
|
|
75692
76225
|
*/
|
|
75693
|
-
//# sourceMappingURL=chunk-
|
|
76226
|
+
//# sourceMappingURL=chunk-W3R4GR3E.js.map
|