@memberjunction/realtime-widget 6.2.2 → 6.3.0-edge.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
- RealtimeSessionResumption,
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-JOGHPRST.js";
43
+ } from "./chunk-CIZSPKQR.js";
30
44
  import {
31
45
  BaseSingleton,
32
46
  MJGlobal,
33
47
  RegisterClass,
34
48
  __commonJS,
35
49
  __toESM
36
- } from "./chunk-DIDGGUK7.js";
50
+ } from "./chunk-KHEWGJIZ.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
- const { [REQUESTED_TRACKS_SESSION_KEY]: _clientOnly, ...providerConfig } = sessionConfig;
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) {
@@ -1040,12 +1695,19 @@ var RealtimePcmPlayback = class {
1040
1695
  }
1041
1696
  }
1042
1697
  }
1698
+ /** Resumes the audio context if the browser constructed or left it suspended. */
1699
+ ensureRunning() {
1700
+ if (this.context.state === "suspended" && typeof this.context.resume === "function") {
1701
+ void this.context.resume().catch(() => void 0);
1702
+ }
1703
+ }
1043
1704
  /** @inheritdoc */
1044
1705
  Enqueue(pcm16, mediaTimeMs) {
1045
1706
  const samples = Pcm16ToFloat32(pcm16);
1046
1707
  if (samples.length === 0) {
1047
1708
  return;
1048
1709
  }
1710
+ this.ensureRunning();
1049
1711
  const buffer = this.context.createBuffer(1, samples.length, this.sampleRate);
1050
1712
  buffer.copyToChannel(samples, 0);
1051
1713
  const source = this.context.createBufferSource();
@@ -1111,6 +1773,7 @@ var RealtimePcmPlayback = class {
1111
1773
  * goes on without that element's voice.
1112
1774
  */
1113
1775
  ConnectMediaElement(element) {
1776
+ this.ensureRunning();
1114
1777
  if (this.connectedElements.has(element)) {
1115
1778
  return;
1116
1779
  }
@@ -1211,10 +1874,19 @@ async function CreatePcmMicCapture(micStream, sampleRate, onPcmChunk) {
1211
1874
  }
1212
1875
 
1213
1876
  // ../../AI/RealtimeClient/dist/generic/openAIProtocolClient.js
1214
- var OpenAIProtocolRealtimeClient = class extends BaseRealtimeClient {
1877
+ var PENDING_USER_UTTERANCE_MAX_AGE_MS = 15e3;
1878
+ var UNIDENTIFIED_UTTERANCE_KEY = "";
1879
+ var OpenAIProtocolRealtimeClient = class _OpenAIProtocolRealtimeClient extends BaseRealtimeClient {
1215
1880
  constructor() {
1216
1881
  super(...arguments);
1217
1882
  this.pendingAssistantText = "";
1883
+ this.textHeldDuringReconnect = [];
1884
+ this.toolResultsHeldDuringReconnect = [];
1885
+ this.deliveringHeldInput = false;
1886
+ this.responseOwedByHeldInput = false;
1887
+ this.callWentLive = false;
1888
+ this.answerOwedAfterMove = false;
1889
+ this.pendingUserUtterances = /* @__PURE__ */ new Map();
1218
1890
  this.responseActive = false;
1219
1891
  this.pendingResultResponse = false;
1220
1892
  this.pendingLocalResponseCreates = 0;
@@ -1224,6 +1896,13 @@ var OpenAIProtocolRealtimeClient = class extends BaseRealtimeClient {
1224
1896
  this.currentState = "closed";
1225
1897
  this.micStream = null;
1226
1898
  }
1899
+ /**
1900
+ * Whether the transport can carry the call, which a failed move's return to it needs: by default, whether it can
1901
+ * deliver events ({@link canSendEvents}). A transport whose open state can outlast its network path overrides it.
1902
+ */
1903
+ isTransportUsable() {
1904
+ return this.canSendEvents();
1905
+ }
1227
1906
  // ── Virtual per-provider behavior seams (sensible OpenAI defaults) ─────────
1228
1907
  /** Debug label used in the shared console diagnostics. */
1229
1908
  get providerDebugLabel() {
@@ -1297,6 +1976,34 @@ var OpenAIProtocolRealtimeClient = class extends BaseRealtimeClient {
1297
1976
  * active the cancel is a no-op and the reply triggers immediately.
1298
1977
  */
1299
1978
  SendText(text) {
1979
+ if (this.IsReconnecting) {
1980
+ this.textHeldDuringReconnect.push(text);
1981
+ return;
1982
+ }
1983
+ this.deliverUserText(text);
1984
+ }
1985
+ /**
1986
+ * @inheritdoc
1987
+ *
1988
+ * During a move a result is held, like typed text, and goes out once the call is live again: on the new connection
1989
+ * after the swap ({@link onReconnected}), or on the old one when a planned move goes back to it
1990
+ * ({@link ResumeOnOldConnection}). Sent on now, it would be lost: a lost transport cannot carry it, and a closing
1991
+ * one takes it along after the seed for the new connection was built. It is recorded into memory when it goes out,
1992
+ * so it reaches the model and the seed of a later move exactly once.
1993
+ */
1994
+ SendToolResult(callID, outputJson) {
1995
+ if (this.IsReconnecting) {
1996
+ this.toolResultsHeldDuringReconnect.push({ CallID: callID, OutputJson: outputJson });
1997
+ return;
1998
+ }
1999
+ super.SendToolResult(callID, outputJson);
2000
+ }
2001
+ /**
2002
+ * Sends one typed user turn and records it in conversation memory. The provider sends no input transcription for a
2003
+ * text item (only for audio), so without the record a later reseed would drop the turn. It is recorded when sent,
2004
+ * not when held, so a held turn is not also in the seed of the move it waited for.
2005
+ */
2006
+ deliverUserText(text) {
1300
2007
  if (!this.canSendEvents()) {
1301
2008
  return;
1302
2009
  }
@@ -1305,8 +2012,93 @@ var OpenAIProtocolRealtimeClient = class extends BaseRealtimeClient {
1305
2012
  type: "conversation.item.create",
1306
2013
  item: { type: "message", role: "user", content: [{ type: "input_text", text }] }
1307
2014
  });
2015
+ this.ConversationMemory.Record({ Kind: "user", Text: text });
1308
2016
  this.requestResultResponse();
1309
2017
  }
2018
+ /**
2019
+ * The move has started, so the holds it waited on are spent: the utterances belong to the connection being left,
2020
+ * and the next connection's speech starts holds of its own.
2021
+ */
2022
+ onReconnecting(reason) {
2023
+ this.forgetUserUtterances();
2024
+ this.answerOwedAfterMove = false;
2025
+ super.onReconnecting(reason);
2026
+ }
2027
+ /**
2028
+ * Sends the input held during the move to the new connection, after the seed, and asks for one answer covering it
2029
+ * and an answer the move cut off (see {@link seedConversationAfterMove}). After `super`, so a result for a call
2030
+ * from before a reseed goes out as a late-result note.
2031
+ */
2032
+ onReconnected(usedNativeResumption) {
2033
+ super.onReconnected(usedNativeResumption);
2034
+ const answerOwed = this.answerOwedAfterMove;
2035
+ this.answerOwedAfterMove = false;
2036
+ if (answerOwed) {
2037
+ RealtimeDiagLog(`[${this.providerDebugLabel}] the move cut off an answer; asking the new connection for it`);
2038
+ }
2039
+ this.deliverHeldInput(answerOwed);
2040
+ }
2041
+ /**
2042
+ * Sends the tool results, then the typed text, held during a move, oldest first, and then ONE `response.create`
2043
+ * when any of them (or `answerOwed`) asks for a reply. One request answers every item, and it comes after the
2044
+ * last one: a reply requested per item would be cancelled by the next typed turn (text implies barge-in).
2045
+ */
2046
+ deliverHeldInput(answerOwed) {
2047
+ const results = this.toolResultsHeldDuringReconnect;
2048
+ const texts = this.textHeldDuringReconnect;
2049
+ this.toolResultsHeldDuringReconnect = [];
2050
+ this.textHeldDuringReconnect = [];
2051
+ this.deliveringHeldInput = true;
2052
+ this.responseOwedByHeldInput = false;
2053
+ try {
2054
+ for (const result of results) {
2055
+ super.SendToolResult(result.CallID, result.OutputJson);
2056
+ }
2057
+ for (const text of texts) {
2058
+ this.deliverUserText(text);
2059
+ }
2060
+ } finally {
2061
+ this.deliveringHeldInput = false;
2062
+ }
2063
+ const owed = answerOwed || this.responseOwedByHeldInput;
2064
+ this.responseOwedByHeldInput = false;
2065
+ if (owed) {
2066
+ this.requestResultResponse();
2067
+ }
2068
+ }
2069
+ /**
2070
+ * A planned move's attempt failed and the old transport can still carry the call ({@link isTransportUsable}): the
2071
+ * call goes on there until the next attempt. The state the move replaced is reported again, and the text and tool
2072
+ * results held for the move go out on it now instead of waiting for (or being dropped with) the cycle. `false` when
2073
+ * the old transport is gone too.
2074
+ */
2075
+ ResumeOnOldConnection() {
2076
+ if (!this.isTransportUsable() || this.currentState === "error" || this.currentState === "closed") {
2077
+ return false;
2078
+ }
2079
+ const restore = this.StateToRestoreOnOldConnection;
2080
+ if (restore) {
2081
+ this.setState(restore);
2082
+ }
2083
+ this.deliverHeldInput(false);
2084
+ return true;
2085
+ }
2086
+ /** The move failed and the call is over, so the held input has no connection to go to. */
2087
+ onReconnectFailed(error, code) {
2088
+ this.dropInputHeldDuringReconnect("the reconnect failed");
2089
+ super.onReconnectFailed(error, code);
2090
+ }
2091
+ /** Drops the text and tool results held for a move that will not complete, logging how many and why. */
2092
+ dropInputHeldDuringReconnect(why) {
2093
+ const texts = this.textHeldDuringReconnect.length;
2094
+ const results = this.toolResultsHeldDuringReconnect.length;
2095
+ this.textHeldDuringReconnect = [];
2096
+ this.toolResultsHeldDuringReconnect = [];
2097
+ if (texts === 0 && results === 0) {
2098
+ return;
2099
+ }
2100
+ RealtimeDiagLog(`[${this.providerDebugLabel}] dropping ${texts} typed turn(s) and ${results} tool result(s) held during a reconnect: ${why}`);
2101
+ }
1310
2102
  /**
1311
2103
  * @inheritdoc
1312
2104
  *
@@ -1343,7 +2135,8 @@ var OpenAIProtocolRealtimeClient = class extends BaseRealtimeClient {
1343
2135
  * NOTE: role must be 'system' — gpt-realtime (and the compatible endpoints) reject
1344
2136
  * 'developer' items ("Developer messages are only supported for quicksilver sessions").
1345
2137
  */
1346
- SendContextNote(text) {
2138
+ SendContextNote(text, options) {
2139
+ this.ConversationMemory.Record({ Kind: "note", Text: text, ...options });
1347
2140
  if (!this.canSendEvents()) {
1348
2141
  return;
1349
2142
  }
@@ -1352,6 +2145,73 @@ var OpenAIProtocolRealtimeClient = class extends BaseRealtimeClient {
1352
2145
  item: { type: "message", role: "system", content: [{ type: "input_text", text }] }
1353
2146
  });
1354
2147
  }
2148
+ /**
2149
+ * Resets the response bookkeeping for a connection that has just replaced the old one, and returns whether an
2150
+ * answer was in flight (or queued) on the old one. Every count and flag here describes the old connection: a
2151
+ * `response.create` it never confirmed would otherwise make the new connection's real `response.done` look stale
2152
+ * and leave {@link IsBusy} stuck.
2153
+ */
2154
+ resetResponseStateForNewConnection() {
2155
+ const answerWasInFlight = this.responseActive || this.pendingResultResponse;
2156
+ this.responseActive = false;
2157
+ this.confirmedResponseActive = false;
2158
+ this.pendingResultResponse = false;
2159
+ this.pendingLocalResponseCreates = 0;
2160
+ this.pendingNarrationKind = false;
2161
+ this.activeResponseKind = "normal";
2162
+ this.pendingAssistantText = "";
2163
+ return answerWasInFlight;
2164
+ }
2165
+ /**
2166
+ * Seeds the new connection after a move (when `sendsSeed`; a natively resumed one already has the history) and
2167
+ * notes whether the move cut off an answer the user is still owed: one was in flight on the old connection
2168
+ * (`answerWasInFlight`, from {@link resetResponseStateForNewConnection}) and the conversation ends with what it
2169
+ * answers (a user turn or a tool result), not counting the context notes after it. Neither a seeded nor a resumed
2170
+ * session replies by itself, so without this the question sits unanswered in every later seed. An answer that
2171
+ * completed is in memory as an assistant turn and is not asked for again.
2172
+ *
2173
+ * A seeded connection knows the conversation as the seed sent it. A resumed one knows it as the provider kept it,
2174
+ * which includes what the old connection heard while the attempt was opening, after `context.Seed` was built: so
2175
+ * then the memory as it is now decides.
2176
+ */
2177
+ seedConversationAfterMove(context, answerWasInFlight, sendsSeed) {
2178
+ if (sendsSeed) {
2179
+ this.seedConversationHistory(context.ConversationSeed);
2180
+ }
2181
+ const conversation = sendsSeed ? context.Seed : this.ConversationMemory.Seed();
2182
+ this.answerOwedAfterMove = answerWasInFlight && _OpenAIProtocolRealtimeClient.endsAwaitingAnswer(conversation);
2183
+ }
2184
+ /** Whether the conversation's last entry other than a context note is a user turn or a tool result. */
2185
+ static endsAwaitingAnswer(seed) {
2186
+ for (let i = seed.Entries.length - 1; i >= 0; i--) {
2187
+ const kind = seed.Entries[i].Kind;
2188
+ if (kind !== "note") {
2189
+ return kind === "user" || kind === "toolResult";
2190
+ }
2191
+ }
2192
+ return false;
2193
+ }
2194
+ /**
2195
+ * Seeds bounded conversation history turns into a freshly reconnected OpenAI-protocol session.
2196
+ */
2197
+ seedConversationHistory(seed) {
2198
+ if (!seed || seed.Entries.length === 0) {
2199
+ return;
2200
+ }
2201
+ const turns = RenderRealtimeMemorySeed(seed);
2202
+ for (const turn of turns) {
2203
+ const role = turn.Role === "model" ? "assistant" : "user";
2204
+ const contentType = role === "assistant" ? "output_text" : "input_text";
2205
+ this.sendEvent({
2206
+ type: "conversation.item.create",
2207
+ item: {
2208
+ type: "message",
2209
+ role,
2210
+ content: turn.Texts.map((text) => ({ type: contentType, text }))
2211
+ }
2212
+ });
2213
+ }
2214
+ }
1355
2215
  /**
1356
2216
  * Triggers ONE short spoken update with the given instructions. Marks the upcoming
1357
2217
  * response as `'narration'` (flag consumed by the next `response.created`) so its
@@ -1464,8 +2324,21 @@ ${direction}` }
1464
2324
  * would collide with an in-flight narration and be dropped, leaving the model silent when
1465
2325
  * delegated work comes back.
1466
2326
  */
1467
- SendToolResult(callID, outputJson) {
2327
+ doSendToolResult(callID, outputJson) {
1468
2328
  if (!this.canSendEvents()) {
2329
+ return false;
2330
+ }
2331
+ const name = this.resolveToolName(callID);
2332
+ if (this.callsFromBeforeReseed.delete(callID)) {
2333
+ this.sendEvent({
2334
+ type: "conversation.item.create",
2335
+ item: {
2336
+ type: "message",
2337
+ role: "user",
2338
+ content: [{ type: "input_text", text: RenderLateToolResultNote(name, outputJson) }]
2339
+ }
2340
+ });
2341
+ this.requestResultResponse();
1469
2342
  return;
1470
2343
  }
1471
2344
  this.sendEvent({
@@ -1488,6 +2361,71 @@ ${direction}` }
1488
2361
  get IsBusy() {
1489
2362
  return this.responseActive;
1490
2363
  }
2364
+ /**
2365
+ * @inheritdoc
2366
+ *
2367
+ * Adds the user's pending utterances: the controller's turn opens only on `response.created`, and the input meter
2368
+ * sees speech only at the instant it is read (not in a pause between words, nor after the commit).
2369
+ */
2370
+ isTurnActiveForReconnect() {
2371
+ return this.pendingUserUtterances.size > 0 || super.isTurnActiveForReconnect();
2372
+ }
2373
+ /** Starts (or restarts the max age of) the hold for one user utterance. */
2374
+ trackUserUtterance(itemId, committed) {
2375
+ const key = itemId ?? UNIDENTIFIED_UTTERANCE_KEY;
2376
+ const existing = this.pendingUserUtterances.get(key);
2377
+ if (existing) {
2378
+ clearTimeout(existing.Expiry);
2379
+ }
2380
+ const expiry = setTimeout(() => {
2381
+ 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`);
2382
+ this.releaseUserUtterances((_utterance, k) => k === key);
2383
+ }, PENDING_USER_UTTERANCE_MAX_AGE_MS);
2384
+ this.pendingUserUtterances.set(key, { Committed: committed || (existing?.Committed ?? false), Expiry: expiry });
2385
+ }
2386
+ /**
2387
+ * The provider committed the utterance's audio. Its `speech_started` may have carried no id (then that entry takes
2388
+ * this id), and a commit with no `speech_started` (a manual commit) is still audio only this connection holds.
2389
+ */
2390
+ markUserUtteranceCommitted(itemId) {
2391
+ if (itemId !== void 0 && !this.pendingUserUtterances.has(itemId)) {
2392
+ const unidentified = this.pendingUserUtterances.get(UNIDENTIFIED_UTTERANCE_KEY);
2393
+ if (unidentified) {
2394
+ clearTimeout(unidentified.Expiry);
2395
+ this.pendingUserUtterances.delete(UNIDENTIFIED_UTTERANCE_KEY);
2396
+ }
2397
+ }
2398
+ this.trackUserUtterance(itemId, true);
2399
+ }
2400
+ /**
2401
+ * The utterance's transcription settled, so the seed of a move carries it (or nothing will). Only a committed
2402
+ * utterance is released: Grok streams `.completed` frames while the user is still speaking. A frame with no id
2403
+ * settles every committed utterance.
2404
+ */
2405
+ releaseCommittedUserUtterance(itemId) {
2406
+ this.releaseUserUtterances((utterance, key) => utterance.Committed && (itemId === void 0 || key === itemId));
2407
+ }
2408
+ /** Releases the matching holds and, when none is left, lets a deferred soft-window move go ahead. */
2409
+ releaseUserUtterances(matches) {
2410
+ let released = false;
2411
+ for (const [key, utterance] of this.pendingUserUtterances) {
2412
+ if (matches(utterance, key)) {
2413
+ clearTimeout(utterance.Expiry);
2414
+ this.pendingUserUtterances.delete(key);
2415
+ released = true;
2416
+ }
2417
+ }
2418
+ if (released && this.pendingUserUtterances.size === 0) {
2419
+ this.reconnectController.NotifyIdleStateChanged();
2420
+ }
2421
+ }
2422
+ /** Drops every hold without re-checking a move (the connection they belong to is gone). */
2423
+ forgetUserUtterances() {
2424
+ for (const utterance of this.pendingUserUtterances.values()) {
2425
+ clearTimeout(utterance.Expiry);
2426
+ }
2427
+ this.pendingUserUtterances.clear();
2428
+ }
1491
2429
  // ── Inbound event translation (the shared dispatcher) ──────────────────────
1492
2430
  /**
1493
2431
  * Parses one raw inbound payload and dispatches it. Non-JSON frames and non-object JSON
@@ -1513,6 +2451,20 @@ ${direction}` }
1513
2451
  case "session.created":
1514
2452
  this.onSessionCreatedFrame();
1515
2453
  break;
2454
+ case "conversation.created": {
2455
+ const conv = event.conversation;
2456
+ if (typeof conv?.id === "string" && conv.id.trim().length > 0) {
2457
+ this.RecordResumptionHandle(conv.id);
2458
+ }
2459
+ break;
2460
+ }
2461
+ case "session.going_away":
2462
+ case "go_away": {
2463
+ const rawMs = event.time_left_ms;
2464
+ const timeLeftMs = typeof rawMs === "number" && Number.isFinite(rawMs) ? rawMs : void 0;
2465
+ this.NotifyConnectionEnding(timeLeftMs);
2466
+ break;
2467
+ }
1516
2468
  case "response.output_audio_transcript.delta":
1517
2469
  case "response.audio_transcript.delta":
1518
2470
  this.onAssistantDelta(event.delta);
@@ -1528,18 +2480,42 @@ ${direction}` }
1528
2480
  case "conversation.item.input_audio_transcription.completed": {
1529
2481
  const completed = event;
1530
2482
  this.onUserTranscriptFrame(completed.transcript, completed.item_id);
2483
+ this.releaseCommittedUserUtterance(completed.item_id);
1531
2484
  break;
1532
2485
  }
2486
+ case "input_audio_buffer.committed": {
2487
+ const itemId = event.item_id;
2488
+ if (typeof itemId === "string" && itemId.trim().length > 0) {
2489
+ this.ConversationMemory.ReserveUserTurn(itemId);
2490
+ }
2491
+ this.markUserUtteranceCommitted(itemId);
2492
+ break;
2493
+ }
2494
+ case "conversation.item.input_audio_transcription.failed": {
2495
+ const itemId = event.item_id;
2496
+ RealtimeDiagLog(`[${this.providerDebugLabel}] input transcription failed for item ${itemId ?? "(no id)"}; the turn is left out of conversation memory`);
2497
+ if (typeof itemId === "string") {
2498
+ this.ConversationMemory.ReleaseUserTurn(itemId);
2499
+ }
2500
+ this.releaseCommittedUserUtterance(itemId);
2501
+ break;
2502
+ }
2503
+ case "input_audio_buffer.cleared":
2504
+ this.releaseUserUtterances((utterance) => !utterance.Committed);
2505
+ break;
1533
2506
  case "response.function_call_arguments.done":
1534
2507
  this.onToolCallFrame(event);
1535
2508
  break;
1536
2509
  case "input_audio_buffer.speech_started":
1537
2510
  this.emitUserSpeechStart(event.item_id);
2511
+ this.trackUserUtterance(event.item_id, false);
1538
2512
  this.onSpeechStartedFrame();
1539
2513
  break;
1540
2514
  case "response.created": {
1541
2515
  this.responseActive = true;
1542
2516
  this.confirmedResponseActive = true;
2517
+ this.reconnectController.TurnStarted();
2518
+ this.releaseUserUtterances((utterance) => utterance.Committed);
1543
2519
  this.onResponseStarted();
1544
2520
  const wasLocalCreate = this.pendingLocalResponseCreates > 0;
1545
2521
  if (wasLocalCreate) {
@@ -1570,6 +2546,8 @@ ${direction}` }
1570
2546
  this.flushPendingResultResponse();
1571
2547
  if (this.currentState === "speaking") {
1572
2548
  this.setState("listening");
2549
+ } else if (!this.responseActive) {
2550
+ this.reconnectController.TurnEnded();
1573
2551
  }
1574
2552
  break;
1575
2553
  case "error":
@@ -1645,16 +2623,22 @@ ${direction}` }
1645
2623
  /**
1646
2624
  * Emits the completed response's usage to the host as a DELTA (the `response.done` usage
1647
2625
  * payload covers exactly this response, so it is already incremental — the `OnUsage`
1648
- * contract's preferred shape). Frames without a usage payload emit nothing.
2626
+ * contract's preferred shape). Frames without a usage payload emit nothing. The per-modality
2627
+ * split (`input_token_details` / `output_token_details`) rides along when the provider sends it,
2628
+ * so pricing can tell audio tokens from text tokens.
1649
2629
  */
1650
2630
  emitResponseUsage(event) {
1651
2631
  const usage = ResolveResponseDoneUsage(event);
1652
2632
  if (!usage) {
1653
2633
  return;
1654
2634
  }
2635
+ const inputDetails = MapRealtimeUsageModalityDetail(usage["input_token_details"]);
2636
+ const outputDetails = MapRealtimeUsageModalityDetail(usage["output_token_details"]);
1655
2637
  this.emitUsage({
1656
2638
  InputTokens: typeof usage.input_tokens === "number" ? usage.input_tokens : void 0,
1657
2639
  OutputTokens: typeof usage.output_tokens === "number" ? usage.output_tokens : void 0,
2640
+ ...inputDetails ? { InputTokenDetails: inputDetails } : {},
2641
+ ...outputDetails ? { OutputTokenDetails: outputDetails } : {},
1658
2642
  Raw: usage
1659
2643
  });
1660
2644
  }
@@ -1699,6 +2683,10 @@ ${direction}` }
1699
2683
  if (!this.canSendEvents()) {
1700
2684
  return;
1701
2685
  }
2686
+ if (this.deliveringHeldInput) {
2687
+ this.responseOwedByHeldInput = true;
2688
+ return;
2689
+ }
1702
2690
  if (this.responseActive) {
1703
2691
  this.pendingResultResponse = true;
1704
2692
  return;
@@ -1722,6 +2710,9 @@ ${direction}` }
1722
2710
  }
1723
2711
  /** Resets the per-session response state machine (used on Disconnect). */
1724
2712
  resetResponseState() {
2713
+ this.dropInputHeldDuringReconnect("the call ended");
2714
+ this.forgetUserUtterances();
2715
+ this.answerOwedAfterMove = false;
1725
2716
  this.pendingAssistantText = "";
1726
2717
  this.responseActive = false;
1727
2718
  this.confirmedResponseActive = false;
@@ -1733,9 +2724,49 @@ ${direction}` }
1733
2724
  // ── Shared helpers ─────────────────────────────────────────────────────────
1734
2725
  /** Updates the client's own state view and emits the change to the host. */
1735
2726
  setState(state) {
2727
+ if (state === "listening" || state === "speaking") {
2728
+ this.callWentLive = true;
2729
+ } else if (state === "connecting" || state === "closed" || state === "error") {
2730
+ this.callWentLive = false;
2731
+ }
1736
2732
  this.currentState = state;
1737
2733
  this.emitStateChange(state);
1738
2734
  }
2735
+ /**
2736
+ * Whether an unexpected loss of a live call's transport is handed to the shared `connection-lost` reconnect. On by
2737
+ * default for every driver that can reconnect mid-call; a driver whose transport closes benignly and whose host
2738
+ * reads that close as the end of the session overrides it to `false`.
2739
+ */
2740
+ get RecoversLostTransport() {
2741
+ return this.SupportsMidCallReconnect;
2742
+ }
2743
+ /**
2744
+ * Hands an unexpected loss of the live call's transport (a close or error the consumer did not ask for) to the
2745
+ * shared reconnect controller, which retries within its recovery window and reports `reconnect-failed` when the
2746
+ * window closes. Returns `false` when there is no live call to save, so the caller keeps its terminal handling: the
2747
+ * connect has not finished (Connect reports that failure itself), the call already ended, or the driver opts out.
2748
+ *
2749
+ * A loss while a reconnect cycle runs is the loss of the transport the cycle may go back to after a failed attempt
2750
+ * (the callers' identity checks drop events of a transport the cycle opened or already let go of). It goes to the
2751
+ * cycle, even on a driver that opts out of starting one, and returns `true`: the cycle then never returns the call
2752
+ * to a dead transport, and goes on as a lost connection's.
2753
+ *
2754
+ * Live means the call went live and has not ended ({@link callWentLive}), not a speech state: during a tool run the
2755
+ * state is `'connected'` (see {@link onToolCallFrame}), and a loss then is as recoverable as one mid-sentence.
2756
+ */
2757
+ recoverLostTransport(detail) {
2758
+ if (this.IsReconnectCycleActive) {
2759
+ RealtimeDiagLog(`[${this.providerDebugLabel}] transport lost during a reconnect (${detail}); the reconnect takes it`);
2760
+ void this.TriggerReconnect("connection-lost");
2761
+ return true;
2762
+ }
2763
+ if (!this.callWentLive || !this.RecoversLostTransport) {
2764
+ return false;
2765
+ }
2766
+ RealtimeDiagLog(`[${this.providerDebugLabel}] transport lost during a live call (${detail}); reconnecting`);
2767
+ void this.TriggerReconnect("connection-lost");
2768
+ return true;
2769
+ }
1739
2770
  /** Logs (diagnostic hook) and delivers one client event when the transport is open. */
1740
2771
  sendEvent(event) {
1741
2772
  if (!this.canSendEvents()) {
@@ -1752,6 +2783,7 @@ var OpenAIProtocolWebSocketRealtimeClient = class extends OpenAIProtocolRealtime
1752
2783
  this.playback = null;
1753
2784
  this.micCapture = null;
1754
2785
  this.sessionObject = {};
2786
+ this.activeConfig = null;
1755
2787
  this.closedByConsumer = false;
1756
2788
  this.socketOpen = false;
1757
2789
  this.sessionCreatedResolver = null;
@@ -1789,6 +2821,8 @@ var OpenAIProtocolWebSocketRealtimeClient = class extends OpenAIProtocolRealtime
1789
2821
  */
1790
2822
  async Connect(config, micStream) {
1791
2823
  this.AssertTransportSupported(config);
2824
+ this.ApplySessionConfigTiming(config);
2825
+ this.activeConfig = config;
1792
2826
  this.sessionObject = this.resolveSessionObject(config);
1793
2827
  this.micStream = micStream;
1794
2828
  this.closedByConsumer = false;
@@ -1867,6 +2901,7 @@ var OpenAIProtocolWebSocketRealtimeClient = class extends OpenAIProtocolRealtime
1867
2901
  this.micCapture = await this.createMicCapture(micStream, sampleRate, (base64Pcm16) => this.sendMicChunk(base64Pcm16));
1868
2902
  this.attachOutputAudioMeter(this.playback?.CreateMeter?.() ?? null);
1869
2903
  this.attachInputAudioMeter(RealtimeAudioMeter.ForMicStream(micStream));
2904
+ this.ArmConnectionDurationTimer();
1870
2905
  this.setState("listening");
1871
2906
  }
1872
2907
  /** Rebinds the PCM capture and the input meter to the stream's current track (obligation #10); the socket stays open. */
@@ -1885,6 +2920,7 @@ var OpenAIProtocolWebSocketRealtimeClient = class extends OpenAIProtocolRealtime
1885
2920
  */
1886
2921
  async Disconnect() {
1887
2922
  this.closedByConsumer = true;
2923
+ this.DisposeReconnectTimers();
1888
2924
  this.failPendingConnect?.(new Error(`${this.providerDebugLabel} disconnected during connect`));
1889
2925
  this.failPendingConnect = null;
1890
2926
  this.sessionCreatedResolver = null;
@@ -1905,11 +2941,142 @@ var OpenAIProtocolWebSocketRealtimeClient = class extends OpenAIProtocolRealtime
1905
2941
  this.socket = null;
1906
2942
  }
1907
2943
  this.sessionObject = {};
2944
+ this.activeConfig = null;
1908
2945
  this.resetResponseState();
1909
2946
  if (this.currentState !== "error") {
1910
2947
  this.setState("closed");
1911
2948
  }
1912
2949
  }
2950
+ /**
2951
+ * Performs an in-place WebSocket swap on duration expiry or provider GoAway while keeping
2952
+ * the existing `micCapture`, `playback`, and audio meters intact.
2953
+ */
2954
+ async Reconnect(context) {
2955
+ if (!this.activeConfig) {
2956
+ throw new Error(`${this.providerDebugLabel}: cannot reconnect before Connect`);
2957
+ }
2958
+ if (context.Abandoned) {
2959
+ throw new Error(`${this.providerDebugLabel}: reconnect attempt abandoned`);
2960
+ }
2961
+ const refreshedConfig = {
2962
+ ...this.activeConfig,
2963
+ EphemeralToken: context.Credential.EphemeralToken || this.activeConfig.EphemeralToken,
2964
+ ExpiresAt: context.Credential.ExpiresAt || this.activeConfig.ExpiresAt,
2965
+ ...context.Credential.RelayUrl !== void 0 ? { RelayUrl: context.Credential.RelayUrl } : {},
2966
+ ...context.Credential.SessionConfig !== void 0 ? { SessionConfig: context.Credential.SessionConfig } : {},
2967
+ ...context.Credential.TrustNativeResumption !== void 0 ? { TrustNativeResumption: context.Credential.TrustNativeResumption } : {}
2968
+ };
2969
+ this.activeConfig = refreshedConfig;
2970
+ this.sessionObject = this.resolveSessionObject(refreshedConfig);
2971
+ const prevSocket = this.socket;
2972
+ let openSocket = null;
2973
+ const opened = new Promise((resolve) => {
2974
+ openSocket = resolve;
2975
+ });
2976
+ const created = this.waitsForSessionCreated ? new Promise((resolve) => {
2977
+ this.sessionCreatedResolver = resolve;
2978
+ }) : null;
2979
+ let failReconnect = null;
2980
+ const failure = new Promise((_, reject) => {
2981
+ failReconnect = reject;
2982
+ });
2983
+ failure.catch(() => void 0);
2984
+ const nextSocket = this.openProviderSocket(refreshedConfig, context.UseNativeResumption ? context.ResumptionHandle : null);
2985
+ let nextSocketOpen = false;
2986
+ const onAbort = () => {
2987
+ failReconnect?.(new Error(`${this.providerDebugLabel}: reconnect attempt aborted`));
2988
+ try {
2989
+ nextSocket.close();
2990
+ } catch {
2991
+ }
2992
+ };
2993
+ if (context.Signal.aborted) {
2994
+ onAbort();
2995
+ throw new Error(`${this.providerDebugLabel}: reconnect attempt aborted`);
2996
+ }
2997
+ context.Signal.addEventListener("abort", onAbort, { once: true });
2998
+ nextSocket.onopen = () => {
2999
+ nextSocketOpen = true;
3000
+ openSocket?.();
3001
+ };
3002
+ nextSocket.onmessage = (data) => {
3003
+ if (this.socket === nextSocket) {
3004
+ this.handleProtocolMessage(data);
3005
+ return;
3006
+ }
3007
+ try {
3008
+ const event = JSON.parse(data);
3009
+ if (event && typeof event === "object" && event.type === "session.created") {
3010
+ this.onSessionCreatedFrame();
3011
+ } else if (event && typeof event === "object" && event.type === "conversation.created") {
3012
+ const conv = event.conversation;
3013
+ if (typeof conv?.id === "string" && conv.id.trim().length > 0) {
3014
+ this.RecordResumptionHandle(conv.id);
3015
+ }
3016
+ }
3017
+ } catch {
3018
+ }
3019
+ };
3020
+ nextSocket.onerror = (message) => {
3021
+ nextSocketOpen = false;
3022
+ failReconnect?.(new Error(message));
3023
+ if (this.socket === nextSocket) {
3024
+ this.socketOpen = false;
3025
+ this.handleSocketError(message);
3026
+ }
3027
+ };
3028
+ nextSocket.onclose = () => {
3029
+ nextSocketOpen = false;
3030
+ failReconnect?.(new Error(`${this.providerDebugLabel} socket closed during reconnect`));
3031
+ if (this.socket === nextSocket) {
3032
+ this.socketOpen = false;
3033
+ this.handleSocketClose();
3034
+ }
3035
+ };
3036
+ try {
3037
+ await Promise.race([opened, failure]);
3038
+ if (context.Abandoned) {
3039
+ throw new Error(`${this.providerDebugLabel}: reconnect attempt abandoned after open`);
3040
+ }
3041
+ if (created) {
3042
+ await Promise.race([created, failure]);
3043
+ }
3044
+ if (context.Abandoned) {
3045
+ throw new Error(`${this.providerDebugLabel}: reconnect attempt abandoned after session.created`);
3046
+ }
3047
+ } catch (err) {
3048
+ nextSocket.onopen = null;
3049
+ nextSocket.onmessage = null;
3050
+ nextSocket.onerror = null;
3051
+ nextSocket.onclose = null;
3052
+ try {
3053
+ nextSocket.close();
3054
+ } catch {
3055
+ }
3056
+ throw err;
3057
+ } finally {
3058
+ context.Signal.removeEventListener("abort", onAbort);
3059
+ failReconnect = null;
3060
+ this.sessionCreatedResolver = null;
3061
+ }
3062
+ if (prevSocket) {
3063
+ prevSocket.onopen = null;
3064
+ prevSocket.onmessage = null;
3065
+ prevSocket.onerror = null;
3066
+ prevSocket.onclose = null;
3067
+ }
3068
+ this.socket = nextSocket;
3069
+ this.socketOpen = nextSocketOpen;
3070
+ try {
3071
+ prevSocket?.close();
3072
+ } catch {
3073
+ }
3074
+ const answerWasInFlight = this.resetResponseStateForNewConnection();
3075
+ this.applySessionConfig();
3076
+ const resumedNatively = context.UseNativeResumption && Boolean(context.ResumptionHandle);
3077
+ this.seedConversationAfterMove(context, answerWasInFlight, !resumedNatively);
3078
+ this.setState("listening");
3079
+ }
1913
3080
  // ── Brain seam implementations ─────────────────────────────────────────────
1914
3081
  /** @inheritdoc — requires an OPEN socket (a CONNECTING raw WebSocket throws on send). */
1915
3082
  canSendEvents() {
@@ -1989,24 +3156,36 @@ var OpenAIProtocolWebSocketRealtimeClient = class extends OpenAIProtocolRealtime
1989
3156
  get unexpectedCloseMessage() {
1990
3157
  return `${this.providerDebugLabel} connection closed unexpectedly`;
1991
3158
  }
1992
- /** Surfaces a fatal socket error and marks the session unusable (obligation #6). */
3159
+ /**
3160
+ * A socket error. During a live call it starts the `connection-lost` reconnect, and during a running reconnect it
3161
+ * tells that reconnect the socket is gone; before the call is live it is fatal and marks the session unusable
3162
+ * (obligation #6).
3163
+ */
1993
3164
  handleSocketError(message) {
1994
3165
  if (this.currentState === "error" || this.currentState === "closed") {
1995
3166
  return;
1996
3167
  }
3168
+ if (this.recoverLostTransport(`socket error: ${message}`)) {
3169
+ return;
3170
+ }
1997
3171
  this.emitError({ Message: this.formatTransportError(message), Fatal: true });
1998
3172
  this.setState("error");
1999
3173
  }
2000
3174
  /**
2001
- * A socket close the CONSUMER didn't ask for. Default: FATAL — providers hard-close at
2002
- * token expiry and when they end the session themselves, so an unexpected close is how
2003
- * credential / session death reaches the host (obligation #6). Providers with benign
2004
- * close semantics (a self-hosted proxy hop) override.
3175
+ * A socket close the CONSUMER didn't ask for. During a live call it is a lost connection
3176
+ * (a network cut, a dropped proxy hop), so it goes to the shared `connection-lost`
3177
+ * reconnect, or to the reconnect already running; a session the provider really ended
3178
+ * surfaces as `reconnect-failed` once the recovery window closes. Before the call is live
3179
+ * it is FATAL — that is how a rejected credential or session reaches the host (obligation
3180
+ * #6). Providers with benign close semantics (a self-hosted proxy hop) override.
2005
3181
  */
2006
3182
  handleSocketClose() {
2007
3183
  if (this.closedByConsumer || this.currentState === "error" || this.currentState === "closed") {
2008
3184
  return;
2009
3185
  }
3186
+ if (this.recoverLostTransport("socket closed")) {
3187
+ return;
3188
+ }
2010
3189
  this.emitError({ Message: this.unexpectedCloseMessage, Fatal: true });
2011
3190
  this.setState("error");
2012
3191
  }
@@ -2300,7 +3479,12 @@ var VideoSourceArbiter = class _VideoSourceArbiter {
2300
3479
  }
2301
3480
  this.reconcile(true);
2302
3481
  if (notify) {
2303
- this.sendNote(enabled ? this.formatEnabledNote(source.Label) : this.formatDisabledNote(source.Label));
3482
+ const activeLabels = this.computeActive().map((id) => this.sources.get(id)?.Label ?? id);
3483
+ const activeSnapshot = activeLabels.length > 0 ? VideoSourceSeenNote(activeLabels) : void 0;
3484
+ this.sendNote(enabled ? this.formatEnabledNote(source.Label) : this.formatDisabledNote(source.Label), {
3485
+ StateKey: "video-source",
3486
+ ...activeSnapshot ? { MemoryText: activeSnapshot } : {}
3487
+ });
2304
3488
  }
2305
3489
  this.emitChange();
2306
3490
  return true;
@@ -2444,7 +3628,7 @@ var VideoSourceArbiter = class _VideoSourceArbiter {
2444
3628
  return;
2445
3629
  }
2446
3630
  const labels = active.map((id) => this.sources.get(id)?.Label ?? id);
2447
- this.sendNote(this.options.FormatSwitchNote ? this.options.FormatSwitchNote(labels) : VideoSourceSeenNote(labels));
3631
+ this.sendNote(this.options.FormatSwitchNote ? this.options.FormatSwitchNote(labels) : VideoSourceSeenNote(labels), { StateKey: "video-source" });
2448
3632
  }
2449
3633
  // ── plumbing ────────────────────────────────────────────────────────────
2450
3634
  formatDisabledNote(label) {
@@ -2464,13 +3648,13 @@ var VideoSourceArbiter = class _VideoSourceArbiter {
2464
3648
  return false;
2465
3649
  }
2466
3650
  }
2467
- sendNote(note) {
3651
+ sendNote(note, options) {
2468
3652
  const sink = this.sink;
2469
3653
  if (!note || !sink) {
2470
3654
  return;
2471
3655
  }
2472
3656
  try {
2473
- sink.SendContextNote(note);
3657
+ sink.SendContextNote(note, options);
2474
3658
  } catch (error) {
2475
3659
  this.reportError("sending a source note", error);
2476
3660
  }
@@ -2995,6 +4179,10 @@ var IMAGE_FRAME_DECODER = {
2995
4179
  };
2996
4180
 
2997
4181
  // ../../AI/RealtimeClient/dist/media/decoders/mseFmp4Decoder.js
4182
+ var DEFAULT_FMP4_PROBE_TYPES = [
4183
+ 'video/mp4; codecs="avc1.42c01f, mp4a.40.2"',
4184
+ 'video/mp4; codecs="avc1.42c01f"'
4185
+ ];
2998
4186
  var TRIM_STEP_SECONDS = 5;
2999
4187
  var QUOTA_BACK_BUFFER_SECONDS = 2;
3000
4188
  var MAX_PENDING_PIECES = 600;
@@ -3014,10 +4202,23 @@ function mseTypeOf(init) {
3014
4202
  }
3015
4203
  return `video/mp4; codecs="${tracks.map((track) => track.Codec).join(", ")}"`;
3016
4204
  }
4205
+ function resolvePlayableMseType(mimeType) {
4206
+ const ms = mediaSourceClass();
4207
+ if (!ms) {
4208
+ return null;
4209
+ }
4210
+ if (ms.Class.isTypeSupported(mimeType)) {
4211
+ return mimeType;
4212
+ }
4213
+ if (MimeEssence(mimeType) === "video/mp4" && !MimeCodec(mimeType)) {
4214
+ return DEFAULT_FMP4_PROBE_TYPES.find((candidate) => ms.Class.isTypeSupported(candidate)) ?? null;
4215
+ }
4216
+ return null;
4217
+ }
3017
4218
  var MseFmp4Decoder = class {
3018
4219
  /** Whether this browser can play `mimeType` through MSE. */
3019
4220
  static CanPlay(mimeType) {
3020
- return mediaSourceClass()?.Class.isTypeSupported(mimeType) ?? false;
4221
+ return resolvePlayableMseType(mimeType) !== null;
3021
4222
  }
3022
4223
  /** @param context The player this decoder plays for. */
3023
4224
  constructor(context) {
@@ -3126,7 +4327,7 @@ var MseFmp4Decoder = class {
3126
4327
  }
3127
4328
  this.detach();
3128
4329
  const mse = mediaSourceClass();
3129
- if (!mse || !mse.Class.isTypeSupported(this.mimeType)) {
4330
+ if (!mse || !resolvePlayableMseType(this.mimeType)) {
3130
4331
  this.context.Report("unsupported", `This browser cannot play ${this.mimeType} through Media Source Extensions.`);
3131
4332
  return;
3132
4333
  }
@@ -3195,10 +4396,13 @@ var MseFmp4Decoder = class {
3195
4396
  this.handleAppendError(err);
3196
4397
  }
3197
4398
  }
3198
- /** The type for a source buffer that takes `init`: the init's own codecs when this browser plays them, else the player's type. */
4399
+ /** The type for a source buffer that takes `init`: the init's own codecs when this browser plays them, else the player's resolved MSE type. */
3199
4400
  typeFor(init) {
3200
4401
  const fromInit = init ? mseTypeOf(init) : null;
3201
- return fromInit && mediaSourceClass()?.Class.isTypeSupported(fromInit) ? fromInit : this.mimeType;
4402
+ if (fromInit && mediaSourceClass()?.Class.isTypeSupported(fromInit)) {
4403
+ return fromInit;
4404
+ }
4405
+ return resolvePlayableMseType(this.mimeType) ?? this.mimeType;
3202
4406
  }
3203
4407
  /**
3204
4408
  * Switches the source buffer to an init segment's codecs before the init is appended, when they differ from the
@@ -3815,6 +5019,7 @@ var __decorate = function(decorators, target, key, desc) {
3815
5019
  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
5020
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3817
5021
  };
5022
+ var OpenAIRealtimeClient_1;
3818
5023
  var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRealtimeClient {
3819
5024
  constructor() {
3820
5025
  super(...arguments);
@@ -3824,6 +5029,16 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
3824
5029
  this.remoteAudioEl = null;
3825
5030
  this.sessionConfig = null;
3826
5031
  this.audioPlaying = false;
5032
+ this.disconnectedGraceTimer = null;
5033
+ }
5034
+ static {
5035
+ OpenAIRealtimeClient_1 = this;
5036
+ }
5037
+ static {
5038
+ this.PEER_DISCONNECTED_GRACE_MS = 5e3;
5039
+ }
5040
+ get DefaultCallDurationSeconds() {
5041
+ return 3600;
3827
5042
  }
3828
5043
  // ── BaseRealtimeClient: connection lifecycle ───────────────────────────────
3829
5044
  /**
@@ -3834,11 +5049,13 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
3834
5049
  */
3835
5050
  async Connect(config, micStream) {
3836
5051
  this.AssertTransportSupported(config);
5052
+ this.ApplySessionConfigTiming(config);
3837
5053
  this.sessionConfig = config.SessionConfig;
3838
5054
  this.micStream = micStream;
3839
5055
  this.setState("connecting");
3840
5056
  const pc = this.createPeerConnection();
3841
5057
  this.peerConnection = pc;
5058
+ pc.onconnectionstatechange = () => this.handlePeerConnectionState(pc);
3842
5059
  this.attachMicrophone(pc, micStream);
3843
5060
  this.attachRemoteAudio(pc);
3844
5061
  this.adoptDataChannel(pc.createDataChannel("oai-events"));
@@ -3867,6 +5084,8 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
3867
5084
  * response state machine, and emits a final `'closed'` (unless already `'error'`).
3868
5085
  */
3869
5086
  async Disconnect() {
5087
+ this.DisposeReconnectTimers();
5088
+ this.clearDisconnectedGrace();
3870
5089
  this.closeAudioMeters();
3871
5090
  this.micStream?.getTracks().forEach((t) => t.stop());
3872
5091
  this.micStream = null;
@@ -3879,6 +5098,7 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
3879
5098
  this.dataChannel = null;
3880
5099
  }
3881
5100
  if (this.peerConnection) {
5101
+ this.peerConnection.onconnectionstatechange = null;
3882
5102
  try {
3883
5103
  this.peerConnection.close();
3884
5104
  } catch {
@@ -3898,11 +5118,162 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
3898
5118
  this.setState("closed");
3899
5119
  }
3900
5120
  }
5121
+ /**
5122
+ * Performs an in-place WebRTC peer-connection and data-channel swap on duration expiry
5123
+ * while preserving the existing `micStream` and hidden `<audio>` sink.
5124
+ */
5125
+ async Reconnect(context) {
5126
+ if (!this.micStream) {
5127
+ throw new Error("OpenAIRealtimeClient: cannot reconnect without an active microphone stream");
5128
+ }
5129
+ if (context.Abandoned) {
5130
+ throw new Error("OpenAIRealtimeClient: reconnect attempt abandoned");
5131
+ }
5132
+ if (context.Credential.SessionConfig !== void 0) {
5133
+ this.sessionConfig = context.Credential.SessionConfig;
5134
+ }
5135
+ const prevPc = this.peerConnection;
5136
+ const prevDc = this.dataChannel;
5137
+ const nextPc = this.createPeerConnection();
5138
+ const nextSenders = this.micStream.getAudioTracks().map((track) => nextPc.addTrack(track, this.micStream));
5139
+ if (!this.remoteAudioEl) {
5140
+ this.remoteAudioEl = this.createAudioSink();
5141
+ }
5142
+ let pendingRemoteStream = null;
5143
+ nextPc.ontrack = (e) => {
5144
+ if (context.Abandoned || !e.streams[0]) {
5145
+ return;
5146
+ }
5147
+ if (this.peerConnection === nextPc && this.remoteAudioEl) {
5148
+ this.remoteAudioEl.srcObject = e.streams[0];
5149
+ this.publishRemoteMediaStream(e.streams[0]);
5150
+ this.attachOutputAudioMeter(RealtimeAudioMeter.ForStream(e.streams[0]));
5151
+ } else {
5152
+ pendingRemoteStream = e.streams[0];
5153
+ }
5154
+ };
5155
+ const nextDc = nextPc.createDataChannel("oai-events");
5156
+ let openDc = null;
5157
+ let failDc = null;
5158
+ const dcOpened = new Promise((resolve, reject) => {
5159
+ openDc = resolve;
5160
+ failDc = reject;
5161
+ });
5162
+ dcOpened.catch(() => void 0);
5163
+ const onAbort = () => {
5164
+ failDc?.(new Error("OpenAIRealtimeClient: reconnect attempt aborted"));
5165
+ try {
5166
+ nextDc.close();
5167
+ } catch {
5168
+ }
5169
+ try {
5170
+ nextPc.close();
5171
+ } catch {
5172
+ }
5173
+ };
5174
+ if (context.Signal.aborted) {
5175
+ onAbort();
5176
+ throw new Error("OpenAIRealtimeClient: reconnect attempt aborted");
5177
+ }
5178
+ context.Signal.addEventListener("abort", onAbort, { once: true });
5179
+ nextDc.onopen = () => {
5180
+ openDc?.();
5181
+ };
5182
+ nextDc.onmessage = (e) => {
5183
+ if (this.dataChannel === nextDc) {
5184
+ this.handleProtocolMessage(String(e.data));
5185
+ }
5186
+ };
5187
+ nextDc.onerror = (e) => {
5188
+ failDc?.(new Error(`Data channel error: ${String(e)}`));
5189
+ this.handleChannelError(nextDc, e);
5190
+ };
5191
+ nextDc.onclose = () => {
5192
+ failDc?.(new Error("OpenAI data channel closed during reconnect"));
5193
+ this.handleChannelClose(nextDc);
5194
+ };
5195
+ nextPc.onconnectionstatechange = () => {
5196
+ if (nextPc.connectionState === "failed") {
5197
+ failDc?.(new Error("OpenAI peer connection failed during reconnect"));
5198
+ }
5199
+ this.handlePeerConnectionState(nextPc);
5200
+ };
5201
+ try {
5202
+ await this.performSdpHandshake(nextPc, context.Credential.EphemeralToken);
5203
+ if (nextDc.readyState !== "open") {
5204
+ await dcOpened;
5205
+ }
5206
+ if (context.Abandoned) {
5207
+ throw new Error("OpenAIRealtimeClient: reconnect attempt abandoned after open");
5208
+ }
5209
+ } catch (err) {
5210
+ nextDc.onopen = null;
5211
+ nextDc.onmessage = null;
5212
+ nextDc.onerror = null;
5213
+ nextDc.onclose = null;
5214
+ nextPc.ontrack = null;
5215
+ nextPc.onconnectionstatechange = null;
5216
+ try {
5217
+ nextDc.close();
5218
+ } catch {
5219
+ }
5220
+ try {
5221
+ nextPc.close();
5222
+ } catch {
5223
+ }
5224
+ throw err;
5225
+ } finally {
5226
+ context.Signal.removeEventListener("abort", onAbort);
5227
+ }
5228
+ if (prevDc) {
5229
+ prevDc.onopen = null;
5230
+ prevDc.onmessage = null;
5231
+ prevDc.onerror = null;
5232
+ prevDc.onclose = null;
5233
+ }
5234
+ if (prevPc) {
5235
+ prevPc.ontrack = null;
5236
+ prevPc.onconnectionstatechange = null;
5237
+ }
5238
+ this.clearDisconnectedGrace();
5239
+ this.peerConnection = nextPc;
5240
+ this.dataChannel = nextDc;
5241
+ this.micSenders = nextSenders;
5242
+ if (pendingRemoteStream && this.remoteAudioEl) {
5243
+ this.remoteAudioEl.srcObject = pendingRemoteStream;
5244
+ this.publishRemoteMediaStream(pendingRemoteStream);
5245
+ this.attachOutputAudioMeter(RealtimeAudioMeter.ForStream(pendingRemoteStream));
5246
+ pendingRemoteStream = null;
5247
+ }
5248
+ const answerWasInFlight = this.resetResponseStateForNewConnection();
5249
+ this.audioPlaying = false;
5250
+ try {
5251
+ prevDc?.close();
5252
+ } catch {
5253
+ }
5254
+ try {
5255
+ prevPc?.close();
5256
+ } catch {
5257
+ }
5258
+ this.applySessionConfig(nextDc);
5259
+ this.seedConversationAfterMove(context, answerWasInFlight, true);
5260
+ this.setState("listening");
5261
+ }
3901
5262
  // ── Brain seam implementations (WebRTC transport) ──────────────────────────
3902
5263
  /** @inheritdoc — events flow over the `'oai-events'` data channel once it is open. */
3903
5264
  canSendEvents() {
3904
5265
  return this.dataChannel !== null && this.dataChannel.readyState === "open";
3905
5266
  }
5267
+ /**
5268
+ * @inheritdoc
5269
+ *
5270
+ * Also a peer connection that has not lost its network path: the data channel can read `'open'` long after the
5271
+ * path is gone (SCTP keeps waiting), so input sent into it then is lost.
5272
+ */
5273
+ isTransportUsable() {
5274
+ const state = this.peerConnection?.connectionState;
5275
+ return super.isTransportUsable() && state !== "disconnected" && state !== "failed" && state !== "closed";
5276
+ }
3906
5277
  /** @inheritdoc */
3907
5278
  sendProtocolEvent(event) {
3908
5279
  this.dataChannel?.send(JSON.stringify(event));
@@ -3993,29 +5364,104 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
3993
5364
  };
3994
5365
  }
3995
5366
  /**
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.
5367
+ * Adopts + wires the events data channel: applies the session config and reports
5368
+ * `'listening'` on open; translates inbound frames through the shared protocol brain;
5369
+ * reports transport errors / closure. Protected so test subclasses can inject a fake
5370
+ * channel directly.
5371
+ */
5372
+ adoptDataChannel(channel) {
5373
+ this.dataChannel = channel;
5374
+ channel.onopen = () => {
5375
+ this.applySessionConfig(channel);
5376
+ this.ArmConnectionDurationTimer();
5377
+ this.setState("listening");
5378
+ };
5379
+ channel.onmessage = (e) => {
5380
+ this.handleProtocolMessage(String(e.data));
5381
+ };
5382
+ channel.onerror = (e) => this.handleChannelError(channel, e);
5383
+ channel.onclose = () => this.handleChannelClose(channel);
5384
+ }
5385
+ /**
5386
+ * A data-channel error. Ignored for a channel that is no longer current (the user's End or a swap already let go
5387
+ * of it). During a live call it starts the `connection-lost` reconnect, or goes to the reconnect already running;
5388
+ * otherwise it is fatal.
5389
+ */
5390
+ handleChannelError(channel, e) {
5391
+ if (this.dataChannel !== channel) {
5392
+ return;
5393
+ }
5394
+ if (this.recoverLostTransport(`data channel error: ${String(e)}`)) {
5395
+ return;
5396
+ }
5397
+ this.emitError({ Message: `Data channel error: ${String(e)}`, Fatal: true });
5398
+ this.setState("error");
5399
+ }
5400
+ /**
5401
+ * A data-channel close the consumer did not ask for (Disconnect and the swap drop the channel before closing it,
5402
+ * so the identity check filters both). During a live call it starts the `connection-lost` reconnect, or goes to the
5403
+ * reconnect already running; a channel that closes before the call went live ends the session as `'closed'`.
5404
+ */
5405
+ handleChannelClose(channel) {
5406
+ if (this.dataChannel !== channel || this.currentState === "error") {
5407
+ return;
5408
+ }
5409
+ if (this.recoverLostTransport("data channel closed")) {
5410
+ return;
5411
+ }
5412
+ this.setState("closed");
5413
+ }
5414
+ /**
5415
+ * Watches the current peer connection's state. A lost network path often never closes the data channel (SCTP
5416
+ * keeps waiting), so the peer connection's ICE consent checks are the liveness signal: `'failed'` is a loss at
5417
+ * once, `'disconnected'` is one once it outlasts {@link PEER_DISCONNECTED_GRACE_MS}, and `'connected'` (healed)
5418
+ * or a local `'closed'` stops the grace timer.
5419
+ */
5420
+ handlePeerConnectionState(pc) {
5421
+ if (this.peerConnection !== pc) {
5422
+ return;
5423
+ }
5424
+ switch (pc.connectionState) {
5425
+ case "failed":
5426
+ this.clearDisconnectedGrace();
5427
+ this.handlePeerConnectionLost("peer connection failed");
5428
+ break;
5429
+ case "disconnected":
5430
+ this.disconnectedGraceTimer ??= setTimeout(() => {
5431
+ this.disconnectedGraceTimer = null;
5432
+ if (this.peerConnection === pc && pc.connectionState === "disconnected") {
5433
+ this.handlePeerConnectionLost(`peer connection disconnected for ${OpenAIRealtimeClient_1.PEER_DISCONNECTED_GRACE_MS} ms`);
5434
+ }
5435
+ }, OpenAIRealtimeClient_1.PEER_DISCONNECTED_GRACE_MS);
5436
+ break;
5437
+ case "connected":
5438
+ case "closed":
5439
+ this.clearDisconnectedGrace();
5440
+ break;
5441
+ default:
5442
+ break;
5443
+ }
5444
+ }
5445
+ /**
5446
+ * The peer connection lost its network path. During a live call this starts the `connection-lost` reconnect;
5447
+ * before that (or when the driver cannot reconnect) the session is unusable, so it ends as a fatal error instead
5448
+ * of sitting silent on a dead transport.
4000
5449
  */
4001
- adoptDataChannel(channel) {
4002
- this.dataChannel = channel;
4003
- channel.onopen = () => {
4004
- this.applySessionConfig(channel);
4005
- this.setState("listening");
4006
- };
4007
- channel.onmessage = (e) => {
4008
- this.handleProtocolMessage(String(e.data));
4009
- };
4010
- channel.onerror = (e) => {
4011
- this.emitError({ Message: `Data channel error: ${String(e)}`, Fatal: true });
4012
- this.setState("error");
4013
- };
4014
- channel.onclose = () => {
4015
- if (this.currentState !== "error") {
4016
- this.setState("closed");
4017
- }
4018
- };
5450
+ handlePeerConnectionLost(detail) {
5451
+ if (this.recoverLostTransport(detail)) {
5452
+ return;
5453
+ }
5454
+ if (this.currentState === "error" || this.currentState === "closed") {
5455
+ return;
5456
+ }
5457
+ this.emitError({ Message: `OpenAI WebRTC ${detail}`, Fatal: true });
5458
+ this.setState("error");
5459
+ }
5460
+ clearDisconnectedGrace() {
5461
+ if (this.disconnectedGraceTimer !== null) {
5462
+ clearTimeout(this.disconnectedGraceTimer);
5463
+ this.disconnectedGraceTimer = null;
5464
+ }
4019
5465
  }
4020
5466
  /** Performs the offer/answer SDP exchange (POST seam: {@link postSdpOffer}). */
4021
5467
  async performSdpHandshake(pc, ephemeralToken) {
@@ -4051,7 +5497,7 @@ var OpenAIRealtimeClient = class OpenAIRealtimeClient2 extends OpenAIProtocolRea
4051
5497
  }
4052
5498
  }
4053
5499
  };
4054
- OpenAIRealtimeClient = __decorate([
5500
+ OpenAIRealtimeClient = OpenAIRealtimeClient_1 = __decorate([
4055
5501
  RegisterClass(BaseRealtimeClient, "openai")
4056
5502
  ], OpenAIRealtimeClient);
4057
5503
 
@@ -26289,6 +27735,7 @@ var GEMINI_INPUT_AUDIO_MIME_TYPE = "audio/pcm;rate=16000";
26289
27735
  var GEMINI_OUTPUT_SAMPLE_RATE = 24e3;
26290
27736
  var HELD_MIC_AUDIO_SECONDS = 2;
26291
27737
  var MAX_HELD_MIC_AUDIO_BASE64_CHARS = Math.ceil(GEMINI_INPUT_SAMPLE_RATE * 2 * HELD_MIC_AUDIO_SECONDS * 4 / 3);
27738
+ var GEMINI_UNANSWERED_UTTERANCE_HOLD_MS = 5e3;
26292
27739
  var GEMINI_MODALITY_TOKEN_FIELDS = {
26293
27740
  TEXT: "TextTokens",
26294
27741
  AUDIO: "AudioTokens",
@@ -26306,6 +27753,10 @@ var GeminiPcmPlayback = class extends RealtimePcmPlayback {
26306
27753
  var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClient {
26307
27754
  constructor() {
26308
27755
  super(...arguments);
27756
+ this.uncompressedVideoConnectionSeconds = GeminiRealtimeClient_1.GEMINI_LIVE_UNCOMPRESSED_VIDEO_CONNECTION_SECONDS;
27757
+ this.videoCapActive = false;
27758
+ this.hasResumedOnce = false;
27759
+ this.currentClosedPromise = null;
26309
27760
  this.session = null;
26310
27761
  this.micStream = null;
26311
27762
  this.cameraStream = null;
@@ -26316,11 +27767,12 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26316
27767
  this.firstVideoSendTimestamp = 0;
26317
27768
  this.lastVideoSendTimestamp = 0;
26318
27769
  this.videoFramesSent = 0;
26319
- this.resumption = null;
26320
27770
  this.connectionReady = false;
26321
27771
  this.heldMicAudio = [];
26322
27772
  this.heldMicAudioChars = 0;
26323
27773
  this.turnOpen = false;
27774
+ this.unansweredSpeechAtMs = null;
27775
+ this.unansweredSpeechTimer = null;
26324
27776
  this.turnEndAwaitsToolResults = false;
26325
27777
  this.connectTarget = null;
26326
27778
  this.issuedConnections = 0;
@@ -26349,9 +27801,76 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26349
27801
  static {
26350
27802
  this.ASSISTANT_SAFETY_BACKSTOP_MS = 15e3;
26351
27803
  }
26352
- /** Returns the latest session resumption handle reported by the server, if any. */
26353
- get ResumptionHandle() {
26354
- return this.resumption?.Handle ?? null;
27804
+ static {
27805
+ this.GEMINI_LIVE_CONNECTION_SECONDS = 600;
27806
+ }
27807
+ static {
27808
+ this.GEMINI_LIVE_UNCOMPRESSED_VIDEO_CONNECTION_SECONDS = 120;
27809
+ }
27810
+ get DefaultCallDurationSeconds() {
27811
+ return GeminiRealtimeClient_1.GEMINI_LIVE_CONNECTION_SECONDS;
27812
+ }
27813
+ /**
27814
+ * Applies the 120 s uncompressed-video connection cap only when inbound video is active,
27815
+ * at least one frame has been sent on the current connection/stream (`videoCapActive`), AND
27816
+ * `this.uncompressedVideoConnectionSeconds` is defined (`undefined` when sliding-window
27817
+ * compression is enabled in the session pact or connect config).
27818
+ */
27819
+ get RuntimeCallDurationSeconds() {
27820
+ if (this.uncompressedVideoConnectionSeconds !== void 0 && this.IsTrackEstablished("video", "inbound") && this.videoCapActive) {
27821
+ return this.uncompressedVideoConnectionSeconds;
27822
+ }
27823
+ return void 0;
27824
+ }
27825
+ /**
27826
+ * Google Gemini Developer API (`GeminiRealtimeClient`, key `'gemini'`) defaults to `false`
27827
+ * because `BidiGenerateContent` does not reliably honor `sessionResumption.handle` across
27828
+ * connections; `GeminiEnterpriseRealtimeClient` (Vertex AI Live) overrides this to `true`.
27829
+ */
27830
+ get DefaultTrustsNativeResumption() {
27831
+ return false;
27832
+ }
27833
+ /** Gemini / Vertex AI Live emits a fresh resumable handle shortly after each `turnComplete`. */
27834
+ get RequiresPostTurnResumptionHandle() {
27835
+ return true;
27836
+ }
27837
+ /**
27838
+ * Gemini ephemeral tokens open several connections (`SessionConfig.tokenUses`) until `ExpiresAt`, and relay
27839
+ * tickets allow multiple opens until `ExpiresAt`, so refreshes are driven by `ExpiresAt` and the spent uses
27840
+ * ({@link CredentialConnectionLimit}) rather than minting a new token on every reconnect attempt.
27841
+ */
27842
+ get RequiresFreshTokenPerReconnect() {
27843
+ return false;
27844
+ }
27845
+ /**
27846
+ * The connections a minted ephemeral token opens (`tokenUses`, which the server sizes from the effective connection
27847
+ * length). Each resume is a new session to Gemini and spends one; one past the count is refused
27848
+ * "Token has been used too many times". A relay ticket, or a mint that predates the field, has no limit here.
27849
+ */
27850
+ CredentialConnectionLimit(credential) {
27851
+ if (credential.Kind === "relay") {
27852
+ return void 0;
27853
+ }
27854
+ const uses = credential.SessionConfig?.["tokenUses"];
27855
+ return typeof uses === "number" && Number.isInteger(uses) && uses > 0 ? uses : void 0;
27856
+ }
27857
+ /**
27858
+ * Google closes a connection opened on an ephemeral token when that token's `expireTime` passes ("1011 auth token has
27859
+ * expired"), even after the client holds a refreshed one: the token bounds the sessions it opened, not only their
27860
+ * setup. A relay connection runs on the server's key, and its ticket only gates opening the tunnel.
27861
+ */
27862
+ ConnectionClosesAtCredentialExpiry(credential) {
27863
+ return credential.Kind !== "relay";
27864
+ }
27865
+ RemoveTrack(descriptor) {
27866
+ const removed = super.RemoveTrack(descriptor);
27867
+ if (removed && !this.IsTrackEstablished("video", "inbound") && this.videoCapActive) {
27868
+ this.videoCapActive = false;
27869
+ if (this.connectionReady && !this.IsReconnecting) {
27870
+ this.ArmConnectionDurationTimer();
27871
+ }
27872
+ }
27873
+ return removed;
26355
27874
  }
26356
27875
  /**
26357
27876
  * Whether a turn is in progress. A turn opens at its first sign: the user's first transcribed words, a turn this
@@ -26407,18 +27926,20 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26407
27926
  async Connect(config, micStream, cameraStream) {
26408
27927
  this.AssertTransportSupported(config);
26409
27928
  this.resetForConnect(micStream, cameraStream);
27929
+ this.ApplySessionConfigTiming(config);
26410
27930
  this.setState("connecting");
26411
27931
  const session = this.parseSessionConfig(config);
26412
27932
  this.idleSignal = session.idleSignal;
26413
27933
  this.supportsScheduling = session.supportsScheduling;
26414
27934
  this.supportsBlocking = session.supportsBlocking;
27935
+ const hasContextCompression = session.contextWindowCompression ?? (session.uncompressedVideoConnectionMaxSeconds === 0 ? true : Boolean(session.liveConfig.contextWindowCompression));
27936
+ const rawUncompressedVideoSec = session.uncompressedVideoConnectionMaxSeconds;
27937
+ this.uncompressedVideoConnectionSeconds = hasContextCompression ? void 0 : rawUncompressedVideoSec !== void 0 && rawUncompressedVideoSec > 0 ? rawUncompressedVideoSec : GeminiRealtimeClient_1.GEMINI_LIVE_UNCOMPRESSED_VIDEO_CONNECTION_SECONDS;
26415
27938
  this.negotiateSessionTracks(session);
26416
27939
  const playback = this.createPlayback();
26417
27940
  this.playback = playback;
26418
27941
  this.publishRemoteMediaStream(playback.GetOutputStream?.() ?? null);
26419
27942
  const liveConfig = this.prepareAvatar(session, playback);
26420
- this.resumption?.Dispose();
26421
- this.resumption = this.createResumption();
26422
27943
  const target = {
26423
27944
  Model: session.model,
26424
27945
  Config: liveConfig,
@@ -26446,6 +27967,9 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26446
27967
  this.firstVideoSendTimestamp = 0;
26447
27968
  this.lastVideoSendTimestamp = 0;
26448
27969
  this.videoFramesSent = 0;
27970
+ this.videoCapActive = false;
27971
+ this.hasResumedOnce = false;
27972
+ this.currentClosedPromise = null;
26449
27973
  this.resetConnectionState();
26450
27974
  this.disposeAvatarOutput();
26451
27975
  }
@@ -26608,6 +28132,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26608
28132
  * Safe to call more than once.
26609
28133
  */
26610
28134
  async Disconnect() {
28135
+ this.DisposeReconnectTimers();
26611
28136
  this.closeAudioMeters();
26612
28137
  this.clearSafetyBackstop();
26613
28138
  this.toolBatchBarrier.Clear();
@@ -26621,15 +28146,16 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26621
28146
  this.disposeAvatarOutput();
26622
28147
  this.playback?.Close();
26623
28148
  this.playback = null;
26624
- this.resumption?.Dispose();
26625
- this.resumption = null;
26626
28149
  this.connectTarget = null;
26627
28150
  this.currentConnection = 0;
28151
+ this.currentClosedPromise = null;
26628
28152
  this.resetConnectionState();
26629
28153
  this.clearRemoteMediaStream();
26630
28154
  this.firstVideoSendTimestamp = 0;
26631
28155
  this.lastVideoSendTimestamp = 0;
26632
28156
  this.videoFramesSent = 0;
28157
+ this.videoCapActive = false;
28158
+ this.hasResumedOnce = false;
26633
28159
  if (this.session) {
26634
28160
  try {
26635
28161
  this.session.close();
@@ -26658,7 +28184,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26658
28184
  * needed.
26659
28185
  */
26660
28186
  SendText(text) {
26661
- if (!this.session) {
28187
+ if (!this.session && !this.IsReconnecting) {
26662
28188
  return;
26663
28189
  }
26664
28190
  this.CancelActiveResponse();
@@ -26698,7 +28224,12 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26698
28224
  if (this.firstVideoSendTimestamp === 0) {
26699
28225
  this.firstVideoSendTimestamp = now;
26700
28226
  }
28227
+ const wasVideoCapInactive = !this.videoCapActive;
28228
+ this.videoCapActive = true;
26701
28229
  this.videoFramesSent++;
28230
+ if (wasVideoCapInactive && this.uncompressedVideoConnectionSeconds !== void 0) {
28231
+ this.ArmConnectionDurationTimer();
28232
+ }
26702
28233
  this.session?.sendRealtimeInput({
26703
28234
  video: { data: base64Image, mimeType }
26704
28235
  });
@@ -26717,7 +28248,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26717
28248
  * when nothing is active. An avatar's video stops with the voice.
26718
28249
  */
26719
28250
  CancelActiveResponse() {
26720
- if (!this.session) {
28251
+ if (!this.session && !this.IsReconnecting) {
26721
28252
  return;
26722
28253
  }
26723
28254
  if (!this.responseActive && !this.IsAudioPlaying && !this.interactionInProgress) {
@@ -26746,10 +28277,15 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26746
28277
  * holds generation until a `turnComplete: true` commit arrives. {@link openClientTurn}
26747
28278
  * tracks this so {@link SendToolResult} can commit the turn and unblock the spoken reply.
26748
28279
  */
26749
- SendContextNote(text) {
26750
- if (!this.session) {
28280
+ SendContextNote(text, options) {
28281
+ if (!this.session && !this.IsReconnecting) {
26751
28282
  return;
26752
28283
  }
28284
+ this.conversationMemory.Record({
28285
+ Kind: "note",
28286
+ Text: text,
28287
+ ...options
28288
+ });
26753
28289
  this.enqueueOrRun(() => {
26754
28290
  this.session?.sendClientContent({ turns: [{ role: "user", parts: [{ text }] }], turnComplete: false });
26755
28291
  this.openClientTurn = true;
@@ -26765,14 +28301,14 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26765
28301
  * in-flight turn so it can never interrupt a pending reply.
26766
28302
  */
26767
28303
  RequestSpokenUpdate(instructions) {
26768
- if (!this.session) {
28304
+ if (!this.session && !this.IsReconnecting) {
26769
28305
  return;
26770
28306
  }
26771
28307
  this.enqueueOrRun(() => this.sendTriggeringUserTurn(instructions, "narration", false));
26772
28308
  }
26773
28309
  /** A spoken TURN: the same realtime-text trigger as the update, with the reply kept `normal` (MJ#4591). */
26774
28310
  RequestSpokenTurn(instructions) {
26775
- if (!this.session) {
28311
+ if (!this.session && !this.IsReconnecting) {
26776
28312
  return;
26777
28313
  }
26778
28314
  this.enqueueOrRun(() => this.sendTriggeringUserTurn(instructions, "normal", false));
@@ -26788,9 +28324,9 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26788
28324
  * — without it the server keeps waiting for more client input and NEVER starts the spoken
26789
28325
  * reply (observed live as the model staying silent after a delegated agent's result).
26790
28326
  */
26791
- SendToolResult(callID, outputJson) {
26792
- if (!this.session) {
26793
- return;
28327
+ doSendToolResult(callID, outputJson) {
28328
+ if (!this.session && !this.IsReconnecting) {
28329
+ return false;
26794
28330
  }
26795
28331
  const name = this.pendingToolCallNames.get(callID) ?? "";
26796
28332
  this.enqueueOrRun(() => this.sendToolResponseTurn(callID, name, outputJson), !this.isNonBlocking);
@@ -26916,6 +28452,9 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26916
28452
  const maxInboundVideoRate = typeof rawMaxVideoRate === "number" && rawMaxVideoRate > 0 ? rawMaxVideoRate : void 0;
26917
28453
  const rawMaxStreams = sessionConfig["maxInboundVideoStreams"];
26918
28454
  const maxInboundVideoStreams = typeof rawMaxStreams === "number" && Number.isInteger(rawMaxStreams) && rawMaxStreams >= 0 ? rawMaxStreams : void 0;
28455
+ const rawUncompressedVideoSec = sessionConfig["uncompressedVideoConnectionMaxSeconds"];
28456
+ const uncompressedVideoConnectionMaxSeconds = typeof rawUncompressedVideoSec === "number" && Number.isInteger(rawUncompressedVideoSec) && rawUncompressedVideoSec >= 0 ? rawUncompressedVideoSec : void 0;
28457
+ const contextWindowCompression = typeof sessionConfig["contextWindowCompression"] === "boolean" ? sessionConfig["contextWindowCompression"] : void 0;
26919
28458
  return {
26920
28459
  model,
26921
28460
  liveConfig,
@@ -26925,6 +28464,8 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26925
28464
  supportsInboundVideo,
26926
28465
  maxInboundVideoRate,
26927
28466
  maxInboundVideoStreams,
28467
+ uncompressedVideoConnectionMaxSeconds,
28468
+ contextWindowCompression,
26928
28469
  requestedTracks: GeminiRealtimeClient_1.readRequestedTracks(sessionConfig[REQUESTED_TRACKS_SESSION_KEY]),
26929
28470
  avatar: GeminiRealtimeClient_1.readAvatarGrant(sessionConfig["avatar"])
26930
28471
  };
@@ -26977,8 +28518,56 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26977
28518
  this.holdMicChunk(base64Pcm16);
26978
28519
  return;
26979
28520
  }
28521
+ if (this.isUserSpeaking()) {
28522
+ this.noteUnansweredSpeech();
28523
+ }
26980
28524
  this.sendAudio(this.session, base64Pcm16);
26981
28525
  }
28526
+ /** The user's voice went to the connection in use: a timed move waits for its answer (bounded). */
28527
+ noteUnansweredSpeech() {
28528
+ this.unansweredSpeechAtMs = Date.now();
28529
+ if (this.unansweredSpeechTimer === null) {
28530
+ this.armUnansweredSpeechTimer(GEMINI_UNANSWERED_UTTERANCE_HOLD_MS);
28531
+ }
28532
+ }
28533
+ /** One timer per hold, re-armed for the rest of the hold time when the user spoke since it was set. */
28534
+ armUnansweredSpeechTimer(delayMs) {
28535
+ this.unansweredSpeechTimer = setTimeout(() => {
28536
+ this.unansweredSpeechTimer = null;
28537
+ if (this.unansweredSpeechAtMs === null) {
28538
+ return;
28539
+ }
28540
+ const quietMs = Date.now() - this.unansweredSpeechAtMs;
28541
+ if (quietMs < GEMINI_UNANSWERED_UTTERANCE_HOLD_MS) {
28542
+ this.armUnansweredSpeechTimer(GEMINI_UNANSWERED_UTTERANCE_HOLD_MS - quietMs);
28543
+ return;
28544
+ }
28545
+ RealtimeDiagLog(`[GeminiRealtimeClient] no answer ${GEMINI_UNANSWERED_UTTERANCE_HOLD_MS} ms after the user stopped speaking; a timed move may go ahead`);
28546
+ this.clearUnansweredSpeech();
28547
+ this.reconnectController.NotifyIdleStateChanged();
28548
+ }, delayMs);
28549
+ }
28550
+ /** Ends the hold without re-checking a move: a turn now holds it, or the connection it belongs to is left. */
28551
+ clearUnansweredSpeech() {
28552
+ if (this.unansweredSpeechTimer !== null) {
28553
+ clearTimeout(this.unansweredSpeechTimer);
28554
+ this.unansweredSpeechTimer = null;
28555
+ }
28556
+ this.unansweredSpeechAtMs = null;
28557
+ }
28558
+ /** @inheritdoc Here: the user's words wait for their answer, which is the first sign of them Google sends. */
28559
+ holdsHardReconnectPoint() {
28560
+ return this.unansweredSpeechAtMs !== null;
28561
+ }
28562
+ /**
28563
+ * @inheritdoc
28564
+ *
28565
+ * Adds the unanswered words: the meter reads the user only at the instant it is read, not in the second after they
28566
+ * stop and before Google answers.
28567
+ */
28568
+ isTurnActiveForReconnect() {
28569
+ return this.unansweredSpeechAtMs !== null || super.isTurnActiveForReconnect();
28570
+ }
26982
28571
  /** Sends one base64 PCM16 mic chunk on `session`; a failed send is logged, not thrown. */
26983
28572
  sendAudio(session, base64Pcm16) {
26984
28573
  try {
@@ -26991,23 +28580,44 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
26991
28580
  }
26992
28581
  /** Holds a mic chunk during a move, keeping the latest {@link HELD_MIC_AUDIO_SECONDS} seconds; older audio goes first. */
26993
28582
  holdMicChunk(base64Pcm16) {
26994
- this.heldMicAudio.push(base64Pcm16);
28583
+ this.heldMicAudio.push({ Pcm: base64Pcm16, Speech: this.isUserSpeaking() });
26995
28584
  this.heldMicAudioChars += base64Pcm16.length;
26996
28585
  while (this.heldMicAudioChars > MAX_HELD_MIC_AUDIO_BASE64_CHARS && this.heldMicAudio.length > 1) {
26997
- this.heldMicAudioChars -= this.heldMicAudio.shift()?.length ?? 0;
28586
+ this.heldMicAudioChars -= this.heldMicAudio.shift()?.Pcm.length ?? 0;
26998
28587
  }
26999
28588
  }
27000
- /** Sends the mic audio held during a move on the connection now in use, oldest first. */
28589
+ /**
28590
+ * Sends the mic audio held during a move on the connection now in use, oldest first.
28591
+ *
28592
+ * @returns Whether the audio sent carried the user's voice.
28593
+ */
27001
28594
  sendHeldMicAudio() {
27002
28595
  const held = this.heldMicAudio;
27003
28596
  this.heldMicAudio = [];
27004
28597
  this.heldMicAudioChars = 0;
27005
28598
  if (!this.session) {
27006
- return;
28599
+ return false;
27007
28600
  }
27008
28601
  for (const chunk of held) {
27009
- this.sendAudio(this.session, chunk);
28602
+ this.sendAudio(this.session, chunk.Pcm);
28603
+ }
28604
+ return held.some((chunk) => chunk.Speech);
28605
+ }
28606
+ /**
28607
+ * Whether an unexpected close or `goAway` can be recovered via `TriggerReconnect` / `NotifyConnectionEnding`:
28608
+ * a reconnect cycle is running, native resumption has a recorded handle, or history seeding is active
28609
+ * (`TrustsNativeResumption === false` or `hasResumedOnce === true`). A running cycle takes the loss of the
28610
+ * connection it may go back to whatever handle is left: after a failed native attempt it has dropped the handle
28611
+ * and seeds, though this session has never resumed.
28612
+ */
28613
+ canRecoverConnection(allowEmptySeed = false) {
28614
+ if (this.IsReconnectCycleActive || this.ResumptionHandle !== null) {
28615
+ return true;
27010
28616
  }
28617
+ if (this.TrustsNativeResumption && !this.hasResumedOnce) {
28618
+ return false;
28619
+ }
28620
+ return allowEmptySeed || this.hasResumedOnce || this.conversationMemory.Seed().Entries.length > 0;
27011
28621
  }
27012
28622
  /**
27013
28623
  * Surfaces a fatal websocket error and marks the session unusable. When the session can be
@@ -27017,7 +28627,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27017
28627
  handleTransportError(event) {
27018
28628
  const detail = GeminiRealtimeClient_1.transportErrorDetail(event);
27019
28629
  RealtimeDiagLog(`[GeminiRealtimeClient] Transport error: ${detail}`);
27020
- if (this.resumption?.Handle) {
28630
+ if (this.canRecoverConnection()) {
27021
28631
  return;
27022
28632
  }
27023
28633
  this.emitError({ Message: `Gemini Live transport error: ${detail}`, Fatal: true });
@@ -27026,8 +28636,8 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27026
28636
  /**
27027
28637
  * Handles a close of the current connection that the consumer did not ask for. MJAPI's relay
27028
28638
  * closing at the session's time limit ends the call with a `time-limit` error. Otherwise, when
27029
- * Google issued a resumption handle, the session reconnects with it; else the close ends the
27030
- * session, as an error when it was abnormal.
28639
+ * Google issued a resumption handle (or history seeding is active), the session reconnects;
28640
+ * else the close ends the session, as an error when it was abnormal.
27031
28641
  */
27032
28642
  handleTransportClose(event) {
27033
28643
  const code = event?.code;
@@ -27046,7 +28656,8 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27046
28656
  this.setState("error");
27047
28657
  return;
27048
28658
  }
27049
- if (this.resumption?.ConnectionLost()) {
28659
+ if (this.canRecoverConnection()) {
28660
+ void this.TriggerReconnect("connection-lost");
27050
28661
  return;
27051
28662
  }
27052
28663
  const isAbnormal = code !== void 0 && code !== 0 && code !== 1e3 && code !== 1005 || wasClean === false && code !== 1e3 && code !== 0 && code !== 1005 && code !== void 0;
@@ -27069,10 +28680,13 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27069
28680
  this.checkInteractionStatus(message);
27070
28681
  if (message.sessionResumptionUpdate) {
27071
28682
  const update = message.sessionResumptionUpdate;
27072
- this.resumption?.RecordHandle(update.newHandle, update.resumable !== false);
28683
+ this.RecordResumptionHandle(update.newHandle, update.resumable !== false);
27073
28684
  }
27074
28685
  if (message.goAway) {
27075
- this.resumption?.ConnectionEnding(ParseDurationToMs(message.goAway.timeLeft));
28686
+ const timeLeftMs = ParseDurationToMs(message.goAway.timeLeft);
28687
+ if (this.canRecoverConnection(true)) {
28688
+ this.NotifyConnectionEnding(timeLeftMs);
28689
+ }
27076
28690
  }
27077
28691
  if (message.serverContent) {
27078
28692
  this.handleServerContent(message.serverContent);
@@ -27084,43 +28698,147 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27084
28698
  this.handleUsageMetadata(message.usageMetadata);
27085
28699
  }
27086
28700
  }
28701
+ onReconnecting(reason) {
28702
+ RealtimeDiagLog(`[GeminiRealtimeClient] Resuming the session on a new connection (${reason})`);
28703
+ this.connectionReady = false;
28704
+ this.currentState = "connecting";
28705
+ this.clearUnansweredSpeech();
28706
+ this.finalizeUserTranscript();
28707
+ super.onReconnecting(reason);
28708
+ }
27087
28709
  /**
27088
- * Opens a replacement connection that resumes the session from `handle`, switches to it once
27089
- * Google confirms its setup, and closes the old one. Until then the old connection stays in
27090
- * use, so what it still sends (the rest of a turn the deadline cut, its usage) is handled.
27091
- * Mic capture and playout carry over untouched. Rejects when the connection can't be opened or
27092
- * its setup fails, so {@link RealtimeSessionResumption} can retry.
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.
28710
+ * A planned move's attempt failed and the old connection is still the one in use: the call goes on there until the
28711
+ * next attempt. Input flows again (the mic audio held during the attempt goes out first, then queued sends), and
28712
+ * the state the move replaced is reported again. Held audio that carried the user's voice holds the next attempt
28713
+ * as live speech does ({@link noteUnansweredSpeech}): the old connection has not answered those words yet. `false`
28714
+ * when the attempt tore the old connection down (a relay session closes its tunnel before a seeded reopen) or the
28715
+ * session has ended.
27102
28716
  */
27103
- async resumeSession(handle, attempt) {
28717
+ ResumeOnOldConnection() {
28718
+ if (!this.session || this.currentConnection === 0 || this.currentState === "closed" || this.currentState === "error") {
28719
+ return false;
28720
+ }
28721
+ this.connectionReady = true;
28722
+ const restore = this.StateToRestoreOnOldConnection;
28723
+ if (restore) {
28724
+ this.setState(restore);
28725
+ }
28726
+ if (this.sendHeldMicAudio()) {
28727
+ this.noteUnansweredSpeech();
28728
+ }
28729
+ this.flushQueuedSends();
28730
+ return true;
28731
+ }
28732
+ /**
28733
+ * Re-establishes the underlying Gemini Live WebSocket mid-call via `BaseRealtimeClient.reconnectController`
28734
+ * (proactive connection-duration timer, `goAway`, unexpected close, or Attempt 2 seed fallback).
28735
+ *
28736
+ * - Preserves `sessionResumption` only when present on the initial connect config or when `handle` is set
28737
+ * (never adding `sessionResumption: {}` on ZDR sessions that omitted it).
28738
+ * - On a relay session falling back to history seeding (`!handle && target.Transport === 'relay'`), closes the
28739
+ * old tunnel first, awaits its close callback, requests `context.RefreshCredential({ AllowFreshReopen: true })`
28740
+ * so the relay resets `FreshOpened` once `ExpiresAtListeners.size === 0`, and seeds via
28741
+ * `RenderRealtimeMemorySeedAsContextNote`.
28742
+ */
28743
+ async Reconnect(context) {
27104
28744
  const target = this.connectTarget;
27105
28745
  if (!target) {
27106
- throw new Error("there is no Gemini Live session to resume");
28746
+ throw new Error("there is no Gemini Live session to reconnect");
28747
+ }
28748
+ this.connectionReady = false;
28749
+ const handle = context.UseNativeResumption && context.ResumptionHandle ? context.ResumptionHandle : void 0;
28750
+ let refreshedRelayUrl = context.Credential.RelayUrl || target.RelayUrl;
28751
+ if (!handle && target.Transport === "relay") {
28752
+ const prevClosed = this.currentClosedPromise;
28753
+ this.currentClosedPromise = null;
28754
+ this.currentConnection = 0;
28755
+ if (this.session) {
28756
+ GeminiRealtimeClient_1.closeQuietly(this.session);
28757
+ this.session = null;
28758
+ }
28759
+ if (prevClosed) {
28760
+ await prevClosed;
28761
+ }
28762
+ const freshRelayCred = await context.RefreshCredential({ AllowFreshReopen: true });
28763
+ if (freshRelayCred.RelayUrl) {
28764
+ refreshedRelayUrl = freshRelayCred.RelayUrl;
28765
+ }
28766
+ }
28767
+ const refreshedToken = context.Credential.EphemeralToken || target.EphemeralToken;
28768
+ const existingResumption = target.Config.sessionResumption;
28769
+ let nextConfig;
28770
+ if (handle) {
28771
+ nextConfig = {
28772
+ ...target.Config,
28773
+ sessionResumption: { ...existingResumption, handle }
28774
+ };
28775
+ } else if (existingResumption !== void 0) {
28776
+ const { handle: _omitted, ...withoutHandle } = existingResumption;
28777
+ nextConfig = {
28778
+ ...target.Config,
28779
+ sessionResumption: withoutHandle
28780
+ };
28781
+ } else {
28782
+ nextConfig = { ...target.Config };
27107
28783
  }
27108
- const resumeTarget = {
28784
+ const reconnectTarget = {
27109
28785
  ...target,
27110
- Config: { ...target.Config, sessionResumption: { ...target.Config.sessionResumption, handle } }
28786
+ EphemeralToken: refreshedToken,
28787
+ ...refreshedRelayUrl ? { RelayUrl: refreshedRelayUrl } : {},
28788
+ Config: nextConfig
27111
28789
  };
27112
- const opened = await this.openConnection(resumeTarget);
27113
- await GeminiRealtimeClient_1.awaitSetup(opened);
27114
- if (attempt.Abandoned || this.connectTarget !== target) {
28790
+ const opened = await this.openConnection(reconnectTarget);
28791
+ const onAbort = () => {
27115
28792
  GeminiRealtimeClient_1.closeQuietly(opened.Session);
27116
- return;
28793
+ };
28794
+ if (context.Signal.aborted) {
28795
+ onAbort();
28796
+ throw new Error("GeminiRealtimeClient: reconnect attempt aborted");
28797
+ }
28798
+ context.Signal.addEventListener("abort", onAbort, { once: true });
28799
+ try {
28800
+ await GeminiRealtimeClient_1.awaitSetup(opened);
28801
+ } finally {
28802
+ context.Signal.removeEventListener("abort", onAbort);
28803
+ }
28804
+ if (context.Abandoned || this.connectTarget !== target) {
28805
+ GeminiRealtimeClient_1.closeQuietly(opened.Session);
28806
+ throw new Error("GeminiRealtimeClient: reconnect attempt abandoned");
27117
28807
  }
27118
28808
  const previous = this.session;
27119
28809
  this.useConnection(opened);
27120
- this.connectTarget = resumeTarget;
28810
+ this.connectTarget = reconnectTarget;
27121
28811
  if (previous) {
27122
28812
  GeminiRealtimeClient_1.closeQuietly(previous);
27123
28813
  }
28814
+ if (!handle) {
28815
+ for (const callID of this.pendingToolCallNames.keys()) {
28816
+ this.callsFromBeforeReseed.add(callID);
28817
+ }
28818
+ }
28819
+ if (!handle && context.ConversationSeed && context.ConversationSeed.Entries.length > 0) {
28820
+ if (target.Transport === "relay") {
28821
+ const note = RenderRealtimeMemorySeedAsContextNote(context.ConversationSeed);
28822
+ if (note) {
28823
+ this.session?.sendClientContent({
28824
+ turns: [{ role: "user", parts: [{ text: note }] }],
28825
+ turnComplete: false
28826
+ });
28827
+ this.openClientTurn = true;
28828
+ }
28829
+ } else {
28830
+ const seedTurns = RenderRealtimeMemorySeed(context.ConversationSeed);
28831
+ if (seedTurns.length > 0) {
28832
+ const turns = seedTurns.map((t) => ({
28833
+ role: t.Role,
28834
+ parts: t.Texts.map((text) => ({ text }))
28835
+ }));
28836
+ this.session?.sendClientContent({ turns, turnComplete: false });
28837
+ this.openClientTurn = true;
28838
+ }
28839
+ }
28840
+ }
28841
+ this.handleResumed();
27124
28842
  }
27125
28843
  /**
27126
28844
  * Opens a connection through {@link connectLiveSession}. Its callbacks act only while it is the
@@ -27133,6 +28851,10 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27133
28851
  const number = ++this.issuedConnections;
27134
28852
  const isCurrent = () => number === this.currentConnection;
27135
28853
  const setup = new RealtimeConnectionSetup();
28854
+ let markClosed;
28855
+ const closed = new Promise((resolve) => {
28856
+ markClosed = resolve;
28857
+ });
27136
28858
  const session = await this.connectLiveSession({
27137
28859
  ...target,
27138
28860
  OnMessage: (message) => {
@@ -27150,13 +28872,14 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27150
28872
  }
27151
28873
  },
27152
28874
  OnClose: (event) => {
28875
+ markClosed();
27153
28876
  setup.Fail(new Error(`Gemini Live closed the connection before confirming its setup (${event?.code}): ${event?.reason || "no reason given"}`));
27154
28877
  if (isCurrent()) {
27155
28878
  this.handleTransportClose(event);
27156
28879
  }
27157
28880
  }
27158
28881
  });
27159
- return { Session: session, ConnectionNumber: number, Setup: setup };
28882
+ return { Session: session, ConnectionNumber: number, Setup: setup, Closed: closed };
27160
28883
  }
27161
28884
  /** Waits for Google to confirm a new connection's setup. On failure the connection is closed and the error rethrown. */
27162
28885
  static async awaitSetup(opened) {
@@ -27175,23 +28898,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27175
28898
  useConnection(opened) {
27176
28899
  this.session = opened.Session;
27177
28900
  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
- });
28901
+ this.currentClosedPromise = opened.Closed;
27195
28902
  }
27196
28903
  /**
27197
28904
  * The session continues on a new connection, whose setup Google has confirmed. A turn cut off
@@ -27201,6 +28908,8 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27201
28908
  * last frame.
27202
28909
  */
27203
28910
  handleResumed() {
28911
+ this.hasResumedOnce = true;
28912
+ this.videoCapActive = false;
27204
28913
  this.avatarOutput?.Resumed();
27205
28914
  this.emitAvatarVideoSeconds();
27206
28915
  this.finalizeUserTranscript();
@@ -27216,11 +28925,15 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27216
28925
  this.flushQueuedSends();
27217
28926
  }
27218
28927
  /** Every resume attempt failed: the session ends with a fatal error. */
27219
- handleResumeFailed(error) {
28928
+ onReconnectFailed(error, code) {
27220
28929
  if (this.currentState === "closed" || this.currentState === "error") {
27221
28930
  return;
27222
28931
  }
27223
- this.emitError({ Message: `Gemini Live connection was lost and could not be resumed: ${error.message}`, Fatal: true });
28932
+ this.emitError({
28933
+ Message: `Gemini Live connection was lost and could not be resumed: ${error.message}`,
28934
+ ...code ? { Code: code } : {},
28935
+ Fatal: true
28936
+ });
27224
28937
  this.setState("error");
27225
28938
  }
27226
28939
  /** Closes a socket the session no longer uses; it may already be closed. */
@@ -27632,7 +29345,8 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27632
29345
  markTurnOpen() {
27633
29346
  this.turnOpen = true;
27634
29347
  this.turnEndAwaitsToolResults = false;
27635
- this.resumption?.TurnStarted();
29348
+ this.reconnectController.TurnStarted();
29349
+ this.clearUnansweredSpeech();
27636
29350
  }
27637
29351
  /** The turn's `turnComplete` (or true idle): it ends now, or once the results of the tool calls still pending go out. */
27638
29352
  endTurnUnlessToolCallPending() {
@@ -27643,16 +29357,19 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27643
29357
  this.endTurn();
27644
29358
  }
27645
29359
  /** A tool result went out: a turn whose `turnComplete` waited on the pending calls ends once none is left. */
27646
- endTurnIfToolResultsIn() {
29360
+ endTurnIfToolResultsIn(expectsReply = true) {
27647
29361
  if (this.turnEndAwaitsToolResults && this.pendingToolCallNames.size === 0) {
27648
- this.endTurn();
29362
+ this.endTurn(expectsReply);
27649
29363
  }
27650
29364
  }
27651
29365
  /** The turn is over: a planned move happens at the next resumable handle Google issues. */
27652
- endTurn() {
29366
+ endTurn(keepPostToolTurnWait = false) {
27653
29367
  this.turnOpen = false;
27654
29368
  this.turnEndAwaitsToolResults = false;
27655
- this.resumption?.TurnEnded();
29369
+ this.reconnectController.TurnEnded(keepPostToolTurnWait);
29370
+ }
29371
+ isToolResultSilent(outputJson) {
29372
+ return this.supportsScheduling && super.isToolResultSilent(outputJson);
27656
29373
  }
27657
29374
  // ── Collision-safe send machinery ──────────────────────────────────────────
27658
29375
  /**
@@ -27750,6 +29467,19 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27750
29467
  return;
27751
29468
  }
27752
29469
  this.toolBatchBarrier.RecordResult(callID);
29470
+ if (this.callsFromBeforeReseed.delete(callID)) {
29471
+ session.sendRealtimeInput({
29472
+ text: RenderLateToolResultNote(name || callID, outputJson)
29473
+ });
29474
+ if (!this.isNonBlocking) {
29475
+ this.responseActive = true;
29476
+ this.activeResponseKind = "normal";
29477
+ this.setState("speaking");
29478
+ }
29479
+ this.pendingToolCallNames.delete(callID);
29480
+ this.endTurnIfToolResultsIn(true);
29481
+ return;
29482
+ }
27753
29483
  const parsed = this.parseToolOutput(outputJson);
27754
29484
  const sched = this.resolveFunctionScheduling(parsed, name);
27755
29485
  const functionResponse = {
@@ -27773,7 +29503,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27773
29503
  this.setState("speaking");
27774
29504
  }
27775
29505
  this.pendingToolCallNames.delete(callID);
27776
- this.endTurnIfToolResultsIn();
29506
+ this.endTurnIfToolResultsIn(sched !== FunctionResponseScheduling.SILENT);
27777
29507
  }
27778
29508
  /**
27779
29509
  * Parses a JSON-stringified tool result into the structured object Gemini's
@@ -27815,6 +29545,7 @@ var GeminiRealtimeClient = class GeminiRealtimeClient2 extends BaseRealtimeClien
27815
29545
  }
27816
29546
  /** Resets the per-session response state machine (used on Disconnect). */
27817
29547
  resetResponseState() {
29548
+ this.clearUnansweredSpeech();
27818
29549
  this.pendingAssistantText = "";
27819
29550
  this.pendingUserText = "";
27820
29551
  this.pendingThoughtText = "";
@@ -27863,6 +29594,10 @@ var GeminiEnterpriseRealtimeClient = class GeminiEnterpriseRealtimeClient2 exten
27863
29594
  get SupportsRelayTransport() {
27864
29595
  return true;
27865
29596
  }
29597
+ /** Vertex AI / Gemini Enterprise relay sessions accept sessionResumption.handle natively. */
29598
+ get DefaultTrustsNativeResumption() {
29599
+ return true;
29600
+ }
27866
29601
  /**
27867
29602
  * Opens one Live connection through the relay; a resume opens another with the same URL and the new handle.
27868
29603
  *
@@ -27918,13 +29653,16 @@ var __decorate4 = function(decorators, target, key, desc) {
27918
29653
  };
27919
29654
  var ElevenLabsRealtimeClient_1;
27920
29655
  var ELEVENLABS_DEFAULT_SAMPLE_RATE = 16e3;
29656
+ var ELEVENLABS_DEFAULT_CALL_DURATION_SECONDS = 600;
27921
29657
  var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealtimeClient {
27922
29658
  constructor() {
27923
29659
  super(...arguments);
27924
29660
  this.socket = null;
29661
+ this.socketOpen = false;
27925
29662
  this.micStream = null;
27926
29663
  this.micCapture = null;
27927
29664
  this.playback = null;
29665
+ this.activeConfig = null;
27928
29666
  this.responseActive = false;
27929
29667
  this.activeResponseKind = "normal";
27930
29668
  this.queuedSends = [];
@@ -27937,6 +29675,9 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
27937
29675
  static {
27938
29676
  ElevenLabsRealtimeClient_1 = this;
27939
29677
  }
29678
+ get DefaultCallDurationSeconds() {
29679
+ return ELEVENLABS_DEFAULT_CALL_DURATION_SECONDS;
29680
+ }
27940
29681
  // ── BaseRealtimeClient: connection lifecycle ───────────────────────────────
27941
29682
  /**
27942
29683
  * Opens the client-direct conversation: socket to the signed URL, the initiation frame
@@ -27946,8 +29687,11 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
27946
29687
  */
27947
29688
  async Connect(config, micStream) {
27948
29689
  this.AssertTransportSupported(config);
29690
+ this.ApplySessionConfigTiming(config);
29691
+ this.activeConfig = config;
27949
29692
  this.micStream = micStream;
27950
29693
  this.closedByConsumer = false;
29694
+ this.socketOpen = false;
27951
29695
  this.setState("connecting");
27952
29696
  const overrides = this.parseOverrides(config);
27953
29697
  let openSocket = null;
@@ -27970,21 +29714,47 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
27970
29714
  };
27971
29715
  const socket = this.createSocket(config.EphemeralToken);
27972
29716
  this.socket = socket;
27973
- socket.onopen = () => openSocket?.();
27974
- socket.onmessage = (data) => this.handleSocketMessage(data);
29717
+ socket.onopen = () => {
29718
+ if (this.socket !== socket) {
29719
+ return;
29720
+ }
29721
+ this.socketOpen = true;
29722
+ openSocket?.();
29723
+ };
29724
+ socket.onmessage = (data) => {
29725
+ if (this.socket !== socket) {
29726
+ return;
29727
+ }
29728
+ this.handleSocketMessage(data);
29729
+ };
27975
29730
  socket.onerror = (message) => {
29731
+ if (this.socket !== socket) {
29732
+ return;
29733
+ }
29734
+ this.socketOpen = false;
27976
29735
  failConnect(new Error(message));
27977
- this.handleSocketError(message);
29736
+ if (!this.IsReconnecting) {
29737
+ this.handleSocketError(message);
29738
+ }
27978
29739
  };
27979
29740
  socket.onclose = () => {
29741
+ if (this.socket !== socket) {
29742
+ return;
29743
+ }
29744
+ this.socketOpen = false;
27980
29745
  failConnect(new Error("ElevenLabs conversation socket closed during connect"));
27981
- this.handleSocketClose();
29746
+ if (!this.IsReconnecting) {
29747
+ this.handleSocketClose();
29748
+ }
27982
29749
  };
27983
29750
  await opened;
27984
29751
  this.setState("connected");
27985
29752
  this.sendFrame({ type: "conversation_initiation_client_data", conversation_config_override: overrides });
27986
29753
  const metadataEvent = await metadata;
27987
29754
  const formats = metadataEvent.conversation_initiation_metadata_event;
29755
+ if (formats?.conversation_id) {
29756
+ this.RecordResumptionHandle(formats.conversation_id);
29757
+ }
27988
29758
  const outputRate = ElevenLabsRealtimeClient_1.ParsePcmRate(formats?.agent_output_audio_format, "output");
27989
29759
  const inputRate = ElevenLabsRealtimeClient_1.ParsePcmRate(formats?.user_input_audio_format, "input");
27990
29760
  this.playback = this.createPlayback(outputRate);
@@ -27992,6 +29762,7 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
27992
29762
  this.micCapture = await this.createMicCapture(micStream, inputRate, (base64Pcm16) => this.sendMicChunk(base64Pcm16));
27993
29763
  this.attachOutputAudioMeter(this.playback?.CreateMeter?.() ?? null);
27994
29764
  this.attachInputAudioMeter(RealtimeAudioMeter.ForMicStream(micStream));
29765
+ this.ArmConnectionDurationTimer();
27995
29766
  this.setState("listening");
27996
29767
  }
27997
29768
  /**
@@ -28001,6 +29772,9 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
28001
29772
  */
28002
29773
  async Disconnect() {
28003
29774
  this.closedByConsumer = true;
29775
+ this.socketOpen = false;
29776
+ this.DisposeReconnectTimers();
29777
+ this.cancelToolResultNudge();
28004
29778
  this.closeAudioMeters();
28005
29779
  this.micStream?.getTracks().forEach((track) => track.stop());
28006
29780
  this.micStream = null;
@@ -28010,17 +29784,165 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
28010
29784
  this.playback = null;
28011
29785
  this.clearRemoteMediaStream();
28012
29786
  if (this.socket) {
29787
+ const s = this.socket;
29788
+ this.socket = null;
29789
+ s.onopen = null;
29790
+ s.onmessage = null;
29791
+ s.onerror = null;
29792
+ s.onclose = null;
28013
29793
  try {
28014
- this.socket.close();
29794
+ s.close();
28015
29795
  } catch {
28016
29796
  }
28017
- this.socket = null;
28018
29797
  }
29798
+ this.activeConfig = null;
28019
29799
  this.resetResponseState();
28020
29800
  if (this.currentState !== "error") {
28021
29801
  this.setState("closed");
28022
29802
  }
28023
29803
  }
29804
+ async Reconnect(context) {
29805
+ if (!this.activeConfig) {
29806
+ throw new Error("ElevenLabsRealtimeClient: cannot reconnect before Connect");
29807
+ }
29808
+ if (context.Abandoned) {
29809
+ throw new Error("ElevenLabsRealtimeClient: reconnect attempt abandoned");
29810
+ }
29811
+ const refreshedConfig = {
29812
+ ...this.activeConfig,
29813
+ EphemeralToken: context.Credential.EphemeralToken || this.activeConfig.EphemeralToken,
29814
+ ExpiresAt: context.Credential.ExpiresAt || this.activeConfig.ExpiresAt,
29815
+ ...context.Credential.SessionConfig !== void 0 ? { SessionConfig: context.Credential.SessionConfig } : {}
29816
+ };
29817
+ this.activeConfig = refreshedConfig;
29818
+ const overrides = this.stripFirstMessageOverride(this.parseOverrides(refreshedConfig));
29819
+ const prevSocket = this.socket;
29820
+ let openSocket = null;
29821
+ let failOpen = null;
29822
+ let confirmMetadata = null;
29823
+ let failMetadata = null;
29824
+ const opened = new Promise((resolve, reject) => {
29825
+ openSocket = resolve;
29826
+ failOpen = reject;
29827
+ });
29828
+ const metadata = new Promise((resolve, reject) => {
29829
+ confirmMetadata = resolve;
29830
+ failMetadata = reject;
29831
+ });
29832
+ metadata.catch(() => void 0);
29833
+ const failConnect = (error) => {
29834
+ failOpen?.(error);
29835
+ failMetadata?.(error);
29836
+ };
29837
+ const nextSocket = this.createSocket(refreshedConfig.EphemeralToken);
29838
+ let nextSocketOpen = false;
29839
+ const onAbort = () => {
29840
+ failConnect(new Error("ElevenLabsRealtimeClient: reconnect attempt aborted"));
29841
+ try {
29842
+ nextSocket.close();
29843
+ } catch {
29844
+ }
29845
+ };
29846
+ if (context.Signal.aborted) {
29847
+ onAbort();
29848
+ throw new Error("ElevenLabsRealtimeClient: reconnect attempt aborted");
29849
+ }
29850
+ context.Signal.addEventListener("abort", onAbort, { once: true });
29851
+ nextSocket.onopen = () => {
29852
+ nextSocketOpen = true;
29853
+ openSocket?.();
29854
+ };
29855
+ nextSocket.onmessage = (data) => {
29856
+ if (this.socket === nextSocket) {
29857
+ this.handleSocketMessage(data);
29858
+ return;
29859
+ }
29860
+ try {
29861
+ const event = JSON.parse(data);
29862
+ if (event.type === "conversation_initiation_metadata") {
29863
+ confirmMetadata?.(event);
29864
+ confirmMetadata = null;
29865
+ }
29866
+ } catch {
29867
+ }
29868
+ };
29869
+ nextSocket.onerror = (message) => {
29870
+ nextSocketOpen = false;
29871
+ failConnect(new Error(message));
29872
+ if (this.socket === nextSocket && !this.IsReconnecting) {
29873
+ this.socketOpen = false;
29874
+ this.handleSocketError(message);
29875
+ }
29876
+ };
29877
+ nextSocket.onclose = () => {
29878
+ nextSocketOpen = false;
29879
+ failConnect(new Error("ElevenLabs conversation socket closed during reconnect"));
29880
+ if (this.socket === nextSocket && !this.IsReconnecting) {
29881
+ this.socketOpen = false;
29882
+ this.handleSocketClose();
29883
+ }
29884
+ };
29885
+ let metadataEvent;
29886
+ try {
29887
+ await opened;
29888
+ if (context.Abandoned) {
29889
+ throw new Error("ElevenLabsRealtimeClient: reconnect attempt abandoned after open");
29890
+ }
29891
+ nextSocket.send(JSON.stringify({ type: "conversation_initiation_client_data", conversation_config_override: overrides }));
29892
+ metadataEvent = await metadata;
29893
+ if (context.Abandoned) {
29894
+ throw new Error("ElevenLabsRealtimeClient: reconnect attempt abandoned after metadata");
29895
+ }
29896
+ } catch (err) {
29897
+ nextSocket.onopen = null;
29898
+ nextSocket.onmessage = null;
29899
+ nextSocket.onerror = null;
29900
+ nextSocket.onclose = null;
29901
+ try {
29902
+ nextSocket.close();
29903
+ } catch {
29904
+ }
29905
+ throw err;
29906
+ } finally {
29907
+ context.Signal.removeEventListener("abort", onAbort);
29908
+ }
29909
+ if (prevSocket) {
29910
+ prevSocket.onopen = null;
29911
+ prevSocket.onmessage = null;
29912
+ prevSocket.onerror = null;
29913
+ prevSocket.onclose = null;
29914
+ }
29915
+ this.socket = nextSocket;
29916
+ this.socketOpen = nextSocketOpen;
29917
+ const formats = metadataEvent.conversation_initiation_metadata_event;
29918
+ if (formats?.conversation_id) {
29919
+ this.RecordResumptionHandle(formats.conversation_id);
29920
+ }
29921
+ try {
29922
+ prevSocket?.close();
29923
+ } catch {
29924
+ }
29925
+ this.responseActive = false;
29926
+ this.activeResponseKind = "normal";
29927
+ if (context.ConversationSeed && context.ConversationSeed.Entries.length > 0) {
29928
+ const note = RenderRealtimeMemorySeedAsContextNote(context.ConversationSeed);
29929
+ if (note) {
29930
+ this.sendFrame({ type: "contextual_update", text: note });
29931
+ }
29932
+ }
29933
+ this.setState("listening");
29934
+ }
29935
+ stripFirstMessageOverride(overrides) {
29936
+ const agentObj = AsConfigRecord(overrides["agent"]);
29937
+ if (!agentObj || agentObj["first_message"] === void 0) {
29938
+ return overrides;
29939
+ }
29940
+ const { first_message: _dropped, ...restAgent } = agentObj;
29941
+ return {
29942
+ ...overrides,
29943
+ agent: restAgent
29944
+ };
29945
+ }
28024
29946
  // ── BaseRealtimeClient: outbound actions ──────────────────────────────────
28025
29947
  /**
28026
29948
  * Injects typed text as a `user_message` (the platform's "respond to this" trigger).
@@ -28034,7 +29956,7 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
28034
29956
  * turn takes the floor on its own; no explicit cancel frame exists or is needed.
28035
29957
  */
28036
29958
  SendText(text) {
28037
- if (!this.socket) {
29959
+ if (!this.socket || !this.socketOpen) {
28038
29960
  return;
28039
29961
  }
28040
29962
  this.CancelActiveResponse();
@@ -28051,7 +29973,7 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
28051
29973
  * `interruption`). No-op when nothing is active.
28052
29974
  */
28053
29975
  CancelActiveResponse() {
28054
- if (!this.socket) {
29976
+ if (!this.socket || !this.socketOpen) {
28055
29977
  return;
28056
29978
  }
28057
29979
  if (!this.responseActive && !this.IsAudioPlaying) {
@@ -28071,8 +29993,9 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
28071
29993
  * a response is in flight (the platform guarantees it never triggers or disturbs
28072
29994
  * generation), so unlike the Gemini driver no queueing applies.
28073
29995
  */
28074
- SendContextNote(text) {
28075
- if (!this.socket) {
29996
+ SendContextNote(text, options) {
29997
+ this.ConversationMemory.Record({ Kind: "note", Text: text, ...options });
29998
+ if (!this.socket || !this.socketOpen) {
28076
29999
  return;
28077
30000
  }
28078
30001
  this.sendFrame({ type: "contextual_update", text });
@@ -28085,14 +30008,14 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
28085
30008
  * the base contract's collision rule.
28086
30009
  */
28087
30010
  RequestSpokenUpdate(instructions) {
28088
- if (!this.socket) {
30011
+ if (!this.socket || !this.socketOpen) {
28089
30012
  return;
28090
30013
  }
28091
30014
  this.enqueueOrRun(() => this.sendUserMessage(instructions, "narration", false));
28092
30015
  }
28093
30016
  /** A spoken TURN: the same `user_message` trigger as the update, with the reply kept `normal` (MJ#4591). */
28094
30017
  RequestSpokenTurn(instructions) {
28095
- if (!this.socket) {
30018
+ if (!this.socket || !this.socketOpen) {
28096
30019
  return;
28097
30020
  }
28098
30021
  this.enqueueOrRun(() => this.sendUserMessage(instructions, "normal", false));
@@ -28105,15 +30028,21 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
28105
30028
  * otherwise queued behind the in-flight response (e.g. a progress narration) so the
28106
30029
  * trigger is never lost.
28107
30030
  */
28108
- SendToolResult(callID, outputJson) {
28109
- if (!this.socket) {
28110
- return;
30031
+ doSendToolResult(callID, outputJson) {
30032
+ if (!this.socket || !this.socketOpen) {
30033
+ return false;
28111
30034
  }
28112
30035
  if (!this.pendingToolCallIds.has(callID)) {
28113
30036
  console.warn(`ElevenLabsRealtimeClient.SendToolResult: no pending tool call '${callID}' \u2014 duplicate or unknown result dropped.`);
28114
- return;
30037
+ return false;
28115
30038
  }
28116
30039
  this.pendingToolCallIds.delete(callID);
30040
+ const name = this.resolveToolName(callID);
30041
+ if (this.callsFromBeforeReseed.delete(callID)) {
30042
+ this.sendFrame({ type: "contextual_update", text: RenderLateToolResultNote(name, outputJson) });
30043
+ this.enqueueOrRun(() => this.sendUserMessage(`Please continue with the tool result for ${name}.`, "normal", false));
30044
+ return;
30045
+ }
28117
30046
  this.enqueueOrRun(() => this.sendToolResultFrame(callID, outputJson));
28118
30047
  }
28119
30048
  /**
@@ -28221,13 +30150,13 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
28221
30150
  }
28222
30151
  /** Streams one base64 PCM16 mic chunk as a bare-key `user_audio_chunk` frame. */
28223
30152
  sendMicChunk(base64Pcm16) {
28224
- if (this.socket) {
30153
+ if (this.socket && this.socketOpen) {
28225
30154
  this.sendFrame({ user_audio_chunk: base64Pcm16 });
28226
30155
  }
28227
30156
  }
28228
30157
  /** Surfaces a fatal socket error and marks the session unusable (obligation #6). */
28229
30158
  handleSocketError(message) {
28230
- if (this.currentState === "error" || this.currentState === "closed") {
30159
+ if (this.IsReconnecting || this.currentState === "error" || this.currentState === "closed") {
28231
30160
  return;
28232
30161
  }
28233
30162
  this.emitError({ Message: `ElevenLabs realtime transport error: ${message}`, Fatal: true });
@@ -28239,7 +30168,7 @@ var ElevenLabsRealtimeClient = class ElevenLabsRealtimeClient2 extends BaseRealt
28239
30168
  * credential / conversation death reaches the host (obligation #6).
28240
30169
  */
28241
30170
  handleSocketClose() {
28242
- if (this.closedByConsumer || this.currentState === "error" || this.currentState === "closed") {
30171
+ if (this.closedByConsumer || this.IsReconnecting || this.currentState === "error" || this.currentState === "closed") {
28243
30172
  return;
28244
30173
  }
28245
30174
  this.emitError({ Message: "ElevenLabs conversation closed unexpectedly", Fatal: true });
@@ -28514,6 +30443,7 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28514
30443
  constructor() {
28515
30444
  super(...arguments);
28516
30445
  this.socket = null;
30446
+ this.socketOpen = false;
28517
30447
  this.micStream = null;
28518
30448
  this.micCapture = null;
28519
30449
  this.playback = null;
@@ -28527,10 +30457,15 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28527
30457
  this.connectUrl = null;
28528
30458
  this.resumeAttempted = false;
28529
30459
  this.currentState = "closed";
30460
+ this.initialBasePrompt = "";
28530
30461
  this.basePrompt = "";
28531
30462
  this.contextNotes = [];
30463
+ this.activeConfig = null;
28532
30464
  this.onSessionReady = null;
28533
30465
  }
30466
+ get DefaultCallDurationSeconds() {
30467
+ return void 0;
30468
+ }
28534
30469
  // ── BaseRealtimeClient: connection lifecycle ───────────────────────────────
28535
30470
  /**
28536
30471
  * Opens the client-direct session: socket to the token-authenticated endpoint, the
@@ -28540,11 +30475,15 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28540
30475
  */
28541
30476
  async Connect(config, micStream) {
28542
30477
  this.AssertTransportSupported(config);
30478
+ this.ApplySessionConfigTiming(config);
30479
+ this.activeConfig = config;
28543
30480
  this.micStream = micStream;
28544
30481
  this.closedByConsumer = false;
30482
+ this.socketOpen = false;
28545
30483
  this.setState("connecting");
28546
30484
  const sessionObject = this.parseSessionObject(config);
28547
- this.basePrompt = typeof sessionObject["system_prompt"] === "string" ? sessionObject["system_prompt"] : "";
30485
+ this.initialBasePrompt = typeof sessionObject["system_prompt"] === "string" ? sessionObject["system_prompt"] : "";
30486
+ this.basePrompt = this.initialBasePrompt;
28548
30487
  this.contextNotes = [];
28549
30488
  let openSocket = null;
28550
30489
  let failOpen = null;
@@ -28569,15 +30508,38 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28569
30508
  this.resumeAttempted = false;
28570
30509
  const socket = this.createSocket(this.connectUrl);
28571
30510
  this.socket = socket;
28572
- socket.onopen = () => openSocket?.();
28573
- socket.onmessage = (data) => this.handleSocketMessage(data);
30511
+ socket.onopen = () => {
30512
+ if (this.socket !== socket) {
30513
+ return;
30514
+ }
30515
+ this.socketOpen = true;
30516
+ openSocket?.();
30517
+ };
30518
+ socket.onmessage = (data) => {
30519
+ if (this.socket !== socket) {
30520
+ return;
30521
+ }
30522
+ this.handleSocketMessage(data);
30523
+ };
28574
30524
  socket.onerror = (message) => {
30525
+ if (this.socket !== socket) {
30526
+ return;
30527
+ }
30528
+ this.socketOpen = false;
28575
30529
  failConnect(new Error(message));
28576
- this.handleSocketError(message);
30530
+ if (!this.IsReconnecting) {
30531
+ this.handleSocketError(message);
30532
+ }
28577
30533
  };
28578
30534
  socket.onclose = () => {
30535
+ if (this.socket !== socket) {
30536
+ return;
30537
+ }
30538
+ this.socketOpen = false;
28579
30539
  failConnect(new Error("AssemblyAI agent socket closed during connect"));
28580
- this.handleSocketClose();
30540
+ if (!this.IsReconnecting) {
30541
+ this.handleSocketClose();
30542
+ }
28581
30543
  };
28582
30544
  await opened;
28583
30545
  this.setState("connected");
@@ -28588,6 +30550,7 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28588
30550
  this.micCapture = await this.createMicCapture(micStream, ASSEMBLYAI_PCM_SAMPLE_RATE, (base64Pcm16) => this.sendMicChunk(base64Pcm16));
28589
30551
  this.attachOutputAudioMeter(this.playback?.CreateMeter?.() ?? null);
28590
30552
  this.attachInputAudioMeter(RealtimeAudioMeter.ForMicStream(micStream));
30553
+ this.ArmConnectionDurationTimer();
28591
30554
  this.setState("listening");
28592
30555
  }
28593
30556
  /**
@@ -28598,6 +30561,9 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28598
30561
  */
28599
30562
  async Disconnect() {
28600
30563
  this.closedByConsumer = true;
30564
+ this.socketOpen = false;
30565
+ this.DisposeReconnectTimers();
30566
+ this.activeConfig = null;
28601
30567
  this.closeAudioMeters();
28602
30568
  this.micStream?.getTracks().forEach((track) => track.stop());
28603
30569
  this.micStream = null;
@@ -28607,21 +30573,195 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28607
30573
  this.playback = null;
28608
30574
  this.clearRemoteMediaStream();
28609
30575
  if (this.socket) {
30576
+ const s = this.socket;
30577
+ this.socket = null;
30578
+ s.onopen = null;
30579
+ s.onmessage = null;
30580
+ s.onerror = null;
30581
+ s.onclose = null;
28610
30582
  try {
28611
- this.socket.send(JSON.stringify({ type: "session.end" }));
30583
+ s.send(JSON.stringify({ type: "session.end" }));
28612
30584
  } catch {
28613
30585
  }
28614
30586
  try {
28615
- this.socket.close();
30587
+ s.close();
28616
30588
  } catch {
28617
30589
  }
28618
- this.socket = null;
28619
30590
  }
28620
30591
  this.resetResponseState();
28621
30592
  if (this.currentState !== "error") {
28622
30593
  this.setState("closed");
28623
30594
  }
28624
30595
  }
30596
+ /**
30597
+ * Re-establishes the AssemblyAI Voice Agent session on a fresh credential/socket while
30598
+ * keeping the local mic capture and playback pipeline intact. When `UseNativeResumption`
30599
+ * is true and a `ResumptionHandle` (`session_id`) is available, attempts `session.resume`;
30600
+ * otherwise starts a fresh session and seeds prior conversation memory into `system_prompt`
30601
+ * via `RenderRealtimeMemorySeedAsContextNote`.
30602
+ */
30603
+ async Reconnect(context) {
30604
+ const baseConfig = this.activeConfig;
30605
+ if (!baseConfig) {
30606
+ throw new Error("AssemblyAIRealtimeClient.Reconnect: no session config available.");
30607
+ }
30608
+ if (context.Abandoned) {
30609
+ throw new Error("AssemblyAIRealtimeClient.Reconnect: reconnect attempt abandoned.");
30610
+ }
30611
+ const config = {
30612
+ ...baseConfig,
30613
+ EphemeralToken: context.Credential.EphemeralToken || baseConfig.EphemeralToken,
30614
+ ExpiresAt: context.Credential.ExpiresAt || baseConfig.ExpiresAt,
30615
+ ...context.Credential.RelayUrl ? { RelayUrl: context.Credential.RelayUrl } : {},
30616
+ SessionConfig: context.Credential.SessionConfig ?? baseConfig.SessionConfig
30617
+ };
30618
+ const prevSocket = this.socket;
30619
+ const useNativeResume = context.UseNativeResumption && Boolean(context.ResumptionHandle);
30620
+ const sessionObject = { ...this.parseSessionObject(config) };
30621
+ delete sessionObject["greeting"];
30622
+ const nextInitialBasePrompt = typeof sessionObject["system_prompt"] === "string" ? sessionObject["system_prompt"] : this.initialBasePrompt;
30623
+ const notesAtAttemptStart = new Set(this.contextNotes);
30624
+ const seedNote = !useNativeResume && context.Seed.Entries.length > 0 ? RenderRealtimeMemorySeedAsContextNote(context.Seed) : null;
30625
+ const nextBasePrompt = seedNote ? nextInitialBasePrompt ? `${nextInitialBasePrompt}
30626
+
30627
+ ${seedNote}` : seedNote : nextInitialBasePrompt;
30628
+ const carryOverNotes = seedNote ? [] : this.contextNotes.filter((n) => !n.Ephemeral);
30629
+ sessionObject["system_prompt"] = carryOverNotes.length === 0 ? nextBasePrompt : `${nextBasePrompt}
30630
+
30631
+ ## Background updates
30632
+ ${carryOverNotes.map((n) => `- ${n.Text}`).join("\n")}`;
30633
+ let openSocket = null;
30634
+ let failOpen = null;
30635
+ let confirmReady = null;
30636
+ let failReady = null;
30637
+ const opened = new Promise((resolve, reject) => {
30638
+ openSocket = resolve;
30639
+ failOpen = reject;
30640
+ });
30641
+ const ready = new Promise((resolve, reject) => {
30642
+ confirmReady = resolve;
30643
+ failReady = reject;
30644
+ });
30645
+ ready.catch(() => void 0);
30646
+ const failConnect = (error) => {
30647
+ failOpen?.(error);
30648
+ failReady?.(error);
30649
+ };
30650
+ const nextConnectUrl = `${ASSEMBLYAI_AGENT_WS_URL}?token=${encodeURIComponent(config.EphemeralToken)}`;
30651
+ const nextSocket = this.createSocket(nextConnectUrl);
30652
+ let nextSocketOpen = false;
30653
+ let nextProviderSessionId = null;
30654
+ const onAbort = () => {
30655
+ failConnect(new Error("AssemblyAIRealtimeClient: reconnect attempt aborted"));
30656
+ try {
30657
+ nextSocket.close();
30658
+ } catch {
30659
+ }
30660
+ };
30661
+ if (context.Signal.aborted) {
30662
+ onAbort();
30663
+ throw new Error("AssemblyAIRealtimeClient: reconnect attempt aborted");
30664
+ }
30665
+ context.Signal.addEventListener("abort", onAbort, { once: true });
30666
+ nextSocket.onopen = () => {
30667
+ nextSocketOpen = true;
30668
+ openSocket?.();
30669
+ };
30670
+ nextSocket.onmessage = (data) => {
30671
+ if (this.socket === nextSocket) {
30672
+ this.handleSocketMessage(data);
30673
+ return;
30674
+ }
30675
+ try {
30676
+ const event = JSON.parse(data);
30677
+ if (event.type === "session.ready") {
30678
+ if (event.session_id) {
30679
+ nextProviderSessionId = event.session_id;
30680
+ }
30681
+ confirmReady?.();
30682
+ confirmReady = null;
30683
+ }
30684
+ } catch {
30685
+ }
30686
+ };
30687
+ nextSocket.onerror = (message) => {
30688
+ nextSocketOpen = false;
30689
+ failConnect(new Error(message));
30690
+ if (this.socket === nextSocket && !this.IsReconnecting) {
30691
+ this.socketOpen = false;
30692
+ this.handleSocketError(message);
30693
+ }
30694
+ };
30695
+ nextSocket.onclose = () => {
30696
+ nextSocketOpen = false;
30697
+ failConnect(new Error("AssemblyAI agent socket closed during reconnect"));
30698
+ if (this.socket === nextSocket && !this.IsReconnecting) {
30699
+ this.socketOpen = false;
30700
+ this.handleSocketClose();
30701
+ }
30702
+ };
30703
+ try {
30704
+ await opened;
30705
+ if (context.Abandoned) {
30706
+ throw new Error("AssemblyAIRealtimeClient: reconnect attempt abandoned after open");
30707
+ }
30708
+ if (useNativeResume && context.ResumptionHandle) {
30709
+ nextSocket.send(JSON.stringify({ type: "session.resume", session_id: context.ResumptionHandle }));
30710
+ } else {
30711
+ nextSocket.send(JSON.stringify({ type: "session.update", session: sessionObject }));
30712
+ }
30713
+ await ready;
30714
+ if (context.Abandoned) {
30715
+ throw new Error("AssemblyAIRealtimeClient: reconnect attempt abandoned after session.ready");
30716
+ }
30717
+ } catch (err) {
30718
+ nextSocket.onopen = null;
30719
+ nextSocket.onmessage = null;
30720
+ nextSocket.onerror = null;
30721
+ nextSocket.onclose = null;
30722
+ try {
30723
+ nextSocket.close();
30724
+ } catch {
30725
+ }
30726
+ throw err;
30727
+ } finally {
30728
+ context.Signal.removeEventListener("abort", onAbort);
30729
+ }
30730
+ if (prevSocket) {
30731
+ prevSocket.onopen = null;
30732
+ prevSocket.onmessage = null;
30733
+ prevSocket.onerror = null;
30734
+ prevSocket.onclose = null;
30735
+ }
30736
+ this.activeConfig = config;
30737
+ this.ApplySessionConfigTiming(config);
30738
+ if (!useNativeResume) {
30739
+ for (const callID of this.pendingToolCallIds) {
30740
+ this.callsFromBeforeReseed.add(callID);
30741
+ }
30742
+ }
30743
+ const arrivedDuringAttempt = this.contextNotes.filter((n) => !notesAtAttemptStart.has(n));
30744
+ this.contextNotes = seedNote ? arrivedDuringAttempt : [...carryOverNotes, ...arrivedDuringAttempt];
30745
+ this.initialBasePrompt = nextInitialBasePrompt;
30746
+ this.basePrompt = nextBasePrompt;
30747
+ this.connectUrl = nextConnectUrl;
30748
+ this.resumeAttempted = false;
30749
+ this.socket = nextSocket;
30750
+ this.socketOpen = nextSocketOpen;
30751
+ if (nextProviderSessionId) {
30752
+ this.providerSessionId = nextProviderSessionId;
30753
+ this.RecordResumptionHandle(nextProviderSessionId);
30754
+ }
30755
+ try {
30756
+ prevSocket?.close();
30757
+ } catch {
30758
+ }
30759
+ this.responseActive = false;
30760
+ this.suppressReplyAudio = false;
30761
+ this.activeResponseKind = "normal";
30762
+ this.flushQueuedSends();
30763
+ this.setState("listening");
30764
+ }
28625
30765
  // ── BaseRealtimeClient: outbound actions ──────────────────────────────────
28626
30766
  /**
28627
30767
  * Injects typed text — EMULATED via `reply.create` (the protocol accepts no typed user
@@ -28634,7 +30774,7 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28634
30774
  * queued send starts a new reply, the text queues behind it, preserving delivery order.
28635
30775
  */
28636
30776
  SendText(text) {
28637
- if (!this.socket) {
30777
+ if (!this.socket || !this.socketOpen) {
28638
30778
  return;
28639
30779
  }
28640
30780
  this.CancelActiveResponse();
@@ -28651,7 +30791,7 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28651
30791
  * delivery is never dropped by a cancel). No-op when nothing is active.
28652
30792
  */
28653
30793
  CancelActiveResponse() {
28654
- if (!this.socket) {
30794
+ if (!this.socket || !this.socketOpen) {
28655
30795
  return;
28656
30796
  }
28657
30797
  if (!this.responseActive && !this.IsAudioPlaying) {
@@ -28674,12 +30814,29 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28674
30814
  * `session.update`. A config write never triggers or disturbs generation, so it is sent
28675
30815
  * immediately even while a reply is in flight (no queueing applies).
28676
30816
  */
28677
- SendContextNote(text) {
28678
- if (!this.socket) {
30817
+ SendContextNote(text, options) {
30818
+ if ((!this.socket || !this.socketOpen) && !this.IsReconnecting) {
28679
30819
  return;
28680
30820
  }
28681
- this.contextNotes.push(text);
28682
- this.sendFrame({ type: "session.update", session: { system_prompt: this.composePromptWithNotes() } });
30821
+ this.ConversationMemory.Record({ Kind: "note", Text: text, ...options });
30822
+ const stateKey = options?.StateKey?.trim();
30823
+ if (stateKey) {
30824
+ const storedText = options?.MemoryText ?? text;
30825
+ this.contextNotes = this.contextNotes.filter((n) => n.StateKey !== stateKey);
30826
+ if (storedText.trim().length > 0 && !options?.Ephemeral) {
30827
+ this.contextNotes.push({ Text: storedText, StateKey: stateKey });
30828
+ }
30829
+ } else if (options?.Ephemeral) {
30830
+ this.contextNotes = this.contextNotes.filter((n) => !n.Ephemeral);
30831
+ this.contextNotes.push({ Text: text, Ephemeral: true });
30832
+ } else {
30833
+ this.contextNotes.push({ Text: text });
30834
+ }
30835
+ if (this.socket && this.socketOpen) {
30836
+ this.sendFrame({ type: "session.update", session: { system_prompt: this.composePromptWithNotes() } });
30837
+ } else if (this.IsReconnecting) {
30838
+ this.queuedSends.push(() => this.sendFrame({ type: "session.update", session: { system_prompt: this.composePromptWithNotes() } }));
30839
+ }
28683
30840
  }
28684
30841
  /**
28685
30842
  * Triggers ONE short spoken update — NATIVE via `reply.create` with per-response
@@ -28688,14 +30845,14 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28688
30845
  * collision rule (an overlapping `reply.create` would collide with active generation).
28689
30846
  */
28690
30847
  RequestSpokenUpdate(instructions) {
28691
- if (!this.socket) {
30848
+ if (!this.socket || !this.socketOpen) {
28692
30849
  return;
28693
30850
  }
28694
30851
  this.enqueueOrRun(() => this.sendReplyCreate(instructions, "narration", false));
28695
30852
  }
28696
30853
  /** A spoken TURN: the same reply trigger as the update, with the reply kept `normal` (MJ#4591). */
28697
30854
  RequestSpokenTurn(instructions) {
28698
- if (!this.socket) {
30855
+ if (!this.socket || !this.socketOpen) {
28699
30856
  return;
28700
30857
  }
28701
30858
  this.enqueueOrRun(() => this.sendReplyCreate(instructions, "normal", false));
@@ -28710,15 +30867,20 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28710
30867
  * not clobbered. The wire `result` slot expects a JSON-STRING, which is exactly the
28711
30868
  * contract's `outputJson` shape — it passes through verbatim.
28712
30869
  */
28713
- SendToolResult(callID, outputJson) {
28714
- if (!this.socket) {
28715
- return;
30870
+ doSendToolResult(callID, outputJson) {
30871
+ if (!this.socket || !this.socketOpen) {
30872
+ return false;
28716
30873
  }
28717
30874
  if (!this.pendingToolCallIds.has(callID)) {
28718
30875
  console.warn(`AssemblyAIRealtimeClient.SendToolResult: no pending tool call '${callID}' \u2014 duplicate or unknown result dropped.`);
28719
- return;
30876
+ return false;
28720
30877
  }
28721
30878
  this.pendingToolCallIds.delete(callID);
30879
+ const name = this.resolveToolName(callID);
30880
+ if (this.callsFromBeforeReseed.delete(callID)) {
30881
+ this.enqueueOrRun(() => this.sendReplyCreate(RenderLateToolResultNote(name, outputJson), "normal", true));
30882
+ return;
30883
+ }
28722
30884
  this.enqueueOrRun(() => this.sendToolResultFrame(callID, outputJson));
28723
30885
  }
28724
30886
  /**
@@ -28809,13 +30971,13 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28809
30971
  }
28810
30972
  /** Streams one base64 PCM16 mic chunk as an `input.audio` frame. */
28811
30973
  sendMicChunk(base64Pcm16) {
28812
- if (this.socket) {
30974
+ if (this.socket && this.socketOpen) {
28813
30975
  this.sendFrame({ type: "input.audio", audio: base64Pcm16 });
28814
30976
  }
28815
30977
  }
28816
30978
  /** Surfaces a fatal socket error and marks the session unusable (obligation #6). */
28817
30979
  handleSocketError(message) {
28818
- if (this.currentState === "error" || this.currentState === "closed") {
30980
+ if (this.IsReconnecting || this.currentState === "error" || this.currentState === "closed") {
28819
30981
  return;
28820
30982
  }
28821
30983
  this.emitError({ Message: `AssemblyAI realtime transport error: ${message}`, Fatal: true });
@@ -28827,7 +30989,7 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28827
30989
  * session death reaches the host (obligation #6).
28828
30990
  */
28829
30991
  handleSocketClose() {
28830
- if (this.closedByConsumer || this.currentState === "error" || this.currentState === "closed") {
30992
+ if (this.closedByConsumer || this.IsReconnecting || this.currentState === "error" || this.currentState === "closed") {
28831
30993
  return;
28832
30994
  }
28833
30995
  if (this.tryResumeSession()) {
@@ -28855,10 +31017,34 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28855
31017
  try {
28856
31018
  const socket = this.createSocket(this.connectUrl);
28857
31019
  this.socket = socket;
28858
- socket.onopen = () => this.sendFrame({ type: "session.resume", session_id: sessionId });
28859
- socket.onmessage = (data) => this.handleSocketMessage(data);
28860
- socket.onerror = (message) => this.handleSocketError(message);
28861
- socket.onclose = () => this.handleSocketClose();
31020
+ this.socketOpen = false;
31021
+ socket.onopen = () => {
31022
+ if (this.socket !== socket) {
31023
+ return;
31024
+ }
31025
+ this.socketOpen = true;
31026
+ this.sendFrame({ type: "session.resume", session_id: sessionId });
31027
+ };
31028
+ socket.onmessage = (data) => {
31029
+ if (this.socket !== socket) {
31030
+ return;
31031
+ }
31032
+ this.handleSocketMessage(data);
31033
+ };
31034
+ socket.onerror = (message) => {
31035
+ if (this.socket !== socket) {
31036
+ return;
31037
+ }
31038
+ this.socketOpen = false;
31039
+ this.handleSocketError(message);
31040
+ };
31041
+ socket.onclose = () => {
31042
+ if (this.socket !== socket) {
31043
+ return;
31044
+ }
31045
+ this.socketOpen = false;
31046
+ this.handleSocketClose();
31047
+ };
28862
31048
  this.onSessionReady = () => this.setState("listening");
28863
31049
  return true;
28864
31050
  } catch {
@@ -28881,6 +31067,9 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
28881
31067
  switch (event.type) {
28882
31068
  case "session.ready":
28883
31069
  this.providerSessionId = event.session_id ?? this.providerSessionId;
31070
+ if (event.session_id) {
31071
+ this.RecordResumptionHandle(event.session_id);
31072
+ }
28884
31073
  this.onSessionReady?.();
28885
31074
  this.onSessionReady = null;
28886
31075
  break;
@@ -29108,7 +31297,7 @@ var AssemblyAIRealtimeClient = class AssemblyAIRealtimeClient2 extends BaseRealt
29108
31297
  return `${this.basePrompt}
29109
31298
 
29110
31299
  ## Background updates
29111
- ${this.contextNotes.map((n) => `- ${n}`).join("\n")}`;
31300
+ ${this.contextNotes.map((n) => `- ${n.Text}`).join("\n")}`;
29112
31301
  }
29113
31302
  /** JSON-serializes and sends one client frame (no-op once the socket is gone). */
29114
31303
  sendFrame(frame) {
@@ -29121,6 +31310,7 @@ ${this.contextNotes.map((n) => `- ${n}`).join("\n")}`;
29121
31310
  this.queuedSends = [];
29122
31311
  this.suppressReplyAudio = false;
29123
31312
  this.pendingToolCallIds.clear();
31313
+ this.callsFromBeforeReseed.clear();
29124
31314
  this.onSessionReady = null;
29125
31315
  this.contextNotes = [];
29126
31316
  }
@@ -29155,10 +31345,38 @@ var xAIRealtimeClient = class xAIRealtimeClient2 extends OpenAIProtocolWebSocket
29155
31345
  get providerDebugLabel() {
29156
31346
  return "xAIRealtimeClient";
29157
31347
  }
31348
+ get DefaultCallDurationSeconds() {
31349
+ return 7200;
31350
+ }
31351
+ /**
31352
+ * Defaults to `false`: xAI's `?conversation_id=<id>` server-side resumption currently drops
31353
+ * `conversation.item.create` `message` items (`SendContextNote`, `SendText`, and post-drop
31354
+ * `seedConversationAfterMove` history), causing Grok Voice to forget injected context and
31355
+ * replayed turns across reconnects. Text-seed replay into a fresh conversation preserves both
31356
+ * spoken and injected turns losslessly; callers can still opt into native resumption explicitly
31357
+ * via `TrustNativeResumption: true` on `ClientRealtimeSessionConfig`.
31358
+ */
31359
+ get DefaultTrustsNativeResumption() {
31360
+ return false;
31361
+ }
29158
31362
  // ── Transport hooks ────────────────────────────────────────────────────────
31363
+ resolveSessionObject(config) {
31364
+ const sessionObj = super.resolveSessionObject(config);
31365
+ const explicitlyTrusted = config.TrustNativeResumption === true || config.SessionConfig?.["trustNativeResumption"] === true || config.SessionConfig?.["TrustNativeResumption"] === true;
31366
+ if (explicitlyTrusted && this.TrustsNativeResumption && Object.keys(sessionObj).length > 0 && sessionObj["resumption"] === void 0) {
31367
+ return {
31368
+ ...sessionObj,
31369
+ resumption: { enabled: true }
31370
+ };
31371
+ }
31372
+ return sessionObj;
31373
+ }
29159
31374
  /** @inheritdoc — model on the URL, ephemeral secret as the subprotocol. */
29160
- openProviderSocket(config) {
29161
- const url = `${XAI_REALTIME_WS_URL}?model=${encodeURIComponent(config.Model)}`;
31375
+ openProviderSocket(config, resumptionHandle) {
31376
+ let url = `${XAI_REALTIME_WS_URL}?model=${encodeURIComponent(config.Model)}`;
31377
+ if (resumptionHandle && resumptionHandle.trim().length > 0) {
31378
+ url += `&conversation_id=${encodeURIComponent(resumptionHandle.trim())}`;
31379
+ }
29162
31380
  const subprotocol = `${XAI_CLIENT_SECRET_SUBPROTOCOL_PREFIX}${config.EphemeralToken}`;
29163
31381
  return this.createSocket(url, subprotocol);
29164
31382
  }
@@ -29295,6 +31513,9 @@ var ElevenRealtimeClient = class ElevenRealtimeClient2 extends OpenAIProtocolWeb
29295
31513
  get providerDebugLabel() {
29296
31514
  return "ElevenRealtimeClient";
29297
31515
  }
31516
+ get DefaultCallDurationSeconds() {
31517
+ return void 0;
31518
+ }
29298
31519
  // ── Transport hooks ────────────────────────────────────────────────────────
29299
31520
  /** @inheritdoc — model on the URL, client secret in the OpenAI-SDK subprotocol slot. */
29300
31521
  openProviderSocket(config) {
@@ -29397,17 +31618,32 @@ var HuggingFaceRealtimeClient = class HuggingFaceRealtimeClient2 extends OpenAIP
29397
31618
  const raw = config.SessionConfig?.["sampleRate"];
29398
31619
  return typeof raw === "number" && raw > 0 ? raw : HUGGINGFACE_DEFAULT_PCM_SAMPLE_RATE;
29399
31620
  }
31621
+ /**
31622
+ * @inheritdoc
31623
+ *
31624
+ * Off: the proxy hop closes benignly and the host reads `'closed'` as the end of the session
31625
+ * (see {@link handleSocketClose}), so a lost socket does not start a reconnect and a socket
31626
+ * error stays fatal. A loss during a planned move still goes to that move's reconnect.
31627
+ */
31628
+ get RecoversLostTransport() {
31629
+ return false;
31630
+ }
29400
31631
  /**
29401
31632
  * @inheritdoc
29402
31633
  *
29403
31634
  * A close the consumer didn't ask for is reported as a terminal `'closed'` — NOT the fatal
29404
31635
  * error the cloud providers surface: the self-hosted proxy hop closes benignly (ticket
29405
31636
  * expiry, upstream restart), and the host treats `'closed'` as the session-over signal.
31637
+ * During a planned move the closed socket is the one the move may go back to, so the move's
31638
+ * reconnect takes the loss and the call goes on (`recoverLostTransport` answers `true` only then).
29406
31639
  */
29407
31640
  handleSocketClose() {
29408
31641
  if (this.closedByConsumer) {
29409
31642
  return;
29410
31643
  }
31644
+ if (this.recoverLostTransport("socket closed")) {
31645
+ return;
31646
+ }
29411
31647
  if (this.currentState !== "error") {
29412
31648
  this.setState("closed");
29413
31649
  }
@@ -29455,6 +31691,7 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29455
31691
  this.micStream = null;
29456
31692
  this.micSenders = [];
29457
31693
  this.sessionConfig = null;
31694
+ this.activeConfig = null;
29458
31695
  this.currentState = "closed";
29459
31696
  this.responseActive = false;
29460
31697
  this.audioPlaying = false;
@@ -29492,6 +31729,9 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29492
31729
  static {
29493
31730
  this.MAX_OUTBOUND_QUEUE_SIZE = 100;
29494
31731
  }
31732
+ get DefaultCallDurationSeconds() {
31733
+ return 3600;
31734
+ }
29495
31735
  // ── BaseRealtimeClient implementation ──────────────────────────────────────
29496
31736
  get IsBusy() {
29497
31737
  return this.responseActive;
@@ -29510,6 +31750,8 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29510
31750
  */
29511
31751
  async Connect(config, micStream, _cameraStream) {
29512
31752
  this.AssertTransportSupported(config);
31753
+ this.ApplySessionConfigTiming(config);
31754
+ this.activeConfig = config;
29513
31755
  this.sessionConfig = config.SessionConfig;
29514
31756
  this.micStream = micStream;
29515
31757
  this.setState("connecting");
@@ -29525,6 +31767,7 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29525
31767
  await this.waitForIceGatheringComplete(pc);
29526
31768
  const answerSdp = await this.postSdpOffer(offer.sdp ?? "", config);
29527
31769
  await pc.setRemoteDescription({ type: "answer", sdp: answerSdp });
31770
+ this.ArmConnectionDurationTimer();
29528
31771
  this.setState("connected");
29529
31772
  this.totalDurationSeconds = OpenAILiveClient_1.PREBILL_DURATION_SECONDS;
29530
31773
  this.emitUsage({
@@ -29537,6 +31780,7 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29537
31780
  * Tears down the connection, data channel, audio tracks, and audio sink.
29538
31781
  */
29539
31782
  async Disconnect() {
31783
+ this.DisposeReconnectTimers();
29540
31784
  this.finalizeUserTranscript();
29541
31785
  this.finalizeAssistantTranscript();
29542
31786
  this.closeAudioMeters();
@@ -29564,6 +31808,7 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29564
31808
  }
29565
31809
  this.clearRemoteMediaStream();
29566
31810
  this.sessionConfig = null;
31811
+ this.activeConfig = null;
29567
31812
  this.responseActive = false;
29568
31813
  this.audioPlaying = false;
29569
31814
  this.pendingNarration = false;
@@ -29578,6 +31823,159 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29578
31823
  this.setState("closed");
29579
31824
  }
29580
31825
  }
31826
+ async Reconnect(context) {
31827
+ if (!this.activeConfig || !this.micStream) {
31828
+ throw new Error("OpenAILiveClient: cannot reconnect before Connect");
31829
+ }
31830
+ if (context.Abandoned) {
31831
+ throw new Error("OpenAILiveClient: reconnect attempt abandoned");
31832
+ }
31833
+ const refreshedConfig = {
31834
+ ...this.activeConfig,
31835
+ EphemeralToken: context.Credential.EphemeralToken || this.activeConfig.EphemeralToken,
31836
+ ExpiresAt: context.Credential.ExpiresAt || this.activeConfig.ExpiresAt,
31837
+ ...context.Credential.RelayUrl !== void 0 ? { RelayUrl: context.Credential.RelayUrl } : {},
31838
+ ...context.Credential.SessionConfig !== void 0 ? { SessionConfig: context.Credential.SessionConfig } : {}
31839
+ };
31840
+ this.activeConfig = refreshedConfig;
31841
+ this.sessionConfig = refreshedConfig.SessionConfig;
31842
+ const prevPc = this.peerConnection;
31843
+ const prevDc = this.dataChannel;
31844
+ const nextPc = this.createPeerConnection();
31845
+ const nextSenders = this.micStream.getAudioTracks().map((track) => nextPc.addTrack(track, this.micStream));
31846
+ if (!this.remoteAudioEl) {
31847
+ this.remoteAudioEl = this.createAudioSink();
31848
+ }
31849
+ let pendingRemoteStream = null;
31850
+ nextPc.ontrack = (e) => {
31851
+ if (context.Abandoned || !e.streams[0]) {
31852
+ return;
31853
+ }
31854
+ if (this.peerConnection === nextPc && this.remoteAudioEl) {
31855
+ this.remoteAudioEl.srcObject = e.streams[0];
31856
+ this.publishRemoteMediaStream(e.streams[0]);
31857
+ this.attachOutputAudioMeter(RealtimeAudioMeter.ForStream(e.streams[0]));
31858
+ } else {
31859
+ pendingRemoteStream = e.streams[0];
31860
+ }
31861
+ };
31862
+ const nextDc = nextPc.createDataChannel("oai-events");
31863
+ let openDc = null;
31864
+ let failDc = null;
31865
+ const dcOpened = new Promise((resolve, reject) => {
31866
+ openDc = resolve;
31867
+ failDc = reject;
31868
+ });
31869
+ dcOpened.catch(() => void 0);
31870
+ const onAbort = () => {
31871
+ failDc?.(new Error("OpenAILiveClient: reconnect attempt aborted"));
31872
+ try {
31873
+ nextDc.close();
31874
+ } catch {
31875
+ }
31876
+ try {
31877
+ nextPc.close();
31878
+ } catch {
31879
+ }
31880
+ };
31881
+ if (context.Signal.aborted) {
31882
+ onAbort();
31883
+ throw new Error("OpenAILiveClient: reconnect attempt aborted");
31884
+ }
31885
+ context.Signal.addEventListener("abort", onAbort, { once: true });
31886
+ nextDc.onopen = () => {
31887
+ openDc?.();
31888
+ if (this.dataChannel === nextDc) {
31889
+ this.flushOutboundQueue();
31890
+ }
31891
+ };
31892
+ nextDc.onmessage = (e) => {
31893
+ if (this.dataChannel === nextDc) {
31894
+ this.handleDataChannelMessage(String(e.data));
31895
+ }
31896
+ };
31897
+ nextDc.onerror = (e) => {
31898
+ failDc?.(new Error(`OpenAI Live data channel error: ${String(e)}`));
31899
+ this.handleChannelError(nextDc, e);
31900
+ };
31901
+ nextDc.onclose = () => {
31902
+ failDc?.(new Error("OpenAI Live data channel closed during reconnect"));
31903
+ this.handleChannelClose(nextDc);
31904
+ };
31905
+ try {
31906
+ const offer = await nextPc.createOffer();
31907
+ await nextPc.setLocalDescription(offer);
31908
+ await this.waitForIceGatheringComplete(nextPc);
31909
+ if (context.Abandoned) {
31910
+ throw new Error("OpenAILiveClient: reconnect attempt abandoned before SDP exchange");
31911
+ }
31912
+ const answerSdp = await this.postSdpOffer(offer.sdp ?? "", refreshedConfig);
31913
+ await nextPc.setRemoteDescription({ type: "answer", sdp: answerSdp });
31914
+ if (nextDc.readyState !== "open") {
31915
+ await dcOpened;
31916
+ }
31917
+ if (context.Abandoned) {
31918
+ throw new Error("OpenAILiveClient: reconnect attempt abandoned after open");
31919
+ }
31920
+ } catch (err) {
31921
+ nextDc.onopen = null;
31922
+ nextDc.onmessage = null;
31923
+ nextDc.onerror = null;
31924
+ nextDc.onclose = null;
31925
+ nextPc.ontrack = null;
31926
+ try {
31927
+ nextDc.close();
31928
+ } catch {
31929
+ }
31930
+ try {
31931
+ nextPc.close();
31932
+ } catch {
31933
+ }
31934
+ throw err;
31935
+ } finally {
31936
+ context.Signal.removeEventListener("abort", onAbort);
31937
+ }
31938
+ if (prevDc) {
31939
+ prevDc.onopen = null;
31940
+ prevDc.onmessage = null;
31941
+ prevDc.onerror = null;
31942
+ prevDc.onclose = null;
31943
+ }
31944
+ if (prevPc) {
31945
+ prevPc.ontrack = null;
31946
+ }
31947
+ this.peerConnection = nextPc;
31948
+ this.dataChannel = nextDc;
31949
+ this.micSenders = nextSenders;
31950
+ if (pendingRemoteStream && this.remoteAudioEl) {
31951
+ this.remoteAudioEl.srcObject = pendingRemoteStream;
31952
+ this.publishRemoteMediaStream(pendingRemoteStream);
31953
+ this.attachOutputAudioMeter(RealtimeAudioMeter.ForStream(pendingRemoteStream));
31954
+ pendingRemoteStream = null;
31955
+ }
31956
+ this.responseActive = false;
31957
+ this.audioPlaying = false;
31958
+ try {
31959
+ prevDc?.close();
31960
+ } catch {
31961
+ }
31962
+ try {
31963
+ prevPc?.close();
31964
+ } catch {
31965
+ }
31966
+ if (context.ConversationSeed && context.ConversationSeed.Entries.length > 0) {
31967
+ const note = RenderRealtimeMemorySeedAsContextNote(context.ConversationSeed);
31968
+ if (note) {
31969
+ this.sendDataChannelFrame({
31970
+ type: "session.thinking.append",
31971
+ content: note,
31972
+ delegation_id: null
31973
+ });
31974
+ }
31975
+ }
31976
+ this.flushOutboundQueue();
31977
+ this.reportListeningAfterMove();
31978
+ }
29581
31979
  /**
29582
31980
  * Injects user text into the live session and requests a model response.
29583
31981
  * SendText implies barge-in and must NOT synthesize a user transcript (obligation #4).
@@ -29614,7 +32012,8 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29614
32012
  * Injects background context without triggering model speech.
29615
32013
  * Uses `session.thinking.append` with `content` parameter and `delegation_id: null`.
29616
32014
  */
29617
- SendContextNote(text) {
32015
+ SendContextNote(text, options) {
32016
+ this.ConversationMemory.Record({ Kind: "note", Text: text, ...options });
29618
32017
  this.sendDataChannelFrame({
29619
32018
  type: "session.thinking.append",
29620
32019
  content: text,
@@ -29657,7 +32056,8 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29657
32056
  * OpenAI Live remote reasoning plane requires response.item.create followed by response.create.
29658
32057
  * Client delegation plane uses session.commentary.append with the delegation_id.
29659
32058
  */
29660
- SendToolResult(callID, outputJson) {
32059
+ doSendToolResult(callID, outputJson) {
32060
+ const name = this.resolveToolName(callID);
29661
32061
  if (this.clientDelegationCallIds.has(callID)) {
29662
32062
  this.clientDelegationCallIds.delete(callID);
29663
32063
  this.sendDataChannelFrame({
@@ -29667,6 +32067,18 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29667
32067
  });
29668
32068
  return;
29669
32069
  }
32070
+ if (this.callsFromBeforeReseed.delete(callID)) {
32071
+ this.sendDataChannelFrame({
32072
+ type: "session.commentary.append",
32073
+ content: RenderLateToolResultNote(name, outputJson),
32074
+ delegation_id: null
32075
+ });
32076
+ if (this.toolBatchBarrier.RecordResult(callID)) {
32077
+ this.emittedToolCallIds.clear();
32078
+ this.sendDataChannelFrame({ type: "response.create" });
32079
+ }
32080
+ return;
32081
+ }
29670
32082
  this.sendDataChannelFrame({
29671
32083
  type: "response.item.create",
29672
32084
  item: {
@@ -29769,6 +32181,15 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29769
32181
  this.emitStateChange(state);
29770
32182
  }
29771
32183
  }
32184
+ /**
32185
+ * Reports the call live on the new connection. The host was told `'connecting'` when the move started, but this
32186
+ * driver's own state was left as it was (an `error` frame during the move must not read the call as inactive), so
32187
+ * {@link setState} would skip `'listening'` when the move started from it.
32188
+ */
32189
+ reportListeningAfterMove() {
32190
+ this.currentState = "listening";
32191
+ this.emitStateChange("listening");
32192
+ }
29772
32193
  attachMicrophone(pc, micStream) {
29773
32194
  this.micSenders = micStream.getAudioTracks().map((track) => pc.addTrack(track, micStream));
29774
32195
  }
@@ -29808,15 +32229,32 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29808
32229
  channel.onmessage = (e) => {
29809
32230
  this.handleDataChannelMessage(String(e.data));
29810
32231
  };
29811
- channel.onerror = (e) => {
29812
- this.emitError({ Message: `Data channel error: ${String(e)}`, Fatal: true });
29813
- this.setState("error");
29814
- };
29815
- channel.onclose = () => {
29816
- if (this.currentState !== "error") {
29817
- this.setState("closed");
29818
- }
29819
- };
32232
+ channel.onerror = (e) => this.handleChannelError(channel, e);
32233
+ channel.onclose = () => this.handleChannelClose(channel);
32234
+ }
32235
+ /**
32236
+ * A data-channel error, shared by the first connection's channel and each reconnect's. Ignored for a channel that
32237
+ * is no longer current, and while a move is in flight: the move owns the outcome then (it either swaps to the new
32238
+ * channel or fails through the base reconnect path), so the old channel dying must not end the call. Otherwise
32239
+ * it is fatal.
32240
+ */
32241
+ handleChannelError(channel, e) {
32242
+ if (this.dataChannel !== channel || this.IsReconnecting) {
32243
+ return;
32244
+ }
32245
+ this.emitError({ Message: `OpenAI Live data channel error: ${String(e)}`, Fatal: true });
32246
+ this.setState("error");
32247
+ }
32248
+ /**
32249
+ * A data-channel close the consumer did not ask for. Disconnect and the swap drop the channel before closing it,
32250
+ * so the identity check filters both; a close during a move is the move's to handle (see
32251
+ * {@link handleChannelError}). Otherwise the session ends as `'closed'`.
32252
+ */
32253
+ handleChannelClose(channel) {
32254
+ if (this.dataChannel !== channel || this.IsReconnecting || this.currentState === "error") {
32255
+ return;
32256
+ }
32257
+ this.setState("closed");
29820
32258
  }
29821
32259
  finalizeAssistantTranscript() {
29822
32260
  this.stopPlaybackDrainMonitoring();
@@ -29942,10 +32380,14 @@ var OpenAILiveClient = class OpenAILiveClient2 extends BaseRealtimeClient {
29942
32380
  const seconds = typeof usage?.seconds === "number" ? usage.seconds : void 0;
29943
32381
  const duration = seconds !== void 0 ? Math.max(OpenAILiveClient_1.PREBILL_DURATION_SECONDS, seconds) : this.totalDurationSeconds;
29944
32382
  this.totalDurationSeconds = duration;
32383
+ const inputDetails = MapRealtimeUsageModalityDetail(usage?.["input_token_details"]);
32384
+ const outputDetails = MapRealtimeUsageModalityDetail(usage?.["output_token_details"]);
29945
32385
  this.emitUsage({
29946
32386
  InputTokens: typeof usage?.input_tokens === "number" ? usage.input_tokens : 0,
29947
32387
  OutputTokens: typeof usage?.output_tokens === "number" ? usage.output_tokens : 0,
29948
32388
  DurationSeconds: duration,
32389
+ ...inputDetails ? { InputTokenDetails: inputDetails } : {},
32390
+ ...outputDetails ? { OutputTokenDetails: outputDetails } : {},
29949
32391
  Raw: usage
29950
32392
  });
29951
32393
  }