@memberjunction/realtime-widget 6.2.0 → 6.3.0-edge.0
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/dist/embed/chunks/UserViewEngine-SLKE6LBB.js +7 -0
- package/dist/embed/chunks/{chunk-DIDGGUK7.js → chunk-3SGPPDAR.js} +69 -4
- package/dist/embed/chunks/{chunk-LAKO46S5.js → chunk-CFNJUN5T.js} +7625 -1004
- package/dist/embed/chunks/{chunk-JOGHPRST.js → chunk-MIJGWKAT.js} +1478 -260
- package/dist/embed/chunks/{chunk-CLSWXKRZ.js → chunk-P7OZVUW4.js} +11 -11
- package/dist/embed/chunks/{chunk-DAGQZKVY.js → chunk-PYHZMJHO.js} +10139 -4450
- package/dist/embed/chunks/{dist-FCDQGP67.js → dist-PBT4EYQL.js} +5 -5
- package/dist/embed/chunks/{guest-tool-relay-6VPMNSBN.js → guest-tool-relay-US5DJL75.js} +6 -6
- package/dist/embed/chunks/{guest-voice-mint-A4TEME65.js → guest-voice-mint-VBOHRPWJ.js} +6 -6
- package/dist/embed/chunks/{realtime-voice-controller-76SVXCXJ.js → realtime-voice-controller-4ZREZIRH.js} +2596 -182
- package/dist/embed/chunks/{runtime-widget-transport-KJRO54TC.js → runtime-widget-transport-JX4WL4BP.js} +10 -10
- package/dist/embed/mj-widget.js +6 -6
- package/package.json +9 -9
- package/dist/embed/chunks/UserViewEngine-ELH6XPEL.js +0 -7
|
@@ -2,38 +2,52 @@ import {
|
|
|
2
2
|
VoiceAbuseGuard
|
|
3
3
|
} from "./chunk-S3LX5KYE.js";
|
|
4
4
|
import {
|
|
5
|
+
AsConfigRecord,
|
|
6
|
+
ClampSessionSecondsValue,
|
|
7
|
+
DEFAULT_CREDENTIAL_REFRESH_LEAD_MS,
|
|
5
8
|
DEFAULT_REALTIME_AUDIO_TRACKS,
|
|
9
|
+
DEFAULT_REALTIME_RECONNECT_BUFFER_SECONDS,
|
|
10
|
+
DEFAULT_REALTIME_SOFT_RECONNECT_WINDOW_SECONDS,
|
|
11
|
+
ExtractRealtimeTimingConfig,
|
|
6
12
|
ExtractToolSchedulingHint,
|
|
7
13
|
Fmp4PieceToVideoFrame,
|
|
8
14
|
Fmp4VideoSeconds,
|
|
9
15
|
IsPcmAudioMimeType,
|
|
10
16
|
IsTranscriptContinuation,
|
|
17
|
+
MapRealtimeUsageModalityDetail,
|
|
11
18
|
ParseDurationToMs,
|
|
12
19
|
REALTIME_DEFAULT_INBOUND_VIDEO_RATE,
|
|
13
20
|
REALTIME_RELAY_TIME_LIMIT_CLOSE_CODE,
|
|
21
|
+
REALTIME_RESUMPTION_MAX_RETRY_DELAY_MS,
|
|
22
|
+
REALTIME_RESUMPTION_PREPARE_TIMEOUT_MS,
|
|
14
23
|
ReadFmp4Init,
|
|
15
24
|
RealtimeConnectionSetup,
|
|
25
|
+
RealtimeConversationMemory,
|
|
16
26
|
RealtimeDiagLog,
|
|
17
27
|
RealtimeMinVideoFrameSpacingMs,
|
|
18
|
-
|
|
28
|
+
RealtimeReconnectController,
|
|
19
29
|
RealtimeToolBatchBarrier,
|
|
20
30
|
RealtimeTrackKey,
|
|
21
31
|
RealtimeVideoFrameIntervalMs,
|
|
32
|
+
RenderLateToolResultNote,
|
|
33
|
+
RenderRealtimeMemorySeed,
|
|
34
|
+
RenderRealtimeMemorySeedAsContextNote,
|
|
22
35
|
ResolveRequestedTracks,
|
|
23
36
|
ResolveResponseDoneUsage,
|
|
24
37
|
ScaleRealtimeVideoFrame,
|
|
38
|
+
ScrubRealtimeTimingConfigKeys,
|
|
25
39
|
SniffFmp4Piece,
|
|
26
40
|
VideoSourceSeenNote,
|
|
27
41
|
VideoSourceTurnedOffNote,
|
|
28
42
|
VideoSourceTurnedOnNote
|
|
29
|
-
} from "./chunk-
|
|
43
|
+
} from "./chunk-MIJGWKAT.js";
|
|
30
44
|
import {
|
|
31
45
|
BaseSingleton,
|
|
32
46
|
MJGlobal,
|
|
33
47
|
RegisterClass,
|
|
34
48
|
__commonJS,
|
|
35
49
|
__toESM
|
|
36
|
-
} from "./chunk-
|
|
50
|
+
} from "./chunk-3SGPPDAR.js";
|
|
37
51
|
|
|
38
52
|
// ../../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js
|
|
39
53
|
var require_retry_operation = __commonJS({
|
|
@@ -517,12 +531,13 @@ var RealtimeAudioMeter = class _RealtimeAudioMeter {
|
|
|
517
531
|
|
|
518
532
|
// ../../AI/RealtimeClient/dist/generic/baseRealtimeClient.js
|
|
519
533
|
var REQUESTED_TRACKS_SESSION_KEY = "requestedTracks";
|
|
534
|
+
var DEFAULT_USER_SPEECH_ACTIVE_LEVEL_THRESHOLD = 0.02;
|
|
535
|
+
var SHARED_REFRESH_MAX_JOIN_AGE_MS = REALTIME_RESUMPTION_PREPARE_TIMEOUT_MS + REALTIME_RESUMPTION_MAX_RETRY_DELAY_MS;
|
|
520
536
|
function ToProviderSessionConfig(sessionConfig) {
|
|
521
|
-
|
|
522
|
-
return providerConfig;
|
|
537
|
+
return ScrubRealtimeTimingConfigKeys(sessionConfig, [REQUESTED_TRACKS_SESSION_KEY]);
|
|
523
538
|
}
|
|
524
539
|
var REALTIME_CLIENT_TIME_LIMIT_ERROR_CODE = "time-limit";
|
|
525
|
-
var BaseRealtimeClient = class {
|
|
540
|
+
var BaseRealtimeClient = class _BaseRealtimeClient {
|
|
526
541
|
constructor() {
|
|
527
542
|
this.tracks = [];
|
|
528
543
|
this.supportedTracks = null;
|
|
@@ -531,6 +546,59 @@ var BaseRealtimeClient = class {
|
|
|
531
546
|
this.outputAudioMeter = null;
|
|
532
547
|
this.remoteMediaStream = null;
|
|
533
548
|
this.remoteMediaStreamHandlers = [];
|
|
549
|
+
this.conversationMemory = new RealtimeConversationMemory({ Log: RealtimeDiagLog });
|
|
550
|
+
this.configuredReconnectBufferSeconds = DEFAULT_REALTIME_RECONNECT_BUFFER_SECONDS;
|
|
551
|
+
this.tokenRefreshCallback = null;
|
|
552
|
+
this.callsFromBeforeReseed = /* @__PURE__ */ new Set();
|
|
553
|
+
this.toolCallNamesById = /* @__PURE__ */ new Map();
|
|
554
|
+
this.inFlightToolCallIds = /* @__PURE__ */ new Set();
|
|
555
|
+
this.recordedToolCallIds = /* @__PURE__ */ new Set();
|
|
556
|
+
this.currentCredential = {
|
|
557
|
+
Kind: "token",
|
|
558
|
+
EphemeralToken: "",
|
|
559
|
+
ExpiresAt: "",
|
|
560
|
+
SessionConfig: {}
|
|
561
|
+
};
|
|
562
|
+
this.refreshedInActiveCycle = false;
|
|
563
|
+
this.reconnectCredentialRefresh = null;
|
|
564
|
+
this.connectionsOnCredential = 0;
|
|
565
|
+
this.connectionCredential = this.currentCredential;
|
|
566
|
+
this.reconnectController = new RealtimeReconnectController({
|
|
567
|
+
PrepareAttempt: (context) => this.prepareClientReconnectAttempt(context.Attempt),
|
|
568
|
+
Reconnect: (context) => this.executeClientReconnectAttempt(context),
|
|
569
|
+
// The network watch and the cycle's bookkeeping are handled here, not in the hooks, so a driver override cannot
|
|
570
|
+
// skip them.
|
|
571
|
+
OnReconnectFailed: (error, code) => {
|
|
572
|
+
this.endReconnectCycle();
|
|
573
|
+
this.onReconnectFailed(error, code);
|
|
574
|
+
},
|
|
575
|
+
OnReconnecting: (reason) => {
|
|
576
|
+
this.startWatchingNetworkOnline();
|
|
577
|
+
this.onReconnecting(reason);
|
|
578
|
+
},
|
|
579
|
+
OnReconnected: (usedNativeResumption) => {
|
|
580
|
+
this.endReconnectCycle();
|
|
581
|
+
this.onReconnected(usedNativeResumption);
|
|
582
|
+
},
|
|
583
|
+
ReturnToOldConnection: () => this.ResumeOnOldConnection(),
|
|
584
|
+
BuildSeed: () => {
|
|
585
|
+
const seed = this.conversationMemory.Seed();
|
|
586
|
+
return seed.Entries.length > 0 ? seed : null;
|
|
587
|
+
},
|
|
588
|
+
IsIdle: () => !this.isTurnActiveForReconnect(),
|
|
589
|
+
HoldsHardMove: () => this.holdsHardReconnectPoint(),
|
|
590
|
+
TrustsNativeResumption: () => this.TrustsNativeResumption,
|
|
591
|
+
RequiresPostTurnHandle: () => this.RequiresPostTurnResumptionHandle,
|
|
592
|
+
IsNetworkOnline: () => this.isHostNetworkOnline(),
|
|
593
|
+
Log: (msg) => RealtimeDiagLog(msg)
|
|
594
|
+
});
|
|
595
|
+
this.onNetworkOnline = () => {
|
|
596
|
+
this.reconnectController.NotifyNetworkOnline();
|
|
597
|
+
};
|
|
598
|
+
this.watchingNetworkOnline = false;
|
|
599
|
+
this.wasSpeaking = false;
|
|
600
|
+
this.toolResultSentWhileSpeaking = false;
|
|
601
|
+
this.lastEmittedState = null;
|
|
534
602
|
}
|
|
535
603
|
/**
|
|
536
604
|
* Established tracks on this session (tracks in the `'live'` state).
|
|
@@ -770,6 +838,34 @@ var BaseRealtimeClient = class {
|
|
|
770
838
|
console.warn(`[${this.constructor.name}] remote-stream handler threw:`, error);
|
|
771
839
|
}
|
|
772
840
|
}
|
|
841
|
+
/**
|
|
842
|
+
* Feeds an executed tool's result back to the model, correlated by `callID`, and ensures
|
|
843
|
+
* the model SPEAKS the result as soon as possible: immediately when idle, otherwise
|
|
844
|
+
* queued behind the in-flight response (e.g. a progress narration) so the trigger is
|
|
845
|
+
* never dropped by the provider.
|
|
846
|
+
*
|
|
847
|
+
* Template method: dispatches to {@link doSendToolResult} first (so the wire send happens
|
|
848
|
+
* before soft-window reconnect evaluation and rejected/unknown call IDs can return `false`),
|
|
849
|
+
* then records the result into {@link conversationMemory} via {@link recordToolResult}.
|
|
850
|
+
*
|
|
851
|
+
* @param callID The `CallID` from the originating {@link RealtimeClientToolCall}.
|
|
852
|
+
* @param outputJson The tool's result as a JSON-stringified string.
|
|
853
|
+
*/
|
|
854
|
+
SendToolResult(callID, outputJson) {
|
|
855
|
+
const accepted = this.doSendToolResult(callID, outputJson);
|
|
856
|
+
if (accepted === false) {
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
this.recordToolResult(callID, outputJson);
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Concrete driver implementation for sending a tool result on the wire.
|
|
863
|
+
* Return `false` if the `callID` was rejected/ignored (e.g. unknown or duplicate call ID)
|
|
864
|
+
* so {@link SendToolResult} skips recording it into conversation memory.
|
|
865
|
+
*/
|
|
866
|
+
doSendToolResult(_callID, _outputJson) {
|
|
867
|
+
throw new Error(`${this.constructor.name} must implement doSendToolResult(callID, outputJson)`);
|
|
868
|
+
}
|
|
773
869
|
// ── Handler registration ──────────────────────────────────────────────────
|
|
774
870
|
/**
|
|
775
871
|
* Registers the (single) transcript handler. Receives interim deltas (`IsFinal: false`)
|
|
@@ -869,22 +965,581 @@ var BaseRealtimeClient = class {
|
|
|
869
965
|
OnTrackStateChange(handler) {
|
|
870
966
|
this.trackHandler = handler;
|
|
871
967
|
}
|
|
968
|
+
/**
|
|
969
|
+
* Reads catalog-stamped timing and resumption settings from the typed fields of `config`, falling
|
|
970
|
+
* back to `config.SessionConfig` (`connectionMaxSeconds`, `sessionMaxSeconds`, `reconnectBufferSeconds`,
|
|
971
|
+
* `trustNativeResumption`), records the initial credential snapshot, and schedules proactive
|
|
972
|
+
* credential/relay refresh.
|
|
973
|
+
*/
|
|
974
|
+
ApplySessionConfigTiming(config) {
|
|
975
|
+
if (!this.IsReconnectCycleActive) {
|
|
976
|
+
this.reconnectController.Reset();
|
|
977
|
+
this.endReconnectCycle();
|
|
978
|
+
}
|
|
979
|
+
this.currentCredential = {
|
|
980
|
+
Kind: config.Transport === "relay" ? "relay" : "token",
|
|
981
|
+
EphemeralToken: config.EphemeralToken,
|
|
982
|
+
ExpiresAt: config.ExpiresAt,
|
|
983
|
+
...config.RelayUrl ? { RelayUrl: config.RelayUrl } : {},
|
|
984
|
+
SessionConfig: config.SessionConfig
|
|
985
|
+
};
|
|
986
|
+
this.connectionsOnCredential = 1;
|
|
987
|
+
this.connectionCredential = this.currentCredential;
|
|
988
|
+
const fromSessionConfig = ExtractRealtimeTimingConfig(config.SessionConfig);
|
|
989
|
+
this.applyTimingFields({
|
|
990
|
+
ConnectionMaxSeconds: config.ConnectionMaxSeconds ?? fromSessionConfig.ConnectionMaxSeconds,
|
|
991
|
+
SessionMaxSeconds: config.SessionMaxSeconds ?? config.MaxSessionSeconds ?? fromSessionConfig.SessionMaxSeconds,
|
|
992
|
+
ReconnectBufferSeconds: config.ReconnectBufferSeconds ?? fromSessionConfig.ReconnectBufferSeconds,
|
|
993
|
+
TrustNativeResumption: config.TrustNativeResumption ?? fromSessionConfig.TrustNativeResumption
|
|
994
|
+
});
|
|
995
|
+
this.scheduleCredentialRefresh();
|
|
996
|
+
}
|
|
997
|
+
/** Records each timing setting that is present; an absent one keeps the client's current value. */
|
|
998
|
+
applyTimingFields(timing) {
|
|
999
|
+
if (timing.ConnectionMaxSeconds !== void 0) {
|
|
1000
|
+
this.configuredCallDurationSeconds = timing.ConnectionMaxSeconds;
|
|
1001
|
+
}
|
|
1002
|
+
if (timing.SessionMaxSeconds !== void 0) {
|
|
1003
|
+
this.configuredSessionMaxSeconds = timing.SessionMaxSeconds;
|
|
1004
|
+
}
|
|
1005
|
+
if (timing.ReconnectBufferSeconds !== void 0) {
|
|
1006
|
+
this.configuredReconnectBufferSeconds = timing.ReconnectBufferSeconds;
|
|
1007
|
+
}
|
|
1008
|
+
if (timing.TrustNativeResumption !== void 0) {
|
|
1009
|
+
this.configuredTrustNativeResumption = timing.TrustNativeResumption;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
/**
|
|
1013
|
+
* Optional runtime ceiling override (e.g. Gemini's 120s ceiling when uncompressed video is active).
|
|
1014
|
+
* Narrowed against `DefaultCallDurationSeconds` and `configuredCallDurationSeconds` via `ClampSessionSecondsValue`.
|
|
1015
|
+
*/
|
|
1016
|
+
get RuntimeCallDurationSeconds() {
|
|
1017
|
+
return void 0;
|
|
1018
|
+
}
|
|
1019
|
+
/** Driver fallback connection ceiling in seconds when model metadata omits `connectionMaxSeconds`. */
|
|
1020
|
+
get DefaultCallDurationSeconds() {
|
|
1021
|
+
return void 0;
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* Effective connection ceiling in seconds. Metadata and runtime caps narrow the driver's
|
|
1025
|
+
* provider ceiling (`ClampSessionSecondsValue(DefaultCallDurationSeconds, RuntimeCallDurationSeconds, configuredCallDurationSeconds)`),
|
|
1026
|
+
* never widen it.
|
|
1027
|
+
*/
|
|
1028
|
+
get CallDurationSeconds() {
|
|
1029
|
+
return ClampSessionSecondsValue(this.DefaultCallDurationSeconds, this.RuntimeCallDurationSeconds, this.configuredCallDurationSeconds);
|
|
1030
|
+
}
|
|
1031
|
+
/** Seconds before {@link CallDurationSeconds} when the reconnect buffer window opens. */
|
|
1032
|
+
get ReconnectBufferSeconds() {
|
|
1033
|
+
return this.configuredReconnectBufferSeconds;
|
|
1034
|
+
}
|
|
1035
|
+
/** Whether native provider resumption is trusted on the first reconnect attempt. */
|
|
1036
|
+
get TrustsNativeResumption() {
|
|
1037
|
+
return this.configuredTrustNativeResumption ?? this.DefaultTrustsNativeResumption;
|
|
1038
|
+
}
|
|
1039
|
+
get DefaultTrustsNativeResumption() {
|
|
1040
|
+
return false;
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Whether this driver's provider emits a fresh resumable handle shortly after each `turnComplete`
|
|
1044
|
+
* (Gemini / Vertex AI Live), so planned moves wait for that post-turn handle.
|
|
1045
|
+
*/
|
|
1046
|
+
get RequiresPostTurnResumptionHandle() {
|
|
1047
|
+
return false;
|
|
1048
|
+
}
|
|
1049
|
+
/** Whether this driver requires a freshly minted single-use credential on each reconnect. */
|
|
1050
|
+
get RequiresFreshTokenPerReconnect() {
|
|
1051
|
+
return true;
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* How many connections `credential` may open, or `undefined` for no limit (the default). A driver whose provider
|
|
1055
|
+
* counts uses on a credential overrides it, so the client re-mints before it would open a connection the
|
|
1056
|
+
* credential has no use left for, instead of spending a failed attempt finding out.
|
|
1057
|
+
*/
|
|
1058
|
+
CredentialConnectionLimit(_credential) {
|
|
1059
|
+
return void 0;
|
|
1060
|
+
}
|
|
1061
|
+
/**
|
|
1062
|
+
* Whether the provider closes a connection when the credential it opened on expires, even after the client holds a
|
|
1063
|
+
* newer one. `false` (the default) for a credential that only gates opening the connection, as OpenAI's
|
|
1064
|
+
* `client_secret` does. A driver returning `true` gets a planned move onto the refreshed credential before the old
|
|
1065
|
+
* one expires (see {@link connectionDeadlineAtMs}), instead of a drop at the expiry.
|
|
1066
|
+
*/
|
|
1067
|
+
ConnectionClosesAtCredentialExpiry(_credential) {
|
|
1068
|
+
return false;
|
|
1069
|
+
}
|
|
1070
|
+
/**
|
|
1071
|
+
* When the provider will close the live connection before its duration limit: the expiry of the credential it
|
|
1072
|
+
* opened on, for a driver whose connections die with their credential. Only once a refresh has minted a credential
|
|
1073
|
+
* that outlives it: with nothing newer to move onto (the refresh failed, or the session cap bounds the new one too),
|
|
1074
|
+
* an early move would open on the same expiring credential, and moves would follow each other ever faster up to it.
|
|
1075
|
+
*/
|
|
1076
|
+
connectionDeadlineAtMs() {
|
|
1077
|
+
if (!this.ConnectionClosesAtCredentialExpiry(this.connectionCredential)) {
|
|
1078
|
+
return void 0;
|
|
1079
|
+
}
|
|
1080
|
+
const expiresAtMs = Date.parse(this.connectionCredential.ExpiresAt);
|
|
1081
|
+
const currentExpiresAtMs = Date.parse(this.currentCredential.ExpiresAt);
|
|
1082
|
+
if (!Number.isFinite(expiresAtMs) || !Number.isFinite(currentExpiresAtMs) || currentExpiresAtMs <= expiresAtMs) {
|
|
1083
|
+
return void 0;
|
|
1084
|
+
}
|
|
1085
|
+
return expiresAtMs;
|
|
1086
|
+
}
|
|
1087
|
+
/** True when the current credential has opened every connection it allows. */
|
|
1088
|
+
isCredentialSpent() {
|
|
1089
|
+
const limit = this.CredentialConnectionLimit(this.currentCredential);
|
|
1090
|
+
return limit !== void 0 && this.connectionsOnCredential >= limit;
|
|
1091
|
+
}
|
|
1092
|
+
/** Whether this concrete client subclass implements mid-call `Reconnect`. */
|
|
1093
|
+
get SupportsMidCallReconnect() {
|
|
1094
|
+
return this.Reconnect !== _BaseRealtimeClient.prototype.Reconnect;
|
|
1095
|
+
}
|
|
1096
|
+
/** Accessor for the client's rolling conversation memory ledger. */
|
|
1097
|
+
get ConversationMemory() {
|
|
1098
|
+
return this.conversationMemory;
|
|
1099
|
+
}
|
|
1100
|
+
/** True while a mid-call reconnect is actively in flight. */
|
|
1101
|
+
get IsReconnecting() {
|
|
1102
|
+
return this.reconnectController.IsReconnecting;
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* True from the start of a reconnect cycle until it succeeds or fails. Unlike {@link IsReconnecting}, it stays true
|
|
1106
|
+
* while a planned move waits between attempts with the call live again on its old connection. A driver that would
|
|
1107
|
+
* otherwise end the call on a loss of that connection checks this and hands the loss to the running cycle
|
|
1108
|
+
* (`TriggerReconnect('connection-lost')`) instead.
|
|
1109
|
+
*/
|
|
1110
|
+
get IsReconnectCycleActive() {
|
|
1111
|
+
return this.reconnectController.IsReconnectCycleActive;
|
|
1112
|
+
}
|
|
1113
|
+
/** Latest recorded provider resumption handle or conversation ID. */
|
|
1114
|
+
get ResumptionHandle() {
|
|
1115
|
+
return this.reconnectController.Handle;
|
|
1116
|
+
}
|
|
1117
|
+
/** Records a provider resumption handle or conversation ID, along with whether it is resumable now. */
|
|
1118
|
+
RecordResumptionHandle(handle, resumable = true) {
|
|
1119
|
+
this.reconnectController.RecordHandle(handle, resumable);
|
|
1120
|
+
}
|
|
1121
|
+
/** Registers the host callback used to mint a fresh credential before expiry or reconnect. */
|
|
1122
|
+
SetTokenRefreshCallback(callback) {
|
|
1123
|
+
this.tokenRefreshCallback = callback;
|
|
1124
|
+
this.scheduleCredentialRefresh();
|
|
1125
|
+
}
|
|
1126
|
+
/** Mints a fresh credential via the registered host callback, updates `currentCredential`, and re-arms the refresh timer. */
|
|
1127
|
+
async refreshCredentialForReconnect(options) {
|
|
1128
|
+
if (!this.tokenRefreshCallback) {
|
|
1129
|
+
return this.currentCredential;
|
|
1130
|
+
}
|
|
1131
|
+
const refreshed = await this.tokenRefreshCallback(options);
|
|
1132
|
+
this.applyTimingFields(refreshed);
|
|
1133
|
+
if (refreshed.EphemeralToken && refreshed.EphemeralToken !== this.currentCredential.EphemeralToken) {
|
|
1134
|
+
this.connectionsOnCredential = 0;
|
|
1135
|
+
}
|
|
1136
|
+
this.currentCredential = {
|
|
1137
|
+
...refreshed,
|
|
1138
|
+
EphemeralToken: refreshed.EphemeralToken || this.currentCredential.EphemeralToken,
|
|
1139
|
+
...refreshed.RelayUrl || this.currentCredential.RelayUrl ? { RelayUrl: refreshed.RelayUrl || this.currentCredential.RelayUrl } : {}
|
|
1140
|
+
};
|
|
1141
|
+
this.scheduleCredentialRefresh();
|
|
1142
|
+
return this.currentCredential;
|
|
1143
|
+
}
|
|
1144
|
+
scheduleCredentialRefresh() {
|
|
1145
|
+
if (!this.SupportsMidCallReconnect || !this.tokenRefreshCallback || this.reconnectController.IsDisposed) {
|
|
1146
|
+
return;
|
|
1147
|
+
}
|
|
1148
|
+
this.reconnectController.ScheduleCredentialRefresh(this.currentCredential.ExpiresAt, () => {
|
|
1149
|
+
void this.refreshCredentialProactively();
|
|
1150
|
+
}, DEFAULT_CREDENTIAL_REFRESH_LEAD_MS, this.configuredSessionMaxSeconds);
|
|
1151
|
+
}
|
|
1152
|
+
async refreshCredentialProactively() {
|
|
1153
|
+
if (this.reconnectController.IsDisposed || !this.tokenRefreshCallback) {
|
|
1154
|
+
return;
|
|
1155
|
+
}
|
|
1156
|
+
try {
|
|
1157
|
+
await this.refreshCredentialForReconnect();
|
|
1158
|
+
} catch (err) {
|
|
1159
|
+
RealtimeDiagLog(`[${this.constructor.name}] proactive credential refresh failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
1162
|
+
this.armMoveBeforeConnectionCredentialExpires();
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* After a refresh lands: the live connection may close when the credential it opened on expires, so with a newer
|
|
1166
|
+
* one in hand the timers are re-armed and the planned move happens before that expiry. A reconnect in flight arms
|
|
1167
|
+
* them once its connection opens.
|
|
1168
|
+
*/
|
|
1169
|
+
armMoveBeforeConnectionCredentialExpires() {
|
|
1170
|
+
if (!this.IsReconnecting && this.reconnectController.HasDurationTimersArmed && this.connectionDeadlineAtMs() !== void 0) {
|
|
1171
|
+
this.ArmConnectionDurationTimer();
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
/** Returns true when the current credential is expired or within `marginSeconds` of expiry. */
|
|
1175
|
+
isCredentialNearExpiry(marginSeconds = 60) {
|
|
1176
|
+
if (!this.currentCredential.ExpiresAt) {
|
|
1177
|
+
return false;
|
|
1178
|
+
}
|
|
1179
|
+
const expiresAtMs = Date.parse(this.currentCredential.ExpiresAt);
|
|
1180
|
+
if (!Number.isFinite(expiresAtMs)) {
|
|
1181
|
+
return false;
|
|
1182
|
+
}
|
|
1183
|
+
return expiresAtMs - Date.now() <= marginSeconds * 1e3;
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Arms (or re-arms) the soft and hard connection-ceiling timers for the current transport socket.
|
|
1187
|
+
* - Soft timer opens the turn-boundary window before `CallDurationSeconds`.
|
|
1188
|
+
* - Hard timer fires at `CallDurationSeconds - ReconnectBufferSeconds` and forces a reconnect; while the model is
|
|
1189
|
+
* answering it waits for the turn to end, up to shortly before `CallDurationSeconds`.
|
|
1190
|
+
* Both measure from the connection deadline instead when it comes before `CallDurationSeconds`
|
|
1191
|
+
* ({@link connectionDeadlineAtMs}: the expiry of the credential the connection opened on, on a driver whose
|
|
1192
|
+
* connections close with it).
|
|
1193
|
+
*/
|
|
1194
|
+
ArmConnectionDurationTimer() {
|
|
1195
|
+
if (!this.SupportsMidCallReconnect || this.reconnectController.IsDisposed) {
|
|
1196
|
+
return;
|
|
1197
|
+
}
|
|
1198
|
+
this.reconnectController.ArmDurationTimers(this.CallDurationSeconds, this.ReconnectBufferSeconds, DEFAULT_REALTIME_SOFT_RECONNECT_WINDOW_SECONDS, this.connectionDeadlineAtMs());
|
|
1199
|
+
}
|
|
1200
|
+
/** Cancels all reconnect and duration timers when the session is disconnected. */
|
|
1201
|
+
DisposeReconnectTimers() {
|
|
1202
|
+
this.endReconnectCycle();
|
|
1203
|
+
this.reconnectController.InvalidateHandle();
|
|
1204
|
+
this.reconnectController.Dispose();
|
|
1205
|
+
}
|
|
1206
|
+
/** A reconnect cycle ended (it succeeded or failed, or the session closed): the next one starts afresh. */
|
|
1207
|
+
endReconnectCycle() {
|
|
1208
|
+
this.stopWatchingNetworkOnline();
|
|
1209
|
+
this.refreshedInActiveCycle = false;
|
|
1210
|
+
}
|
|
1211
|
+
/**
|
|
1212
|
+
* Returns whether the host environment reports a live network interface (`navigator.onLine !== false`).
|
|
1213
|
+
* Overridable by subclasses and tests so offline retry attempts do not invalidate a resumable provider handle.
|
|
1214
|
+
*/
|
|
1215
|
+
isHostNetworkOnline() {
|
|
1216
|
+
const nav = globalThis.navigator;
|
|
1217
|
+
return nav?.onLine !== false;
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Listens for the browser's `online` event while a reconnect runs. Outside a browser (a Node host or test) there is
|
|
1221
|
+
* no `window`, and the retry schedule alone drives the attempts. `online` only says a network interface is up, not
|
|
1222
|
+
* that the provider is reachable, so it starts one attempt early and never replaces the schedule.
|
|
1223
|
+
*/
|
|
1224
|
+
startWatchingNetworkOnline() {
|
|
1225
|
+
if (this.watchingNetworkOnline || typeof window === "undefined" || typeof window.addEventListener !== "function") {
|
|
1226
|
+
return;
|
|
1227
|
+
}
|
|
1228
|
+
window.addEventListener("online", this.onNetworkOnline);
|
|
1229
|
+
this.watchingNetworkOnline = true;
|
|
1230
|
+
}
|
|
1231
|
+
stopWatchingNetworkOnline() {
|
|
1232
|
+
if (!this.watchingNetworkOnline) {
|
|
1233
|
+
return;
|
|
1234
|
+
}
|
|
1235
|
+
window.removeEventListener("online", this.onNetworkOnline);
|
|
1236
|
+
this.watchingNetworkOnline = false;
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Schedules a turn-boundary reconnect (e.g. on a provider `GoAway` frame).
|
|
1240
|
+
* Runs immediately if the session is idle at a turn boundary, or defers until the active turn ends.
|
|
1241
|
+
*/
|
|
1242
|
+
NotifyConnectionEnding(timeLeftMs) {
|
|
1243
|
+
this.reconnectController.ConnectionEnding(timeLeftMs);
|
|
1244
|
+
}
|
|
1245
|
+
isTurnActiveForReconnect() {
|
|
1246
|
+
return this.reconnectController.IsTurnOpen || this.IsBusy || this.IsAudioPlaying || this.isUserSpeaking() || this.inFlightToolCallIds.size > 0;
|
|
1247
|
+
}
|
|
1248
|
+
/** Whether the mic meter hears the user right now (always `false` when the driver attached no input meter). */
|
|
1249
|
+
isUserSpeaking() {
|
|
1250
|
+
return this.inputAudioMeter !== null && (this.inputAudioMeter.Level() ?? 0) >= DEFAULT_USER_SPEECH_ACTIVE_LEVEL_THRESHOLD;
|
|
1251
|
+
}
|
|
1252
|
+
/**
|
|
1253
|
+
* Whether the user said something the current connection has not answered yet, with no turn open for it. The
|
|
1254
|
+
* hard-point move then waits as it does for an open turn, until shortly before the provider limit. `false` here: a
|
|
1255
|
+
* driver whose provider opens the turn only once the answer starts overrides it, and calls
|
|
1256
|
+
* `reconnectController.NotifyIdleStateChanged()` when the hold ends without a turn.
|
|
1257
|
+
*/
|
|
1258
|
+
holdsHardReconnectPoint() {
|
|
1259
|
+
return false;
|
|
1260
|
+
}
|
|
1261
|
+
/**
|
|
1262
|
+
* Initiates an in-place reconnect that retries through its recovery window (`REALTIME_RESUMPTION_RECOVERY_WINDOW_MS`,
|
|
1263
|
+
* counted from the old connection's end for a planned move), with the rapid-reconnect circuit breaker and Attempt-2
|
|
1264
|
+
* fallback from native handle to history seeding.
|
|
1265
|
+
*/
|
|
1266
|
+
TriggerReconnect(reason) {
|
|
1267
|
+
return this.reconnectController.TriggerReconnect(reason);
|
|
1268
|
+
}
|
|
1269
|
+
/**
|
|
1270
|
+
* The attempt's preparation step, timed by the controller apart from the transport attempt: refreshes the
|
|
1271
|
+
* credential when this cycle has not refreshed yet and the reconnect needs it. The first attempt of a cycle
|
|
1272
|
+
* refreshes only when the token is single-use, near expiry or spent; a retry always refreshes once. A spent or
|
|
1273
|
+
* nearly expired credential is re-minted even after this cycle's refresh: a cycle can retry through an outage for
|
|
1274
|
+
* tens of seconds (a planned move's, back on its old connection between attempts, for that connection's remaining
|
|
1275
|
+
* life), and its failed attempts spend uses too.
|
|
1276
|
+
*
|
|
1277
|
+
* The attempt waits for the refresh only when it cannot connect without one ({@link reconnectWaitsForCredential}).
|
|
1278
|
+
* A retry's refresh on a still-valid, reusable credential runs in the background and serves the attempts after it:
|
|
1279
|
+
* a refresh request that never returns (sent into a dead HTTP/2 connection during the outage) must not hold every
|
|
1280
|
+
* attempt of the cycle at its preparation timeout while the credential in hand still works.
|
|
1281
|
+
*/
|
|
1282
|
+
prepareClientReconnectAttempt(attempt) {
|
|
1283
|
+
if (!this.tokenRefreshCallback) {
|
|
1284
|
+
return Promise.resolve();
|
|
1285
|
+
}
|
|
1286
|
+
const alreadyRefreshed = this.refreshedInActiveCycle && !this.isCredentialSpent() && !this.isCredentialNearExpiry();
|
|
1287
|
+
if (alreadyRefreshed || !this.reconnectNeedsCredentialRefresh(attempt)) {
|
|
1288
|
+
return Promise.resolve();
|
|
1289
|
+
}
|
|
1290
|
+
const refresh = this.joinOrStartReconnectRefresh();
|
|
1291
|
+
if (this.reconnectWaitsForCredential()) {
|
|
1292
|
+
return refresh;
|
|
1293
|
+
}
|
|
1294
|
+
refresh.catch((err) => {
|
|
1295
|
+
RealtimeDiagLog(`[${this.constructor.name}] background credential refresh for attempt ${attempt} failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1296
|
+
});
|
|
1297
|
+
return Promise.resolve();
|
|
1298
|
+
}
|
|
1299
|
+
/**
|
|
1300
|
+
* The refresh in flight when it is young enough to join, else a new one. The attempt that started a refresh times
|
|
1301
|
+
* out at its preparation limit, and the next attempt starts within a retry delay of that, so it still joins: a slow
|
|
1302
|
+
* server gets about two preparation limits to answer, and is not asked twice (F5). Any later attempt sends a new
|
|
1303
|
+
* request, so one that never returns costs the cycle two attempts, not all of them.
|
|
1304
|
+
*/
|
|
1305
|
+
joinOrStartReconnectRefresh() {
|
|
1306
|
+
const inFlight = this.reconnectCredentialRefresh;
|
|
1307
|
+
if (inFlight && Date.now() - inFlight.StartedAtMs < SHARED_REFRESH_MAX_JOIN_AGE_MS) {
|
|
1308
|
+
return inFlight.Promise;
|
|
1309
|
+
}
|
|
1310
|
+
if (inFlight) {
|
|
1311
|
+
RealtimeDiagLog(`[${this.constructor.name}] the credential refresh in flight for ${Date.now() - inFlight.StartedAtMs} ms has not returned; sending a new one`);
|
|
1312
|
+
}
|
|
1313
|
+
const entry = {
|
|
1314
|
+
Promise: this.refreshCredentialBeforeReconnect().finally(() => {
|
|
1315
|
+
if (this.reconnectCredentialRefresh === entry) {
|
|
1316
|
+
this.reconnectCredentialRefresh = null;
|
|
1317
|
+
}
|
|
1318
|
+
}),
|
|
1319
|
+
StartedAtMs: Date.now()
|
|
1320
|
+
};
|
|
1321
|
+
this.reconnectCredentialRefresh = entry;
|
|
1322
|
+
return entry.Promise;
|
|
1323
|
+
}
|
|
1324
|
+
/**
|
|
1325
|
+
* Whether an attempt cannot connect without a fresh credential: the token is single-use, spent, or within a minute
|
|
1326
|
+
* of expiry. Otherwise the credential in hand still opens a connection, and a refresh is only an improvement.
|
|
1327
|
+
*/
|
|
1328
|
+
reconnectWaitsForCredential() {
|
|
1329
|
+
return this.RequiresFreshTokenPerReconnect || this.isCredentialNearExpiry() || this.isCredentialSpent();
|
|
1330
|
+
}
|
|
1331
|
+
reconnectNeedsCredentialRefresh(attempt) {
|
|
1332
|
+
return this.RequiresFreshTokenPerReconnect || this.isCredentialNearExpiry() || this.isCredentialSpent() || attempt > 1;
|
|
1333
|
+
}
|
|
1334
|
+
async refreshCredentialBeforeReconnect() {
|
|
1335
|
+
try {
|
|
1336
|
+
await this.refreshCredentialForReconnect();
|
|
1337
|
+
} catch (refreshErr) {
|
|
1338
|
+
if (this.RequiresFreshTokenPerReconnect || this.isCredentialNearExpiry(0) || this.isCredentialSpent()) {
|
|
1339
|
+
throw refreshErr instanceof Error ? refreshErr : new Error(String(refreshErr));
|
|
1340
|
+
}
|
|
1341
|
+
RealtimeDiagLog(`[${this.constructor.name}] credential refresh failed during reconnect, continuing with unexpired credential: ${refreshErr instanceof Error ? refreshErr.message : String(refreshErr)}`);
|
|
1342
|
+
this.recordReconnectRefresh();
|
|
1343
|
+
return;
|
|
1344
|
+
}
|
|
1345
|
+
this.recordReconnectRefresh();
|
|
1346
|
+
this.armMoveBeforeConnectionCredentialExpires();
|
|
1347
|
+
}
|
|
1348
|
+
/**
|
|
1349
|
+
* Counts a reconnect's refresh for the cycle running when it lands. One that lands after its cycle ended (a retry's
|
|
1350
|
+
* background refresh, outrun by the retry) counts for no cycle: the next cycle's retry still refreshes.
|
|
1351
|
+
*/
|
|
1352
|
+
recordReconnectRefresh() {
|
|
1353
|
+
if (this.IsReconnectCycleActive) {
|
|
1354
|
+
this.refreshedInActiveCycle = true;
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
async executeClientReconnectAttempt(context) {
|
|
1358
|
+
const seed = context.ConversationSeed ?? this.conversationMemory.Seed();
|
|
1359
|
+
let openedOn = this.currentCredential;
|
|
1360
|
+
const clientContext = {
|
|
1361
|
+
Reason: context.Reason,
|
|
1362
|
+
Attempt: context.Attempt,
|
|
1363
|
+
MaxAttempts: context.MaxAttempts,
|
|
1364
|
+
ElapsedConnectionSeconds: context.ElapsedConnectionSeconds,
|
|
1365
|
+
ResumptionHandle: context.ResumptionHandle,
|
|
1366
|
+
UseNativeResumption: context.UseNativeResumption,
|
|
1367
|
+
ConversationSeed: context.ConversationSeed,
|
|
1368
|
+
get Abandoned() {
|
|
1369
|
+
return context.Abandoned;
|
|
1370
|
+
},
|
|
1371
|
+
Signal: context.Signal,
|
|
1372
|
+
Seed: seed,
|
|
1373
|
+
RefreshCredential: async (options) => {
|
|
1374
|
+
openedOn = await this.refreshCredentialForReconnect(options);
|
|
1375
|
+
return openedOn;
|
|
1376
|
+
},
|
|
1377
|
+
Credential: openedOn
|
|
1378
|
+
};
|
|
1379
|
+
try {
|
|
1380
|
+
await this.Reconnect(clientContext);
|
|
1381
|
+
this.connectionCredential = openedOn;
|
|
1382
|
+
} finally {
|
|
1383
|
+
if (openedOn === this.currentCredential) {
|
|
1384
|
+
this.connectionsOnCredential++;
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
onReconnecting(_reason) {
|
|
1389
|
+
this.emitStateChange("connecting");
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* A planned move's attempt failed while the old connection still carries the call: go back to live on it (state,
|
|
1393
|
+
* held input) until the next attempt, which waits for the next idle boundary or the hard point, and return `true`.
|
|
1394
|
+
* Return `false` when the old connection cannot carry the call any more; the cycle then retries on its schedule.
|
|
1395
|
+
* `IsReconnecting` is already `false` when this runs, so sends go to the old connection. `false` here: a driver
|
|
1396
|
+
* opts in by overriding it. See `RealtimeReconnectControllerOptions.ReturnToOldConnection`.
|
|
1397
|
+
*/
|
|
1398
|
+
ResumeOnOldConnection() {
|
|
1399
|
+
return false;
|
|
1400
|
+
}
|
|
1401
|
+
/**
|
|
1402
|
+
* The state to report again when {@link ResumeOnOldConnection} goes back to the old connection, or `null` when the
|
|
1403
|
+
* old connection has reported a state of its own since the move started (it keeps delivering events during the
|
|
1404
|
+
* attempt), which is current. `'speaking'` while the turn is open, else `'listening'`: the turn, not the state the
|
|
1405
|
+
* move replaced, says whether the agent is answering, since a driver can leave `'speaking'` without reporting it
|
|
1406
|
+
* (a tool call) and the old connection can start an answer during the attempt. A `'speaking'` report opens a turn,
|
|
1407
|
+
* and one with no answer behind it would hold the next attempt until the last call. `'connected'` is never
|
|
1408
|
+
* reported: a host keeps showing the move for it.
|
|
1409
|
+
*/
|
|
1410
|
+
get StateToRestoreOnOldConnection() {
|
|
1411
|
+
if (this.lastEmittedState !== "connecting") {
|
|
1412
|
+
return null;
|
|
1413
|
+
}
|
|
1414
|
+
return this.reconnectController.IsTurnOpen ? "speaking" : "listening";
|
|
1415
|
+
}
|
|
1416
|
+
onReconnected(usedNativeResumption) {
|
|
1417
|
+
if (!usedNativeResumption && this.inFlightToolCallIds.size > 0) {
|
|
1418
|
+
for (const callID of this.inFlightToolCallIds) {
|
|
1419
|
+
this.callsFromBeforeReseed.add(callID);
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
this.ArmConnectionDurationTimer();
|
|
1423
|
+
}
|
|
1424
|
+
onReconnectFailed(error, code) {
|
|
1425
|
+
this.emitError({ Message: error.message, Code: code, Fatal: true });
|
|
1426
|
+
this.emitStateChange("error");
|
|
1427
|
+
}
|
|
1428
|
+
/**
|
|
1429
|
+
* Re-establishes the underlying provider connection mid-call, either via native session
|
|
1430
|
+
* resumption or by re-seeding from `context.ConversationSeed`. Concrete drivers MUST override this method.
|
|
1431
|
+
*/
|
|
1432
|
+
Reconnect(_context) {
|
|
1433
|
+
return Promise.reject(new Error(`${this.constructor.name} does not implement mid-call Reconnect()`));
|
|
1434
|
+
}
|
|
1435
|
+
/** Resolves the tool name recorded when `callID` was emitted, or `fallbackName ?? callID`. */
|
|
1436
|
+
resolveToolName(callID, fallbackName) {
|
|
1437
|
+
return fallbackName || this.toolCallNamesById.get(callID) || callID;
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* Whether a tool result's payload requests `SILENT` scheduling (meaning no post-tool model reply is expected).
|
|
1441
|
+
* Subclasses that gate scheduling on model capability (e.g. `GeminiRealtimeClient.supportsScheduling`) can override.
|
|
1442
|
+
*/
|
|
1443
|
+
isToolResultSilent(outputJson) {
|
|
1444
|
+
try {
|
|
1445
|
+
const parsed = JSON.parse(outputJson);
|
|
1446
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
1447
|
+
return false;
|
|
1448
|
+
}
|
|
1449
|
+
const record = parsed;
|
|
1450
|
+
const raw = record["__mj_scheduling"] ?? record["scheduling"];
|
|
1451
|
+
return typeof raw === "string" && raw.trim().toUpperCase() === "SILENT";
|
|
1452
|
+
} catch {
|
|
1453
|
+
return false;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Records a completed tool result into {@link conversationMemory} and clears its in-flight guard.
|
|
1458
|
+
* Invoked automatically by the {@link SendToolResult} template method after {@link doSendToolResult} succeeds.
|
|
1459
|
+
*/
|
|
1460
|
+
recordToolResult(callID, outputJson, toolName) {
|
|
1461
|
+
this.inFlightToolCallIds.delete(callID);
|
|
1462
|
+
const resolvedName = toolName ?? this.toolCallNamesById.get(callID) ?? callID;
|
|
1463
|
+
this.toolCallNamesById.delete(callID);
|
|
1464
|
+
if (!this.recordedToolCallIds.has(callID)) {
|
|
1465
|
+
this.recordedToolCallIds.add(callID);
|
|
1466
|
+
this.conversationMemory.Record({
|
|
1467
|
+
Kind: "toolResult",
|
|
1468
|
+
Name: resolvedName,
|
|
1469
|
+
OutputJson: outputJson
|
|
1470
|
+
});
|
|
1471
|
+
}
|
|
1472
|
+
if (this.inFlightToolCallIds.size === 0) {
|
|
1473
|
+
const expectsReply = !this.isToolResultSilent(outputJson);
|
|
1474
|
+
if (this.wasSpeaking) {
|
|
1475
|
+
this.toolResultSentWhileSpeaking = expectsReply;
|
|
1476
|
+
}
|
|
1477
|
+
this.reconnectController.ToolResultSent(expectsReply);
|
|
1478
|
+
} else {
|
|
1479
|
+
this.reconnectController.NotifyIdleStateChanged();
|
|
1480
|
+
}
|
|
1481
|
+
return resolvedName;
|
|
1482
|
+
}
|
|
872
1483
|
// ── Protected emit helpers for concrete drivers ───────────────────────────
|
|
873
1484
|
/** Emits a track state change to the registered handler (if any). */
|
|
874
1485
|
emitTrackStateChange(track) {
|
|
875
1486
|
this.trackHandler?.(track);
|
|
876
1487
|
}
|
|
877
|
-
/** Emits a transcript event to the registered handler (if any). */
|
|
1488
|
+
/** Emits a transcript event to the registered handler (if any) and records final normal turns in memory. */
|
|
878
1489
|
emitTranscript(transcript) {
|
|
1490
|
+
if (transcript.IsFinal && transcript.Kind === "normal" && !transcript.IsThought) {
|
|
1491
|
+
if (transcript.Role === "User") {
|
|
1492
|
+
this.conversationMemory.Record({
|
|
1493
|
+
Kind: "user",
|
|
1494
|
+
Text: transcript.Text,
|
|
1495
|
+
ReplacesPrevious: transcript.ReplacesPrevious,
|
|
1496
|
+
...transcript.ItemId !== void 0 ? { ItemId: transcript.ItemId } : {}
|
|
1497
|
+
});
|
|
1498
|
+
} else {
|
|
1499
|
+
this.conversationMemory.Record({ Kind: "assistant", Text: transcript.Text, ReplacesPrevious: transcript.ReplacesPrevious });
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
879
1502
|
this.transcriptHandler?.(transcript);
|
|
880
1503
|
}
|
|
881
|
-
/** Emits a tool-call request to the registered handler (if any). */
|
|
1504
|
+
/** Emits a tool-call request to the registered handler (if any) and records it in memory. */
|
|
882
1505
|
emitToolCall(call) {
|
|
1506
|
+
this.inFlightToolCallIds.add(call.CallID);
|
|
1507
|
+
this.recordedToolCallIds.delete(call.CallID);
|
|
1508
|
+
this.toolCallNamesById.set(call.CallID, call.ToolName);
|
|
1509
|
+
this.conversationMemory.Record({
|
|
1510
|
+
Kind: "toolCall",
|
|
1511
|
+
Name: call.ToolName,
|
|
1512
|
+
ArgumentsJson: call.ArgumentsJson
|
|
1513
|
+
});
|
|
883
1514
|
this.toolCallHandler?.(call);
|
|
884
1515
|
}
|
|
885
|
-
/** Emits a state change to the registered handler (if any). */
|
|
1516
|
+
/** Emits a state change to the registered handler (if any) and flushes any deferred turn-boundary reconnect. */
|
|
886
1517
|
emitStateChange(state) {
|
|
1518
|
+
this.lastEmittedState = state;
|
|
1519
|
+
if (state === "closed" || state === "error") {
|
|
1520
|
+
this.wasSpeaking = false;
|
|
1521
|
+
this.toolResultSentWhileSpeaking = false;
|
|
1522
|
+
this.DisposeReconnectTimers();
|
|
1523
|
+
this.inFlightToolCallIds.clear();
|
|
1524
|
+
this.recordedToolCallIds.clear();
|
|
1525
|
+
this.toolCallNamesById.clear();
|
|
1526
|
+
} else if (state === "connecting") {
|
|
1527
|
+
this.wasSpeaking = false;
|
|
1528
|
+
this.toolResultSentWhileSpeaking = false;
|
|
1529
|
+
} else if (state === "speaking") {
|
|
1530
|
+
this.wasSpeaking = true;
|
|
1531
|
+
this.toolResultSentWhileSpeaking = false;
|
|
1532
|
+
this.reconnectController.TurnStarted();
|
|
1533
|
+
} else if (state === "listening" && !this.reconnectController.HasDurationTimersArmed && !this.reconnectController.IsReconnecting && !this.reconnectController.IsInSoftWindow) {
|
|
1534
|
+
this.ArmConnectionDurationTimer();
|
|
1535
|
+
}
|
|
887
1536
|
this.stateChangeHandler?.(state);
|
|
1537
|
+
if (state === "listening") {
|
|
1538
|
+
const keepPostToolTurnWait = this.wasSpeaking && this.toolResultSentWhileSpeaking;
|
|
1539
|
+
this.wasSpeaking = false;
|
|
1540
|
+
this.toolResultSentWhileSpeaking = false;
|
|
1541
|
+
this.reconnectController.TurnEnded(keepPostToolTurnWait);
|
|
1542
|
+
}
|
|
888
1543
|
}
|
|
889
1544
|
/** Emits an error to the registered handler (if any). */
|
|
890
1545
|
emitError(error) {
|
|
@@ -1211,10 +1866,19 @@ async function CreatePcmMicCapture(micStream, sampleRate, onPcmChunk) {
|
|
|
1211
1866
|
}
|
|
1212
1867
|
|
|
1213
1868
|
// ../../AI/RealtimeClient/dist/generic/openAIProtocolClient.js
|
|
1214
|
-
var
|
|
1869
|
+
var PENDING_USER_UTTERANCE_MAX_AGE_MS = 15e3;
|
|
1870
|
+
var UNIDENTIFIED_UTTERANCE_KEY = "";
|
|
1871
|
+
var OpenAIProtocolRealtimeClient = class _OpenAIProtocolRealtimeClient extends BaseRealtimeClient {
|
|
1215
1872
|
constructor() {
|
|
1216
1873
|
super(...arguments);
|
|
1217
1874
|
this.pendingAssistantText = "";
|
|
1875
|
+
this.textHeldDuringReconnect = [];
|
|
1876
|
+
this.toolResultsHeldDuringReconnect = [];
|
|
1877
|
+
this.deliveringHeldInput = false;
|
|
1878
|
+
this.responseOwedByHeldInput = false;
|
|
1879
|
+
this.callWentLive = false;
|
|
1880
|
+
this.answerOwedAfterMove = false;
|
|
1881
|
+
this.pendingUserUtterances = /* @__PURE__ */ new Map();
|
|
1218
1882
|
this.responseActive = false;
|
|
1219
1883
|
this.pendingResultResponse = false;
|
|
1220
1884
|
this.pendingLocalResponseCreates = 0;
|
|
@@ -1224,6 +1888,13 @@ var OpenAIProtocolRealtimeClient = class extends BaseRealtimeClient {
|
|
|
1224
1888
|
this.currentState = "closed";
|
|
1225
1889
|
this.micStream = null;
|
|
1226
1890
|
}
|
|
1891
|
+
/**
|
|
1892
|
+
* Whether the transport can carry the call, which a failed move's return to it needs: by default, whether it can
|
|
1893
|
+
* deliver events ({@link canSendEvents}). A transport whose open state can outlast its network path overrides it.
|
|
1894
|
+
*/
|
|
1895
|
+
isTransportUsable() {
|
|
1896
|
+
return this.canSendEvents();
|
|
1897
|
+
}
|
|
1227
1898
|
// ── Virtual per-provider behavior seams (sensible OpenAI defaults) ─────────
|
|
1228
1899
|
/** Debug label used in the shared console diagnostics. */
|
|
1229
1900
|
get providerDebugLabel() {
|
|
@@ -1297,6 +1968,34 @@ var OpenAIProtocolRealtimeClient = class extends BaseRealtimeClient {
|
|
|
1297
1968
|
* active the cancel is a no-op and the reply triggers immediately.
|
|
1298
1969
|
*/
|
|
1299
1970
|
SendText(text) {
|
|
1971
|
+
if (this.IsReconnecting) {
|
|
1972
|
+
this.textHeldDuringReconnect.push(text);
|
|
1973
|
+
return;
|
|
1974
|
+
}
|
|
1975
|
+
this.deliverUserText(text);
|
|
1976
|
+
}
|
|
1977
|
+
/**
|
|
1978
|
+
* @inheritdoc
|
|
1979
|
+
*
|
|
1980
|
+
* During a move a result is held, like typed text, and goes out once the call is live again: on the new connection
|
|
1981
|
+
* after the swap ({@link onReconnected}), or on the old one when a planned move goes back to it
|
|
1982
|
+
* ({@link ResumeOnOldConnection}). Sent on now, it would be lost: a lost transport cannot carry it, and a closing
|
|
1983
|
+
* one takes it along after the seed for the new connection was built. It is recorded into memory when it goes out,
|
|
1984
|
+
* so it reaches the model and the seed of a later move exactly once.
|
|
1985
|
+
*/
|
|
1986
|
+
SendToolResult(callID, outputJson) {
|
|
1987
|
+
if (this.IsReconnecting) {
|
|
1988
|
+
this.toolResultsHeldDuringReconnect.push({ CallID: callID, OutputJson: outputJson });
|
|
1989
|
+
return;
|
|
1990
|
+
}
|
|
1991
|
+
super.SendToolResult(callID, outputJson);
|
|
1992
|
+
}
|
|
1993
|
+
/**
|
|
1994
|
+
* Sends one typed user turn and records it in conversation memory. The provider sends no input transcription for a
|
|
1995
|
+
* text item (only for audio), so without the record a later reseed would drop the turn. It is recorded when sent,
|
|
1996
|
+
* not when held, so a held turn is not also in the seed of the move it waited for.
|
|
1997
|
+
*/
|
|
1998
|
+
deliverUserText(text) {
|
|
1300
1999
|
if (!this.canSendEvents()) {
|
|
1301
2000
|
return;
|
|
1302
2001
|
}
|
|
@@ -1305,8 +2004,93 @@ var OpenAIProtocolRealtimeClient = class extends BaseRealtimeClient {
|
|
|
1305
2004
|
type: "conversation.item.create",
|
|
1306
2005
|
item: { type: "message", role: "user", content: [{ type: "input_text", text }] }
|
|
1307
2006
|
});
|
|
2007
|
+
this.ConversationMemory.Record({ Kind: "user", Text: text });
|
|
1308
2008
|
this.requestResultResponse();
|
|
1309
2009
|
}
|
|
2010
|
+
/**
|
|
2011
|
+
* The move has started, so the holds it waited on are spent: the utterances belong to the connection being left,
|
|
2012
|
+
* and the next connection's speech starts holds of its own.
|
|
2013
|
+
*/
|
|
2014
|
+
onReconnecting(reason) {
|
|
2015
|
+
this.forgetUserUtterances();
|
|
2016
|
+
this.answerOwedAfterMove = false;
|
|
2017
|
+
super.onReconnecting(reason);
|
|
2018
|
+
}
|
|
2019
|
+
/**
|
|
2020
|
+
* Sends the input held during the move to the new connection, after the seed, and asks for one answer covering it
|
|
2021
|
+
* and an answer the move cut off (see {@link seedConversationAfterMove}). After `super`, so a result for a call
|
|
2022
|
+
* from before a reseed goes out as a late-result note.
|
|
2023
|
+
*/
|
|
2024
|
+
onReconnected(usedNativeResumption) {
|
|
2025
|
+
super.onReconnected(usedNativeResumption);
|
|
2026
|
+
const answerOwed = this.answerOwedAfterMove;
|
|
2027
|
+
this.answerOwedAfterMove = false;
|
|
2028
|
+
if (answerOwed) {
|
|
2029
|
+
RealtimeDiagLog(`[${this.providerDebugLabel}] the move cut off an answer; asking the new connection for it`);
|
|
2030
|
+
}
|
|
2031
|
+
this.deliverHeldInput(answerOwed);
|
|
2032
|
+
}
|
|
2033
|
+
/**
|
|
2034
|
+
* Sends the tool results, then the typed text, held during a move, oldest first, and then ONE `response.create`
|
|
2035
|
+
* when any of them (or `answerOwed`) asks for a reply. One request answers every item, and it comes after the
|
|
2036
|
+
* last one: a reply requested per item would be cancelled by the next typed turn (text implies barge-in).
|
|
2037
|
+
*/
|
|
2038
|
+
deliverHeldInput(answerOwed) {
|
|
2039
|
+
const results = this.toolResultsHeldDuringReconnect;
|
|
2040
|
+
const texts = this.textHeldDuringReconnect;
|
|
2041
|
+
this.toolResultsHeldDuringReconnect = [];
|
|
2042
|
+
this.textHeldDuringReconnect = [];
|
|
2043
|
+
this.deliveringHeldInput = true;
|
|
2044
|
+
this.responseOwedByHeldInput = false;
|
|
2045
|
+
try {
|
|
2046
|
+
for (const result of results) {
|
|
2047
|
+
super.SendToolResult(result.CallID, result.OutputJson);
|
|
2048
|
+
}
|
|
2049
|
+
for (const text of texts) {
|
|
2050
|
+
this.deliverUserText(text);
|
|
2051
|
+
}
|
|
2052
|
+
} finally {
|
|
2053
|
+
this.deliveringHeldInput = false;
|
|
2054
|
+
}
|
|
2055
|
+
const owed = answerOwed || this.responseOwedByHeldInput;
|
|
2056
|
+
this.responseOwedByHeldInput = false;
|
|
2057
|
+
if (owed) {
|
|
2058
|
+
this.requestResultResponse();
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
/**
|
|
2062
|
+
* A planned move's attempt failed and the old transport can still carry the call ({@link isTransportUsable}): the
|
|
2063
|
+
* call goes on there until the next attempt. The state the move replaced is reported again, and the text and tool
|
|
2064
|
+
* results held for the move go out on it now instead of waiting for (or being dropped with) the cycle. `false` when
|
|
2065
|
+
* the old transport is gone too.
|
|
2066
|
+
*/
|
|
2067
|
+
ResumeOnOldConnection() {
|
|
2068
|
+
if (!this.isTransportUsable() || this.currentState === "error" || this.currentState === "closed") {
|
|
2069
|
+
return false;
|
|
2070
|
+
}
|
|
2071
|
+
const restore = this.StateToRestoreOnOldConnection;
|
|
2072
|
+
if (restore) {
|
|
2073
|
+
this.setState(restore);
|
|
2074
|
+
}
|
|
2075
|
+
this.deliverHeldInput(false);
|
|
2076
|
+
return true;
|
|
2077
|
+
}
|
|
2078
|
+
/** The move failed and the call is over, so the held input has no connection to go to. */
|
|
2079
|
+
onReconnectFailed(error, code) {
|
|
2080
|
+
this.dropInputHeldDuringReconnect("the reconnect failed");
|
|
2081
|
+
super.onReconnectFailed(error, code);
|
|
2082
|
+
}
|
|
2083
|
+
/** Drops the text and tool results held for a move that will not complete, logging how many and why. */
|
|
2084
|
+
dropInputHeldDuringReconnect(why) {
|
|
2085
|
+
const texts = this.textHeldDuringReconnect.length;
|
|
2086
|
+
const results = this.toolResultsHeldDuringReconnect.length;
|
|
2087
|
+
this.textHeldDuringReconnect = [];
|
|
2088
|
+
this.toolResultsHeldDuringReconnect = [];
|
|
2089
|
+
if (texts === 0 && results === 0) {
|
|
2090
|
+
return;
|
|
2091
|
+
}
|
|
2092
|
+
RealtimeDiagLog(`[${this.providerDebugLabel}] dropping ${texts} typed turn(s) and ${results} tool result(s) held during a reconnect: ${why}`);
|
|
2093
|
+
}
|
|
1310
2094
|
/**
|
|
1311
2095
|
* @inheritdoc
|
|
1312
2096
|
*
|
|
@@ -1343,7 +2127,8 @@ var OpenAIProtocolRealtimeClient = class extends BaseRealtimeClient {
|
|
|
1343
2127
|
* NOTE: role must be 'system' — gpt-realtime (and the compatible endpoints) reject
|
|
1344
2128
|
* 'developer' items ("Developer messages are only supported for quicksilver sessions").
|
|
1345
2129
|
*/
|
|
1346
|
-
SendContextNote(text) {
|
|
2130
|
+
SendContextNote(text, options) {
|
|
2131
|
+
this.ConversationMemory.Record({ Kind: "note", Text: text, ...options });
|
|
1347
2132
|
if (!this.canSendEvents()) {
|
|
1348
2133
|
return;
|
|
1349
2134
|
}
|
|
@@ -1352,6 +2137,73 @@ var OpenAIProtocolRealtimeClient = class extends BaseRealtimeClient {
|
|
|
1352
2137
|
item: { type: "message", role: "system", content: [{ type: "input_text", text }] }
|
|
1353
2138
|
});
|
|
1354
2139
|
}
|
|
2140
|
+
/**
|
|
2141
|
+
* Resets the response bookkeeping for a connection that has just replaced the old one, and returns whether an
|
|
2142
|
+
* answer was in flight (or queued) on the old one. Every count and flag here describes the old connection: a
|
|
2143
|
+
* `response.create` it never confirmed would otherwise make the new connection's real `response.done` look stale
|
|
2144
|
+
* and leave {@link IsBusy} stuck.
|
|
2145
|
+
*/
|
|
2146
|
+
resetResponseStateForNewConnection() {
|
|
2147
|
+
const answerWasInFlight = this.responseActive || this.pendingResultResponse;
|
|
2148
|
+
this.responseActive = false;
|
|
2149
|
+
this.confirmedResponseActive = false;
|
|
2150
|
+
this.pendingResultResponse = false;
|
|
2151
|
+
this.pendingLocalResponseCreates = 0;
|
|
2152
|
+
this.pendingNarrationKind = false;
|
|
2153
|
+
this.activeResponseKind = "normal";
|
|
2154
|
+
this.pendingAssistantText = "";
|
|
2155
|
+
return answerWasInFlight;
|
|
2156
|
+
}
|
|
2157
|
+
/**
|
|
2158
|
+
* Seeds the new connection after a move (when `sendsSeed`; a natively resumed one already has the history) and
|
|
2159
|
+
* notes whether the move cut off an answer the user is still owed: one was in flight on the old connection
|
|
2160
|
+
* (`answerWasInFlight`, from {@link resetResponseStateForNewConnection}) and the conversation ends with what it
|
|
2161
|
+
* answers (a user turn or a tool result), not counting the context notes after it. Neither a seeded nor a resumed
|
|
2162
|
+
* session replies by itself, so without this the question sits unanswered in every later seed. An answer that
|
|
2163
|
+
* completed is in memory as an assistant turn and is not asked for again.
|
|
2164
|
+
*
|
|
2165
|
+
* A seeded connection knows the conversation as the seed sent it. A resumed one knows it as the provider kept it,
|
|
2166
|
+
* which includes what the old connection heard while the attempt was opening, after `context.Seed` was built: so
|
|
2167
|
+
* then the memory as it is now decides.
|
|
2168
|
+
*/
|
|
2169
|
+
seedConversationAfterMove(context, answerWasInFlight, sendsSeed) {
|
|
2170
|
+
if (sendsSeed) {
|
|
2171
|
+
this.seedConversationHistory(context.ConversationSeed);
|
|
2172
|
+
}
|
|
2173
|
+
const conversation = sendsSeed ? context.Seed : this.ConversationMemory.Seed();
|
|
2174
|
+
this.answerOwedAfterMove = answerWasInFlight && _OpenAIProtocolRealtimeClient.endsAwaitingAnswer(conversation);
|
|
2175
|
+
}
|
|
2176
|
+
/** Whether the conversation's last entry other than a context note is a user turn or a tool result. */
|
|
2177
|
+
static endsAwaitingAnswer(seed) {
|
|
2178
|
+
for (let i = seed.Entries.length - 1; i >= 0; i--) {
|
|
2179
|
+
const kind = seed.Entries[i].Kind;
|
|
2180
|
+
if (kind !== "note") {
|
|
2181
|
+
return kind === "user" || kind === "toolResult";
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
return false;
|
|
2185
|
+
}
|
|
2186
|
+
/**
|
|
2187
|
+
* Seeds bounded conversation history turns into a freshly reconnected OpenAI-protocol session.
|
|
2188
|
+
*/
|
|
2189
|
+
seedConversationHistory(seed) {
|
|
2190
|
+
if (!seed || seed.Entries.length === 0) {
|
|
2191
|
+
return;
|
|
2192
|
+
}
|
|
2193
|
+
const turns = RenderRealtimeMemorySeed(seed);
|
|
2194
|
+
for (const turn of turns) {
|
|
2195
|
+
const role = turn.Role === "model" ? "assistant" : "user";
|
|
2196
|
+
const contentType = role === "assistant" ? "output_text" : "input_text";
|
|
2197
|
+
this.sendEvent({
|
|
2198
|
+
type: "conversation.item.create",
|
|
2199
|
+
item: {
|
|
2200
|
+
type: "message",
|
|
2201
|
+
role,
|
|
2202
|
+
content: turn.Texts.map((text) => ({ type: contentType, text }))
|
|
2203
|
+
}
|
|
2204
|
+
});
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
1355
2207
|
/**
|
|
1356
2208
|
* Triggers ONE short spoken update with the given instructions. Marks the upcoming
|
|
1357
2209
|
* response as `'narration'` (flag consumed by the next `response.created`) so its
|
|
@@ -1464,8 +2316,21 @@ ${direction}` }
|
|
|
1464
2316
|
* would collide with an in-flight narration and be dropped, leaving the model silent when
|
|
1465
2317
|
* delegated work comes back.
|
|
1466
2318
|
*/
|
|
1467
|
-
|
|
2319
|
+
doSendToolResult(callID, outputJson) {
|
|
1468
2320
|
if (!this.canSendEvents()) {
|
|
2321
|
+
return false;
|
|
2322
|
+
}
|
|
2323
|
+
const name = this.resolveToolName(callID);
|
|
2324
|
+
if (this.callsFromBeforeReseed.delete(callID)) {
|
|
2325
|
+
this.sendEvent({
|
|
2326
|
+
type: "conversation.item.create",
|
|
2327
|
+
item: {
|
|
2328
|
+
type: "message",
|
|
2329
|
+
role: "user",
|
|
2330
|
+
content: [{ type: "input_text", text: RenderLateToolResultNote(name, outputJson) }]
|
|
2331
|
+
}
|
|
2332
|
+
});
|
|
2333
|
+
this.requestResultResponse();
|
|
1469
2334
|
return;
|
|
1470
2335
|
}
|
|
1471
2336
|
this.sendEvent({
|
|
@@ -1488,6 +2353,71 @@ ${direction}` }
|
|
|
1488
2353
|
get IsBusy() {
|
|
1489
2354
|
return this.responseActive;
|
|
1490
2355
|
}
|
|
2356
|
+
/**
|
|
2357
|
+
* @inheritdoc
|
|
2358
|
+
*
|
|
2359
|
+
* Adds the user's pending utterances: the controller's turn opens only on `response.created`, and the input meter
|
|
2360
|
+
* sees speech only at the instant it is read (not in a pause between words, nor after the commit).
|
|
2361
|
+
*/
|
|
2362
|
+
isTurnActiveForReconnect() {
|
|
2363
|
+
return this.pendingUserUtterances.size > 0 || super.isTurnActiveForReconnect();
|
|
2364
|
+
}
|
|
2365
|
+
/** Starts (or restarts the max age of) the hold for one user utterance. */
|
|
2366
|
+
trackUserUtterance(itemId, committed) {
|
|
2367
|
+
const key = itemId ?? UNIDENTIFIED_UTTERANCE_KEY;
|
|
2368
|
+
const existing = this.pendingUserUtterances.get(key);
|
|
2369
|
+
if (existing) {
|
|
2370
|
+
clearTimeout(existing.Expiry);
|
|
2371
|
+
}
|
|
2372
|
+
const expiry = setTimeout(() => {
|
|
2373
|
+
RealtimeDiagLog(`[${this.providerDebugLabel}] user utterance ${key || "(no id)"} held the reconnect for ${PENDING_USER_UTTERANCE_MAX_AGE_MS} ms with no answer or transcript; releasing it`);
|
|
2374
|
+
this.releaseUserUtterances((_utterance, k) => k === key);
|
|
2375
|
+
}, PENDING_USER_UTTERANCE_MAX_AGE_MS);
|
|
2376
|
+
this.pendingUserUtterances.set(key, { Committed: committed || (existing?.Committed ?? false), Expiry: expiry });
|
|
2377
|
+
}
|
|
2378
|
+
/**
|
|
2379
|
+
* The provider committed the utterance's audio. Its `speech_started` may have carried no id (then that entry takes
|
|
2380
|
+
* this id), and a commit with no `speech_started` (a manual commit) is still audio only this connection holds.
|
|
2381
|
+
*/
|
|
2382
|
+
markUserUtteranceCommitted(itemId) {
|
|
2383
|
+
if (itemId !== void 0 && !this.pendingUserUtterances.has(itemId)) {
|
|
2384
|
+
const unidentified = this.pendingUserUtterances.get(UNIDENTIFIED_UTTERANCE_KEY);
|
|
2385
|
+
if (unidentified) {
|
|
2386
|
+
clearTimeout(unidentified.Expiry);
|
|
2387
|
+
this.pendingUserUtterances.delete(UNIDENTIFIED_UTTERANCE_KEY);
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
this.trackUserUtterance(itemId, true);
|
|
2391
|
+
}
|
|
2392
|
+
/**
|
|
2393
|
+
* The utterance's transcription settled, so the seed of a move carries it (or nothing will). Only a committed
|
|
2394
|
+
* utterance is released: Grok streams `.completed` frames while the user is still speaking. A frame with no id
|
|
2395
|
+
* settles every committed utterance.
|
|
2396
|
+
*/
|
|
2397
|
+
releaseCommittedUserUtterance(itemId) {
|
|
2398
|
+
this.releaseUserUtterances((utterance, key) => utterance.Committed && (itemId === void 0 || key === itemId));
|
|
2399
|
+
}
|
|
2400
|
+
/** Releases the matching holds and, when none is left, lets a deferred soft-window move go ahead. */
|
|
2401
|
+
releaseUserUtterances(matches) {
|
|
2402
|
+
let released = false;
|
|
2403
|
+
for (const [key, utterance] of this.pendingUserUtterances) {
|
|
2404
|
+
if (matches(utterance, key)) {
|
|
2405
|
+
clearTimeout(utterance.Expiry);
|
|
2406
|
+
this.pendingUserUtterances.delete(key);
|
|
2407
|
+
released = true;
|
|
2408
|
+
}
|
|
2409
|
+
}
|
|
2410
|
+
if (released && this.pendingUserUtterances.size === 0) {
|
|
2411
|
+
this.reconnectController.NotifyIdleStateChanged();
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
/** Drops every hold without re-checking a move (the connection they belong to is gone). */
|
|
2415
|
+
forgetUserUtterances() {
|
|
2416
|
+
for (const utterance of this.pendingUserUtterances.values()) {
|
|
2417
|
+
clearTimeout(utterance.Expiry);
|
|
2418
|
+
}
|
|
2419
|
+
this.pendingUserUtterances.clear();
|
|
2420
|
+
}
|
|
1491
2421
|
// ── Inbound event translation (the shared dispatcher) ──────────────────────
|
|
1492
2422
|
/**
|
|
1493
2423
|
* Parses one raw inbound payload and dispatches it. Non-JSON frames and non-object JSON
|
|
@@ -1513,6 +2443,20 @@ ${direction}` }
|
|
|
1513
2443
|
case "session.created":
|
|
1514
2444
|
this.onSessionCreatedFrame();
|
|
1515
2445
|
break;
|
|
2446
|
+
case "conversation.created": {
|
|
2447
|
+
const conv = event.conversation;
|
|
2448
|
+
if (typeof conv?.id === "string" && conv.id.trim().length > 0) {
|
|
2449
|
+
this.RecordResumptionHandle(conv.id);
|
|
2450
|
+
}
|
|
2451
|
+
break;
|
|
2452
|
+
}
|
|
2453
|
+
case "session.going_away":
|
|
2454
|
+
case "go_away": {
|
|
2455
|
+
const rawMs = event.time_left_ms;
|
|
2456
|
+
const timeLeftMs = typeof rawMs === "number" && Number.isFinite(rawMs) ? rawMs : void 0;
|
|
2457
|
+
this.NotifyConnectionEnding(timeLeftMs);
|
|
2458
|
+
break;
|
|
2459
|
+
}
|
|
1516
2460
|
case "response.output_audio_transcript.delta":
|
|
1517
2461
|
case "response.audio_transcript.delta":
|
|
1518
2462
|
this.onAssistantDelta(event.delta);
|
|
@@ -1528,18 +2472,42 @@ ${direction}` }
|
|
|
1528
2472
|
case "conversation.item.input_audio_transcription.completed": {
|
|
1529
2473
|
const completed = event;
|
|
1530
2474
|
this.onUserTranscriptFrame(completed.transcript, completed.item_id);
|
|
2475
|
+
this.releaseCommittedUserUtterance(completed.item_id);
|
|
2476
|
+
break;
|
|
2477
|
+
}
|
|
2478
|
+
case "input_audio_buffer.committed": {
|
|
2479
|
+
const itemId = event.item_id;
|
|
2480
|
+
if (typeof itemId === "string" && itemId.trim().length > 0) {
|
|
2481
|
+
this.ConversationMemory.ReserveUserTurn(itemId);
|
|
2482
|
+
}
|
|
2483
|
+
this.markUserUtteranceCommitted(itemId);
|
|
1531
2484
|
break;
|
|
1532
2485
|
}
|
|
2486
|
+
case "conversation.item.input_audio_transcription.failed": {
|
|
2487
|
+
const itemId = event.item_id;
|
|
2488
|
+
RealtimeDiagLog(`[${this.providerDebugLabel}] input transcription failed for item ${itemId ?? "(no id)"}; the turn is left out of conversation memory`);
|
|
2489
|
+
if (typeof itemId === "string") {
|
|
2490
|
+
this.ConversationMemory.ReleaseUserTurn(itemId);
|
|
2491
|
+
}
|
|
2492
|
+
this.releaseCommittedUserUtterance(itemId);
|
|
2493
|
+
break;
|
|
2494
|
+
}
|
|
2495
|
+
case "input_audio_buffer.cleared":
|
|
2496
|
+
this.releaseUserUtterances((utterance) => !utterance.Committed);
|
|
2497
|
+
break;
|
|
1533
2498
|
case "response.function_call_arguments.done":
|
|
1534
2499
|
this.onToolCallFrame(event);
|
|
1535
2500
|
break;
|
|
1536
2501
|
case "input_audio_buffer.speech_started":
|
|
1537
2502
|
this.emitUserSpeechStart(event.item_id);
|
|
2503
|
+
this.trackUserUtterance(event.item_id, false);
|
|
1538
2504
|
this.onSpeechStartedFrame();
|
|
1539
2505
|
break;
|
|
1540
2506
|
case "response.created": {
|
|
1541
2507
|
this.responseActive = true;
|
|
1542
2508
|
this.confirmedResponseActive = true;
|
|
2509
|
+
this.reconnectController.TurnStarted();
|
|
2510
|
+
this.releaseUserUtterances((utterance) => utterance.Committed);
|
|
1543
2511
|
this.onResponseStarted();
|
|
1544
2512
|
const wasLocalCreate = this.pendingLocalResponseCreates > 0;
|
|
1545
2513
|
if (wasLocalCreate) {
|
|
@@ -1570,6 +2538,8 @@ ${direction}` }
|
|
|
1570
2538
|
this.flushPendingResultResponse();
|
|
1571
2539
|
if (this.currentState === "speaking") {
|
|
1572
2540
|
this.setState("listening");
|
|
2541
|
+
} else if (!this.responseActive) {
|
|
2542
|
+
this.reconnectController.TurnEnded();
|
|
1573
2543
|
}
|
|
1574
2544
|
break;
|
|
1575
2545
|
case "error":
|
|
@@ -1645,16 +2615,22 @@ ${direction}` }
|
|
|
1645
2615
|
/**
|
|
1646
2616
|
* Emits the completed response's usage to the host as a DELTA (the `response.done` usage
|
|
1647
2617
|
* payload covers exactly this response, so it is already incremental — the `OnUsage`
|
|
1648
|
-
* contract's preferred shape). Frames without a usage payload emit nothing.
|
|
2618
|
+
* contract's preferred shape). Frames without a usage payload emit nothing. The per-modality
|
|
2619
|
+
* split (`input_token_details` / `output_token_details`) rides along when the provider sends it,
|
|
2620
|
+
* so pricing can tell audio tokens from text tokens.
|
|
1649
2621
|
*/
|
|
1650
2622
|
emitResponseUsage(event) {
|
|
1651
2623
|
const usage = ResolveResponseDoneUsage(event);
|
|
1652
2624
|
if (!usage) {
|
|
1653
2625
|
return;
|
|
1654
2626
|
}
|
|
2627
|
+
const inputDetails = MapRealtimeUsageModalityDetail(usage["input_token_details"]);
|
|
2628
|
+
const outputDetails = MapRealtimeUsageModalityDetail(usage["output_token_details"]);
|
|
1655
2629
|
this.emitUsage({
|
|
1656
2630
|
InputTokens: typeof usage.input_tokens === "number" ? usage.input_tokens : void 0,
|
|
1657
2631
|
OutputTokens: typeof usage.output_tokens === "number" ? usage.output_tokens : void 0,
|
|
2632
|
+
...inputDetails ? { InputTokenDetails: inputDetails } : {},
|
|
2633
|
+
...outputDetails ? { OutputTokenDetails: outputDetails } : {},
|
|
1658
2634
|
Raw: usage
|
|
1659
2635
|
});
|
|
1660
2636
|
}
|
|
@@ -1699,6 +2675,10 @@ ${direction}` }
|
|
|
1699
2675
|
if (!this.canSendEvents()) {
|
|
1700
2676
|
return;
|
|
1701
2677
|
}
|
|
2678
|
+
if (this.deliveringHeldInput) {
|
|
2679
|
+
this.responseOwedByHeldInput = true;
|
|
2680
|
+
return;
|
|
2681
|
+
}
|
|
1702
2682
|
if (this.responseActive) {
|
|
1703
2683
|
this.pendingResultResponse = true;
|
|
1704
2684
|
return;
|
|
@@ -1722,6 +2702,9 @@ ${direction}` }
|
|
|
1722
2702
|
}
|
|
1723
2703
|
/** Resets the per-session response state machine (used on Disconnect). */
|
|
1724
2704
|
resetResponseState() {
|
|
2705
|
+
this.dropInputHeldDuringReconnect("the call ended");
|
|
2706
|
+
this.forgetUserUtterances();
|
|
2707
|
+
this.answerOwedAfterMove = false;
|
|
1725
2708
|
this.pendingAssistantText = "";
|
|
1726
2709
|
this.responseActive = false;
|
|
1727
2710
|
this.confirmedResponseActive = false;
|
|
@@ -1733,9 +2716,49 @@ ${direction}` }
|
|
|
1733
2716
|
// ── Shared helpers ─────────────────────────────────────────────────────────
|
|
1734
2717
|
/** Updates the client's own state view and emits the change to the host. */
|
|
1735
2718
|
setState(state) {
|
|
2719
|
+
if (state === "listening" || state === "speaking") {
|
|
2720
|
+
this.callWentLive = true;
|
|
2721
|
+
} else if (state === "connecting" || state === "closed" || state === "error") {
|
|
2722
|
+
this.callWentLive = false;
|
|
2723
|
+
}
|
|
1736
2724
|
this.currentState = state;
|
|
1737
2725
|
this.emitStateChange(state);
|
|
1738
2726
|
}
|
|
2727
|
+
/**
|
|
2728
|
+
* Whether an unexpected loss of a live call's transport is handed to the shared `connection-lost` reconnect. On by
|
|
2729
|
+
* default for every driver that can reconnect mid-call; a driver whose transport closes benignly and whose host
|
|
2730
|
+
* reads that close as the end of the session overrides it to `false`.
|
|
2731
|
+
*/
|
|
2732
|
+
get RecoversLostTransport() {
|
|
2733
|
+
return this.SupportsMidCallReconnect;
|
|
2734
|
+
}
|
|
2735
|
+
/**
|
|
2736
|
+
* Hands an unexpected loss of the live call's transport (a close or error the consumer did not ask for) to the
|
|
2737
|
+
* shared reconnect controller, which retries within its recovery window and reports `reconnect-failed` when the
|
|
2738
|
+
* window closes. Returns `false` when there is no live call to save, so the caller keeps its terminal handling: the
|
|
2739
|
+
* connect has not finished (Connect reports that failure itself), the call already ended, or the driver opts out.
|
|
2740
|
+
*
|
|
2741
|
+
* A loss while a reconnect cycle runs is the loss of the transport the cycle may go back to after a failed attempt
|
|
2742
|
+
* (the callers' identity checks drop events of a transport the cycle opened or already let go of). It goes to the
|
|
2743
|
+
* cycle, even on a driver that opts out of starting one, and returns `true`: the cycle then never returns the call
|
|
2744
|
+
* to a dead transport, and goes on as a lost connection's.
|
|
2745
|
+
*
|
|
2746
|
+
* Live means the call went live and has not ended ({@link callWentLive}), not a speech state: during a tool run the
|
|
2747
|
+
* state is `'connected'` (see {@link onToolCallFrame}), and a loss then is as recoverable as one mid-sentence.
|
|
2748
|
+
*/
|
|
2749
|
+
recoverLostTransport(detail) {
|
|
2750
|
+
if (this.IsReconnectCycleActive) {
|
|
2751
|
+
RealtimeDiagLog(`[${this.providerDebugLabel}] transport lost during a reconnect (${detail}); the reconnect takes it`);
|
|
2752
|
+
void this.TriggerReconnect("connection-lost");
|
|
2753
|
+
return true;
|
|
2754
|
+
}
|
|
2755
|
+
if (!this.callWentLive || !this.RecoversLostTransport) {
|
|
2756
|
+
return false;
|
|
2757
|
+
}
|
|
2758
|
+
RealtimeDiagLog(`[${this.providerDebugLabel}] transport lost during a live call (${detail}); reconnecting`);
|
|
2759
|
+
void this.TriggerReconnect("connection-lost");
|
|
2760
|
+
return true;
|
|
2761
|
+
}
|
|
1739
2762
|
/** Logs (diagnostic hook) and delivers one client event when the transport is open. */
|
|
1740
2763
|
sendEvent(event) {
|
|
1741
2764
|
if (!this.canSendEvents()) {
|
|
@@ -1752,6 +2775,7 @@ var OpenAIProtocolWebSocketRealtimeClient = class extends OpenAIProtocolRealtime
|
|
|
1752
2775
|
this.playback = null;
|
|
1753
2776
|
this.micCapture = null;
|
|
1754
2777
|
this.sessionObject = {};
|
|
2778
|
+
this.activeConfig = null;
|
|
1755
2779
|
this.closedByConsumer = false;
|
|
1756
2780
|
this.socketOpen = false;
|
|
1757
2781
|
this.sessionCreatedResolver = null;
|
|
@@ -1789,6 +2813,8 @@ var OpenAIProtocolWebSocketRealtimeClient = class extends OpenAIProtocolRealtime
|
|
|
1789
2813
|
*/
|
|
1790
2814
|
async Connect(config, micStream) {
|
|
1791
2815
|
this.AssertTransportSupported(config);
|
|
2816
|
+
this.ApplySessionConfigTiming(config);
|
|
2817
|
+
this.activeConfig = config;
|
|
1792
2818
|
this.sessionObject = this.resolveSessionObject(config);
|
|
1793
2819
|
this.micStream = micStream;
|
|
1794
2820
|
this.closedByConsumer = false;
|
|
@@ -1867,6 +2893,7 @@ var OpenAIProtocolWebSocketRealtimeClient = class extends OpenAIProtocolRealtime
|
|
|
1867
2893
|
this.micCapture = await this.createMicCapture(micStream, sampleRate, (base64Pcm16) => this.sendMicChunk(base64Pcm16));
|
|
1868
2894
|
this.attachOutputAudioMeter(this.playback?.CreateMeter?.() ?? null);
|
|
1869
2895
|
this.attachInputAudioMeter(RealtimeAudioMeter.ForMicStream(micStream));
|
|
2896
|
+
this.ArmConnectionDurationTimer();
|
|
1870
2897
|
this.setState("listening");
|
|
1871
2898
|
}
|
|
1872
2899
|
/** Rebinds the PCM capture and the input meter to the stream's current track (obligation #10); the socket stays open. */
|
|
@@ -1885,6 +2912,7 @@ var OpenAIProtocolWebSocketRealtimeClient = class extends OpenAIProtocolRealtime
|
|
|
1885
2912
|
*/
|
|
1886
2913
|
async Disconnect() {
|
|
1887
2914
|
this.closedByConsumer = true;
|
|
2915
|
+
this.DisposeReconnectTimers();
|
|
1888
2916
|
this.failPendingConnect?.(new Error(`${this.providerDebugLabel} disconnected during connect`));
|
|
1889
2917
|
this.failPendingConnect = null;
|
|
1890
2918
|
this.sessionCreatedResolver = null;
|
|
@@ -1905,11 +2933,142 @@ var OpenAIProtocolWebSocketRealtimeClient = class extends OpenAIProtocolRealtime
|
|
|
1905
2933
|
this.socket = null;
|
|
1906
2934
|
}
|
|
1907
2935
|
this.sessionObject = {};
|
|
2936
|
+
this.activeConfig = null;
|
|
1908
2937
|
this.resetResponseState();
|
|
1909
2938
|
if (this.currentState !== "error") {
|
|
1910
2939
|
this.setState("closed");
|
|
1911
2940
|
}
|
|
1912
2941
|
}
|
|
2942
|
+
/**
|
|
2943
|
+
* Performs an in-place WebSocket swap on duration expiry or provider GoAway while keeping
|
|
2944
|
+
* the existing `micCapture`, `playback`, and audio meters intact.
|
|
2945
|
+
*/
|
|
2946
|
+
async Reconnect(context) {
|
|
2947
|
+
if (!this.activeConfig) {
|
|
2948
|
+
throw new Error(`${this.providerDebugLabel}: cannot reconnect before Connect`);
|
|
2949
|
+
}
|
|
2950
|
+
if (context.Abandoned) {
|
|
2951
|
+
throw new Error(`${this.providerDebugLabel}: reconnect attempt abandoned`);
|
|
2952
|
+
}
|
|
2953
|
+
const refreshedConfig = {
|
|
2954
|
+
...this.activeConfig,
|
|
2955
|
+
EphemeralToken: context.Credential.EphemeralToken || this.activeConfig.EphemeralToken,
|
|
2956
|
+
ExpiresAt: context.Credential.ExpiresAt || this.activeConfig.ExpiresAt,
|
|
2957
|
+
...context.Credential.RelayUrl !== void 0 ? { RelayUrl: context.Credential.RelayUrl } : {},
|
|
2958
|
+
...context.Credential.SessionConfig !== void 0 ? { SessionConfig: context.Credential.SessionConfig } : {},
|
|
2959
|
+
...context.Credential.TrustNativeResumption !== void 0 ? { TrustNativeResumption: context.Credential.TrustNativeResumption } : {}
|
|
2960
|
+
};
|
|
2961
|
+
this.activeConfig = refreshedConfig;
|
|
2962
|
+
this.sessionObject = this.resolveSessionObject(refreshedConfig);
|
|
2963
|
+
const prevSocket = this.socket;
|
|
2964
|
+
let openSocket = null;
|
|
2965
|
+
const opened = new Promise((resolve) => {
|
|
2966
|
+
openSocket = resolve;
|
|
2967
|
+
});
|
|
2968
|
+
const created = this.waitsForSessionCreated ? new Promise((resolve) => {
|
|
2969
|
+
this.sessionCreatedResolver = resolve;
|
|
2970
|
+
}) : null;
|
|
2971
|
+
let failReconnect = null;
|
|
2972
|
+
const failure = new Promise((_, reject) => {
|
|
2973
|
+
failReconnect = reject;
|
|
2974
|
+
});
|
|
2975
|
+
failure.catch(() => void 0);
|
|
2976
|
+
const nextSocket = this.openProviderSocket(refreshedConfig, context.UseNativeResumption ? context.ResumptionHandle : null);
|
|
2977
|
+
let nextSocketOpen = false;
|
|
2978
|
+
const onAbort = () => {
|
|
2979
|
+
failReconnect?.(new Error(`${this.providerDebugLabel}: reconnect attempt aborted`));
|
|
2980
|
+
try {
|
|
2981
|
+
nextSocket.close();
|
|
2982
|
+
} catch {
|
|
2983
|
+
}
|
|
2984
|
+
};
|
|
2985
|
+
if (context.Signal.aborted) {
|
|
2986
|
+
onAbort();
|
|
2987
|
+
throw new Error(`${this.providerDebugLabel}: reconnect attempt aborted`);
|
|
2988
|
+
}
|
|
2989
|
+
context.Signal.addEventListener("abort", onAbort, { once: true });
|
|
2990
|
+
nextSocket.onopen = () => {
|
|
2991
|
+
nextSocketOpen = true;
|
|
2992
|
+
openSocket?.();
|
|
2993
|
+
};
|
|
2994
|
+
nextSocket.onmessage = (data) => {
|
|
2995
|
+
if (this.socket === nextSocket) {
|
|
2996
|
+
this.handleProtocolMessage(data);
|
|
2997
|
+
return;
|
|
2998
|
+
}
|
|
2999
|
+
try {
|
|
3000
|
+
const event = JSON.parse(data);
|
|
3001
|
+
if (event && typeof event === "object" && event.type === "session.created") {
|
|
3002
|
+
this.onSessionCreatedFrame();
|
|
3003
|
+
} else if (event && typeof event === "object" && event.type === "conversation.created") {
|
|
3004
|
+
const conv = event.conversation;
|
|
3005
|
+
if (typeof conv?.id === "string" && conv.id.trim().length > 0) {
|
|
3006
|
+
this.RecordResumptionHandle(conv.id);
|
|
3007
|
+
}
|
|
3008
|
+
}
|
|
3009
|
+
} catch {
|
|
3010
|
+
}
|
|
3011
|
+
};
|
|
3012
|
+
nextSocket.onerror = (message) => {
|
|
3013
|
+
nextSocketOpen = false;
|
|
3014
|
+
failReconnect?.(new Error(message));
|
|
3015
|
+
if (this.socket === nextSocket) {
|
|
3016
|
+
this.socketOpen = false;
|
|
3017
|
+
this.handleSocketError(message);
|
|
3018
|
+
}
|
|
3019
|
+
};
|
|
3020
|
+
nextSocket.onclose = () => {
|
|
3021
|
+
nextSocketOpen = false;
|
|
3022
|
+
failReconnect?.(new Error(`${this.providerDebugLabel} socket closed during reconnect`));
|
|
3023
|
+
if (this.socket === nextSocket) {
|
|
3024
|
+
this.socketOpen = false;
|
|
3025
|
+
this.handleSocketClose();
|
|
3026
|
+
}
|
|
3027
|
+
};
|
|
3028
|
+
try {
|
|
3029
|
+
await Promise.race([opened, failure]);
|
|
3030
|
+
if (context.Abandoned) {
|
|
3031
|
+
throw new Error(`${this.providerDebugLabel}: reconnect attempt abandoned after open`);
|
|
3032
|
+
}
|
|
3033
|
+
if (created) {
|
|
3034
|
+
await Promise.race([created, failure]);
|
|
3035
|
+
}
|
|
3036
|
+
if (context.Abandoned) {
|
|
3037
|
+
throw new Error(`${this.providerDebugLabel}: reconnect attempt abandoned after session.created`);
|
|
3038
|
+
}
|
|
3039
|
+
} catch (err) {
|
|
3040
|
+
nextSocket.onopen = null;
|
|
3041
|
+
nextSocket.onmessage = null;
|
|
3042
|
+
nextSocket.onerror = null;
|
|
3043
|
+
nextSocket.onclose = null;
|
|
3044
|
+
try {
|
|
3045
|
+
nextSocket.close();
|
|
3046
|
+
} catch {
|
|
3047
|
+
}
|
|
3048
|
+
throw err;
|
|
3049
|
+
} finally {
|
|
3050
|
+
context.Signal.removeEventListener("abort", onAbort);
|
|
3051
|
+
failReconnect = null;
|
|
3052
|
+
this.sessionCreatedResolver = null;
|
|
3053
|
+
}
|
|
3054
|
+
if (prevSocket) {
|
|
3055
|
+
prevSocket.onopen = null;
|
|
3056
|
+
prevSocket.onmessage = null;
|
|
3057
|
+
prevSocket.onerror = null;
|
|
3058
|
+
prevSocket.onclose = null;
|
|
3059
|
+
}
|
|
3060
|
+
this.socket = nextSocket;
|
|
3061
|
+
this.socketOpen = nextSocketOpen;
|
|
3062
|
+
try {
|
|
3063
|
+
prevSocket?.close();
|
|
3064
|
+
} catch {
|
|
3065
|
+
}
|
|
3066
|
+
const answerWasInFlight = this.resetResponseStateForNewConnection();
|
|
3067
|
+
this.applySessionConfig();
|
|
3068
|
+
const resumedNatively = context.UseNativeResumption && Boolean(context.ResumptionHandle);
|
|
3069
|
+
this.seedConversationAfterMove(context, answerWasInFlight, !resumedNatively);
|
|
3070
|
+
this.setState("listening");
|
|
3071
|
+
}
|
|
1913
3072
|
// ── Brain seam implementations ─────────────────────────────────────────────
|
|
1914
3073
|
/** @inheritdoc — requires an OPEN socket (a CONNECTING raw WebSocket throws on send). */
|
|
1915
3074
|
canSendEvents() {
|
|
@@ -1989,24 +3148,36 @@ var OpenAIProtocolWebSocketRealtimeClient = class extends OpenAIProtocolRealtime
|
|
|
1989
3148
|
get unexpectedCloseMessage() {
|
|
1990
3149
|
return `${this.providerDebugLabel} connection closed unexpectedly`;
|
|
1991
3150
|
}
|
|
1992
|
-
/**
|
|
3151
|
+
/**
|
|
3152
|
+
* A socket error. During a live call it starts the `connection-lost` reconnect, and during a running reconnect it
|
|
3153
|
+
* tells that reconnect the socket is gone; before the call is live it is fatal and marks the session unusable
|
|
3154
|
+
* (obligation #6).
|
|
3155
|
+
*/
|
|
1993
3156
|
handleSocketError(message) {
|
|
1994
3157
|
if (this.currentState === "error" || this.currentState === "closed") {
|
|
1995
3158
|
return;
|
|
1996
3159
|
}
|
|
3160
|
+
if (this.recoverLostTransport(`socket error: ${message}`)) {
|
|
3161
|
+
return;
|
|
3162
|
+
}
|
|
1997
3163
|
this.emitError({ Message: this.formatTransportError(message), Fatal: true });
|
|
1998
3164
|
this.setState("error");
|
|
1999
3165
|
}
|
|
2000
3166
|
/**
|
|
2001
|
-
* A socket close the CONSUMER didn't ask for.
|
|
2002
|
-
*
|
|
2003
|
-
*
|
|
2004
|
-
*
|
|
3167
|
+
* A socket close the CONSUMER didn't ask for. During a live call it is a lost connection
|
|
3168
|
+
* (a network cut, a dropped proxy hop), so it goes to the shared `connection-lost`
|
|
3169
|
+
* reconnect, or to the reconnect already running; a session the provider really ended
|
|
3170
|
+
* surfaces as `reconnect-failed` once the recovery window closes. Before the call is live
|
|
3171
|
+
* it is FATAL — that is how a rejected credential or session reaches the host (obligation
|
|
3172
|
+
* #6). Providers with benign close semantics (a self-hosted proxy hop) override.
|
|
2005
3173
|
*/
|
|
2006
3174
|
handleSocketClose() {
|
|
2007
3175
|
if (this.closedByConsumer || this.currentState === "error" || this.currentState === "closed") {
|
|
2008
3176
|
return;
|
|
2009
3177
|
}
|
|
3178
|
+
if (this.recoverLostTransport("socket closed")) {
|
|
3179
|
+
return;
|
|
3180
|
+
}
|
|
2010
3181
|
this.emitError({ Message: this.unexpectedCloseMessage, Fatal: true });
|
|
2011
3182
|
this.setState("error");
|
|
2012
3183
|
}
|
|
@@ -2300,7 +3471,12 @@ var VideoSourceArbiter = class _VideoSourceArbiter {
|
|
|
2300
3471
|
}
|
|
2301
3472
|
this.reconcile(true);
|
|
2302
3473
|
if (notify) {
|
|
2303
|
-
|
|
3474
|
+
const activeLabels = this.computeActive().map((id) => this.sources.get(id)?.Label ?? id);
|
|
3475
|
+
const activeSnapshot = activeLabels.length > 0 ? VideoSourceSeenNote(activeLabels) : void 0;
|
|
3476
|
+
this.sendNote(enabled ? this.formatEnabledNote(source.Label) : this.formatDisabledNote(source.Label), {
|
|
3477
|
+
StateKey: "video-source",
|
|
3478
|
+
...activeSnapshot ? { MemoryText: activeSnapshot } : {}
|
|
3479
|
+
});
|
|
2304
3480
|
}
|
|
2305
3481
|
this.emitChange();
|
|
2306
3482
|
return true;
|
|
@@ -2444,7 +3620,7 @@ var VideoSourceArbiter = class _VideoSourceArbiter {
|
|
|
2444
3620
|
return;
|
|
2445
3621
|
}
|
|
2446
3622
|
const labels = active.map((id) => this.sources.get(id)?.Label ?? id);
|
|
2447
|
-
this.sendNote(this.options.FormatSwitchNote ? this.options.FormatSwitchNote(labels) : VideoSourceSeenNote(labels));
|
|
3623
|
+
this.sendNote(this.options.FormatSwitchNote ? this.options.FormatSwitchNote(labels) : VideoSourceSeenNote(labels), { StateKey: "video-source" });
|
|
2448
3624
|
}
|
|
2449
3625
|
// ── plumbing ────────────────────────────────────────────────────────────
|
|
2450
3626
|
formatDisabledNote(label) {
|
|
@@ -2464,13 +3640,13 @@ var VideoSourceArbiter = class _VideoSourceArbiter {
|
|
|
2464
3640
|
return false;
|
|
2465
3641
|
}
|
|
2466
3642
|
}
|
|
2467
|
-
sendNote(note) {
|
|
3643
|
+
sendNote(note, options) {
|
|
2468
3644
|
const sink = this.sink;
|
|
2469
3645
|
if (!note || !sink) {
|
|
2470
3646
|
return;
|
|
2471
3647
|
}
|
|
2472
3648
|
try {
|
|
2473
|
-
sink.SendContextNote(note);
|
|
3649
|
+
sink.SendContextNote(note, options);
|
|
2474
3650
|
} catch (error) {
|
|
2475
3651
|
this.reportError("sending a source note", error);
|
|
2476
3652
|
}
|
|
@@ -3815,6 +4991,7 @@ var __decorate = function(decorators, target, key, desc) {
|
|
|
3815
4991
|
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
3816
4992
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
3817
4993
|
};
|
|
4994
|
+
var OpenAIRealtimeClient_1;
|
|
3818
4995
|
var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRealtimeClient {
|
|
3819
4996
|
constructor() {
|
|
3820
4997
|
super(...arguments);
|
|
@@ -3824,6 +5001,16 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
|
|
|
3824
5001
|
this.remoteAudioEl = null;
|
|
3825
5002
|
this.sessionConfig = null;
|
|
3826
5003
|
this.audioPlaying = false;
|
|
5004
|
+
this.disconnectedGraceTimer = null;
|
|
5005
|
+
}
|
|
5006
|
+
static {
|
|
5007
|
+
OpenAIRealtimeClient_1 = this;
|
|
5008
|
+
}
|
|
5009
|
+
static {
|
|
5010
|
+
this.PEER_DISCONNECTED_GRACE_MS = 5e3;
|
|
5011
|
+
}
|
|
5012
|
+
get DefaultCallDurationSeconds() {
|
|
5013
|
+
return 3600;
|
|
3827
5014
|
}
|
|
3828
5015
|
// ── BaseRealtimeClient: connection lifecycle ───────────────────────────────
|
|
3829
5016
|
/**
|
|
@@ -3834,11 +5021,13 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
|
|
|
3834
5021
|
*/
|
|
3835
5022
|
async Connect(config, micStream) {
|
|
3836
5023
|
this.AssertTransportSupported(config);
|
|
5024
|
+
this.ApplySessionConfigTiming(config);
|
|
3837
5025
|
this.sessionConfig = config.SessionConfig;
|
|
3838
5026
|
this.micStream = micStream;
|
|
3839
5027
|
this.setState("connecting");
|
|
3840
5028
|
const pc = this.createPeerConnection();
|
|
3841
5029
|
this.peerConnection = pc;
|
|
5030
|
+
pc.onconnectionstatechange = () => this.handlePeerConnectionState(pc);
|
|
3842
5031
|
this.attachMicrophone(pc, micStream);
|
|
3843
5032
|
this.attachRemoteAudio(pc);
|
|
3844
5033
|
this.adoptDataChannel(pc.createDataChannel("oai-events"));
|
|
@@ -3867,6 +5056,8 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
|
|
|
3867
5056
|
* response state machine, and emits a final `'closed'` (unless already `'error'`).
|
|
3868
5057
|
*/
|
|
3869
5058
|
async Disconnect() {
|
|
5059
|
+
this.DisposeReconnectTimers();
|
|
5060
|
+
this.clearDisconnectedGrace();
|
|
3870
5061
|
this.closeAudioMeters();
|
|
3871
5062
|
this.micStream?.getTracks().forEach((t) => t.stop());
|
|
3872
5063
|
this.micStream = null;
|
|
@@ -3879,6 +5070,7 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
|
|
|
3879
5070
|
this.dataChannel = null;
|
|
3880
5071
|
}
|
|
3881
5072
|
if (this.peerConnection) {
|
|
5073
|
+
this.peerConnection.onconnectionstatechange = null;
|
|
3882
5074
|
try {
|
|
3883
5075
|
this.peerConnection.close();
|
|
3884
5076
|
} catch {
|
|
@@ -3898,11 +5090,162 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
|
|
|
3898
5090
|
this.setState("closed");
|
|
3899
5091
|
}
|
|
3900
5092
|
}
|
|
5093
|
+
/**
|
|
5094
|
+
* Performs an in-place WebRTC peer-connection and data-channel swap on duration expiry
|
|
5095
|
+
* while preserving the existing `micStream` and hidden `<audio>` sink.
|
|
5096
|
+
*/
|
|
5097
|
+
async Reconnect(context) {
|
|
5098
|
+
if (!this.micStream) {
|
|
5099
|
+
throw new Error("OpenAIRealtimeClient: cannot reconnect without an active microphone stream");
|
|
5100
|
+
}
|
|
5101
|
+
if (context.Abandoned) {
|
|
5102
|
+
throw new Error("OpenAIRealtimeClient: reconnect attempt abandoned");
|
|
5103
|
+
}
|
|
5104
|
+
if (context.Credential.SessionConfig !== void 0) {
|
|
5105
|
+
this.sessionConfig = context.Credential.SessionConfig;
|
|
5106
|
+
}
|
|
5107
|
+
const prevPc = this.peerConnection;
|
|
5108
|
+
const prevDc = this.dataChannel;
|
|
5109
|
+
const nextPc = this.createPeerConnection();
|
|
5110
|
+
const nextSenders = this.micStream.getAudioTracks().map((track) => nextPc.addTrack(track, this.micStream));
|
|
5111
|
+
if (!this.remoteAudioEl) {
|
|
5112
|
+
this.remoteAudioEl = this.createAudioSink();
|
|
5113
|
+
}
|
|
5114
|
+
let pendingRemoteStream = null;
|
|
5115
|
+
nextPc.ontrack = (e) => {
|
|
5116
|
+
if (context.Abandoned || !e.streams[0]) {
|
|
5117
|
+
return;
|
|
5118
|
+
}
|
|
5119
|
+
if (this.peerConnection === nextPc && this.remoteAudioEl) {
|
|
5120
|
+
this.remoteAudioEl.srcObject = e.streams[0];
|
|
5121
|
+
this.publishRemoteMediaStream(e.streams[0]);
|
|
5122
|
+
this.attachOutputAudioMeter(RealtimeAudioMeter.ForStream(e.streams[0]));
|
|
5123
|
+
} else {
|
|
5124
|
+
pendingRemoteStream = e.streams[0];
|
|
5125
|
+
}
|
|
5126
|
+
};
|
|
5127
|
+
const nextDc = nextPc.createDataChannel("oai-events");
|
|
5128
|
+
let openDc = null;
|
|
5129
|
+
let failDc = null;
|
|
5130
|
+
const dcOpened = new Promise((resolve, reject) => {
|
|
5131
|
+
openDc = resolve;
|
|
5132
|
+
failDc = reject;
|
|
5133
|
+
});
|
|
5134
|
+
dcOpened.catch(() => void 0);
|
|
5135
|
+
const onAbort = () => {
|
|
5136
|
+
failDc?.(new Error("OpenAIRealtimeClient: reconnect attempt aborted"));
|
|
5137
|
+
try {
|
|
5138
|
+
nextDc.close();
|
|
5139
|
+
} catch {
|
|
5140
|
+
}
|
|
5141
|
+
try {
|
|
5142
|
+
nextPc.close();
|
|
5143
|
+
} catch {
|
|
5144
|
+
}
|
|
5145
|
+
};
|
|
5146
|
+
if (context.Signal.aborted) {
|
|
5147
|
+
onAbort();
|
|
5148
|
+
throw new Error("OpenAIRealtimeClient: reconnect attempt aborted");
|
|
5149
|
+
}
|
|
5150
|
+
context.Signal.addEventListener("abort", onAbort, { once: true });
|
|
5151
|
+
nextDc.onopen = () => {
|
|
5152
|
+
openDc?.();
|
|
5153
|
+
};
|
|
5154
|
+
nextDc.onmessage = (e) => {
|
|
5155
|
+
if (this.dataChannel === nextDc) {
|
|
5156
|
+
this.handleProtocolMessage(String(e.data));
|
|
5157
|
+
}
|
|
5158
|
+
};
|
|
5159
|
+
nextDc.onerror = (e) => {
|
|
5160
|
+
failDc?.(new Error(`Data channel error: ${String(e)}`));
|
|
5161
|
+
this.handleChannelError(nextDc, e);
|
|
5162
|
+
};
|
|
5163
|
+
nextDc.onclose = () => {
|
|
5164
|
+
failDc?.(new Error("OpenAI data channel closed during reconnect"));
|
|
5165
|
+
this.handleChannelClose(nextDc);
|
|
5166
|
+
};
|
|
5167
|
+
nextPc.onconnectionstatechange = () => {
|
|
5168
|
+
if (nextPc.connectionState === "failed") {
|
|
5169
|
+
failDc?.(new Error("OpenAI peer connection failed during reconnect"));
|
|
5170
|
+
}
|
|
5171
|
+
this.handlePeerConnectionState(nextPc);
|
|
5172
|
+
};
|
|
5173
|
+
try {
|
|
5174
|
+
await this.performSdpHandshake(nextPc, context.Credential.EphemeralToken);
|
|
5175
|
+
if (nextDc.readyState !== "open") {
|
|
5176
|
+
await dcOpened;
|
|
5177
|
+
}
|
|
5178
|
+
if (context.Abandoned) {
|
|
5179
|
+
throw new Error("OpenAIRealtimeClient: reconnect attempt abandoned after open");
|
|
5180
|
+
}
|
|
5181
|
+
} catch (err) {
|
|
5182
|
+
nextDc.onopen = null;
|
|
5183
|
+
nextDc.onmessage = null;
|
|
5184
|
+
nextDc.onerror = null;
|
|
5185
|
+
nextDc.onclose = null;
|
|
5186
|
+
nextPc.ontrack = null;
|
|
5187
|
+
nextPc.onconnectionstatechange = null;
|
|
5188
|
+
try {
|
|
5189
|
+
nextDc.close();
|
|
5190
|
+
} catch {
|
|
5191
|
+
}
|
|
5192
|
+
try {
|
|
5193
|
+
nextPc.close();
|
|
5194
|
+
} catch {
|
|
5195
|
+
}
|
|
5196
|
+
throw err;
|
|
5197
|
+
} finally {
|
|
5198
|
+
context.Signal.removeEventListener("abort", onAbort);
|
|
5199
|
+
}
|
|
5200
|
+
if (prevDc) {
|
|
5201
|
+
prevDc.onopen = null;
|
|
5202
|
+
prevDc.onmessage = null;
|
|
5203
|
+
prevDc.onerror = null;
|
|
5204
|
+
prevDc.onclose = null;
|
|
5205
|
+
}
|
|
5206
|
+
if (prevPc) {
|
|
5207
|
+
prevPc.ontrack = null;
|
|
5208
|
+
prevPc.onconnectionstatechange = null;
|
|
5209
|
+
}
|
|
5210
|
+
this.clearDisconnectedGrace();
|
|
5211
|
+
this.peerConnection = nextPc;
|
|
5212
|
+
this.dataChannel = nextDc;
|
|
5213
|
+
this.micSenders = nextSenders;
|
|
5214
|
+
if (pendingRemoteStream && this.remoteAudioEl) {
|
|
5215
|
+
this.remoteAudioEl.srcObject = pendingRemoteStream;
|
|
5216
|
+
this.publishRemoteMediaStream(pendingRemoteStream);
|
|
5217
|
+
this.attachOutputAudioMeter(RealtimeAudioMeter.ForStream(pendingRemoteStream));
|
|
5218
|
+
pendingRemoteStream = null;
|
|
5219
|
+
}
|
|
5220
|
+
const answerWasInFlight = this.resetResponseStateForNewConnection();
|
|
5221
|
+
this.audioPlaying = false;
|
|
5222
|
+
try {
|
|
5223
|
+
prevDc?.close();
|
|
5224
|
+
} catch {
|
|
5225
|
+
}
|
|
5226
|
+
try {
|
|
5227
|
+
prevPc?.close();
|
|
5228
|
+
} catch {
|
|
5229
|
+
}
|
|
5230
|
+
this.applySessionConfig(nextDc);
|
|
5231
|
+
this.seedConversationAfterMove(context, answerWasInFlight, true);
|
|
5232
|
+
this.setState("listening");
|
|
5233
|
+
}
|
|
3901
5234
|
// ── Brain seam implementations (WebRTC transport) ──────────────────────────
|
|
3902
5235
|
/** @inheritdoc — events flow over the `'oai-events'` data channel once it is open. */
|
|
3903
5236
|
canSendEvents() {
|
|
3904
5237
|
return this.dataChannel !== null && this.dataChannel.readyState === "open";
|
|
3905
5238
|
}
|
|
5239
|
+
/**
|
|
5240
|
+
* @inheritdoc
|
|
5241
|
+
*
|
|
5242
|
+
* Also a peer connection that has not lost its network path: the data channel can read `'open'` long after the
|
|
5243
|
+
* path is gone (SCTP keeps waiting), so input sent into it then is lost.
|
|
5244
|
+
*/
|
|
5245
|
+
isTransportUsable() {
|
|
5246
|
+
const state = this.peerConnection?.connectionState;
|
|
5247
|
+
return super.isTransportUsable() && state !== "disconnected" && state !== "failed" && state !== "closed";
|
|
5248
|
+
}
|
|
3906
5249
|
/** @inheritdoc */
|
|
3907
5250
|
sendProtocolEvent(event) {
|
|
3908
5251
|
this.dataChannel?.send(JSON.stringify(event));
|
|
@@ -3993,29 +5336,104 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
|
|
|
3993
5336
|
};
|
|
3994
5337
|
}
|
|
3995
5338
|
/**
|
|
3996
|
-
* Adopts + wires the events data channel: applies the session config and reports
|
|
3997
|
-
* `'listening'` on open; translates inbound frames through the shared protocol brain;
|
|
3998
|
-
* reports transport errors / closure. Protected so test subclasses can inject a fake
|
|
3999
|
-
* channel directly.
|
|
5339
|
+
* Adopts + wires the events data channel: applies the session config and reports
|
|
5340
|
+
* `'listening'` on open; translates inbound frames through the shared protocol brain;
|
|
5341
|
+
* reports transport errors / closure. Protected so test subclasses can inject a fake
|
|
5342
|
+
* channel directly.
|
|
5343
|
+
*/
|
|
5344
|
+
adoptDataChannel(channel) {
|
|
5345
|
+
this.dataChannel = channel;
|
|
5346
|
+
channel.onopen = () => {
|
|
5347
|
+
this.applySessionConfig(channel);
|
|
5348
|
+
this.ArmConnectionDurationTimer();
|
|
5349
|
+
this.setState("listening");
|
|
5350
|
+
};
|
|
5351
|
+
channel.onmessage = (e) => {
|
|
5352
|
+
this.handleProtocolMessage(String(e.data));
|
|
5353
|
+
};
|
|
5354
|
+
channel.onerror = (e) => this.handleChannelError(channel, e);
|
|
5355
|
+
channel.onclose = () => this.handleChannelClose(channel);
|
|
5356
|
+
}
|
|
5357
|
+
/**
|
|
5358
|
+
* A data-channel error. Ignored for a channel that is no longer current (the user's End or a swap already let go
|
|
5359
|
+
* of it). During a live call it starts the `connection-lost` reconnect, or goes to the reconnect already running;
|
|
5360
|
+
* otherwise it is fatal.
|
|
5361
|
+
*/
|
|
5362
|
+
handleChannelError(channel, e) {
|
|
5363
|
+
if (this.dataChannel !== channel) {
|
|
5364
|
+
return;
|
|
5365
|
+
}
|
|
5366
|
+
if (this.recoverLostTransport(`data channel error: ${String(e)}`)) {
|
|
5367
|
+
return;
|
|
5368
|
+
}
|
|
5369
|
+
this.emitError({ Message: `Data channel error: ${String(e)}`, Fatal: true });
|
|
5370
|
+
this.setState("error");
|
|
5371
|
+
}
|
|
5372
|
+
/**
|
|
5373
|
+
* A data-channel close the consumer did not ask for (Disconnect and the swap drop the channel before closing it,
|
|
5374
|
+
* so the identity check filters both). During a live call it starts the `connection-lost` reconnect, or goes to the
|
|
5375
|
+
* reconnect already running; a channel that closes before the call went live ends the session as `'closed'`.
|
|
5376
|
+
*/
|
|
5377
|
+
handleChannelClose(channel) {
|
|
5378
|
+
if (this.dataChannel !== channel || this.currentState === "error") {
|
|
5379
|
+
return;
|
|
5380
|
+
}
|
|
5381
|
+
if (this.recoverLostTransport("data channel closed")) {
|
|
5382
|
+
return;
|
|
5383
|
+
}
|
|
5384
|
+
this.setState("closed");
|
|
5385
|
+
}
|
|
5386
|
+
/**
|
|
5387
|
+
* Watches the current peer connection's state. A lost network path often never closes the data channel (SCTP
|
|
5388
|
+
* keeps waiting), so the peer connection's ICE consent checks are the liveness signal: `'failed'` is a loss at
|
|
5389
|
+
* once, `'disconnected'` is one once it outlasts {@link PEER_DISCONNECTED_GRACE_MS}, and `'connected'` (healed)
|
|
5390
|
+
* or a local `'closed'` stops the grace timer.
|
|
5391
|
+
*/
|
|
5392
|
+
handlePeerConnectionState(pc) {
|
|
5393
|
+
if (this.peerConnection !== pc) {
|
|
5394
|
+
return;
|
|
5395
|
+
}
|
|
5396
|
+
switch (pc.connectionState) {
|
|
5397
|
+
case "failed":
|
|
5398
|
+
this.clearDisconnectedGrace();
|
|
5399
|
+
this.handlePeerConnectionLost("peer connection failed");
|
|
5400
|
+
break;
|
|
5401
|
+
case "disconnected":
|
|
5402
|
+
this.disconnectedGraceTimer ??= setTimeout(() => {
|
|
5403
|
+
this.disconnectedGraceTimer = null;
|
|
5404
|
+
if (this.peerConnection === pc && pc.connectionState === "disconnected") {
|
|
5405
|
+
this.handlePeerConnectionLost(`peer connection disconnected for ${OpenAIRealtimeClient_1.PEER_DISCONNECTED_GRACE_MS} ms`);
|
|
5406
|
+
}
|
|
5407
|
+
}, OpenAIRealtimeClient_1.PEER_DISCONNECTED_GRACE_MS);
|
|
5408
|
+
break;
|
|
5409
|
+
case "connected":
|
|
5410
|
+
case "closed":
|
|
5411
|
+
this.clearDisconnectedGrace();
|
|
5412
|
+
break;
|
|
5413
|
+
default:
|
|
5414
|
+
break;
|
|
5415
|
+
}
|
|
5416
|
+
}
|
|
5417
|
+
/**
|
|
5418
|
+
* The peer connection lost its network path. During a live call this starts the `connection-lost` reconnect;
|
|
5419
|
+
* before that (or when the driver cannot reconnect) the session is unusable, so it ends as a fatal error instead
|
|
5420
|
+
* of sitting silent on a dead transport.
|
|
4000
5421
|
*/
|
|
4001
|
-
|
|
4002
|
-
this.
|
|
4003
|
-
|
|
4004
|
-
|
|
4005
|
-
|
|
4006
|
-
|
|
4007
|
-
|
|
4008
|
-
|
|
4009
|
-
|
|
4010
|
-
|
|
4011
|
-
|
|
4012
|
-
|
|
4013
|
-
|
|
4014
|
-
|
|
4015
|
-
|
|
4016
|
-
this.setState("closed");
|
|
4017
|
-
}
|
|
4018
|
-
};
|
|
5422
|
+
handlePeerConnectionLost(detail) {
|
|
5423
|
+
if (this.recoverLostTransport(detail)) {
|
|
5424
|
+
return;
|
|
5425
|
+
}
|
|
5426
|
+
if (this.currentState === "error" || this.currentState === "closed") {
|
|
5427
|
+
return;
|
|
5428
|
+
}
|
|
5429
|
+
this.emitError({ Message: `OpenAI WebRTC ${detail}`, Fatal: true });
|
|
5430
|
+
this.setState("error");
|
|
5431
|
+
}
|
|
5432
|
+
clearDisconnectedGrace() {
|
|
5433
|
+
if (this.disconnectedGraceTimer !== null) {
|
|
5434
|
+
clearTimeout(this.disconnectedGraceTimer);
|
|
5435
|
+
this.disconnectedGraceTimer = null;
|
|
5436
|
+
}
|
|
4019
5437
|
}
|
|
4020
5438
|
/** Performs the offer/answer SDP exchange (POST seam: {@link postSdpOffer}). */
|
|
4021
5439
|
async performSdpHandshake(pc, ephemeralToken) {
|
|
@@ -4051,7 +5469,7 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
|
|
|
4051
5469
|
}
|
|
4052
5470
|
}
|
|
4053
5471
|
};
|
|
4054
|
-
OpenAIRealtimeClient = __decorate([
|
|
5472
|
+
OpenAIRealtimeClient = OpenAIRealtimeClient_1 = __decorate([
|
|
4055
5473
|
RegisterClass(BaseRealtimeClient, "openai")
|
|
4056
5474
|
], OpenAIRealtimeClient);
|
|
4057
5475
|
|
|
@@ -26289,6 +27707,7 @@ var GEMINI_INPUT_AUDIO_MIME_TYPE = "audio/pcm;rate=16000";
|
|
|
26289
27707
|
var GEMINI_OUTPUT_SAMPLE_RATE = 24e3;
|
|
26290
27708
|
var HELD_MIC_AUDIO_SECONDS = 2;
|
|
26291
27709
|
var MAX_HELD_MIC_AUDIO_BASE64_CHARS = Math.ceil(GEMINI_INPUT_SAMPLE_RATE * 2 * HELD_MIC_AUDIO_SECONDS * 4 / 3);
|
|
27710
|
+
var GEMINI_UNANSWERED_UTTERANCE_HOLD_MS = 5e3;
|
|
26292
27711
|
var GEMINI_MODALITY_TOKEN_FIELDS = {
|
|
26293
27712
|
TEXT: "TextTokens",
|
|
26294
27713
|
AUDIO: "AudioTokens",
|
|
@@ -26306,6 +27725,10 @@ var GeminiPcmPlayback = class extends RealtimePcmPlayback {
|
|
|
26306
27725
|
var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClient {
|
|
26307
27726
|
constructor() {
|
|
26308
27727
|
super(...arguments);
|
|
27728
|
+
this.uncompressedVideoConnectionSeconds = GeminiRealtimeClient_1.GEMINI_LIVE_UNCOMPRESSED_VIDEO_CONNECTION_SECONDS;
|
|
27729
|
+
this.videoCapActive = false;
|
|
27730
|
+
this.hasResumedOnce = false;
|
|
27731
|
+
this.currentClosedPromise = null;
|
|
26309
27732
|
this.session = null;
|
|
26310
27733
|
this.micStream = null;
|
|
26311
27734
|
this.cameraStream = null;
|
|
@@ -26316,11 +27739,12 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26316
27739
|
this.firstVideoSendTimestamp = 0;
|
|
26317
27740
|
this.lastVideoSendTimestamp = 0;
|
|
26318
27741
|
this.videoFramesSent = 0;
|
|
26319
|
-
this.resumption = null;
|
|
26320
27742
|
this.connectionReady = false;
|
|
26321
27743
|
this.heldMicAudio = [];
|
|
26322
27744
|
this.heldMicAudioChars = 0;
|
|
26323
27745
|
this.turnOpen = false;
|
|
27746
|
+
this.unansweredSpeechAtMs = null;
|
|
27747
|
+
this.unansweredSpeechTimer = null;
|
|
26324
27748
|
this.turnEndAwaitsToolResults = false;
|
|
26325
27749
|
this.connectTarget = null;
|
|
26326
27750
|
this.issuedConnections = 0;
|
|
@@ -26349,9 +27773,76 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26349
27773
|
static {
|
|
26350
27774
|
this.ASSISTANT_SAFETY_BACKSTOP_MS = 15e3;
|
|
26351
27775
|
}
|
|
26352
|
-
|
|
26353
|
-
|
|
26354
|
-
|
|
27776
|
+
static {
|
|
27777
|
+
this.GEMINI_LIVE_CONNECTION_SECONDS = 600;
|
|
27778
|
+
}
|
|
27779
|
+
static {
|
|
27780
|
+
this.GEMINI_LIVE_UNCOMPRESSED_VIDEO_CONNECTION_SECONDS = 120;
|
|
27781
|
+
}
|
|
27782
|
+
get DefaultCallDurationSeconds() {
|
|
27783
|
+
return GeminiRealtimeClient_1.GEMINI_LIVE_CONNECTION_SECONDS;
|
|
27784
|
+
}
|
|
27785
|
+
/**
|
|
27786
|
+
* Applies the 120 s uncompressed-video connection cap only when inbound video is active,
|
|
27787
|
+
* at least one frame has been sent on the current connection/stream (`videoCapActive`), AND
|
|
27788
|
+
* `this.uncompressedVideoConnectionSeconds` is defined (`undefined` when sliding-window
|
|
27789
|
+
* compression is enabled in the session pact or connect config).
|
|
27790
|
+
*/
|
|
27791
|
+
get RuntimeCallDurationSeconds() {
|
|
27792
|
+
if (this.uncompressedVideoConnectionSeconds !== void 0 && this.IsTrackEstablished("video", "inbound") && this.videoCapActive) {
|
|
27793
|
+
return this.uncompressedVideoConnectionSeconds;
|
|
27794
|
+
}
|
|
27795
|
+
return void 0;
|
|
27796
|
+
}
|
|
27797
|
+
/**
|
|
27798
|
+
* Google Gemini Developer API (`GeminiRealtimeClient`, key `'gemini'`) defaults to `false`
|
|
27799
|
+
* because `BidiGenerateContent` does not reliably honor `sessionResumption.handle` across
|
|
27800
|
+
* connections; `GeminiEnterpriseRealtimeClient` (Vertex AI Live) overrides this to `true`.
|
|
27801
|
+
*/
|
|
27802
|
+
get DefaultTrustsNativeResumption() {
|
|
27803
|
+
return false;
|
|
27804
|
+
}
|
|
27805
|
+
/** Gemini / Vertex AI Live emits a fresh resumable handle shortly after each `turnComplete`. */
|
|
27806
|
+
get RequiresPostTurnResumptionHandle() {
|
|
27807
|
+
return true;
|
|
27808
|
+
}
|
|
27809
|
+
/**
|
|
27810
|
+
* Gemini ephemeral tokens open several connections (`SessionConfig.tokenUses`) until `ExpiresAt`, and relay
|
|
27811
|
+
* tickets allow multiple opens until `ExpiresAt`, so refreshes are driven by `ExpiresAt` and the spent uses
|
|
27812
|
+
* ({@link CredentialConnectionLimit}) rather than minting a new token on every reconnect attempt.
|
|
27813
|
+
*/
|
|
27814
|
+
get RequiresFreshTokenPerReconnect() {
|
|
27815
|
+
return false;
|
|
27816
|
+
}
|
|
27817
|
+
/**
|
|
27818
|
+
* The connections a minted ephemeral token opens (`tokenUses`, which the server sizes from the effective connection
|
|
27819
|
+
* length). Each resume is a new session to Gemini and spends one; one past the count is refused
|
|
27820
|
+
* "Token has been used too many times". A relay ticket, or a mint that predates the field, has no limit here.
|
|
27821
|
+
*/
|
|
27822
|
+
CredentialConnectionLimit(credential) {
|
|
27823
|
+
if (credential.Kind === "relay") {
|
|
27824
|
+
return void 0;
|
|
27825
|
+
}
|
|
27826
|
+
const uses = credential.SessionConfig?.["tokenUses"];
|
|
27827
|
+
return typeof uses === "number" && Number.isInteger(uses) && uses > 0 ? uses : void 0;
|
|
27828
|
+
}
|
|
27829
|
+
/**
|
|
27830
|
+
* Google closes a connection opened on an ephemeral token when that token's `expireTime` passes ("1011 auth token has
|
|
27831
|
+
* expired"), even after the client holds a refreshed one: the token bounds the sessions it opened, not only their
|
|
27832
|
+
* setup. A relay connection runs on the server's key, and its ticket only gates opening the tunnel.
|
|
27833
|
+
*/
|
|
27834
|
+
ConnectionClosesAtCredentialExpiry(credential) {
|
|
27835
|
+
return credential.Kind !== "relay";
|
|
27836
|
+
}
|
|
27837
|
+
RemoveTrack(descriptor) {
|
|
27838
|
+
const removed = super.RemoveTrack(descriptor);
|
|
27839
|
+
if (removed && !this.IsTrackEstablished("video", "inbound") && this.videoCapActive) {
|
|
27840
|
+
this.videoCapActive = false;
|
|
27841
|
+
if (this.connectionReady && !this.IsReconnecting) {
|
|
27842
|
+
this.ArmConnectionDurationTimer();
|
|
27843
|
+
}
|
|
27844
|
+
}
|
|
27845
|
+
return removed;
|
|
26355
27846
|
}
|
|
26356
27847
|
/**
|
|
26357
27848
|
* Whether a turn is in progress. A turn opens at its first sign: the user's first transcribed words, a turn this
|
|
@@ -26407,18 +27898,20 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26407
27898
|
async Connect(config, micStream, cameraStream) {
|
|
26408
27899
|
this.AssertTransportSupported(config);
|
|
26409
27900
|
this.resetForConnect(micStream, cameraStream);
|
|
27901
|
+
this.ApplySessionConfigTiming(config);
|
|
26410
27902
|
this.setState("connecting");
|
|
26411
27903
|
const session = this.parseSessionConfig(config);
|
|
26412
27904
|
this.idleSignal = session.idleSignal;
|
|
26413
27905
|
this.supportsScheduling = session.supportsScheduling;
|
|
26414
27906
|
this.supportsBlocking = session.supportsBlocking;
|
|
27907
|
+
const hasContextCompression = session.contextWindowCompression ?? (session.uncompressedVideoConnectionMaxSeconds === 0 ? true : Boolean(session.liveConfig.contextWindowCompression));
|
|
27908
|
+
const rawUncompressedVideoSec = session.uncompressedVideoConnectionMaxSeconds;
|
|
27909
|
+
this.uncompressedVideoConnectionSeconds = hasContextCompression ? void 0 : rawUncompressedVideoSec !== void 0 && rawUncompressedVideoSec > 0 ? rawUncompressedVideoSec : GeminiRealtimeClient_1.GEMINI_LIVE_UNCOMPRESSED_VIDEO_CONNECTION_SECONDS;
|
|
26415
27910
|
this.negotiateSessionTracks(session);
|
|
26416
27911
|
const playback = this.createPlayback();
|
|
26417
27912
|
this.playback = playback;
|
|
26418
27913
|
this.publishRemoteMediaStream(playback.GetOutputStream?.() ?? null);
|
|
26419
27914
|
const liveConfig = this.prepareAvatar(session, playback);
|
|
26420
|
-
this.resumption?.Dispose();
|
|
26421
|
-
this.resumption = this.createResumption();
|
|
26422
27915
|
const target = {
|
|
26423
27916
|
Model: session.model,
|
|
26424
27917
|
Config: liveConfig,
|
|
@@ -26446,6 +27939,9 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26446
27939
|
this.firstVideoSendTimestamp = 0;
|
|
26447
27940
|
this.lastVideoSendTimestamp = 0;
|
|
26448
27941
|
this.videoFramesSent = 0;
|
|
27942
|
+
this.videoCapActive = false;
|
|
27943
|
+
this.hasResumedOnce = false;
|
|
27944
|
+
this.currentClosedPromise = null;
|
|
26449
27945
|
this.resetConnectionState();
|
|
26450
27946
|
this.disposeAvatarOutput();
|
|
26451
27947
|
}
|
|
@@ -26608,6 +28104,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26608
28104
|
* Safe to call more than once.
|
|
26609
28105
|
*/
|
|
26610
28106
|
async Disconnect() {
|
|
28107
|
+
this.DisposeReconnectTimers();
|
|
26611
28108
|
this.closeAudioMeters();
|
|
26612
28109
|
this.clearSafetyBackstop();
|
|
26613
28110
|
this.toolBatchBarrier.Clear();
|
|
@@ -26621,15 +28118,16 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26621
28118
|
this.disposeAvatarOutput();
|
|
26622
28119
|
this.playback?.Close();
|
|
26623
28120
|
this.playback = null;
|
|
26624
|
-
this.resumption?.Dispose();
|
|
26625
|
-
this.resumption = null;
|
|
26626
28121
|
this.connectTarget = null;
|
|
26627
28122
|
this.currentConnection = 0;
|
|
28123
|
+
this.currentClosedPromise = null;
|
|
26628
28124
|
this.resetConnectionState();
|
|
26629
28125
|
this.clearRemoteMediaStream();
|
|
26630
28126
|
this.firstVideoSendTimestamp = 0;
|
|
26631
28127
|
this.lastVideoSendTimestamp = 0;
|
|
26632
28128
|
this.videoFramesSent = 0;
|
|
28129
|
+
this.videoCapActive = false;
|
|
28130
|
+
this.hasResumedOnce = false;
|
|
26633
28131
|
if (this.session) {
|
|
26634
28132
|
try {
|
|
26635
28133
|
this.session.close();
|
|
@@ -26658,7 +28156,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26658
28156
|
* needed.
|
|
26659
28157
|
*/
|
|
26660
28158
|
SendText(text) {
|
|
26661
|
-
if (!this.session) {
|
|
28159
|
+
if (!this.session && !this.IsReconnecting) {
|
|
26662
28160
|
return;
|
|
26663
28161
|
}
|
|
26664
28162
|
this.CancelActiveResponse();
|
|
@@ -26698,7 +28196,12 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26698
28196
|
if (this.firstVideoSendTimestamp === 0) {
|
|
26699
28197
|
this.firstVideoSendTimestamp = now;
|
|
26700
28198
|
}
|
|
28199
|
+
const wasVideoCapInactive = !this.videoCapActive;
|
|
28200
|
+
this.videoCapActive = true;
|
|
26701
28201
|
this.videoFramesSent++;
|
|
28202
|
+
if (wasVideoCapInactive && this.uncompressedVideoConnectionSeconds !== void 0) {
|
|
28203
|
+
this.ArmConnectionDurationTimer();
|
|
28204
|
+
}
|
|
26702
28205
|
this.session?.sendRealtimeInput({
|
|
26703
28206
|
video: { data: base64Image, mimeType }
|
|
26704
28207
|
});
|
|
@@ -26717,7 +28220,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26717
28220
|
* when nothing is active. An avatar's video stops with the voice.
|
|
26718
28221
|
*/
|
|
26719
28222
|
CancelActiveResponse() {
|
|
26720
|
-
if (!this.session) {
|
|
28223
|
+
if (!this.session && !this.IsReconnecting) {
|
|
26721
28224
|
return;
|
|
26722
28225
|
}
|
|
26723
28226
|
if (!this.responseActive && !this.IsAudioPlaying && !this.interactionInProgress) {
|
|
@@ -26746,10 +28249,15 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26746
28249
|
* holds generation until a `turnComplete: true` commit arrives. {@link openClientTurn}
|
|
26747
28250
|
* tracks this so {@link SendToolResult} can commit the turn and unblock the spoken reply.
|
|
26748
28251
|
*/
|
|
26749
|
-
SendContextNote(text) {
|
|
26750
|
-
if (!this.session) {
|
|
28252
|
+
SendContextNote(text, options) {
|
|
28253
|
+
if (!this.session && !this.IsReconnecting) {
|
|
26751
28254
|
return;
|
|
26752
28255
|
}
|
|
28256
|
+
this.conversationMemory.Record({
|
|
28257
|
+
Kind: "note",
|
|
28258
|
+
Text: text,
|
|
28259
|
+
...options
|
|
28260
|
+
});
|
|
26753
28261
|
this.enqueueOrRun(() => {
|
|
26754
28262
|
this.session?.sendClientContent({ turns: [{ role: "user", parts: [{ text }] }], turnComplete: false });
|
|
26755
28263
|
this.openClientTurn = true;
|
|
@@ -26765,14 +28273,14 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26765
28273
|
* in-flight turn so it can never interrupt a pending reply.
|
|
26766
28274
|
*/
|
|
26767
28275
|
RequestSpokenUpdate(instructions) {
|
|
26768
|
-
if (!this.session) {
|
|
28276
|
+
if (!this.session && !this.IsReconnecting) {
|
|
26769
28277
|
return;
|
|
26770
28278
|
}
|
|
26771
28279
|
this.enqueueOrRun(() => this.sendTriggeringUserTurn(instructions, "narration", false));
|
|
26772
28280
|
}
|
|
26773
28281
|
/** A spoken TURN: the same realtime-text trigger as the update, with the reply kept `normal` (MJ#4591). */
|
|
26774
28282
|
RequestSpokenTurn(instructions) {
|
|
26775
|
-
if (!this.session) {
|
|
28283
|
+
if (!this.session && !this.IsReconnecting) {
|
|
26776
28284
|
return;
|
|
26777
28285
|
}
|
|
26778
28286
|
this.enqueueOrRun(() => this.sendTriggeringUserTurn(instructions, "normal", false));
|
|
@@ -26788,9 +28296,9 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26788
28296
|
* — without it the server keeps waiting for more client input and NEVER starts the spoken
|
|
26789
28297
|
* reply (observed live as the model staying silent after a delegated agent's result).
|
|
26790
28298
|
*/
|
|
26791
|
-
|
|
26792
|
-
if (!this.session) {
|
|
26793
|
-
return;
|
|
28299
|
+
doSendToolResult(callID, outputJson) {
|
|
28300
|
+
if (!this.session && !this.IsReconnecting) {
|
|
28301
|
+
return false;
|
|
26794
28302
|
}
|
|
26795
28303
|
const name = this.pendingToolCallNames.get(callID) ?? "";
|
|
26796
28304
|
this.enqueueOrRun(() => this.sendToolResponseTurn(callID, name, outputJson), !this.isNonBlocking);
|
|
@@ -26916,6 +28424,9 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26916
28424
|
const maxInboundVideoRate = typeof rawMaxVideoRate === "number" && rawMaxVideoRate > 0 ? rawMaxVideoRate : void 0;
|
|
26917
28425
|
const rawMaxStreams = sessionConfig["maxInboundVideoStreams"];
|
|
26918
28426
|
const maxInboundVideoStreams = typeof rawMaxStreams === "number" && Number.isInteger(rawMaxStreams) && rawMaxStreams >= 0 ? rawMaxStreams : void 0;
|
|
28427
|
+
const rawUncompressedVideoSec = sessionConfig["uncompressedVideoConnectionMaxSeconds"];
|
|
28428
|
+
const uncompressedVideoConnectionMaxSeconds = typeof rawUncompressedVideoSec === "number" && Number.isInteger(rawUncompressedVideoSec) && rawUncompressedVideoSec >= 0 ? rawUncompressedVideoSec : void 0;
|
|
28429
|
+
const contextWindowCompression = typeof sessionConfig["contextWindowCompression"] === "boolean" ? sessionConfig["contextWindowCompression"] : void 0;
|
|
26919
28430
|
return {
|
|
26920
28431
|
model,
|
|
26921
28432
|
liveConfig,
|
|
@@ -26925,6 +28436,8 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26925
28436
|
supportsInboundVideo,
|
|
26926
28437
|
maxInboundVideoRate,
|
|
26927
28438
|
maxInboundVideoStreams,
|
|
28439
|
+
uncompressedVideoConnectionMaxSeconds,
|
|
28440
|
+
contextWindowCompression,
|
|
26928
28441
|
requestedTracks: GeminiRealtimeClient_1.readRequestedTracks(sessionConfig[REQUESTED_TRACKS_SESSION_KEY]),
|
|
26929
28442
|
avatar: GeminiRealtimeClient_1.readAvatarGrant(sessionConfig["avatar"])
|
|
26930
28443
|
};
|
|
@@ -26977,8 +28490,56 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26977
28490
|
this.holdMicChunk(base64Pcm16);
|
|
26978
28491
|
return;
|
|
26979
28492
|
}
|
|
28493
|
+
if (this.isUserSpeaking()) {
|
|
28494
|
+
this.noteUnansweredSpeech();
|
|
28495
|
+
}
|
|
26980
28496
|
this.sendAudio(this.session, base64Pcm16);
|
|
26981
28497
|
}
|
|
28498
|
+
/** The user's voice went to the connection in use: a timed move waits for its answer (bounded). */
|
|
28499
|
+
noteUnansweredSpeech() {
|
|
28500
|
+
this.unansweredSpeechAtMs = Date.now();
|
|
28501
|
+
if (this.unansweredSpeechTimer === null) {
|
|
28502
|
+
this.armUnansweredSpeechTimer(GEMINI_UNANSWERED_UTTERANCE_HOLD_MS);
|
|
28503
|
+
}
|
|
28504
|
+
}
|
|
28505
|
+
/** One timer per hold, re-armed for the rest of the hold time when the user spoke since it was set. */
|
|
28506
|
+
armUnansweredSpeechTimer(delayMs) {
|
|
28507
|
+
this.unansweredSpeechTimer = setTimeout(() => {
|
|
28508
|
+
this.unansweredSpeechTimer = null;
|
|
28509
|
+
if (this.unansweredSpeechAtMs === null) {
|
|
28510
|
+
return;
|
|
28511
|
+
}
|
|
28512
|
+
const quietMs = Date.now() - this.unansweredSpeechAtMs;
|
|
28513
|
+
if (quietMs < GEMINI_UNANSWERED_UTTERANCE_HOLD_MS) {
|
|
28514
|
+
this.armUnansweredSpeechTimer(GEMINI_UNANSWERED_UTTERANCE_HOLD_MS - quietMs);
|
|
28515
|
+
return;
|
|
28516
|
+
}
|
|
28517
|
+
RealtimeDiagLog(`[GeminiRealtimeClient] no answer ${GEMINI_UNANSWERED_UTTERANCE_HOLD_MS} ms after the user stopped speaking; a timed move may go ahead`);
|
|
28518
|
+
this.clearUnansweredSpeech();
|
|
28519
|
+
this.reconnectController.NotifyIdleStateChanged();
|
|
28520
|
+
}, delayMs);
|
|
28521
|
+
}
|
|
28522
|
+
/** Ends the hold without re-checking a move: a turn now holds it, or the connection it belongs to is left. */
|
|
28523
|
+
clearUnansweredSpeech() {
|
|
28524
|
+
if (this.unansweredSpeechTimer !== null) {
|
|
28525
|
+
clearTimeout(this.unansweredSpeechTimer);
|
|
28526
|
+
this.unansweredSpeechTimer = null;
|
|
28527
|
+
}
|
|
28528
|
+
this.unansweredSpeechAtMs = null;
|
|
28529
|
+
}
|
|
28530
|
+
/** @inheritdoc Here: the user's words wait for their answer, which is the first sign of them Google sends. */
|
|
28531
|
+
holdsHardReconnectPoint() {
|
|
28532
|
+
return this.unansweredSpeechAtMs !== null;
|
|
28533
|
+
}
|
|
28534
|
+
/**
|
|
28535
|
+
* @inheritdoc
|
|
28536
|
+
*
|
|
28537
|
+
* Adds the unanswered words: the meter reads the user only at the instant it is read, not in the second after they
|
|
28538
|
+
* stop and before Google answers.
|
|
28539
|
+
*/
|
|
28540
|
+
isTurnActiveForReconnect() {
|
|
28541
|
+
return this.unansweredSpeechAtMs !== null || super.isTurnActiveForReconnect();
|
|
28542
|
+
}
|
|
26982
28543
|
/** Sends one base64 PCM16 mic chunk on `session`; a failed send is logged, not thrown. */
|
|
26983
28544
|
sendAudio(session, base64Pcm16) {
|
|
26984
28545
|
try {
|
|
@@ -26991,23 +28552,44 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
26991
28552
|
}
|
|
26992
28553
|
/** Holds a mic chunk during a move, keeping the latest {@link HELD_MIC_AUDIO_SECONDS} seconds; older audio goes first. */
|
|
26993
28554
|
holdMicChunk(base64Pcm16) {
|
|
26994
|
-
this.heldMicAudio.push(base64Pcm16);
|
|
28555
|
+
this.heldMicAudio.push({ Pcm: base64Pcm16, Speech: this.isUserSpeaking() });
|
|
26995
28556
|
this.heldMicAudioChars += base64Pcm16.length;
|
|
26996
28557
|
while (this.heldMicAudioChars > MAX_HELD_MIC_AUDIO_BASE64_CHARS && this.heldMicAudio.length > 1) {
|
|
26997
|
-
this.heldMicAudioChars -= this.heldMicAudio.shift()?.length ?? 0;
|
|
28558
|
+
this.heldMicAudioChars -= this.heldMicAudio.shift()?.Pcm.length ?? 0;
|
|
26998
28559
|
}
|
|
26999
28560
|
}
|
|
27000
|
-
/**
|
|
28561
|
+
/**
|
|
28562
|
+
* Sends the mic audio held during a move on the connection now in use, oldest first.
|
|
28563
|
+
*
|
|
28564
|
+
* @returns Whether the audio sent carried the user's voice.
|
|
28565
|
+
*/
|
|
27001
28566
|
sendHeldMicAudio() {
|
|
27002
28567
|
const held = this.heldMicAudio;
|
|
27003
28568
|
this.heldMicAudio = [];
|
|
27004
28569
|
this.heldMicAudioChars = 0;
|
|
27005
28570
|
if (!this.session) {
|
|
27006
|
-
return;
|
|
28571
|
+
return false;
|
|
27007
28572
|
}
|
|
27008
28573
|
for (const chunk of held) {
|
|
27009
|
-
this.sendAudio(this.session, chunk);
|
|
28574
|
+
this.sendAudio(this.session, chunk.Pcm);
|
|
28575
|
+
}
|
|
28576
|
+
return held.some((chunk) => chunk.Speech);
|
|
28577
|
+
}
|
|
28578
|
+
/**
|
|
28579
|
+
* Whether an unexpected close or `goAway` can be recovered via `TriggerReconnect` / `NotifyConnectionEnding`:
|
|
28580
|
+
* a reconnect cycle is running, native resumption has a recorded handle, or history seeding is active
|
|
28581
|
+
* (`TrustsNativeResumption === false` or `hasResumedOnce === true`). A running cycle takes the loss of the
|
|
28582
|
+
* connection it may go back to whatever handle is left: after a failed native attempt it has dropped the handle
|
|
28583
|
+
* and seeds, though this session has never resumed.
|
|
28584
|
+
*/
|
|
28585
|
+
canRecoverConnection(allowEmptySeed = false) {
|
|
28586
|
+
if (this.IsReconnectCycleActive || this.ResumptionHandle !== null) {
|
|
28587
|
+
return true;
|
|
27010
28588
|
}
|
|
28589
|
+
if (this.TrustsNativeResumption && !this.hasResumedOnce) {
|
|
28590
|
+
return false;
|
|
28591
|
+
}
|
|
28592
|
+
return allowEmptySeed || this.hasResumedOnce || this.conversationMemory.Seed().Entries.length > 0;
|
|
27011
28593
|
}
|
|
27012
28594
|
/**
|
|
27013
28595
|
* Surfaces a fatal websocket error and marks the session unusable. When the session can be
|
|
@@ -27017,7 +28599,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27017
28599
|
handleTransportError(event) {
|
|
27018
28600
|
const detail = GeminiRealtimeClient_1.transportErrorDetail(event);
|
|
27019
28601
|
RealtimeDiagLog(`[GeminiRealtimeClient] Transport error: ${detail}`);
|
|
27020
|
-
if (this.
|
|
28602
|
+
if (this.canRecoverConnection()) {
|
|
27021
28603
|
return;
|
|
27022
28604
|
}
|
|
27023
28605
|
this.emitError({ Message: `Gemini Live transport error: ${detail}`, Fatal: true });
|
|
@@ -27026,8 +28608,8 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27026
28608
|
/**
|
|
27027
28609
|
* Handles a close of the current connection that the consumer did not ask for. MJAPI's relay
|
|
27028
28610
|
* closing at the session's time limit ends the call with a `time-limit` error. Otherwise, when
|
|
27029
|
-
* Google issued a resumption handle
|
|
27030
|
-
* session, as an error when it was abnormal.
|
|
28611
|
+
* Google issued a resumption handle (or history seeding is active), the session reconnects;
|
|
28612
|
+
* else the close ends the session, as an error when it was abnormal.
|
|
27031
28613
|
*/
|
|
27032
28614
|
handleTransportClose(event) {
|
|
27033
28615
|
const code = event?.code;
|
|
@@ -27046,7 +28628,8 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27046
28628
|
this.setState("error");
|
|
27047
28629
|
return;
|
|
27048
28630
|
}
|
|
27049
|
-
if (this.
|
|
28631
|
+
if (this.canRecoverConnection()) {
|
|
28632
|
+
void this.TriggerReconnect("connection-lost");
|
|
27050
28633
|
return;
|
|
27051
28634
|
}
|
|
27052
28635
|
const isAbnormal = code !== void 0 && code !== 0 && code !== 1e3 && code !== 1005 || wasClean === false && code !== 1e3 && code !== 0 && code !== 1005 && code !== void 0;
|
|
@@ -27069,10 +28652,13 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27069
28652
|
this.checkInteractionStatus(message);
|
|
27070
28653
|
if (message.sessionResumptionUpdate) {
|
|
27071
28654
|
const update = message.sessionResumptionUpdate;
|
|
27072
|
-
this.
|
|
28655
|
+
this.RecordResumptionHandle(update.newHandle, update.resumable !== false);
|
|
27073
28656
|
}
|
|
27074
28657
|
if (message.goAway) {
|
|
27075
|
-
|
|
28658
|
+
const timeLeftMs = ParseDurationToMs(message.goAway.timeLeft);
|
|
28659
|
+
if (this.canRecoverConnection(true)) {
|
|
28660
|
+
this.NotifyConnectionEnding(timeLeftMs);
|
|
28661
|
+
}
|
|
27076
28662
|
}
|
|
27077
28663
|
if (message.serverContent) {
|
|
27078
28664
|
this.handleServerContent(message.serverContent);
|
|
@@ -27084,43 +28670,147 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27084
28670
|
this.handleUsageMetadata(message.usageMetadata);
|
|
27085
28671
|
}
|
|
27086
28672
|
}
|
|
28673
|
+
onReconnecting(reason) {
|
|
28674
|
+
RealtimeDiagLog(`[GeminiRealtimeClient] Resuming the session on a new connection (${reason})`);
|
|
28675
|
+
this.connectionReady = false;
|
|
28676
|
+
this.currentState = "connecting";
|
|
28677
|
+
this.clearUnansweredSpeech();
|
|
28678
|
+
this.finalizeUserTranscript();
|
|
28679
|
+
super.onReconnecting(reason);
|
|
28680
|
+
}
|
|
27087
28681
|
/**
|
|
27088
|
-
*
|
|
27089
|
-
*
|
|
27090
|
-
*
|
|
27091
|
-
*
|
|
27092
|
-
* its
|
|
27093
|
-
*
|
|
27094
|
-
* The resume reuses the session's ephemeral token. Google counts a resume as a new session, so
|
|
27095
|
-
* the server driver mints the token to open several connections until its `expireTime`
|
|
27096
|
-
* (30 minutes). After that, or once those connections are spent, every attempt fails and the
|
|
27097
|
-
* session ends with a fatal error.
|
|
27098
|
-
*
|
|
27099
|
-
* @param handle The resumption handle Google issued.
|
|
27100
|
-
* @param attempt Marks the attempt abandoned after a timeout or a consumer close; a
|
|
27101
|
-
* connection that opens after that is closed instead of used.
|
|
28682
|
+
* A planned move's attempt failed and the old connection is still the one in use: the call goes on there until the
|
|
28683
|
+
* next attempt. Input flows again (the mic audio held during the attempt goes out first, then queued sends), and
|
|
28684
|
+
* the state the move replaced is reported again. Held audio that carried the user's voice holds the next attempt
|
|
28685
|
+
* as live speech does ({@link noteUnansweredSpeech}): the old connection has not answered those words yet. `false`
|
|
28686
|
+
* when the attempt tore the old connection down (a relay session closes its tunnel before a seeded reopen) or the
|
|
28687
|
+
* session has ended.
|
|
27102
28688
|
*/
|
|
27103
|
-
|
|
28689
|
+
ResumeOnOldConnection() {
|
|
28690
|
+
if (!this.session || this.currentConnection === 0 || this.currentState === "closed" || this.currentState === "error") {
|
|
28691
|
+
return false;
|
|
28692
|
+
}
|
|
28693
|
+
this.connectionReady = true;
|
|
28694
|
+
const restore = this.StateToRestoreOnOldConnection;
|
|
28695
|
+
if (restore) {
|
|
28696
|
+
this.setState(restore);
|
|
28697
|
+
}
|
|
28698
|
+
if (this.sendHeldMicAudio()) {
|
|
28699
|
+
this.noteUnansweredSpeech();
|
|
28700
|
+
}
|
|
28701
|
+
this.flushQueuedSends();
|
|
28702
|
+
return true;
|
|
28703
|
+
}
|
|
28704
|
+
/**
|
|
28705
|
+
* Re-establishes the underlying Gemini Live WebSocket mid-call via `BaseRealtimeClient.reconnectController`
|
|
28706
|
+
* (proactive connection-duration timer, `goAway`, unexpected close, or Attempt 2 seed fallback).
|
|
28707
|
+
*
|
|
28708
|
+
* - Preserves `sessionResumption` only when present on the initial connect config or when `handle` is set
|
|
28709
|
+
* (never adding `sessionResumption: {}` on ZDR sessions that omitted it).
|
|
28710
|
+
* - On a relay session falling back to history seeding (`!handle && target.Transport === 'relay'`), closes the
|
|
28711
|
+
* old tunnel first, awaits its close callback, requests `context.RefreshCredential({ AllowFreshReopen: true })`
|
|
28712
|
+
* so the relay resets `FreshOpened` once `ExpiresAtListeners.size === 0`, and seeds via
|
|
28713
|
+
* `RenderRealtimeMemorySeedAsContextNote`.
|
|
28714
|
+
*/
|
|
28715
|
+
async Reconnect(context) {
|
|
27104
28716
|
const target = this.connectTarget;
|
|
27105
28717
|
if (!target) {
|
|
27106
|
-
throw new Error("there is no Gemini Live session to
|
|
28718
|
+
throw new Error("there is no Gemini Live session to reconnect");
|
|
28719
|
+
}
|
|
28720
|
+
this.connectionReady = false;
|
|
28721
|
+
const handle = context.UseNativeResumption && context.ResumptionHandle ? context.ResumptionHandle : void 0;
|
|
28722
|
+
let refreshedRelayUrl = context.Credential.RelayUrl || target.RelayUrl;
|
|
28723
|
+
if (!handle && target.Transport === "relay") {
|
|
28724
|
+
const prevClosed = this.currentClosedPromise;
|
|
28725
|
+
this.currentClosedPromise = null;
|
|
28726
|
+
this.currentConnection = 0;
|
|
28727
|
+
if (this.session) {
|
|
28728
|
+
GeminiRealtimeClient_1.closeQuietly(this.session);
|
|
28729
|
+
this.session = null;
|
|
28730
|
+
}
|
|
28731
|
+
if (prevClosed) {
|
|
28732
|
+
await prevClosed;
|
|
28733
|
+
}
|
|
28734
|
+
const freshRelayCred = await context.RefreshCredential({ AllowFreshReopen: true });
|
|
28735
|
+
if (freshRelayCred.RelayUrl) {
|
|
28736
|
+
refreshedRelayUrl = freshRelayCred.RelayUrl;
|
|
28737
|
+
}
|
|
28738
|
+
}
|
|
28739
|
+
const refreshedToken = context.Credential.EphemeralToken || target.EphemeralToken;
|
|
28740
|
+
const existingResumption = target.Config.sessionResumption;
|
|
28741
|
+
let nextConfig;
|
|
28742
|
+
if (handle) {
|
|
28743
|
+
nextConfig = {
|
|
28744
|
+
...target.Config,
|
|
28745
|
+
sessionResumption: { ...existingResumption, handle }
|
|
28746
|
+
};
|
|
28747
|
+
} else if (existingResumption !== void 0) {
|
|
28748
|
+
const { handle: _omitted, ...withoutHandle } = existingResumption;
|
|
28749
|
+
nextConfig = {
|
|
28750
|
+
...target.Config,
|
|
28751
|
+
sessionResumption: withoutHandle
|
|
28752
|
+
};
|
|
28753
|
+
} else {
|
|
28754
|
+
nextConfig = { ...target.Config };
|
|
27107
28755
|
}
|
|
27108
|
-
const
|
|
28756
|
+
const reconnectTarget = {
|
|
27109
28757
|
...target,
|
|
27110
|
-
|
|
28758
|
+
EphemeralToken: refreshedToken,
|
|
28759
|
+
...refreshedRelayUrl ? { RelayUrl: refreshedRelayUrl } : {},
|
|
28760
|
+
Config: nextConfig
|
|
27111
28761
|
};
|
|
27112
|
-
const opened = await this.openConnection(
|
|
27113
|
-
|
|
27114
|
-
if (attempt.Abandoned || this.connectTarget !== target) {
|
|
28762
|
+
const opened = await this.openConnection(reconnectTarget);
|
|
28763
|
+
const onAbort = () => {
|
|
27115
28764
|
GeminiRealtimeClient_1.closeQuietly(opened.Session);
|
|
27116
|
-
|
|
28765
|
+
};
|
|
28766
|
+
if (context.Signal.aborted) {
|
|
28767
|
+
onAbort();
|
|
28768
|
+
throw new Error("GeminiRealtimeClient: reconnect attempt aborted");
|
|
28769
|
+
}
|
|
28770
|
+
context.Signal.addEventListener("abort", onAbort, { once: true });
|
|
28771
|
+
try {
|
|
28772
|
+
await GeminiRealtimeClient_1.awaitSetup(opened);
|
|
28773
|
+
} finally {
|
|
28774
|
+
context.Signal.removeEventListener("abort", onAbort);
|
|
28775
|
+
}
|
|
28776
|
+
if (context.Abandoned || this.connectTarget !== target) {
|
|
28777
|
+
GeminiRealtimeClient_1.closeQuietly(opened.Session);
|
|
28778
|
+
throw new Error("GeminiRealtimeClient: reconnect attempt abandoned");
|
|
27117
28779
|
}
|
|
27118
28780
|
const previous = this.session;
|
|
27119
28781
|
this.useConnection(opened);
|
|
27120
|
-
this.connectTarget =
|
|
28782
|
+
this.connectTarget = reconnectTarget;
|
|
27121
28783
|
if (previous) {
|
|
27122
28784
|
GeminiRealtimeClient_1.closeQuietly(previous);
|
|
27123
28785
|
}
|
|
28786
|
+
if (!handle) {
|
|
28787
|
+
for (const callID of this.pendingToolCallNames.keys()) {
|
|
28788
|
+
this.callsFromBeforeReseed.add(callID);
|
|
28789
|
+
}
|
|
28790
|
+
}
|
|
28791
|
+
if (!handle && context.ConversationSeed && context.ConversationSeed.Entries.length > 0) {
|
|
28792
|
+
if (target.Transport === "relay") {
|
|
28793
|
+
const note = RenderRealtimeMemorySeedAsContextNote(context.ConversationSeed);
|
|
28794
|
+
if (note) {
|
|
28795
|
+
this.session?.sendClientContent({
|
|
28796
|
+
turns: [{ role: "user", parts: [{ text: note }] }],
|
|
28797
|
+
turnComplete: false
|
|
28798
|
+
});
|
|
28799
|
+
this.openClientTurn = true;
|
|
28800
|
+
}
|
|
28801
|
+
} else {
|
|
28802
|
+
const seedTurns = RenderRealtimeMemorySeed(context.ConversationSeed);
|
|
28803
|
+
if (seedTurns.length > 0) {
|
|
28804
|
+
const turns = seedTurns.map((t) => ({
|
|
28805
|
+
role: t.Role,
|
|
28806
|
+
parts: t.Texts.map((text) => ({ text }))
|
|
28807
|
+
}));
|
|
28808
|
+
this.session?.sendClientContent({ turns, turnComplete: false });
|
|
28809
|
+
this.openClientTurn = true;
|
|
28810
|
+
}
|
|
28811
|
+
}
|
|
28812
|
+
}
|
|
28813
|
+
this.handleResumed();
|
|
27124
28814
|
}
|
|
27125
28815
|
/**
|
|
27126
28816
|
* Opens a connection through {@link connectLiveSession}. Its callbacks act only while it is the
|
|
@@ -27133,6 +28823,10 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27133
28823
|
const number = ++this.issuedConnections;
|
|
27134
28824
|
const isCurrent = () => number === this.currentConnection;
|
|
27135
28825
|
const setup = new RealtimeConnectionSetup();
|
|
28826
|
+
let markClosed;
|
|
28827
|
+
const closed = new Promise((resolve) => {
|
|
28828
|
+
markClosed = resolve;
|
|
28829
|
+
});
|
|
27136
28830
|
const session = await this.connectLiveSession({
|
|
27137
28831
|
...target,
|
|
27138
28832
|
OnMessage: (message) => {
|
|
@@ -27150,13 +28844,14 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27150
28844
|
}
|
|
27151
28845
|
},
|
|
27152
28846
|
OnClose: (event) => {
|
|
28847
|
+
markClosed();
|
|
27153
28848
|
setup.Fail(new Error(`Gemini Live closed the connection before confirming its setup (${event?.code}): ${event?.reason || "no reason given"}`));
|
|
27154
28849
|
if (isCurrent()) {
|
|
27155
28850
|
this.handleTransportClose(event);
|
|
27156
28851
|
}
|
|
27157
28852
|
}
|
|
27158
28853
|
});
|
|
27159
|
-
return { Session: session, ConnectionNumber: number, Setup: setup };
|
|
28854
|
+
return { Session: session, ConnectionNumber: number, Setup: setup, Closed: closed };
|
|
27160
28855
|
}
|
|
27161
28856
|
/** Waits for Google to confirm a new connection's setup. On failure the connection is closed and the error rethrown. */
|
|
27162
28857
|
static async awaitSetup(opened) {
|
|
@@ -27175,23 +28870,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27175
28870
|
useConnection(opened) {
|
|
27176
28871
|
this.session = opened.Session;
|
|
27177
28872
|
this.currentConnection = opened.ConnectionNumber;
|
|
27178
|
-
|
|
27179
|
-
/**
|
|
27180
|
-
* Builds the resumption helper for a newly connected session; see {@link resumption}. From the
|
|
27181
|
-
* moment a move starts, input waits for the new connection ({@link connectionReady}).
|
|
27182
|
-
*/
|
|
27183
|
-
createResumption() {
|
|
27184
|
-
return new RealtimeSessionResumption({
|
|
27185
|
-
Reconnect: (handle, attempt) => this.resumeSession(handle, attempt),
|
|
27186
|
-
OnReconnecting: (reason) => {
|
|
27187
|
-
RealtimeDiagLog(`[GeminiRealtimeClient] Resuming the session on a new connection (${reason})`);
|
|
27188
|
-
this.connectionReady = false;
|
|
27189
|
-
this.setState("connecting");
|
|
27190
|
-
},
|
|
27191
|
-
OnReconnected: () => this.handleResumed(),
|
|
27192
|
-
OnReconnectFailed: (error) => this.handleResumeFailed(error),
|
|
27193
|
-
Log: (message) => RealtimeDiagLog(message)
|
|
27194
|
-
});
|
|
28873
|
+
this.currentClosedPromise = opened.Closed;
|
|
27195
28874
|
}
|
|
27196
28875
|
/**
|
|
27197
28876
|
* The session continues on a new connection, whose setup Google has confirmed. A turn cut off
|
|
@@ -27201,6 +28880,8 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27201
28880
|
* last frame.
|
|
27202
28881
|
*/
|
|
27203
28882
|
handleResumed() {
|
|
28883
|
+
this.hasResumedOnce = true;
|
|
28884
|
+
this.videoCapActive = false;
|
|
27204
28885
|
this.avatarOutput?.Resumed();
|
|
27205
28886
|
this.emitAvatarVideoSeconds();
|
|
27206
28887
|
this.finalizeUserTranscript();
|
|
@@ -27216,11 +28897,15 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27216
28897
|
this.flushQueuedSends();
|
|
27217
28898
|
}
|
|
27218
28899
|
/** Every resume attempt failed: the session ends with a fatal error. */
|
|
27219
|
-
|
|
28900
|
+
onReconnectFailed(error, code) {
|
|
27220
28901
|
if (this.currentState === "closed" || this.currentState === "error") {
|
|
27221
28902
|
return;
|
|
27222
28903
|
}
|
|
27223
|
-
this.emitError({
|
|
28904
|
+
this.emitError({
|
|
28905
|
+
Message: `Gemini Live connection was lost and could not be resumed: ${error.message}`,
|
|
28906
|
+
...code ? { Code: code } : {},
|
|
28907
|
+
Fatal: true
|
|
28908
|
+
});
|
|
27224
28909
|
this.setState("error");
|
|
27225
28910
|
}
|
|
27226
28911
|
/** Closes a socket the session no longer uses; it may already be closed. */
|
|
@@ -27632,7 +29317,8 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27632
29317
|
markTurnOpen() {
|
|
27633
29318
|
this.turnOpen = true;
|
|
27634
29319
|
this.turnEndAwaitsToolResults = false;
|
|
27635
|
-
this.
|
|
29320
|
+
this.reconnectController.TurnStarted();
|
|
29321
|
+
this.clearUnansweredSpeech();
|
|
27636
29322
|
}
|
|
27637
29323
|
/** The turn's `turnComplete` (or true idle): it ends now, or once the results of the tool calls still pending go out. */
|
|
27638
29324
|
endTurnUnlessToolCallPending() {
|
|
@@ -27643,16 +29329,19 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27643
29329
|
this.endTurn();
|
|
27644
29330
|
}
|
|
27645
29331
|
/** A tool result went out: a turn whose `turnComplete` waited on the pending calls ends once none is left. */
|
|
27646
|
-
endTurnIfToolResultsIn() {
|
|
29332
|
+
endTurnIfToolResultsIn(expectsReply = true) {
|
|
27647
29333
|
if (this.turnEndAwaitsToolResults && this.pendingToolCallNames.size === 0) {
|
|
27648
|
-
this.endTurn();
|
|
29334
|
+
this.endTurn(expectsReply);
|
|
27649
29335
|
}
|
|
27650
29336
|
}
|
|
27651
29337
|
/** The turn is over: a planned move happens at the next resumable handle Google issues. */
|
|
27652
|
-
endTurn() {
|
|
29338
|
+
endTurn(keepPostToolTurnWait = false) {
|
|
27653
29339
|
this.turnOpen = false;
|
|
27654
29340
|
this.turnEndAwaitsToolResults = false;
|
|
27655
|
-
this.
|
|
29341
|
+
this.reconnectController.TurnEnded(keepPostToolTurnWait);
|
|
29342
|
+
}
|
|
29343
|
+
isToolResultSilent(outputJson) {
|
|
29344
|
+
return this.supportsScheduling && super.isToolResultSilent(outputJson);
|
|
27656
29345
|
}
|
|
27657
29346
|
// ── Collision-safe send machinery ──────────────────────────────────────────
|
|
27658
29347
|
/**
|
|
@@ -27750,6 +29439,19 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27750
29439
|
return;
|
|
27751
29440
|
}
|
|
27752
29441
|
this.toolBatchBarrier.RecordResult(callID);
|
|
29442
|
+
if (this.callsFromBeforeReseed.delete(callID)) {
|
|
29443
|
+
session.sendRealtimeInput({
|
|
29444
|
+
text: RenderLateToolResultNote(name || callID, outputJson)
|
|
29445
|
+
});
|
|
29446
|
+
if (!this.isNonBlocking) {
|
|
29447
|
+
this.responseActive = true;
|
|
29448
|
+
this.activeResponseKind = "normal";
|
|
29449
|
+
this.setState("speaking");
|
|
29450
|
+
}
|
|
29451
|
+
this.pendingToolCallNames.delete(callID);
|
|
29452
|
+
this.endTurnIfToolResultsIn(true);
|
|
29453
|
+
return;
|
|
29454
|
+
}
|
|
27753
29455
|
const parsed = this.parseToolOutput(outputJson);
|
|
27754
29456
|
const sched = this.resolveFunctionScheduling(parsed, name);
|
|
27755
29457
|
const functionResponse = {
|
|
@@ -27773,7 +29475,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27773
29475
|
this.setState("speaking");
|
|
27774
29476
|
}
|
|
27775
29477
|
this.pendingToolCallNames.delete(callID);
|
|
27776
|
-
this.endTurnIfToolResultsIn();
|
|
29478
|
+
this.endTurnIfToolResultsIn(sched !== FunctionResponseScheduling.SILENT);
|
|
27777
29479
|
}
|
|
27778
29480
|
/**
|
|
27779
29481
|
* Parses a JSON-stringified tool result into the structured object Gemini's
|
|
@@ -27815,6 +29517,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
|
|
|
27815
29517
|
}
|
|
27816
29518
|
/** Resets the per-session response state machine (used on Disconnect). */
|
|
27817
29519
|
resetResponseState() {
|
|
29520
|
+
this.clearUnansweredSpeech();
|
|
27818
29521
|
this.pendingAssistantText = "";
|
|
27819
29522
|
this.pendingUserText = "";
|
|
27820
29523
|
this.pendingThoughtText = "";
|
|
@@ -27863,6 +29566,10 @@ var GeminiEnterpriseRealtimeClient = class GeminiEnterpriseRealtimeClient2 exten
|
|
|
27863
29566
|
get SupportsRelayTransport() {
|
|
27864
29567
|
return true;
|
|
27865
29568
|
}
|
|
29569
|
+
/** Vertex AI / Gemini Enterprise relay sessions accept sessionResumption.handle natively. */
|
|
29570
|
+
get DefaultTrustsNativeResumption() {
|
|
29571
|
+
return true;
|
|
29572
|
+
}
|
|
27866
29573
|
/**
|
|
27867
29574
|
* Opens one Live connection through the relay; a resume opens another with the same URL and the new handle.
|
|
27868
29575
|
*
|
|
@@ -27918,13 +29625,16 @@ var __decorate4 = function(decorators, target, key, desc) {
|
|
|
27918
29625
|
};
|
|
27919
29626
|
var ElevenLabsRealtimeClient_1;
|
|
27920
29627
|
var ELEVENLABS_DEFAULT_SAMPLE_RATE = 16e3;
|
|
29628
|
+
var ELEVENLABS_DEFAULT_CALL_DURATION_SECONDS = 600;
|
|
27921
29629
|
var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealtimeClient {
|
|
27922
29630
|
constructor() {
|
|
27923
29631
|
super(...arguments);
|
|
27924
29632
|
this.socket = null;
|
|
29633
|
+
this.socketOpen = false;
|
|
27925
29634
|
this.micStream = null;
|
|
27926
29635
|
this.micCapture = null;
|
|
27927
29636
|
this.playback = null;
|
|
29637
|
+
this.activeConfig = null;
|
|
27928
29638
|
this.responseActive = false;
|
|
27929
29639
|
this.activeResponseKind = "normal";
|
|
27930
29640
|
this.queuedSends = [];
|
|
@@ -27937,6 +29647,9 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
27937
29647
|
static {
|
|
27938
29648
|
ElevenLabsRealtimeClient_1 = this;
|
|
27939
29649
|
}
|
|
29650
|
+
get DefaultCallDurationSeconds() {
|
|
29651
|
+
return ELEVENLABS_DEFAULT_CALL_DURATION_SECONDS;
|
|
29652
|
+
}
|
|
27940
29653
|
// ── BaseRealtimeClient: connection lifecycle ───────────────────────────────
|
|
27941
29654
|
/**
|
|
27942
29655
|
* Opens the client-direct conversation: socket to the signed URL, the initiation frame
|
|
@@ -27946,8 +29659,11 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
27946
29659
|
*/
|
|
27947
29660
|
async Connect(config, micStream) {
|
|
27948
29661
|
this.AssertTransportSupported(config);
|
|
29662
|
+
this.ApplySessionConfigTiming(config);
|
|
29663
|
+
this.activeConfig = config;
|
|
27949
29664
|
this.micStream = micStream;
|
|
27950
29665
|
this.closedByConsumer = false;
|
|
29666
|
+
this.socketOpen = false;
|
|
27951
29667
|
this.setState("connecting");
|
|
27952
29668
|
const overrides = this.parseOverrides(config);
|
|
27953
29669
|
let openSocket = null;
|
|
@@ -27970,21 +29686,47 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
27970
29686
|
};
|
|
27971
29687
|
const socket = this.createSocket(config.EphemeralToken);
|
|
27972
29688
|
this.socket = socket;
|
|
27973
|
-
socket.onopen = () =>
|
|
27974
|
-
|
|
29689
|
+
socket.onopen = () => {
|
|
29690
|
+
if (this.socket !== socket) {
|
|
29691
|
+
return;
|
|
29692
|
+
}
|
|
29693
|
+
this.socketOpen = true;
|
|
29694
|
+
openSocket?.();
|
|
29695
|
+
};
|
|
29696
|
+
socket.onmessage = (data) => {
|
|
29697
|
+
if (this.socket !== socket) {
|
|
29698
|
+
return;
|
|
29699
|
+
}
|
|
29700
|
+
this.handleSocketMessage(data);
|
|
29701
|
+
};
|
|
27975
29702
|
socket.onerror = (message) => {
|
|
29703
|
+
if (this.socket !== socket) {
|
|
29704
|
+
return;
|
|
29705
|
+
}
|
|
29706
|
+
this.socketOpen = false;
|
|
27976
29707
|
failConnect(new Error(message));
|
|
27977
|
-
this.
|
|
29708
|
+
if (!this.IsReconnecting) {
|
|
29709
|
+
this.handleSocketError(message);
|
|
29710
|
+
}
|
|
27978
29711
|
};
|
|
27979
29712
|
socket.onclose = () => {
|
|
29713
|
+
if (this.socket !== socket) {
|
|
29714
|
+
return;
|
|
29715
|
+
}
|
|
29716
|
+
this.socketOpen = false;
|
|
27980
29717
|
failConnect(new Error("ElevenLabs conversation socket closed during connect"));
|
|
27981
|
-
this.
|
|
29718
|
+
if (!this.IsReconnecting) {
|
|
29719
|
+
this.handleSocketClose();
|
|
29720
|
+
}
|
|
27982
29721
|
};
|
|
27983
29722
|
await opened;
|
|
27984
29723
|
this.setState("connected");
|
|
27985
29724
|
this.sendFrame({ type: "conversation_initiation_client_data", conversation_config_override: overrides });
|
|
27986
29725
|
const metadataEvent = await metadata;
|
|
27987
29726
|
const formats = metadataEvent.conversation_initiation_metadata_event;
|
|
29727
|
+
if (formats?.conversation_id) {
|
|
29728
|
+
this.RecordResumptionHandle(formats.conversation_id);
|
|
29729
|
+
}
|
|
27988
29730
|
const outputRate = ElevenLabsRealtimeClient_1.ParsePcmRate(formats?.agent_output_audio_format, "output");
|
|
27989
29731
|
const inputRate = ElevenLabsRealtimeClient_1.ParsePcmRate(formats?.user_input_audio_format, "input");
|
|
27990
29732
|
this.playback = this.createPlayback(outputRate);
|
|
@@ -27992,6 +29734,7 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
27992
29734
|
this.micCapture = await this.createMicCapture(micStream, inputRate, (base64Pcm16) => this.sendMicChunk(base64Pcm16));
|
|
27993
29735
|
this.attachOutputAudioMeter(this.playback?.CreateMeter?.() ?? null);
|
|
27994
29736
|
this.attachInputAudioMeter(RealtimeAudioMeter.ForMicStream(micStream));
|
|
29737
|
+
this.ArmConnectionDurationTimer();
|
|
27995
29738
|
this.setState("listening");
|
|
27996
29739
|
}
|
|
27997
29740
|
/**
|
|
@@ -28001,6 +29744,9 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
28001
29744
|
*/
|
|
28002
29745
|
async Disconnect() {
|
|
28003
29746
|
this.closedByConsumer = true;
|
|
29747
|
+
this.socketOpen = false;
|
|
29748
|
+
this.DisposeReconnectTimers();
|
|
29749
|
+
this.cancelToolResultNudge();
|
|
28004
29750
|
this.closeAudioMeters();
|
|
28005
29751
|
this.micStream?.getTracks().forEach((track) => track.stop());
|
|
28006
29752
|
this.micStream = null;
|
|
@@ -28010,17 +29756,165 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
28010
29756
|
this.playback = null;
|
|
28011
29757
|
this.clearRemoteMediaStream();
|
|
28012
29758
|
if (this.socket) {
|
|
29759
|
+
const s = this.socket;
|
|
29760
|
+
this.socket = null;
|
|
29761
|
+
s.onopen = null;
|
|
29762
|
+
s.onmessage = null;
|
|
29763
|
+
s.onerror = null;
|
|
29764
|
+
s.onclose = null;
|
|
28013
29765
|
try {
|
|
28014
|
-
|
|
29766
|
+
s.close();
|
|
28015
29767
|
} catch {
|
|
28016
29768
|
}
|
|
28017
|
-
this.socket = null;
|
|
28018
29769
|
}
|
|
29770
|
+
this.activeConfig = null;
|
|
28019
29771
|
this.resetResponseState();
|
|
28020
29772
|
if (this.currentState !== "error") {
|
|
28021
29773
|
this.setState("closed");
|
|
28022
29774
|
}
|
|
28023
29775
|
}
|
|
29776
|
+
async Reconnect(context) {
|
|
29777
|
+
if (!this.activeConfig) {
|
|
29778
|
+
throw new Error("ElevenLabsRealtimeClient: cannot reconnect before Connect");
|
|
29779
|
+
}
|
|
29780
|
+
if (context.Abandoned) {
|
|
29781
|
+
throw new Error("ElevenLabsRealtimeClient: reconnect attempt abandoned");
|
|
29782
|
+
}
|
|
29783
|
+
const refreshedConfig = {
|
|
29784
|
+
...this.activeConfig,
|
|
29785
|
+
EphemeralToken: context.Credential.EphemeralToken || this.activeConfig.EphemeralToken,
|
|
29786
|
+
ExpiresAt: context.Credential.ExpiresAt || this.activeConfig.ExpiresAt,
|
|
29787
|
+
...context.Credential.SessionConfig !== void 0 ? { SessionConfig: context.Credential.SessionConfig } : {}
|
|
29788
|
+
};
|
|
29789
|
+
this.activeConfig = refreshedConfig;
|
|
29790
|
+
const overrides = this.stripFirstMessageOverride(this.parseOverrides(refreshedConfig));
|
|
29791
|
+
const prevSocket = this.socket;
|
|
29792
|
+
let openSocket = null;
|
|
29793
|
+
let failOpen = null;
|
|
29794
|
+
let confirmMetadata = null;
|
|
29795
|
+
let failMetadata = null;
|
|
29796
|
+
const opened = new Promise((resolve, reject) => {
|
|
29797
|
+
openSocket = resolve;
|
|
29798
|
+
failOpen = reject;
|
|
29799
|
+
});
|
|
29800
|
+
const metadata = new Promise((resolve, reject) => {
|
|
29801
|
+
confirmMetadata = resolve;
|
|
29802
|
+
failMetadata = reject;
|
|
29803
|
+
});
|
|
29804
|
+
metadata.catch(() => void 0);
|
|
29805
|
+
const failConnect = (error) => {
|
|
29806
|
+
failOpen?.(error);
|
|
29807
|
+
failMetadata?.(error);
|
|
29808
|
+
};
|
|
29809
|
+
const nextSocket = this.createSocket(refreshedConfig.EphemeralToken);
|
|
29810
|
+
let nextSocketOpen = false;
|
|
29811
|
+
const onAbort = () => {
|
|
29812
|
+
failConnect(new Error("ElevenLabsRealtimeClient: reconnect attempt aborted"));
|
|
29813
|
+
try {
|
|
29814
|
+
nextSocket.close();
|
|
29815
|
+
} catch {
|
|
29816
|
+
}
|
|
29817
|
+
};
|
|
29818
|
+
if (context.Signal.aborted) {
|
|
29819
|
+
onAbort();
|
|
29820
|
+
throw new Error("ElevenLabsRealtimeClient: reconnect attempt aborted");
|
|
29821
|
+
}
|
|
29822
|
+
context.Signal.addEventListener("abort", onAbort, { once: true });
|
|
29823
|
+
nextSocket.onopen = () => {
|
|
29824
|
+
nextSocketOpen = true;
|
|
29825
|
+
openSocket?.();
|
|
29826
|
+
};
|
|
29827
|
+
nextSocket.onmessage = (data) => {
|
|
29828
|
+
if (this.socket === nextSocket) {
|
|
29829
|
+
this.handleSocketMessage(data);
|
|
29830
|
+
return;
|
|
29831
|
+
}
|
|
29832
|
+
try {
|
|
29833
|
+
const event = JSON.parse(data);
|
|
29834
|
+
if (event.type === "conversation_initiation_metadata") {
|
|
29835
|
+
confirmMetadata?.(event);
|
|
29836
|
+
confirmMetadata = null;
|
|
29837
|
+
}
|
|
29838
|
+
} catch {
|
|
29839
|
+
}
|
|
29840
|
+
};
|
|
29841
|
+
nextSocket.onerror = (message) => {
|
|
29842
|
+
nextSocketOpen = false;
|
|
29843
|
+
failConnect(new Error(message));
|
|
29844
|
+
if (this.socket === nextSocket && !this.IsReconnecting) {
|
|
29845
|
+
this.socketOpen = false;
|
|
29846
|
+
this.handleSocketError(message);
|
|
29847
|
+
}
|
|
29848
|
+
};
|
|
29849
|
+
nextSocket.onclose = () => {
|
|
29850
|
+
nextSocketOpen = false;
|
|
29851
|
+
failConnect(new Error("ElevenLabs conversation socket closed during reconnect"));
|
|
29852
|
+
if (this.socket === nextSocket && !this.IsReconnecting) {
|
|
29853
|
+
this.socketOpen = false;
|
|
29854
|
+
this.handleSocketClose();
|
|
29855
|
+
}
|
|
29856
|
+
};
|
|
29857
|
+
let metadataEvent;
|
|
29858
|
+
try {
|
|
29859
|
+
await opened;
|
|
29860
|
+
if (context.Abandoned) {
|
|
29861
|
+
throw new Error("ElevenLabsRealtimeClient: reconnect attempt abandoned after open");
|
|
29862
|
+
}
|
|
29863
|
+
nextSocket.send(JSON.stringify({ type: "conversation_initiation_client_data", conversation_config_override: overrides }));
|
|
29864
|
+
metadataEvent = await metadata;
|
|
29865
|
+
if (context.Abandoned) {
|
|
29866
|
+
throw new Error("ElevenLabsRealtimeClient: reconnect attempt abandoned after metadata");
|
|
29867
|
+
}
|
|
29868
|
+
} catch (err) {
|
|
29869
|
+
nextSocket.onopen = null;
|
|
29870
|
+
nextSocket.onmessage = null;
|
|
29871
|
+
nextSocket.onerror = null;
|
|
29872
|
+
nextSocket.onclose = null;
|
|
29873
|
+
try {
|
|
29874
|
+
nextSocket.close();
|
|
29875
|
+
} catch {
|
|
29876
|
+
}
|
|
29877
|
+
throw err;
|
|
29878
|
+
} finally {
|
|
29879
|
+
context.Signal.removeEventListener("abort", onAbort);
|
|
29880
|
+
}
|
|
29881
|
+
if (prevSocket) {
|
|
29882
|
+
prevSocket.onopen = null;
|
|
29883
|
+
prevSocket.onmessage = null;
|
|
29884
|
+
prevSocket.onerror = null;
|
|
29885
|
+
prevSocket.onclose = null;
|
|
29886
|
+
}
|
|
29887
|
+
this.socket = nextSocket;
|
|
29888
|
+
this.socketOpen = nextSocketOpen;
|
|
29889
|
+
const formats = metadataEvent.conversation_initiation_metadata_event;
|
|
29890
|
+
if (formats?.conversation_id) {
|
|
29891
|
+
this.RecordResumptionHandle(formats.conversation_id);
|
|
29892
|
+
}
|
|
29893
|
+
try {
|
|
29894
|
+
prevSocket?.close();
|
|
29895
|
+
} catch {
|
|
29896
|
+
}
|
|
29897
|
+
this.responseActive = false;
|
|
29898
|
+
this.activeResponseKind = "normal";
|
|
29899
|
+
if (context.ConversationSeed && context.ConversationSeed.Entries.length > 0) {
|
|
29900
|
+
const note = RenderRealtimeMemorySeedAsContextNote(context.ConversationSeed);
|
|
29901
|
+
if (note) {
|
|
29902
|
+
this.sendFrame({ type: "contextual_update", text: note });
|
|
29903
|
+
}
|
|
29904
|
+
}
|
|
29905
|
+
this.setState("listening");
|
|
29906
|
+
}
|
|
29907
|
+
stripFirstMessageOverride(overrides) {
|
|
29908
|
+
const agentObj = AsConfigRecord(overrides["agent"]);
|
|
29909
|
+
if (!agentObj || agentObj["first_message"] === void 0) {
|
|
29910
|
+
return overrides;
|
|
29911
|
+
}
|
|
29912
|
+
const { first_message: _dropped, ...restAgent } = agentObj;
|
|
29913
|
+
return {
|
|
29914
|
+
...overrides,
|
|
29915
|
+
agent: restAgent
|
|
29916
|
+
};
|
|
29917
|
+
}
|
|
28024
29918
|
// ── BaseRealtimeClient: outbound actions ──────────────────────────────────
|
|
28025
29919
|
/**
|
|
28026
29920
|
* Injects typed text as a `user_message` (the platform's "respond to this" trigger).
|
|
@@ -28034,7 +29928,7 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
28034
29928
|
* turn takes the floor on its own; no explicit cancel frame exists or is needed.
|
|
28035
29929
|
*/
|
|
28036
29930
|
SendText(text) {
|
|
28037
|
-
if (!this.socket) {
|
|
29931
|
+
if (!this.socket || !this.socketOpen) {
|
|
28038
29932
|
return;
|
|
28039
29933
|
}
|
|
28040
29934
|
this.CancelActiveResponse();
|
|
@@ -28051,7 +29945,7 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
28051
29945
|
* `interruption`). No-op when nothing is active.
|
|
28052
29946
|
*/
|
|
28053
29947
|
CancelActiveResponse() {
|
|
28054
|
-
if (!this.socket) {
|
|
29948
|
+
if (!this.socket || !this.socketOpen) {
|
|
28055
29949
|
return;
|
|
28056
29950
|
}
|
|
28057
29951
|
if (!this.responseActive && !this.IsAudioPlaying) {
|
|
@@ -28071,8 +29965,9 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
28071
29965
|
* a response is in flight (the platform guarantees it never triggers or disturbs
|
|
28072
29966
|
* generation), so unlike the Gemini driver no queueing applies.
|
|
28073
29967
|
*/
|
|
28074
|
-
SendContextNote(text) {
|
|
28075
|
-
|
|
29968
|
+
SendContextNote(text, options) {
|
|
29969
|
+
this.ConversationMemory.Record({ Kind: "note", Text: text, ...options });
|
|
29970
|
+
if (!this.socket || !this.socketOpen) {
|
|
28076
29971
|
return;
|
|
28077
29972
|
}
|
|
28078
29973
|
this.sendFrame({ type: "contextual_update", text });
|
|
@@ -28085,14 +29980,14 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
28085
29980
|
* the base contract's collision rule.
|
|
28086
29981
|
*/
|
|
28087
29982
|
RequestSpokenUpdate(instructions) {
|
|
28088
|
-
if (!this.socket) {
|
|
29983
|
+
if (!this.socket || !this.socketOpen) {
|
|
28089
29984
|
return;
|
|
28090
29985
|
}
|
|
28091
29986
|
this.enqueueOrRun(() => this.sendUserMessage(instructions, "narration", false));
|
|
28092
29987
|
}
|
|
28093
29988
|
/** A spoken TURN: the same `user_message` trigger as the update, with the reply kept `normal` (MJ#4591). */
|
|
28094
29989
|
RequestSpokenTurn(instructions) {
|
|
28095
|
-
if (!this.socket) {
|
|
29990
|
+
if (!this.socket || !this.socketOpen) {
|
|
28096
29991
|
return;
|
|
28097
29992
|
}
|
|
28098
29993
|
this.enqueueOrRun(() => this.sendUserMessage(instructions, "normal", false));
|
|
@@ -28105,15 +30000,21 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
28105
30000
|
* otherwise queued behind the in-flight response (e.g. a progress narration) so the
|
|
28106
30001
|
* trigger is never lost.
|
|
28107
30002
|
*/
|
|
28108
|
-
|
|
28109
|
-
if (!this.socket) {
|
|
28110
|
-
return;
|
|
30003
|
+
doSendToolResult(callID, outputJson) {
|
|
30004
|
+
if (!this.socket || !this.socketOpen) {
|
|
30005
|
+
return false;
|
|
28111
30006
|
}
|
|
28112
30007
|
if (!this.pendingToolCallIds.has(callID)) {
|
|
28113
30008
|
console.warn(`ElevenLabsRealtimeClient.SendToolResult: no pending tool call '${callID}' \u2014 duplicate or unknown result dropped.`);
|
|
28114
|
-
return;
|
|
30009
|
+
return false;
|
|
28115
30010
|
}
|
|
28116
30011
|
this.pendingToolCallIds.delete(callID);
|
|
30012
|
+
const name = this.resolveToolName(callID);
|
|
30013
|
+
if (this.callsFromBeforeReseed.delete(callID)) {
|
|
30014
|
+
this.sendFrame({ type: "contextual_update", text: RenderLateToolResultNote(name, outputJson) });
|
|
30015
|
+
this.enqueueOrRun(() => this.sendUserMessage(`Please continue with the tool result for ${name}.`, "normal", false));
|
|
30016
|
+
return;
|
|
30017
|
+
}
|
|
28117
30018
|
this.enqueueOrRun(() => this.sendToolResultFrame(callID, outputJson));
|
|
28118
30019
|
}
|
|
28119
30020
|
/**
|
|
@@ -28221,13 +30122,13 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
28221
30122
|
}
|
|
28222
30123
|
/** Streams one base64 PCM16 mic chunk as a bare-key `user_audio_chunk` frame. */
|
|
28223
30124
|
sendMicChunk(base64Pcm16) {
|
|
28224
|
-
if (this.socket) {
|
|
30125
|
+
if (this.socket && this.socketOpen) {
|
|
28225
30126
|
this.sendFrame({ user_audio_chunk: base64Pcm16 });
|
|
28226
30127
|
}
|
|
28227
30128
|
}
|
|
28228
30129
|
/** Surfaces a fatal socket error and marks the session unusable (obligation #6). */
|
|
28229
30130
|
handleSocketError(message) {
|
|
28230
|
-
if (this.currentState === "error" || this.currentState === "closed") {
|
|
30131
|
+
if (this.IsReconnecting || this.currentState === "error" || this.currentState === "closed") {
|
|
28231
30132
|
return;
|
|
28232
30133
|
}
|
|
28233
30134
|
this.emitError({ Message: `ElevenLabs realtime transport error: ${message}`, Fatal: true });
|
|
@@ -28239,7 +30140,7 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
|
|
|
28239
30140
|
* credential / conversation death reaches the host (obligation #6).
|
|
28240
30141
|
*/
|
|
28241
30142
|
handleSocketClose() {
|
|
28242
|
-
if (this.closedByConsumer || this.currentState === "error" || this.currentState === "closed") {
|
|
30143
|
+
if (this.closedByConsumer || this.IsReconnecting || this.currentState === "error" || this.currentState === "closed") {
|
|
28243
30144
|
return;
|
|
28244
30145
|
}
|
|
28245
30146
|
this.emitError({ Message: "ElevenLabs conversation closed unexpectedly", Fatal: true });
|
|
@@ -28514,6 +30415,7 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28514
30415
|
constructor() {
|
|
28515
30416
|
super(...arguments);
|
|
28516
30417
|
this.socket = null;
|
|
30418
|
+
this.socketOpen = false;
|
|
28517
30419
|
this.micStream = null;
|
|
28518
30420
|
this.micCapture = null;
|
|
28519
30421
|
this.playback = null;
|
|
@@ -28527,10 +30429,15 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28527
30429
|
this.connectUrl = null;
|
|
28528
30430
|
this.resumeAttempted = false;
|
|
28529
30431
|
this.currentState = "closed";
|
|
30432
|
+
this.initialBasePrompt = "";
|
|
28530
30433
|
this.basePrompt = "";
|
|
28531
30434
|
this.contextNotes = [];
|
|
30435
|
+
this.activeConfig = null;
|
|
28532
30436
|
this.onSessionReady = null;
|
|
28533
30437
|
}
|
|
30438
|
+
get DefaultCallDurationSeconds() {
|
|
30439
|
+
return void 0;
|
|
30440
|
+
}
|
|
28534
30441
|
// ── BaseRealtimeClient: connection lifecycle ───────────────────────────────
|
|
28535
30442
|
/**
|
|
28536
30443
|
* Opens the client-direct session: socket to the token-authenticated endpoint, the
|
|
@@ -28540,11 +30447,15 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28540
30447
|
*/
|
|
28541
30448
|
async Connect(config, micStream) {
|
|
28542
30449
|
this.AssertTransportSupported(config);
|
|
30450
|
+
this.ApplySessionConfigTiming(config);
|
|
30451
|
+
this.activeConfig = config;
|
|
28543
30452
|
this.micStream = micStream;
|
|
28544
30453
|
this.closedByConsumer = false;
|
|
30454
|
+
this.socketOpen = false;
|
|
28545
30455
|
this.setState("connecting");
|
|
28546
30456
|
const sessionObject = this.parseSessionObject(config);
|
|
28547
|
-
this.
|
|
30457
|
+
this.initialBasePrompt = typeof sessionObject["system_prompt"] === "string" ? sessionObject["system_prompt"] : "";
|
|
30458
|
+
this.basePrompt = this.initialBasePrompt;
|
|
28548
30459
|
this.contextNotes = [];
|
|
28549
30460
|
let openSocket = null;
|
|
28550
30461
|
let failOpen = null;
|
|
@@ -28569,15 +30480,38 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28569
30480
|
this.resumeAttempted = false;
|
|
28570
30481
|
const socket = this.createSocket(this.connectUrl);
|
|
28571
30482
|
this.socket = socket;
|
|
28572
|
-
socket.onopen = () =>
|
|
28573
|
-
|
|
30483
|
+
socket.onopen = () => {
|
|
30484
|
+
if (this.socket !== socket) {
|
|
30485
|
+
return;
|
|
30486
|
+
}
|
|
30487
|
+
this.socketOpen = true;
|
|
30488
|
+
openSocket?.();
|
|
30489
|
+
};
|
|
30490
|
+
socket.onmessage = (data) => {
|
|
30491
|
+
if (this.socket !== socket) {
|
|
30492
|
+
return;
|
|
30493
|
+
}
|
|
30494
|
+
this.handleSocketMessage(data);
|
|
30495
|
+
};
|
|
28574
30496
|
socket.onerror = (message) => {
|
|
30497
|
+
if (this.socket !== socket) {
|
|
30498
|
+
return;
|
|
30499
|
+
}
|
|
30500
|
+
this.socketOpen = false;
|
|
28575
30501
|
failConnect(new Error(message));
|
|
28576
|
-
this.
|
|
30502
|
+
if (!this.IsReconnecting) {
|
|
30503
|
+
this.handleSocketError(message);
|
|
30504
|
+
}
|
|
28577
30505
|
};
|
|
28578
30506
|
socket.onclose = () => {
|
|
30507
|
+
if (this.socket !== socket) {
|
|
30508
|
+
return;
|
|
30509
|
+
}
|
|
30510
|
+
this.socketOpen = false;
|
|
28579
30511
|
failConnect(new Error("AssemblyAI agent socket closed during connect"));
|
|
28580
|
-
this.
|
|
30512
|
+
if (!this.IsReconnecting) {
|
|
30513
|
+
this.handleSocketClose();
|
|
30514
|
+
}
|
|
28581
30515
|
};
|
|
28582
30516
|
await opened;
|
|
28583
30517
|
this.setState("connected");
|
|
@@ -28588,6 +30522,7 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28588
30522
|
this.micCapture = await this.createMicCapture(micStream, ASSEMBLYAI_PCM_SAMPLE_RATE, (base64Pcm16) => this.sendMicChunk(base64Pcm16));
|
|
28589
30523
|
this.attachOutputAudioMeter(this.playback?.CreateMeter?.() ?? null);
|
|
28590
30524
|
this.attachInputAudioMeter(RealtimeAudioMeter.ForMicStream(micStream));
|
|
30525
|
+
this.ArmConnectionDurationTimer();
|
|
28591
30526
|
this.setState("listening");
|
|
28592
30527
|
}
|
|
28593
30528
|
/**
|
|
@@ -28598,6 +30533,9 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28598
30533
|
*/
|
|
28599
30534
|
async Disconnect() {
|
|
28600
30535
|
this.closedByConsumer = true;
|
|
30536
|
+
this.socketOpen = false;
|
|
30537
|
+
this.DisposeReconnectTimers();
|
|
30538
|
+
this.activeConfig = null;
|
|
28601
30539
|
this.closeAudioMeters();
|
|
28602
30540
|
this.micStream?.getTracks().forEach((track) => track.stop());
|
|
28603
30541
|
this.micStream = null;
|
|
@@ -28607,21 +30545,195 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28607
30545
|
this.playback = null;
|
|
28608
30546
|
this.clearRemoteMediaStream();
|
|
28609
30547
|
if (this.socket) {
|
|
30548
|
+
const s = this.socket;
|
|
30549
|
+
this.socket = null;
|
|
30550
|
+
s.onopen = null;
|
|
30551
|
+
s.onmessage = null;
|
|
30552
|
+
s.onerror = null;
|
|
30553
|
+
s.onclose = null;
|
|
28610
30554
|
try {
|
|
28611
|
-
|
|
30555
|
+
s.send(JSON.stringify({ type: "session.end" }));
|
|
28612
30556
|
} catch {
|
|
28613
30557
|
}
|
|
28614
30558
|
try {
|
|
28615
|
-
|
|
30559
|
+
s.close();
|
|
28616
30560
|
} catch {
|
|
28617
30561
|
}
|
|
28618
|
-
this.socket = null;
|
|
28619
30562
|
}
|
|
28620
30563
|
this.resetResponseState();
|
|
28621
30564
|
if (this.currentState !== "error") {
|
|
28622
30565
|
this.setState("closed");
|
|
28623
30566
|
}
|
|
28624
30567
|
}
|
|
30568
|
+
/**
|
|
30569
|
+
* Re-establishes the AssemblyAI Voice Agent session on a fresh credential/socket while
|
|
30570
|
+
* keeping the local mic capture and playback pipeline intact. When `UseNativeResumption`
|
|
30571
|
+
* is true and a `ResumptionHandle` (`session_id`) is available, attempts `session.resume`;
|
|
30572
|
+
* otherwise starts a fresh session and seeds prior conversation memory into `system_prompt`
|
|
30573
|
+
* via `RenderRealtimeMemorySeedAsContextNote`.
|
|
30574
|
+
*/
|
|
30575
|
+
async Reconnect(context) {
|
|
30576
|
+
const baseConfig = this.activeConfig;
|
|
30577
|
+
if (!baseConfig) {
|
|
30578
|
+
throw new Error("AssemblyAIRealtimeClient.Reconnect: no session config available.");
|
|
30579
|
+
}
|
|
30580
|
+
if (context.Abandoned) {
|
|
30581
|
+
throw new Error("AssemblyAIRealtimeClient.Reconnect: reconnect attempt abandoned.");
|
|
30582
|
+
}
|
|
30583
|
+
const config = {
|
|
30584
|
+
...baseConfig,
|
|
30585
|
+
EphemeralToken: context.Credential.EphemeralToken || baseConfig.EphemeralToken,
|
|
30586
|
+
ExpiresAt: context.Credential.ExpiresAt || baseConfig.ExpiresAt,
|
|
30587
|
+
...context.Credential.RelayUrl ? { RelayUrl: context.Credential.RelayUrl } : {},
|
|
30588
|
+
SessionConfig: context.Credential.SessionConfig ?? baseConfig.SessionConfig
|
|
30589
|
+
};
|
|
30590
|
+
const prevSocket = this.socket;
|
|
30591
|
+
const useNativeResume = context.UseNativeResumption && Boolean(context.ResumptionHandle);
|
|
30592
|
+
const sessionObject = { ...this.parseSessionObject(config) };
|
|
30593
|
+
delete sessionObject["greeting"];
|
|
30594
|
+
const nextInitialBasePrompt = typeof sessionObject["system_prompt"] === "string" ? sessionObject["system_prompt"] : this.initialBasePrompt;
|
|
30595
|
+
const notesAtAttemptStart = new Set(this.contextNotes);
|
|
30596
|
+
const seedNote = !useNativeResume && context.Seed.Entries.length > 0 ? RenderRealtimeMemorySeedAsContextNote(context.Seed) : null;
|
|
30597
|
+
const nextBasePrompt = seedNote ? nextInitialBasePrompt ? `${nextInitialBasePrompt}
|
|
30598
|
+
|
|
30599
|
+
${seedNote}` : seedNote : nextInitialBasePrompt;
|
|
30600
|
+
const carryOverNotes = seedNote ? [] : this.contextNotes.filter((n) => !n.Ephemeral);
|
|
30601
|
+
sessionObject["system_prompt"] = carryOverNotes.length === 0 ? nextBasePrompt : `${nextBasePrompt}
|
|
30602
|
+
|
|
30603
|
+
## Background updates
|
|
30604
|
+
${carryOverNotes.map((n) => `- ${n.Text}`).join("\n")}`;
|
|
30605
|
+
let openSocket = null;
|
|
30606
|
+
let failOpen = null;
|
|
30607
|
+
let confirmReady = null;
|
|
30608
|
+
let failReady = null;
|
|
30609
|
+
const opened = new Promise((resolve, reject) => {
|
|
30610
|
+
openSocket = resolve;
|
|
30611
|
+
failOpen = reject;
|
|
30612
|
+
});
|
|
30613
|
+
const ready = new Promise((resolve, reject) => {
|
|
30614
|
+
confirmReady = resolve;
|
|
30615
|
+
failReady = reject;
|
|
30616
|
+
});
|
|
30617
|
+
ready.catch(() => void 0);
|
|
30618
|
+
const failConnect = (error) => {
|
|
30619
|
+
failOpen?.(error);
|
|
30620
|
+
failReady?.(error);
|
|
30621
|
+
};
|
|
30622
|
+
const nextConnectUrl = `${ASSEMBLYAI_AGENT_WS_URL}?token=${encodeURIComponent(config.EphemeralToken)}`;
|
|
30623
|
+
const nextSocket = this.createSocket(nextConnectUrl);
|
|
30624
|
+
let nextSocketOpen = false;
|
|
30625
|
+
let nextProviderSessionId = null;
|
|
30626
|
+
const onAbort = () => {
|
|
30627
|
+
failConnect(new Error("AssemblyAIRealtimeClient: reconnect attempt aborted"));
|
|
30628
|
+
try {
|
|
30629
|
+
nextSocket.close();
|
|
30630
|
+
} catch {
|
|
30631
|
+
}
|
|
30632
|
+
};
|
|
30633
|
+
if (context.Signal.aborted) {
|
|
30634
|
+
onAbort();
|
|
30635
|
+
throw new Error("AssemblyAIRealtimeClient: reconnect attempt aborted");
|
|
30636
|
+
}
|
|
30637
|
+
context.Signal.addEventListener("abort", onAbort, { once: true });
|
|
30638
|
+
nextSocket.onopen = () => {
|
|
30639
|
+
nextSocketOpen = true;
|
|
30640
|
+
openSocket?.();
|
|
30641
|
+
};
|
|
30642
|
+
nextSocket.onmessage = (data) => {
|
|
30643
|
+
if (this.socket === nextSocket) {
|
|
30644
|
+
this.handleSocketMessage(data);
|
|
30645
|
+
return;
|
|
30646
|
+
}
|
|
30647
|
+
try {
|
|
30648
|
+
const event = JSON.parse(data);
|
|
30649
|
+
if (event.type === "session.ready") {
|
|
30650
|
+
if (event.session_id) {
|
|
30651
|
+
nextProviderSessionId = event.session_id;
|
|
30652
|
+
}
|
|
30653
|
+
confirmReady?.();
|
|
30654
|
+
confirmReady = null;
|
|
30655
|
+
}
|
|
30656
|
+
} catch {
|
|
30657
|
+
}
|
|
30658
|
+
};
|
|
30659
|
+
nextSocket.onerror = (message) => {
|
|
30660
|
+
nextSocketOpen = false;
|
|
30661
|
+
failConnect(new Error(message));
|
|
30662
|
+
if (this.socket === nextSocket && !this.IsReconnecting) {
|
|
30663
|
+
this.socketOpen = false;
|
|
30664
|
+
this.handleSocketError(message);
|
|
30665
|
+
}
|
|
30666
|
+
};
|
|
30667
|
+
nextSocket.onclose = () => {
|
|
30668
|
+
nextSocketOpen = false;
|
|
30669
|
+
failConnect(new Error("AssemblyAI agent socket closed during reconnect"));
|
|
30670
|
+
if (this.socket === nextSocket && !this.IsReconnecting) {
|
|
30671
|
+
this.socketOpen = false;
|
|
30672
|
+
this.handleSocketClose();
|
|
30673
|
+
}
|
|
30674
|
+
};
|
|
30675
|
+
try {
|
|
30676
|
+
await opened;
|
|
30677
|
+
if (context.Abandoned) {
|
|
30678
|
+
throw new Error("AssemblyAIRealtimeClient: reconnect attempt abandoned after open");
|
|
30679
|
+
}
|
|
30680
|
+
if (useNativeResume && context.ResumptionHandle) {
|
|
30681
|
+
nextSocket.send(JSON.stringify({ type: "session.resume", session_id: context.ResumptionHandle }));
|
|
30682
|
+
} else {
|
|
30683
|
+
nextSocket.send(JSON.stringify({ type: "session.update", session: sessionObject }));
|
|
30684
|
+
}
|
|
30685
|
+
await ready;
|
|
30686
|
+
if (context.Abandoned) {
|
|
30687
|
+
throw new Error("AssemblyAIRealtimeClient: reconnect attempt abandoned after session.ready");
|
|
30688
|
+
}
|
|
30689
|
+
} catch (err) {
|
|
30690
|
+
nextSocket.onopen = null;
|
|
30691
|
+
nextSocket.onmessage = null;
|
|
30692
|
+
nextSocket.onerror = null;
|
|
30693
|
+
nextSocket.onclose = null;
|
|
30694
|
+
try {
|
|
30695
|
+
nextSocket.close();
|
|
30696
|
+
} catch {
|
|
30697
|
+
}
|
|
30698
|
+
throw err;
|
|
30699
|
+
} finally {
|
|
30700
|
+
context.Signal.removeEventListener("abort", onAbort);
|
|
30701
|
+
}
|
|
30702
|
+
if (prevSocket) {
|
|
30703
|
+
prevSocket.onopen = null;
|
|
30704
|
+
prevSocket.onmessage = null;
|
|
30705
|
+
prevSocket.onerror = null;
|
|
30706
|
+
prevSocket.onclose = null;
|
|
30707
|
+
}
|
|
30708
|
+
this.activeConfig = config;
|
|
30709
|
+
this.ApplySessionConfigTiming(config);
|
|
30710
|
+
if (!useNativeResume) {
|
|
30711
|
+
for (const callID of this.pendingToolCallIds) {
|
|
30712
|
+
this.callsFromBeforeReseed.add(callID);
|
|
30713
|
+
}
|
|
30714
|
+
}
|
|
30715
|
+
const arrivedDuringAttempt = this.contextNotes.filter((n) => !notesAtAttemptStart.has(n));
|
|
30716
|
+
this.contextNotes = seedNote ? arrivedDuringAttempt : [...carryOverNotes, ...arrivedDuringAttempt];
|
|
30717
|
+
this.initialBasePrompt = nextInitialBasePrompt;
|
|
30718
|
+
this.basePrompt = nextBasePrompt;
|
|
30719
|
+
this.connectUrl = nextConnectUrl;
|
|
30720
|
+
this.resumeAttempted = false;
|
|
30721
|
+
this.socket = nextSocket;
|
|
30722
|
+
this.socketOpen = nextSocketOpen;
|
|
30723
|
+
if (nextProviderSessionId) {
|
|
30724
|
+
this.providerSessionId = nextProviderSessionId;
|
|
30725
|
+
this.RecordResumptionHandle(nextProviderSessionId);
|
|
30726
|
+
}
|
|
30727
|
+
try {
|
|
30728
|
+
prevSocket?.close();
|
|
30729
|
+
} catch {
|
|
30730
|
+
}
|
|
30731
|
+
this.responseActive = false;
|
|
30732
|
+
this.suppressReplyAudio = false;
|
|
30733
|
+
this.activeResponseKind = "normal";
|
|
30734
|
+
this.flushQueuedSends();
|
|
30735
|
+
this.setState("listening");
|
|
30736
|
+
}
|
|
28625
30737
|
// ── BaseRealtimeClient: outbound actions ──────────────────────────────────
|
|
28626
30738
|
/**
|
|
28627
30739
|
* Injects typed text — EMULATED via `reply.create` (the protocol accepts no typed user
|
|
@@ -28634,7 +30746,7 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28634
30746
|
* queued send starts a new reply, the text queues behind it, preserving delivery order.
|
|
28635
30747
|
*/
|
|
28636
30748
|
SendText(text) {
|
|
28637
|
-
if (!this.socket) {
|
|
30749
|
+
if (!this.socket || !this.socketOpen) {
|
|
28638
30750
|
return;
|
|
28639
30751
|
}
|
|
28640
30752
|
this.CancelActiveResponse();
|
|
@@ -28651,7 +30763,7 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28651
30763
|
* delivery is never dropped by a cancel). No-op when nothing is active.
|
|
28652
30764
|
*/
|
|
28653
30765
|
CancelActiveResponse() {
|
|
28654
|
-
if (!this.socket) {
|
|
30766
|
+
if (!this.socket || !this.socketOpen) {
|
|
28655
30767
|
return;
|
|
28656
30768
|
}
|
|
28657
30769
|
if (!this.responseActive && !this.IsAudioPlaying) {
|
|
@@ -28674,12 +30786,29 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28674
30786
|
* `session.update`. A config write never triggers or disturbs generation, so it is sent
|
|
28675
30787
|
* immediately even while a reply is in flight (no queueing applies).
|
|
28676
30788
|
*/
|
|
28677
|
-
SendContextNote(text) {
|
|
28678
|
-
if (!this.socket) {
|
|
30789
|
+
SendContextNote(text, options) {
|
|
30790
|
+
if ((!this.socket || !this.socketOpen) && !this.IsReconnecting) {
|
|
28679
30791
|
return;
|
|
28680
30792
|
}
|
|
28681
|
-
this.
|
|
28682
|
-
|
|
30793
|
+
this.ConversationMemory.Record({ Kind: "note", Text: text, ...options });
|
|
30794
|
+
const stateKey = options?.StateKey?.trim();
|
|
30795
|
+
if (stateKey) {
|
|
30796
|
+
const storedText = options?.MemoryText ?? text;
|
|
30797
|
+
this.contextNotes = this.contextNotes.filter((n) => n.StateKey !== stateKey);
|
|
30798
|
+
if (storedText.trim().length > 0 && !options?.Ephemeral) {
|
|
30799
|
+
this.contextNotes.push({ Text: storedText, StateKey: stateKey });
|
|
30800
|
+
}
|
|
30801
|
+
} else if (options?.Ephemeral) {
|
|
30802
|
+
this.contextNotes = this.contextNotes.filter((n) => !n.Ephemeral);
|
|
30803
|
+
this.contextNotes.push({ Text: text, Ephemeral: true });
|
|
30804
|
+
} else {
|
|
30805
|
+
this.contextNotes.push({ Text: text });
|
|
30806
|
+
}
|
|
30807
|
+
if (this.socket && this.socketOpen) {
|
|
30808
|
+
this.sendFrame({ type: "session.update", session: { system_prompt: this.composePromptWithNotes() } });
|
|
30809
|
+
} else if (this.IsReconnecting) {
|
|
30810
|
+
this.queuedSends.push(() => this.sendFrame({ type: "session.update", session: { system_prompt: this.composePromptWithNotes() } }));
|
|
30811
|
+
}
|
|
28683
30812
|
}
|
|
28684
30813
|
/**
|
|
28685
30814
|
* Triggers ONE short spoken update — NATIVE via `reply.create` with per-response
|
|
@@ -28688,14 +30817,14 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28688
30817
|
* collision rule (an overlapping `reply.create` would collide with active generation).
|
|
28689
30818
|
*/
|
|
28690
30819
|
RequestSpokenUpdate(instructions) {
|
|
28691
|
-
if (!this.socket) {
|
|
30820
|
+
if (!this.socket || !this.socketOpen) {
|
|
28692
30821
|
return;
|
|
28693
30822
|
}
|
|
28694
30823
|
this.enqueueOrRun(() => this.sendReplyCreate(instructions, "narration", false));
|
|
28695
30824
|
}
|
|
28696
30825
|
/** A spoken TURN: the same reply trigger as the update, with the reply kept `normal` (MJ#4591). */
|
|
28697
30826
|
RequestSpokenTurn(instructions) {
|
|
28698
|
-
if (!this.socket) {
|
|
30827
|
+
if (!this.socket || !this.socketOpen) {
|
|
28699
30828
|
return;
|
|
28700
30829
|
}
|
|
28701
30830
|
this.enqueueOrRun(() => this.sendReplyCreate(instructions, "normal", false));
|
|
@@ -28710,15 +30839,20 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28710
30839
|
* not clobbered. The wire `result` slot expects a JSON-STRING, which is exactly the
|
|
28711
30840
|
* contract's `outputJson` shape — it passes through verbatim.
|
|
28712
30841
|
*/
|
|
28713
|
-
|
|
28714
|
-
if (!this.socket) {
|
|
28715
|
-
return;
|
|
30842
|
+
doSendToolResult(callID, outputJson) {
|
|
30843
|
+
if (!this.socket || !this.socketOpen) {
|
|
30844
|
+
return false;
|
|
28716
30845
|
}
|
|
28717
30846
|
if (!this.pendingToolCallIds.has(callID)) {
|
|
28718
30847
|
console.warn(`AssemblyAIRealtimeClient.SendToolResult: no pending tool call '${callID}' \u2014 duplicate or unknown result dropped.`);
|
|
28719
|
-
return;
|
|
30848
|
+
return false;
|
|
28720
30849
|
}
|
|
28721
30850
|
this.pendingToolCallIds.delete(callID);
|
|
30851
|
+
const name = this.resolveToolName(callID);
|
|
30852
|
+
if (this.callsFromBeforeReseed.delete(callID)) {
|
|
30853
|
+
this.enqueueOrRun(() => this.sendReplyCreate(RenderLateToolResultNote(name, outputJson), "normal", true));
|
|
30854
|
+
return;
|
|
30855
|
+
}
|
|
28722
30856
|
this.enqueueOrRun(() => this.sendToolResultFrame(callID, outputJson));
|
|
28723
30857
|
}
|
|
28724
30858
|
/**
|
|
@@ -28809,13 +30943,13 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28809
30943
|
}
|
|
28810
30944
|
/** Streams one base64 PCM16 mic chunk as an `input.audio` frame. */
|
|
28811
30945
|
sendMicChunk(base64Pcm16) {
|
|
28812
|
-
if (this.socket) {
|
|
30946
|
+
if (this.socket && this.socketOpen) {
|
|
28813
30947
|
this.sendFrame({ type: "input.audio", audio: base64Pcm16 });
|
|
28814
30948
|
}
|
|
28815
30949
|
}
|
|
28816
30950
|
/** Surfaces a fatal socket error and marks the session unusable (obligation #6). */
|
|
28817
30951
|
handleSocketError(message) {
|
|
28818
|
-
if (this.currentState === "error" || this.currentState === "closed") {
|
|
30952
|
+
if (this.IsReconnecting || this.currentState === "error" || this.currentState === "closed") {
|
|
28819
30953
|
return;
|
|
28820
30954
|
}
|
|
28821
30955
|
this.emitError({ Message: `AssemblyAI realtime transport error: ${message}`, Fatal: true });
|
|
@@ -28827,7 +30961,7 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28827
30961
|
* session death reaches the host (obligation #6).
|
|
28828
30962
|
*/
|
|
28829
30963
|
handleSocketClose() {
|
|
28830
|
-
if (this.closedByConsumer || this.currentState === "error" || this.currentState === "closed") {
|
|
30964
|
+
if (this.closedByConsumer || this.IsReconnecting || this.currentState === "error" || this.currentState === "closed") {
|
|
28831
30965
|
return;
|
|
28832
30966
|
}
|
|
28833
30967
|
if (this.tryResumeSession()) {
|
|
@@ -28855,10 +30989,34 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28855
30989
|
try {
|
|
28856
30990
|
const socket = this.createSocket(this.connectUrl);
|
|
28857
30991
|
this.socket = socket;
|
|
28858
|
-
|
|
28859
|
-
socket.
|
|
28860
|
-
|
|
28861
|
-
|
|
30992
|
+
this.socketOpen = false;
|
|
30993
|
+
socket.onopen = () => {
|
|
30994
|
+
if (this.socket !== socket) {
|
|
30995
|
+
return;
|
|
30996
|
+
}
|
|
30997
|
+
this.socketOpen = true;
|
|
30998
|
+
this.sendFrame({ type: "session.resume", session_id: sessionId });
|
|
30999
|
+
};
|
|
31000
|
+
socket.onmessage = (data) => {
|
|
31001
|
+
if (this.socket !== socket) {
|
|
31002
|
+
return;
|
|
31003
|
+
}
|
|
31004
|
+
this.handleSocketMessage(data);
|
|
31005
|
+
};
|
|
31006
|
+
socket.onerror = (message) => {
|
|
31007
|
+
if (this.socket !== socket) {
|
|
31008
|
+
return;
|
|
31009
|
+
}
|
|
31010
|
+
this.socketOpen = false;
|
|
31011
|
+
this.handleSocketError(message);
|
|
31012
|
+
};
|
|
31013
|
+
socket.onclose = () => {
|
|
31014
|
+
if (this.socket !== socket) {
|
|
31015
|
+
return;
|
|
31016
|
+
}
|
|
31017
|
+
this.socketOpen = false;
|
|
31018
|
+
this.handleSocketClose();
|
|
31019
|
+
};
|
|
28862
31020
|
this.onSessionReady = () => this.setState("listening");
|
|
28863
31021
|
return true;
|
|
28864
31022
|
} catch {
|
|
@@ -28881,6 +31039,9 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
28881
31039
|
switch (event.type) {
|
|
28882
31040
|
case "session.ready":
|
|
28883
31041
|
this.providerSessionId = event.session_id ?? this.providerSessionId;
|
|
31042
|
+
if (event.session_id) {
|
|
31043
|
+
this.RecordResumptionHandle(event.session_id);
|
|
31044
|
+
}
|
|
28884
31045
|
this.onSessionReady?.();
|
|
28885
31046
|
this.onSessionReady = null;
|
|
28886
31047
|
break;
|
|
@@ -29108,7 +31269,7 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
|
|
|
29108
31269
|
return `${this.basePrompt}
|
|
29109
31270
|
|
|
29110
31271
|
## Background updates
|
|
29111
|
-
${this.contextNotes.map((n) => `- ${n}`).join("\n")}`;
|
|
31272
|
+
${this.contextNotes.map((n) => `- ${n.Text}`).join("\n")}`;
|
|
29112
31273
|
}
|
|
29113
31274
|
/** JSON-serializes and sends one client frame (no-op once the socket is gone). */
|
|
29114
31275
|
sendFrame(frame) {
|
|
@@ -29121,6 +31282,7 @@ ${this.contextNotes.map((n) => `- ${n}`).join("\n")}`;
|
|
|
29121
31282
|
this.queuedSends = [];
|
|
29122
31283
|
this.suppressReplyAudio = false;
|
|
29123
31284
|
this.pendingToolCallIds.clear();
|
|
31285
|
+
this.callsFromBeforeReseed.clear();
|
|
29124
31286
|
this.onSessionReady = null;
|
|
29125
31287
|
this.contextNotes = [];
|
|
29126
31288
|
}
|
|
@@ -29155,10 +31317,38 @@ var xAIRealtimeClient = class xAIRealtimeClient2 extends OpenAIProtocolWebSocket
|
|
|
29155
31317
|
get providerDebugLabel() {
|
|
29156
31318
|
return "xAIRealtimeClient";
|
|
29157
31319
|
}
|
|
31320
|
+
get DefaultCallDurationSeconds() {
|
|
31321
|
+
return 7200;
|
|
31322
|
+
}
|
|
31323
|
+
/**
|
|
31324
|
+
* Defaults to `false`: xAI's `?conversation_id=<id>` server-side resumption currently drops
|
|
31325
|
+
* `conversation.item.create` `message` items (`SendContextNote`, `SendText`, and post-drop
|
|
31326
|
+
* `seedConversationAfterMove` history), causing Grok Voice to forget injected context and
|
|
31327
|
+
* replayed turns across reconnects. Text-seed replay into a fresh conversation preserves both
|
|
31328
|
+
* spoken and injected turns losslessly; callers can still opt into native resumption explicitly
|
|
31329
|
+
* via `TrustNativeResumption: true` on `ClientRealtimeSessionConfig`.
|
|
31330
|
+
*/
|
|
31331
|
+
get DefaultTrustsNativeResumption() {
|
|
31332
|
+
return false;
|
|
31333
|
+
}
|
|
29158
31334
|
// ── Transport hooks ────────────────────────────────────────────────────────
|
|
31335
|
+
resolveSessionObject(config) {
|
|
31336
|
+
const sessionObj = super.resolveSessionObject(config);
|
|
31337
|
+
const explicitlyTrusted = config.TrustNativeResumption === true || config.SessionConfig?.["trustNativeResumption"] === true || config.SessionConfig?.["TrustNativeResumption"] === true;
|
|
31338
|
+
if (explicitlyTrusted && this.TrustsNativeResumption && Object.keys(sessionObj).length > 0 && sessionObj["resumption"] === void 0) {
|
|
31339
|
+
return {
|
|
31340
|
+
...sessionObj,
|
|
31341
|
+
resumption: { enabled: true }
|
|
31342
|
+
};
|
|
31343
|
+
}
|
|
31344
|
+
return sessionObj;
|
|
31345
|
+
}
|
|
29159
31346
|
/** @inheritdoc — model on the URL, ephemeral secret as the subprotocol. */
|
|
29160
|
-
openProviderSocket(config) {
|
|
29161
|
-
|
|
31347
|
+
openProviderSocket(config, resumptionHandle) {
|
|
31348
|
+
let url = `${XAI_REALTIME_WS_URL}?model=${encodeURIComponent(config.Model)}`;
|
|
31349
|
+
if (resumptionHandle && resumptionHandle.trim().length > 0) {
|
|
31350
|
+
url += `&conversation_id=${encodeURIComponent(resumptionHandle.trim())}`;
|
|
31351
|
+
}
|
|
29162
31352
|
const subprotocol = `${XAI_CLIENT_SECRET_SUBPROTOCOL_PREFIX}${config.EphemeralToken}`;
|
|
29163
31353
|
return this.createSocket(url, subprotocol);
|
|
29164
31354
|
}
|
|
@@ -29295,6 +31485,9 @@ var ElevenRealtimeClient = class ElevenRealtimeClient2 extends OpenAIProtocolWeb
|
|
|
29295
31485
|
get providerDebugLabel() {
|
|
29296
31486
|
return "ElevenRealtimeClient";
|
|
29297
31487
|
}
|
|
31488
|
+
get DefaultCallDurationSeconds() {
|
|
31489
|
+
return void 0;
|
|
31490
|
+
}
|
|
29298
31491
|
// ── Transport hooks ────────────────────────────────────────────────────────
|
|
29299
31492
|
/** @inheritdoc — model on the URL, client secret in the OpenAI-SDK subprotocol slot. */
|
|
29300
31493
|
openProviderSocket(config) {
|
|
@@ -29397,17 +31590,32 @@ var HuggingFaceRealtimeClient = class HuggingFaceRealtimeClient2 extends OpenAIP
|
|
|
29397
31590
|
const raw = config.SessionConfig?.["sampleRate"];
|
|
29398
31591
|
return typeof raw === "number" && raw > 0 ? raw : HUGGINGFACE_DEFAULT_PCM_SAMPLE_RATE;
|
|
29399
31592
|
}
|
|
31593
|
+
/**
|
|
31594
|
+
* @inheritdoc
|
|
31595
|
+
*
|
|
31596
|
+
* Off: the proxy hop closes benignly and the host reads `'closed'` as the end of the session
|
|
31597
|
+
* (see {@link handleSocketClose}), so a lost socket does not start a reconnect and a socket
|
|
31598
|
+
* error stays fatal. A loss during a planned move still goes to that move's reconnect.
|
|
31599
|
+
*/
|
|
31600
|
+
get RecoversLostTransport() {
|
|
31601
|
+
return false;
|
|
31602
|
+
}
|
|
29400
31603
|
/**
|
|
29401
31604
|
* @inheritdoc
|
|
29402
31605
|
*
|
|
29403
31606
|
* A close the consumer didn't ask for is reported as a terminal `'closed'` — NOT the fatal
|
|
29404
31607
|
* error the cloud providers surface: the self-hosted proxy hop closes benignly (ticket
|
|
29405
31608
|
* expiry, upstream restart), and the host treats `'closed'` as the session-over signal.
|
|
31609
|
+
* During a planned move the closed socket is the one the move may go back to, so the move's
|
|
31610
|
+
* reconnect takes the loss and the call goes on (`recoverLostTransport` answers `true` only then).
|
|
29406
31611
|
*/
|
|
29407
31612
|
handleSocketClose() {
|
|
29408
31613
|
if (this.closedByConsumer) {
|
|
29409
31614
|
return;
|
|
29410
31615
|
}
|
|
31616
|
+
if (this.recoverLostTransport("socket closed")) {
|
|
31617
|
+
return;
|
|
31618
|
+
}
|
|
29411
31619
|
if (this.currentState !== "error") {
|
|
29412
31620
|
this.setState("closed");
|
|
29413
31621
|
}
|
|
@@ -29455,6 +31663,7 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29455
31663
|
this.micStream = null;
|
|
29456
31664
|
this.micSenders = [];
|
|
29457
31665
|
this.sessionConfig = null;
|
|
31666
|
+
this.activeConfig = null;
|
|
29458
31667
|
this.currentState = "closed";
|
|
29459
31668
|
this.responseActive = false;
|
|
29460
31669
|
this.audioPlaying = false;
|
|
@@ -29492,6 +31701,9 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29492
31701
|
static {
|
|
29493
31702
|
this.MAX_OUTBOUND_QUEUE_SIZE = 100;
|
|
29494
31703
|
}
|
|
31704
|
+
get DefaultCallDurationSeconds() {
|
|
31705
|
+
return 3600;
|
|
31706
|
+
}
|
|
29495
31707
|
// ── BaseRealtimeClient implementation ──────────────────────────────────────
|
|
29496
31708
|
get IsBusy() {
|
|
29497
31709
|
return this.responseActive;
|
|
@@ -29510,6 +31722,8 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29510
31722
|
*/
|
|
29511
31723
|
async Connect(config, micStream, _cameraStream) {
|
|
29512
31724
|
this.AssertTransportSupported(config);
|
|
31725
|
+
this.ApplySessionConfigTiming(config);
|
|
31726
|
+
this.activeConfig = config;
|
|
29513
31727
|
this.sessionConfig = config.SessionConfig;
|
|
29514
31728
|
this.micStream = micStream;
|
|
29515
31729
|
this.setState("connecting");
|
|
@@ -29525,6 +31739,7 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29525
31739
|
await this.waitForIceGatheringComplete(pc);
|
|
29526
31740
|
const answerSdp = await this.postSdpOffer(offer.sdp ?? "", config);
|
|
29527
31741
|
await pc.setRemoteDescription({ type: "answer", sdp: answerSdp });
|
|
31742
|
+
this.ArmConnectionDurationTimer();
|
|
29528
31743
|
this.setState("connected");
|
|
29529
31744
|
this.totalDurationSeconds = OpenAILiveClient_1.PREBILL_DURATION_SECONDS;
|
|
29530
31745
|
this.emitUsage({
|
|
@@ -29537,6 +31752,7 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29537
31752
|
* Tears down the connection, data channel, audio tracks, and audio sink.
|
|
29538
31753
|
*/
|
|
29539
31754
|
async Disconnect() {
|
|
31755
|
+
this.DisposeReconnectTimers();
|
|
29540
31756
|
this.finalizeUserTranscript();
|
|
29541
31757
|
this.finalizeAssistantTranscript();
|
|
29542
31758
|
this.closeAudioMeters();
|
|
@@ -29564,6 +31780,7 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29564
31780
|
}
|
|
29565
31781
|
this.clearRemoteMediaStream();
|
|
29566
31782
|
this.sessionConfig = null;
|
|
31783
|
+
this.activeConfig = null;
|
|
29567
31784
|
this.responseActive = false;
|
|
29568
31785
|
this.audioPlaying = false;
|
|
29569
31786
|
this.pendingNarration = false;
|
|
@@ -29578,6 +31795,159 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29578
31795
|
this.setState("closed");
|
|
29579
31796
|
}
|
|
29580
31797
|
}
|
|
31798
|
+
async Reconnect(context) {
|
|
31799
|
+
if (!this.activeConfig || !this.micStream) {
|
|
31800
|
+
throw new Error("OpenAILiveClient: cannot reconnect before Connect");
|
|
31801
|
+
}
|
|
31802
|
+
if (context.Abandoned) {
|
|
31803
|
+
throw new Error("OpenAILiveClient: reconnect attempt abandoned");
|
|
31804
|
+
}
|
|
31805
|
+
const refreshedConfig = {
|
|
31806
|
+
...this.activeConfig,
|
|
31807
|
+
EphemeralToken: context.Credential.EphemeralToken || this.activeConfig.EphemeralToken,
|
|
31808
|
+
ExpiresAt: context.Credential.ExpiresAt || this.activeConfig.ExpiresAt,
|
|
31809
|
+
...context.Credential.RelayUrl !== void 0 ? { RelayUrl: context.Credential.RelayUrl } : {},
|
|
31810
|
+
...context.Credential.SessionConfig !== void 0 ? { SessionConfig: context.Credential.SessionConfig } : {}
|
|
31811
|
+
};
|
|
31812
|
+
this.activeConfig = refreshedConfig;
|
|
31813
|
+
this.sessionConfig = refreshedConfig.SessionConfig;
|
|
31814
|
+
const prevPc = this.peerConnection;
|
|
31815
|
+
const prevDc = this.dataChannel;
|
|
31816
|
+
const nextPc = this.createPeerConnection();
|
|
31817
|
+
const nextSenders = this.micStream.getAudioTracks().map((track) => nextPc.addTrack(track, this.micStream));
|
|
31818
|
+
if (!this.remoteAudioEl) {
|
|
31819
|
+
this.remoteAudioEl = this.createAudioSink();
|
|
31820
|
+
}
|
|
31821
|
+
let pendingRemoteStream = null;
|
|
31822
|
+
nextPc.ontrack = (e) => {
|
|
31823
|
+
if (context.Abandoned || !e.streams[0]) {
|
|
31824
|
+
return;
|
|
31825
|
+
}
|
|
31826
|
+
if (this.peerConnection === nextPc && this.remoteAudioEl) {
|
|
31827
|
+
this.remoteAudioEl.srcObject = e.streams[0];
|
|
31828
|
+
this.publishRemoteMediaStream(e.streams[0]);
|
|
31829
|
+
this.attachOutputAudioMeter(RealtimeAudioMeter.ForStream(e.streams[0]));
|
|
31830
|
+
} else {
|
|
31831
|
+
pendingRemoteStream = e.streams[0];
|
|
31832
|
+
}
|
|
31833
|
+
};
|
|
31834
|
+
const nextDc = nextPc.createDataChannel("oai-events");
|
|
31835
|
+
let openDc = null;
|
|
31836
|
+
let failDc = null;
|
|
31837
|
+
const dcOpened = new Promise((resolve, reject) => {
|
|
31838
|
+
openDc = resolve;
|
|
31839
|
+
failDc = reject;
|
|
31840
|
+
});
|
|
31841
|
+
dcOpened.catch(() => void 0);
|
|
31842
|
+
const onAbort = () => {
|
|
31843
|
+
failDc?.(new Error("OpenAILiveClient: reconnect attempt aborted"));
|
|
31844
|
+
try {
|
|
31845
|
+
nextDc.close();
|
|
31846
|
+
} catch {
|
|
31847
|
+
}
|
|
31848
|
+
try {
|
|
31849
|
+
nextPc.close();
|
|
31850
|
+
} catch {
|
|
31851
|
+
}
|
|
31852
|
+
};
|
|
31853
|
+
if (context.Signal.aborted) {
|
|
31854
|
+
onAbort();
|
|
31855
|
+
throw new Error("OpenAILiveClient: reconnect attempt aborted");
|
|
31856
|
+
}
|
|
31857
|
+
context.Signal.addEventListener("abort", onAbort, { once: true });
|
|
31858
|
+
nextDc.onopen = () => {
|
|
31859
|
+
openDc?.();
|
|
31860
|
+
if (this.dataChannel === nextDc) {
|
|
31861
|
+
this.flushOutboundQueue();
|
|
31862
|
+
}
|
|
31863
|
+
};
|
|
31864
|
+
nextDc.onmessage = (e) => {
|
|
31865
|
+
if (this.dataChannel === nextDc) {
|
|
31866
|
+
this.handleDataChannelMessage(String(e.data));
|
|
31867
|
+
}
|
|
31868
|
+
};
|
|
31869
|
+
nextDc.onerror = (e) => {
|
|
31870
|
+
failDc?.(new Error(`OpenAI Live data channel error: ${String(e)}`));
|
|
31871
|
+
this.handleChannelError(nextDc, e);
|
|
31872
|
+
};
|
|
31873
|
+
nextDc.onclose = () => {
|
|
31874
|
+
failDc?.(new Error("OpenAI Live data channel closed during reconnect"));
|
|
31875
|
+
this.handleChannelClose(nextDc);
|
|
31876
|
+
};
|
|
31877
|
+
try {
|
|
31878
|
+
const offer = await nextPc.createOffer();
|
|
31879
|
+
await nextPc.setLocalDescription(offer);
|
|
31880
|
+
await this.waitForIceGatheringComplete(nextPc);
|
|
31881
|
+
if (context.Abandoned) {
|
|
31882
|
+
throw new Error("OpenAILiveClient: reconnect attempt abandoned before SDP exchange");
|
|
31883
|
+
}
|
|
31884
|
+
const answerSdp = await this.postSdpOffer(offer.sdp ?? "", refreshedConfig);
|
|
31885
|
+
await nextPc.setRemoteDescription({ type: "answer", sdp: answerSdp });
|
|
31886
|
+
if (nextDc.readyState !== "open") {
|
|
31887
|
+
await dcOpened;
|
|
31888
|
+
}
|
|
31889
|
+
if (context.Abandoned) {
|
|
31890
|
+
throw new Error("OpenAILiveClient: reconnect attempt abandoned after open");
|
|
31891
|
+
}
|
|
31892
|
+
} catch (err) {
|
|
31893
|
+
nextDc.onopen = null;
|
|
31894
|
+
nextDc.onmessage = null;
|
|
31895
|
+
nextDc.onerror = null;
|
|
31896
|
+
nextDc.onclose = null;
|
|
31897
|
+
nextPc.ontrack = null;
|
|
31898
|
+
try {
|
|
31899
|
+
nextDc.close();
|
|
31900
|
+
} catch {
|
|
31901
|
+
}
|
|
31902
|
+
try {
|
|
31903
|
+
nextPc.close();
|
|
31904
|
+
} catch {
|
|
31905
|
+
}
|
|
31906
|
+
throw err;
|
|
31907
|
+
} finally {
|
|
31908
|
+
context.Signal.removeEventListener("abort", onAbort);
|
|
31909
|
+
}
|
|
31910
|
+
if (prevDc) {
|
|
31911
|
+
prevDc.onopen = null;
|
|
31912
|
+
prevDc.onmessage = null;
|
|
31913
|
+
prevDc.onerror = null;
|
|
31914
|
+
prevDc.onclose = null;
|
|
31915
|
+
}
|
|
31916
|
+
if (prevPc) {
|
|
31917
|
+
prevPc.ontrack = null;
|
|
31918
|
+
}
|
|
31919
|
+
this.peerConnection = nextPc;
|
|
31920
|
+
this.dataChannel = nextDc;
|
|
31921
|
+
this.micSenders = nextSenders;
|
|
31922
|
+
if (pendingRemoteStream && this.remoteAudioEl) {
|
|
31923
|
+
this.remoteAudioEl.srcObject = pendingRemoteStream;
|
|
31924
|
+
this.publishRemoteMediaStream(pendingRemoteStream);
|
|
31925
|
+
this.attachOutputAudioMeter(RealtimeAudioMeter.ForStream(pendingRemoteStream));
|
|
31926
|
+
pendingRemoteStream = null;
|
|
31927
|
+
}
|
|
31928
|
+
this.responseActive = false;
|
|
31929
|
+
this.audioPlaying = false;
|
|
31930
|
+
try {
|
|
31931
|
+
prevDc?.close();
|
|
31932
|
+
} catch {
|
|
31933
|
+
}
|
|
31934
|
+
try {
|
|
31935
|
+
prevPc?.close();
|
|
31936
|
+
} catch {
|
|
31937
|
+
}
|
|
31938
|
+
if (context.ConversationSeed && context.ConversationSeed.Entries.length > 0) {
|
|
31939
|
+
const note = RenderRealtimeMemorySeedAsContextNote(context.ConversationSeed);
|
|
31940
|
+
if (note) {
|
|
31941
|
+
this.sendDataChannelFrame({
|
|
31942
|
+
type: "session.thinking.append",
|
|
31943
|
+
content: note,
|
|
31944
|
+
delegation_id: null
|
|
31945
|
+
});
|
|
31946
|
+
}
|
|
31947
|
+
}
|
|
31948
|
+
this.flushOutboundQueue();
|
|
31949
|
+
this.reportListeningAfterMove();
|
|
31950
|
+
}
|
|
29581
31951
|
/**
|
|
29582
31952
|
* Injects user text into the live session and requests a model response.
|
|
29583
31953
|
* SendText implies barge-in and must NOT synthesize a user transcript (obligation #4).
|
|
@@ -29614,7 +31984,8 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29614
31984
|
* Injects background context without triggering model speech.
|
|
29615
31985
|
* Uses `session.thinking.append` with `content` parameter and `delegation_id: null`.
|
|
29616
31986
|
*/
|
|
29617
|
-
SendContextNote(text) {
|
|
31987
|
+
SendContextNote(text, options) {
|
|
31988
|
+
this.ConversationMemory.Record({ Kind: "note", Text: text, ...options });
|
|
29618
31989
|
this.sendDataChannelFrame({
|
|
29619
31990
|
type: "session.thinking.append",
|
|
29620
31991
|
content: text,
|
|
@@ -29657,7 +32028,8 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29657
32028
|
* OpenAI Live remote reasoning plane requires response.item.create followed by response.create.
|
|
29658
32029
|
* Client delegation plane uses session.commentary.append with the delegation_id.
|
|
29659
32030
|
*/
|
|
29660
|
-
|
|
32031
|
+
doSendToolResult(callID, outputJson) {
|
|
32032
|
+
const name = this.resolveToolName(callID);
|
|
29661
32033
|
if (this.clientDelegationCallIds.has(callID)) {
|
|
29662
32034
|
this.clientDelegationCallIds.delete(callID);
|
|
29663
32035
|
this.sendDataChannelFrame({
|
|
@@ -29667,6 +32039,18 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29667
32039
|
});
|
|
29668
32040
|
return;
|
|
29669
32041
|
}
|
|
32042
|
+
if (this.callsFromBeforeReseed.delete(callID)) {
|
|
32043
|
+
this.sendDataChannelFrame({
|
|
32044
|
+
type: "session.commentary.append",
|
|
32045
|
+
content: RenderLateToolResultNote(name, outputJson),
|
|
32046
|
+
delegation_id: null
|
|
32047
|
+
});
|
|
32048
|
+
if (this.toolBatchBarrier.RecordResult(callID)) {
|
|
32049
|
+
this.emittedToolCallIds.clear();
|
|
32050
|
+
this.sendDataChannelFrame({ type: "response.create" });
|
|
32051
|
+
}
|
|
32052
|
+
return;
|
|
32053
|
+
}
|
|
29670
32054
|
this.sendDataChannelFrame({
|
|
29671
32055
|
type: "response.item.create",
|
|
29672
32056
|
item: {
|
|
@@ -29769,6 +32153,15 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29769
32153
|
this.emitStateChange(state);
|
|
29770
32154
|
}
|
|
29771
32155
|
}
|
|
32156
|
+
/**
|
|
32157
|
+
* Reports the call live on the new connection. The host was told `'connecting'` when the move started, but this
|
|
32158
|
+
* driver's own state was left as it was (an `error` frame during the move must not read the call as inactive), so
|
|
32159
|
+
* {@link setState} would skip `'listening'` when the move started from it.
|
|
32160
|
+
*/
|
|
32161
|
+
reportListeningAfterMove() {
|
|
32162
|
+
this.currentState = "listening";
|
|
32163
|
+
this.emitStateChange("listening");
|
|
32164
|
+
}
|
|
29772
32165
|
attachMicrophone(pc, micStream) {
|
|
29773
32166
|
this.micSenders = micStream.getAudioTracks().map((track) => pc.addTrack(track, micStream));
|
|
29774
32167
|
}
|
|
@@ -29808,15 +32201,32 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29808
32201
|
channel.onmessage = (e) => {
|
|
29809
32202
|
this.handleDataChannelMessage(String(e.data));
|
|
29810
32203
|
};
|
|
29811
|
-
channel.onerror = (e) =>
|
|
29812
|
-
|
|
29813
|
-
|
|
29814
|
-
|
|
29815
|
-
|
|
29816
|
-
|
|
29817
|
-
|
|
29818
|
-
|
|
29819
|
-
|
|
32204
|
+
channel.onerror = (e) => this.handleChannelError(channel, e);
|
|
32205
|
+
channel.onclose = () => this.handleChannelClose(channel);
|
|
32206
|
+
}
|
|
32207
|
+
/**
|
|
32208
|
+
* A data-channel error, shared by the first connection's channel and each reconnect's. Ignored for a channel that
|
|
32209
|
+
* is no longer current, and while a move is in flight: the move owns the outcome then (it either swaps to the new
|
|
32210
|
+
* channel or fails through the base reconnect path), so the old channel dying must not end the call. Otherwise
|
|
32211
|
+
* it is fatal.
|
|
32212
|
+
*/
|
|
32213
|
+
handleChannelError(channel, e) {
|
|
32214
|
+
if (this.dataChannel !== channel || this.IsReconnecting) {
|
|
32215
|
+
return;
|
|
32216
|
+
}
|
|
32217
|
+
this.emitError({ Message: `OpenAI Live data channel error: ${String(e)}`, Fatal: true });
|
|
32218
|
+
this.setState("error");
|
|
32219
|
+
}
|
|
32220
|
+
/**
|
|
32221
|
+
* A data-channel close the consumer did not ask for. Disconnect and the swap drop the channel before closing it,
|
|
32222
|
+
* so the identity check filters both; a close during a move is the move's to handle (see
|
|
32223
|
+
* {@link handleChannelError}). Otherwise the session ends as `'closed'`.
|
|
32224
|
+
*/
|
|
32225
|
+
handleChannelClose(channel) {
|
|
32226
|
+
if (this.dataChannel !== channel || this.IsReconnecting || this.currentState === "error") {
|
|
32227
|
+
return;
|
|
32228
|
+
}
|
|
32229
|
+
this.setState("closed");
|
|
29820
32230
|
}
|
|
29821
32231
|
finalizeAssistantTranscript() {
|
|
29822
32232
|
this.stopPlaybackDrainMonitoring();
|
|
@@ -29942,10 +32352,14 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
|
|
|
29942
32352
|
const seconds = typeof usage?.seconds === "number" ? usage.seconds : void 0;
|
|
29943
32353
|
const duration = seconds !== void 0 ? Math.max(OpenAILiveClient_1.PREBILL_DURATION_SECONDS, seconds) : this.totalDurationSeconds;
|
|
29944
32354
|
this.totalDurationSeconds = duration;
|
|
32355
|
+
const inputDetails = MapRealtimeUsageModalityDetail(usage?.["input_token_details"]);
|
|
32356
|
+
const outputDetails = MapRealtimeUsageModalityDetail(usage?.["output_token_details"]);
|
|
29945
32357
|
this.emitUsage({
|
|
29946
32358
|
InputTokens: typeof usage?.input_tokens === "number" ? usage.input_tokens : 0,
|
|
29947
32359
|
OutputTokens: typeof usage?.output_tokens === "number" ? usage.output_tokens : 0,
|
|
29948
32360
|
DurationSeconds: duration,
|
|
32361
|
+
...inputDetails ? { InputTokenDetails: inputDetails } : {},
|
|
32362
|
+
...outputDetails ? { OutputTokenDetails: outputDetails } : {},
|
|
29949
32363
|
Raw: usage
|
|
29950
32364
|
});
|
|
29951
32365
|
}
|