@memberjunction/ai-gemini 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.
@@ -11,7 +11,7 @@ var GeminiRealtime_1;
11
11
  // Google Gemini Live API imports
12
12
  import { GoogleGenAI, Modality, Behavior, FunctionResponseScheduling, TurnCoverage, ThinkingLevel, } from '@google/genai';
13
13
  // MemberJunction AI core contract
14
- import { BaseRealtimeModel, RealtimeDiagLog, NormalizeTurnDetectionSettings, RealtimeDroppedInputReporter, REALTIME_SHARED_CONFIG_KEYS, ExtractToolSchedulingHint, ParseDurationToMs, IsPcmAudioMimeType, RealtimeConnectionSetup, RealtimeSessionResumption, RealtimeDriverFactsOf, } from '@memberjunction/ai';
14
+ import { BaseRealtimeModel, BaseRealtimeSession, AsConfigRecord, ResolveRealtimeTiming, RenderRealtimeMemorySeed, RenderLateToolResultNote, RealtimeDiagLog, NormalizeTurnDetectionSettings, RealtimeDroppedInputReporter, REALTIME_SHARED_CONFIG_KEYS, ExtractToolSchedulingHint, ParseDurationToMs, IsPcmAudioMimeType, RealtimeConnectionSetup, RealtimeDriverFactsOf, } from '@memberjunction/ai';
15
15
  import { ResolveGeminiLiveProfile, ResolveGeminiMaxInboundVideoStreams, ResolveGeminiThinkingLevel, ResolveGeminiTurnCoverage, GEMINI_LIVE_FALLBACK_PROFILE, } from './geminiLiveProfiles.js';
16
16
  import { GeminiBridgedAvatarOutput } from './geminiBridgedAvatar.js';
17
17
  import { ResolveGeminiAvatarVideoBitrateBps } from './geminiAvatarVideoBitrate.js';
@@ -51,6 +51,11 @@ const MAX_HELD_INPUT_AUDIO_BYTES = 16000 * 2 * 2;
51
51
  * SAME token, which Gemini counts as a new session: a single-use token is refused "Token has been used too many times".
52
52
  */
53
53
  const GEMINI_LIVE_CONNECTION_SECONDS = 600;
54
+ /**
55
+ * Connection duration cap (seconds) when inbound video is streamed WITHOUT `contextWindowCompression`.
56
+ * Google's Live API session-management docs specify ~2 minutes for uncompressed audio+video.
57
+ */
58
+ const GEMINI_LIVE_UNCOMPRESSED_VIDEO_CONNECTION_SECONDS = 120;
54
59
  /** Extra connections a token allows beyond one per {@link GEMINI_LIVE_CONNECTION_SECONDS}: resumes after a dropped network or a `goAway`. */
55
60
  const GEMINI_CLIENT_TOKEN_RESUME_MARGIN = 3;
56
61
  /** Slack past the session cap before the token dies, so the browser's own deadline alarm ends the call first. */
@@ -91,6 +96,25 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
91
96
  ProviderMaxSessionSeconds: 1800,
92
97
  SupportedTurnSettings: { Eagerness: 'approximate', SilenceDurationMs: 'exact', Threshold: 'approximate', Coverage: 'exact' },
93
98
  }; }
99
+ /** Gemini Live caps each WebSocket connection at ~10 minutes (600 s). */
100
+ get DefaultCallDurationSeconds() {
101
+ return GEMINI_LIVE_CONNECTION_SECONDS;
102
+ }
103
+ /** Server-side Gemini Live sessions trust Google's native sessionResumption handles (with Attempt 2 fallback to seed). */
104
+ get TrustsNativeResumption() {
105
+ return true;
106
+ }
107
+ /**
108
+ * Resolves whether a client-direct session minted by this driver trusts native resumption handles.
109
+ * On the Developer API (`transport === 'direct'`), browser sessions authenticate with `v1alpha`
110
+ * ephemeral tokens, where resuming with a handle connects and restores an empty session; those
111
+ * sessions use `RealtimeConversationMemory` seeding (`false`). Relay sessions on Gemini Enterprise
112
+ * (`transport === 'relay'`) use server-side OAuth/API-key credentials on `v1`, where native
113
+ * `sessionResumption` handles preserve full audio context (`true`).
114
+ */
115
+ ClientSessionTrustsNativeResumption(transport = 'direct') {
116
+ return transport === 'relay' || this.Endpoint === 'enterprise';
117
+ }
94
118
  constructor(apiKey) {
95
119
  super(apiKey);
96
120
  this.geminiClient = null;
@@ -142,9 +166,12 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
142
166
  */
143
167
  async StartSession(params) {
144
168
  const profile = ResolveGeminiLiveProfile(params.Model, this.Endpoint);
145
- const session = new GeminiRealtimeSession(profile, RealtimeDriverFactsOf(this));
169
+ const session = new GeminiRealtimeSession(profile, RealtimeDriverFactsOf(this), this);
146
170
  session.SetConnectTimeTools(params.Tools ?? []);
171
+ session.SetZeroDataRetention(params.ZeroDataRetention === true);
172
+ session.ApplySessionTimingConfig(AsConfigRecord(params.Config));
147
173
  const config = this.BuildConnectConfig(this.withoutAvatarOnServer(params));
174
+ session.SetContextWindowCompressionEnabled(GeminiRealtime_1.hasContextWindowCompression(config));
148
175
  session.SetAvatar(this.serverAvatarStatus(params, config), profile.AvatarOutputEncoding);
149
176
  // Meeting mode (auto activity detection disabled) → the session must drive turns manually.
150
177
  session.SetMeetingMode(config.realtimeInputConfig?.automaticActivityDetection?.disabled === true);
@@ -156,6 +183,7 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
156
183
  ...callbacks,
157
184
  }));
158
185
  await session.Open();
186
+ session.ArmConnectionDurationTimer();
159
187
  // If the caller provided initial context, seed it as client content (without completing the
160
188
  // turn) so the model starts with the same history a loop agent would assemble.
161
189
  if (params.InitialContext && params.InitialContext.trim().length > 0) {
@@ -206,20 +234,32 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
206
234
  *
207
235
  * Expiry: the token opens connections (the first, and each resume, which Gemini counts as a new
208
236
  * session) until the session cap plus {@link GEMINI_CLIENT_TOKEN_CAP_SKEW_SECONDS} (at most
209
- * {@link GEMINI_CLIENT_TOKEN_EXPIRY_MS}), one per {@link GEMINI_LIVE_CONNECTION_SECONDS} of the cap plus
210
- * {@link GEMINI_CLIENT_TOKEN_RESUME_MARGIN}; the session's ability to send messages dies with it.
237
+ * {@link GEMINI_CLIENT_TOKEN_EXPIRY_MS}), one per effective connection length (`ConnectionMaxSeconds`, at most
238
+ * {@link GEMINI_LIVE_CONNECTION_SECONDS}) of the cap plus {@link GEMINI_CLIENT_TOKEN_RESUME_MARGIN}; the session's
239
+ * ability to send messages dies with it. The count rides `SessionConfig.tokenUses` so the browser refreshes before
240
+ * it spends the last use.
211
241
  *
212
242
  * @param params Session configuration (model, system prompt, tools, config bag).
213
243
  * @returns The minted {@link ClientRealtimeSessionConfig} the browser authenticates + applies.
214
244
  */
215
245
  async CreateClientSession(params) {
246
+ const resolvedTiming = ResolveRealtimeTiming({
247
+ Config: params.Config,
248
+ DriverDefaultConnectionSeconds: this.DefaultCallDurationSeconds,
249
+ DriverDefaultBufferSeconds: this.ReconnectBufferSeconds,
250
+ DefaultTrustNativeResumption: this.ClientSessionTrustsNativeResumption('direct'),
251
+ ZeroDataRetention: params.ZeroDataRetention,
252
+ });
216
253
  const config = this.BuildConnectConfig(params);
217
254
  const maxSessionSeconds = this.ClampSessionSeconds(RealtimeDriverFactsOf(this).ProviderMaxSessionSeconds, params.MaxSessionSeconds);
218
255
  // The token is a credential the browser holds, so it lives no longer than the session cap (plus a little slack)
219
256
  // and opens only enough connections for that cap: a leaked token cannot outlast the host's deadline.
220
257
  const capSeconds = maxSessionSeconds ?? GEMINI_CLIENT_TOKEN_EXPIRY_MS / 1000;
221
258
  const lifetimeMs = Math.min(GEMINI_CLIENT_TOKEN_EXPIRY_MS, (capSeconds + GEMINI_CLIENT_TOKEN_CAP_SKEW_SECONDS) * 1000);
222
- const uses = Math.ceil(capSeconds / GEMINI_LIVE_CONNECTION_SECONDS) + GEMINI_CLIENT_TOKEN_RESUME_MARGIN;
259
+ // One use per connection the browser opens, and it opens one per EFFECTIVE connection length (the catalog cap
260
+ // narrowed to Gemini's ceiling), not per 10-minute ceiling: a 45 s cap needs 40 opens for a 30-minute call.
261
+ const connectionSeconds = resolvedTiming.ConnectionMaxSeconds ?? GEMINI_LIVE_CONNECTION_SECONDS;
262
+ const uses = Math.ceil(capSeconds / connectionSeconds) + GEMINI_CLIENT_TOKEN_RESUME_MARGIN;
223
263
  const now = Date.now();
224
264
  const expireTime = new Date(now + lifetimeMs).toISOString();
225
265
  const token = await this.mintAuthToken({
@@ -252,9 +292,14 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
252
292
  ExpiresAt: expireTime,
253
293
  // The browser passes the full config to live.connect; the token lock above makes its
254
294
  // values authoritative even if a client tampers.
255
- SessionConfig: this.SessionPactFor(params.Model, config),
295
+ // `tokenUses`: the connections this token opens. Drops and the 120 s uncompressed-video cap spend uses no
296
+ // mint-time count can bound, so the browser counts its opens and re-mints before it would open one too many.
297
+ SessionConfig: { ...this.SessionPactFor(params.Model, config), tokenUses: uses },
256
298
  ...(avatarStatus ? { AvatarStatus: avatarStatus } : {}),
257
299
  MaxSessionSeconds: maxSessionSeconds,
300
+ ConnectionMaxSeconds: resolvedTiming.ConnectionMaxSeconds,
301
+ ReconnectBufferSeconds: resolvedTiming.ReconnectBufferSeconds,
302
+ TrustNativeResumption: resolvedTiming.TrustNativeResumption,
258
303
  };
259
304
  }
260
305
  /**
@@ -284,6 +329,12 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
284
329
  // How many concurrent inbound video streams the model accepts (0 without video support).
285
330
  // The browser's source arbiter maps live sources onto this many streams.
286
331
  maxInboundVideoStreams: ResolveGeminiMaxInboundVideoStreams(profile),
332
+ ...(GeminiRealtime_1.hasContextWindowCompression(config)
333
+ ? { contextWindowCompression: true }
334
+ : {
335
+ contextWindowCompression: false,
336
+ uncompressedVideoConnectionMaxSeconds: GEMINI_LIVE_UNCOMPRESSED_VIDEO_CONNECTION_SECONDS,
337
+ }),
287
338
  ...this.AvatarPactFor(config, profile),
288
339
  }));
289
340
  }
@@ -481,6 +532,20 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
481
532
  *
482
533
  * @param cfg The copy of the session config bag that is merged into the connect config. The keys are deleted from it.
483
534
  */
535
+ static { this.CONSUMED_CONTINUITY_KEYS = new Set([
536
+ 'connectionMaxSeconds',
537
+ 'ConnectionMaxSeconds',
538
+ 'sessionMaxSeconds',
539
+ 'SessionMaxSeconds',
540
+ 'maxSessionSeconds',
541
+ 'MaxSessionSeconds',
542
+ 'reconnectBufferSeconds',
543
+ 'ReconnectBufferSeconds',
544
+ 'trustNativeResumption',
545
+ 'TrustNativeResumption',
546
+ 'zeroDataRetention',
547
+ 'ZeroDataRetention',
548
+ ]); }
484
549
  static scrubSharedKeys(cfg) {
485
550
  const notApplied = [];
486
551
  for (const key of REALTIME_SHARED_CONFIG_KEYS) {
@@ -489,6 +554,9 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
489
554
  }
490
555
  const value = cfg[key];
491
556
  delete cfg[key];
557
+ if (GeminiRealtime_1.CONSUMED_CONTINUITY_KEYS.has(key)) {
558
+ continue;
559
+ }
492
560
  const shape = GEMINI_SHARED_KEYS_APPLIED_AFTER_MERGE.get(key);
493
561
  if (shape === undefined) {
494
562
  notApplied.push(key);
@@ -506,12 +574,17 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
506
574
  }
507
575
  }
508
576
  /**
509
- * Keeps a config-bag `contextWindowCompression` only when it is an object. The bag is untyped
510
- * JSON, so a string, array or null would otherwise reach the wire and fail the session at
511
- * connect. A malformed value is replaced by the default and reported; a well-formed one wins
512
- * over the default, like every other bag key.
577
+ * Keeps a config-bag `contextWindowCompression` only when it is an object, or `null` / `false`
578
+ * when the caller explicitly disables compression. The bag is untyped JSON, so a string or array
579
+ * would otherwise reach the wire and fail the session at connect. A malformed value is replaced
580
+ * by the default and reported; a well-formed object wins over the default, and `null`/`false`
581
+ * deletes `contextWindowCompression` so uncompressed video uses the 120s limit.
513
582
  */
514
- static ensureContextWindowCompression(config) {
583
+ static ensureContextWindowCompression(config, rawBagCompression) {
584
+ if (rawBagCompression === false) {
585
+ delete config.contextWindowCompression;
586
+ return;
587
+ }
515
588
  const compression = config.contextWindowCompression;
516
589
  if (GeminiRealtime_1.readObject(compression)) {
517
590
  return;
@@ -520,6 +593,10 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
520
593
  console.warn(`[GeminiRealtime] Ignored the session config bag's \`contextWindowCompression\` because it is not an object (got ${got}); using the default sliding window.`);
521
594
  config.contextWindowCompression = GeminiRealtime_1.DefaultContextWindowCompression();
522
595
  }
596
+ /** Returns true when `contextWindowCompression` is enabled on the resolved connect config. */
597
+ static hasContextWindowCompression(config) {
598
+ return GeminiRealtime_1.readObject(config.contextWindowCompression) !== undefined;
599
+ }
523
600
  /** Narrows an unenforced config-bag value to a real object — not a string, array, or null. */
524
601
  static isPlainObject(value) {
525
602
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -561,7 +638,7 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
561
638
  config.sessionResumption = {};
562
639
  }
563
640
  if (params.Tools && params.Tools.length > 0) {
564
- const bag = params.Config ?? {};
641
+ const bag = AsConfigRecord(params.Config) ?? {};
565
642
  const tooling = GeminiRealtime_1.readObject(bag['tooling']);
566
643
  const requestedBehavior = GeminiRealtime_1.readString(tooling?.['Behavior']) ??
567
644
  GeminiRealtime_1.readString(bag['toolBehavior']) ??
@@ -578,7 +655,8 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
578
655
  // (activityStart on input, activityEnd on RequestSpokenUpdate). This is the Gemini-native
579
656
  // equivalent of OpenAI's `turn_detection.create_response=false`, kept entirely in this subclass.
580
657
  // See plans/realtime/multi-agent-meeting-turn-taking.md §4.
581
- const cfg = { ...params.Config };
658
+ const cfg = { ...(AsConfigRecord(params.Config) ?? {}) };
659
+ const rawBagCompression = cfg.contextWindowCompression;
582
660
  const disableAutoResponse = cfg.disableAutoResponse === true;
583
661
  delete cfg.disableAutoResponse;
584
662
  delete cfg.tooling;
@@ -621,7 +699,7 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
621
699
  // `LiveConnectConfig` field — tracked separately rather than widened here.
622
700
  GeminiRealtime_1.scrubSharedKeys(cfg);
623
701
  Object.assign(config, cfg);
624
- GeminiRealtime_1.ensureContextWindowCompression(config);
702
+ GeminiRealtime_1.ensureContextWindowCompression(config, rawBagCompression);
625
703
  // Captured BEFORE the mapping below replaces or deletes it, so the warning can report the
626
704
  // type that was actually rejected rather than the type that replaced it.
627
705
  const rawSpeechConfig = config.speechConfig;
@@ -810,7 +888,7 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
810
888
  // RealtimeSessionParams — so read it from there. A shared key read here belongs in
811
889
  // GEMINI_SHARED_KEYS_APPLIED_AFTER_MERGE; otherwise the scrub logs it as a key Gemini Live
812
890
  // does not apply.
813
- const bag = params.Config ?? {};
891
+ const bag = AsConfigRecord(params.Config) ?? {};
814
892
  const reasoning = GeminiRealtime_1.readObject(bag['reasoning']);
815
893
  const turnDetection = GeminiRealtime_1.readObject(bag['turnDetection']);
816
894
  // Structured `reasoning.Remote.Effort` first; fall back to `reasoning.Level` / `reasoning.Effort`
@@ -1074,12 +1152,13 @@ export { GeminiRealtime };
1074
1152
  * translation (Core calls → Gemini send methods). It is created by {@link GeminiRealtime.StartSession}
1075
1153
  * and never instantiated directly by consumers.
1076
1154
  */
1077
- class GeminiRealtimeSession {
1155
+ class GeminiRealtimeSession extends BaseRealtimeSession {
1078
1156
  /**
1079
1157
  * @param driverFacts The creating driver's static facts, passed in so a subclass driver's own
1080
1158
  * ceiling wins; direct construction defaults to Gemini's.
1081
1159
  */
1082
- constructor(profile, driverFacts = GeminiRealtime.DriverFacts) {
1160
+ constructor(profile, driverFacts = GeminiRealtime.DriverFacts, model) {
1161
+ super(model);
1083
1162
  /**
1084
1163
  * Gemini Live consumes **16 kHz** PCM input ({@link GEMINI_INPUT_AUDIO_MIME_TYPE}) and emits 24 kHz. A
1085
1164
  * server-bridged host reads these to resample room audio correctly — without it the bridge feeds Gemini
@@ -1089,6 +1168,9 @@ class GeminiRealtimeSession {
1089
1168
  this.InputSampleRate = 16000;
1090
1169
  this.OutputSampleRate = 24000;
1091
1170
  this.live = null;
1171
+ this.zeroDataRetention = false;
1172
+ this.contextWindowCompressionEnabled = true;
1173
+ this.videoStreamActive = false;
1092
1174
  this.outputHandler = null;
1093
1175
  this.videoFrameHandler = null;
1094
1176
  this.transcriptHandler = null;
@@ -1096,17 +1178,10 @@ class GeminiRealtimeSession {
1096
1178
  this.interruptionHandler = null;
1097
1179
  this.usageHandler = null;
1098
1180
  this.errorHandler = null;
1099
- /** True once Close() ran — an expected close must not surface as a fatal error. */
1100
- this.closedByConsumer = false;
1101
- /**
1102
- * Maps each pending tool call's `CallID` to its function name. Gemini's `sendToolResponse`
1103
- * requires the function name, but the Core {@link IRealtimeSession.SendToolResult} contract only
1104
- * carries `callID` + `output`. We cache the name when a tool call arrives and clear the entry
1105
- * once the result is sent.
1106
- */
1107
- this.pendingToolCallNames = new Map();
1108
1181
  /** Accumulates in-flight thought text deltas until finalized on turn completion. */
1109
1182
  this.pendingThoughtText = '';
1183
+ this.pendingUserTranscript = '';
1184
+ this.pendingAssistantTranscript = '';
1110
1185
  /** MIME types of model output this session dropped, so each is reported once. */
1111
1186
  this.droppedOutputTypes = new Set();
1112
1187
  /** Reports the input frames {@link SendInput} drops, once per kind and type. */
@@ -1158,13 +1233,6 @@ class GeminiRealtimeSession {
1158
1233
  * into a room; null on every other session, whose output is PCM only.
1159
1234
  */
1160
1235
  this.avatarOutput = null;
1161
- /**
1162
- * Moves the session to a new connection with Google's resumption handle: when Google announces
1163
- * the connection is ending (`goAway`, with the time left; on Vertex AI it came about 9 minutes
1164
- * into a connection, with 30 s left) and after an unexpected drop. A planned move waits until
1165
- * no turn is in progress ({@link IsTurnOpen}). Created by {@link Open}.
1166
- */
1167
- this.resumption = null;
1168
1236
  /**
1169
1237
  * Whether the session is moving to a new connection: from the start of a move until Google
1170
1238
  * confirms the new connection's setup (`setupComplete`). Input waits meanwhile, in
@@ -1178,8 +1246,6 @@ class GeminiRealtimeSession {
1178
1246
  this.heldAudio = [];
1179
1247
  /** Bytes in {@link heldAudio}, kept under {@link MAX_HELD_INPUT_AUDIO_BYTES}. */
1180
1248
  this.heldAudioBytes = 0;
1181
- /** See {@link IsTurnOpen}. */
1182
- this.turnOpen = false;
1183
1249
  /** A turn's `turnComplete` came while a tool call was pending: the turn ends once the last pending call's result goes out. */
1184
1250
  this.turnEndAwaitsToolResults = false;
1185
1251
  /** Last connection number handed out by {@link openConnection}. */
@@ -1190,9 +1256,42 @@ class GeminiRealtimeSession {
1190
1256
  * that replaced it. `0` while no connection is in use.
1191
1257
  */
1192
1258
  this.currentConnection = 0;
1259
+ this.hasResumedOnce = false;
1193
1260
  this.profile = profile ?? GEMINI_LIVE_FALLBACK_PROFILE;
1194
1261
  this.driverFacts = driverFacts;
1195
1262
  }
1263
+ SetZeroDataRetention(on) {
1264
+ this.zeroDataRetention = on;
1265
+ }
1266
+ /** Records whether `contextWindowCompression` is enabled in the effective connect config. */
1267
+ SetContextWindowCompressionEnabled(enabled) {
1268
+ this.contextWindowCompressionEnabled = enabled;
1269
+ }
1270
+ /** Clears the uncompressed video stream cap when inbound video stops. */
1271
+ ClearVideoLimit() {
1272
+ if (!this.videoStreamActive) {
1273
+ return;
1274
+ }
1275
+ this.videoStreamActive = false;
1276
+ this.ArmConnectionDurationTimer();
1277
+ }
1278
+ get DefaultCallDurationSeconds() {
1279
+ return GEMINI_LIVE_CONNECTION_SECONDS;
1280
+ }
1281
+ get RuntimeCallDurationSeconds() {
1282
+ return this.videoStreamActive && !this.contextWindowCompressionEnabled
1283
+ ? GEMINI_LIVE_UNCOMPRESSED_VIDEO_CONNECTION_SECONDS
1284
+ : undefined;
1285
+ }
1286
+ get DefaultTrustsNativeResumption() {
1287
+ return !this.zeroDataRetention;
1288
+ }
1289
+ get RequiresPostTurnResumptionHandle() {
1290
+ return true;
1291
+ }
1292
+ get TrustsNativeResumption() {
1293
+ return !this.zeroDataRetention && super.TrustsNativeResumption;
1294
+ }
1196
1295
  /** Sets how this session opens its Live connections. Called by the driver before {@link Open}. */
1197
1296
  SetConnector(connector) {
1198
1297
  this.connector = connector;
@@ -1227,17 +1326,6 @@ class GeminiRealtimeSession {
1227
1326
  * @throws When the connection closes or fails before Google confirms its setup, or no confirmation comes in time.
1228
1327
  */
1229
1328
  async Open() {
1230
- this.resumption = new RealtimeSessionResumption({
1231
- Reconnect: (handle, attempt) => this.resume(handle, attempt),
1232
- OnReconnecting: (reason) => {
1233
- RealtimeDiagLog(`[GeminiRealtime] Resuming the session on a new connection (${reason})`);
1234
- // From the moment a move starts, input waits for the new connection.
1235
- this.moving = true;
1236
- },
1237
- OnReconnected: () => this.handleResumed(),
1238
- OnReconnectFailed: (error) => this.handleResumeFailed(error),
1239
- Log: (message) => RealtimeDiagLog(message),
1240
- });
1241
1329
  const opened = await this.openConnection(undefined);
1242
1330
  await GeminiRealtimeSession.awaitSetup(opened);
1243
1331
  this.useConnection(opened);
@@ -1372,6 +1460,12 @@ class GeminiRealtimeSession {
1372
1460
  this.droppedInput.Report(frame);
1373
1461
  return;
1374
1462
  }
1463
+ const wasInactive = !this.videoStreamActive;
1464
+ this.videoStreamActive = true;
1465
+ if (wasInactive && !this.contextWindowCompressionEnabled) {
1466
+ // Re-arm connection duration timer under the 120s uncompressed video cap.
1467
+ this.ArmConnectionDurationTimer();
1468
+ }
1375
1469
  this.requireLive().sendRealtimeInput({ video: { data: GeminiRealtimeSession.arrayBufferToBase64(frame.Data), mimeType } });
1376
1470
  }
1377
1471
  /**
@@ -1431,9 +1525,36 @@ class GeminiRealtimeSession {
1431
1525
  OnUsage(handler) {
1432
1526
  this.usageHandler = handler;
1433
1527
  }
1528
+ /** @inheritdoc */
1434
1529
  OnError(handler) {
1435
1530
  this.errorHandler = handler;
1436
1531
  }
1532
+ get canAttemptReconnect() {
1533
+ return (!this.TrustsNativeResumption ||
1534
+ this.ResumptionHandle !== null ||
1535
+ this.hasResumedOnce ||
1536
+ this.conversationMemory.Seed().Entries.length > 0 ||
1537
+ this.IsReconnecting);
1538
+ }
1539
+ onReconnecting(reason) {
1540
+ RealtimeDiagLog(`[GeminiRealtime] Resuming the session on a new connection (${reason})`);
1541
+ this.moving = true;
1542
+ }
1543
+ onReconnectFailed(error, code = 'reconnect-failed') {
1544
+ this.moving = false;
1545
+ this.heldAudio = [];
1546
+ this.heldAudioBytes = 0;
1547
+ if (this.closedByConsumer) {
1548
+ return;
1549
+ }
1550
+ super.onReconnectFailed(error, code);
1551
+ }
1552
+ formatReconnectFailureMessage(error, _code) {
1553
+ return `Gemini Live connection was lost and could not be resumed: ${error.message}`;
1554
+ }
1555
+ emitSessionError(error) {
1556
+ this.errorHandler?.(error);
1557
+ }
1437
1558
  /**
1438
1559
  * Surfaces a websocket-level failure as a FATAL session error — the transport is gone,
1439
1560
  * so the consumer (e.g. the session runner) should finalize cleanly instead of idling.
@@ -1441,7 +1562,7 @@ class GeminiRealtimeSession {
1441
1562
  * followed by a `close`, and {@link HandleTransportClose} resumes from there.
1442
1563
  */
1443
1564
  HandleTransportError(message) {
1444
- if (this.resumption?.Handle) {
1565
+ if (this.canAttemptReconnect) {
1445
1566
  RealtimeDiagLog(`[GeminiRealtime] Transport error, resuming on close: ${message}`);
1446
1567
  return;
1447
1568
  }
@@ -1449,14 +1570,17 @@ class GeminiRealtimeSession {
1449
1570
  }
1450
1571
  /**
1451
1572
  * Handles a close of the current connection that the consumer did not ask for. When Google
1452
- * issued a resumption handle, the session reconnects with it; otherwise the close surfaces as a
1453
- * fatal error, as before (expected closes, after {@link Close}, stay silent).
1573
+ * issued a resumption handle (or when native resumption is disabled/untrusted and the session
1574
+ * reseeds from conversation memory, including under ZeroDataRetention), the session reconnects;
1575
+ * otherwise the close surfaces as a fatal error, as before (expected closes, after {@link Close},
1576
+ * stay silent).
1454
1577
  */
1455
1578
  HandleTransportClose(code, reason) {
1456
1579
  if (this.closedByConsumer) {
1457
1580
  return;
1458
1581
  }
1459
- if (this.resumption?.ConnectionLost()) {
1582
+ if (this.canAttemptReconnect) {
1583
+ void this.TriggerReconnect('connection-lost');
1460
1584
  return;
1461
1585
  }
1462
1586
  const detail = [code != null ? `code ${code}` : null, reason || null].filter(Boolean).join(' — ');
@@ -1517,24 +1641,45 @@ class GeminiRealtimeSession {
1517
1641
  this.currentConnection = opened.ConnectionNumber;
1518
1642
  }
1519
1643
  /**
1520
- * Opens a replacement connection that resumes the session from `handle`, switches to it once
1521
- * Google confirms its setup, and closes the old one. Until then the old connection stays in
1522
- * use, so what it still sends (the rest of a turn the deadline cut, its usage) is handled.
1523
- * Rejects when the connection can't be opened or its setup fails, so
1524
- * {@link RealtimeSessionResumption} can retry. A connection that opens after the attempt was
1525
- * abandoned (timeout, or {@link Close}) is closed instead of used.
1644
+ * Reconnects the Gemini Live session via `BaseRealtimeSession.TriggerReconnect` (proactive
1645
+ * duration timer, `goAway`, unexpected close, or Attempt 2 seed fallback after a native
1646
+ * resumption failure).
1526
1647
  */
1527
- async resume(handle, attempt) {
1528
- const opened = await this.openConnection(handle);
1529
- await GeminiRealtimeSession.awaitSetup(opened);
1530
- if (attempt.Abandoned || this.closedByConsumer) {
1531
- GeminiRealtimeSession.closeQuietly(opened.Live);
1532
- return;
1648
+ async Reconnect(context) {
1649
+ this.moving = true;
1650
+ try {
1651
+ const handle = context.UseNativeResumption && context.ResumptionHandle ? context.ResumptionHandle : undefined;
1652
+ if (!handle) {
1653
+ for (const callID of this.pendingToolCallNames.keys()) {
1654
+ this.callsFromBeforeReseed.add(callID);
1655
+ }
1656
+ }
1657
+ const opened = await this.openConnection(handle);
1658
+ await GeminiRealtimeSession.awaitSetup(opened);
1659
+ if (context.Abandoned || this.closedByConsumer) {
1660
+ GeminiRealtimeSession.closeQuietly(opened.Live);
1661
+ throw new Error('Gemini realtime reconnect attempt was abandoned.');
1662
+ }
1663
+ const previous = this.live;
1664
+ this.useConnection(opened);
1665
+ if (previous) {
1666
+ GeminiRealtimeSession.closeQuietly(previous);
1667
+ }
1668
+ if (!handle && context.ConversationSeed && context.ConversationSeed.Entries.length > 0) {
1669
+ const seedTurns = RenderRealtimeMemorySeed(context.ConversationSeed);
1670
+ if (seedTurns.length > 0) {
1671
+ const turns = seedTurns.map((t) => ({
1672
+ role: t.Role,
1673
+ parts: t.Texts.map((text) => ({ text })),
1674
+ }));
1675
+ this.requireLive().sendClientContent({ turns, turnComplete: false });
1676
+ this.openClientTurn = true;
1677
+ }
1678
+ }
1679
+ this.handleResumed();
1533
1680
  }
1534
- const previous = this.live;
1535
- this.useConnection(opened);
1536
- if (previous) {
1537
- GeminiRealtimeSession.closeQuietly(previous);
1681
+ catch (error) {
1682
+ throw error;
1538
1683
  }
1539
1684
  }
1540
1685
  /**
@@ -1544,26 +1689,16 @@ class GeminiRealtimeSession {
1544
1689
  * flag cleared. The audio held during the move goes out, then the queued sends.
1545
1690
  */
1546
1691
  handleResumed() {
1692
+ this.hasResumedOnce = true;
1693
+ this.videoStreamActive = false;
1547
1694
  this.manualActivityOpen = false;
1548
1695
  this.avatarOutput?.Resumed();
1549
1696
  this.endTurn();
1550
1697
  this.moving = false;
1698
+ this.ArmConnectionDurationTimer();
1551
1699
  this.sendHeldAudio();
1552
1700
  this.completeTurn();
1553
1701
  }
1554
- /**
1555
- * Every resume attempt failed: the session ends with a fatal error. Input no longer waits for a new connection; the
1556
- * audio held for one is dropped.
1557
- */
1558
- handleResumeFailed(error) {
1559
- this.moving = false;
1560
- this.heldAudio = [];
1561
- this.heldAudioBytes = 0;
1562
- if (this.closedByConsumer) {
1563
- return;
1564
- }
1565
- this.errorHandler?.({ Message: `Gemini Live connection was lost and could not be resumed: ${error.message}`, Fatal: true });
1566
- }
1567
1702
  /** Closes a connection the session no longer uses; it may already be closed. */
1568
1703
  static closeQuietly(live) {
1569
1704
  try {
@@ -1592,8 +1727,14 @@ class GeminiRealtimeSession {
1592
1727
  */
1593
1728
  async SendToolResult(callID, output) {
1594
1729
  const name = this.pendingToolCallNames.get(callID) ?? '';
1730
+ this.conversationMemory.Record({
1731
+ Kind: 'toolResult',
1732
+ Name: name || callID,
1733
+ OutputJson: output,
1734
+ });
1595
1735
  const parsed = this.parseToolOutput(output);
1596
1736
  const sched = GeminiRealtime.ExtractAndResolveScheduling(parsed, this.profile.Tooling.SupportsScheduling ?? false, name);
1737
+ const expectsReply = sched !== FunctionResponseScheduling.SILENT;
1597
1738
  const functionResponse = {
1598
1739
  id: callID,
1599
1740
  name,
@@ -1602,10 +1743,24 @@ class GeminiRealtimeSession {
1602
1743
  };
1603
1744
  const send = () => {
1604
1745
  const live = this.requireLive();
1605
- live.sendToolResponse({ functionResponses: [functionResponse] });
1606
- this.closeOpenClientTurn(live);
1746
+ if (this.callsFromBeforeReseed.delete(callID)) {
1747
+ const noteText = RenderLateToolResultNote(name || callID, output);
1748
+ if (this.meetingMode && !this.manualActivityOpen) {
1749
+ live.sendRealtimeInput({ activityStart: {} });
1750
+ }
1751
+ live.sendRealtimeInput({ text: noteText });
1752
+ if (this.meetingMode) {
1753
+ live.sendRealtimeInput({ activityEnd: {} });
1754
+ this.manualActivityOpen = false;
1755
+ }
1756
+ this.openClientTurn = false;
1757
+ }
1758
+ else {
1759
+ live.sendToolResponse({ functionResponses: [functionResponse] });
1760
+ this.closeOpenClientTurn(live);
1761
+ }
1607
1762
  this.pendingToolCallNames.delete(callID);
1608
- this.endTurnIfToolResultsIn();
1763
+ this.endTurnIfToolResultsIn(expectsReply);
1609
1764
  };
1610
1765
  if (this.moving) {
1611
1766
  this.queuedSends.push(send);
@@ -1662,7 +1817,12 @@ class GeminiRealtimeSession {
1662
1817
  *
1663
1818
  * @param text The context note to append to the conversation.
1664
1819
  */
1665
- SendContextNote(text) {
1820
+ SendContextNote(text, options) {
1821
+ this.conversationMemory.Record({
1822
+ Kind: 'note',
1823
+ Text: text,
1824
+ ...options,
1825
+ });
1666
1826
  this.enqueueOrRun(() => {
1667
1827
  this.requireLive().sendClientContent({ turns: [{ role: 'user', parts: [{ text }] }], turnComplete: false });
1668
1828
  this.openClientTurn = true;
@@ -1784,6 +1944,7 @@ class GeminiRealtimeSession {
1784
1944
  IsThought: true,
1785
1945
  });
1786
1946
  }
1947
+ this.flushPendingMemoryTranscripts();
1787
1948
  RealtimeDiagLog(`[GeminiRealtime][diag] turn boundary — clearing responseActive (was ${this.responseActive}), draining ${this.queuedSends.length} queued send(s)`);
1788
1949
  this.responseActive = false;
1789
1950
  while (!this.responseActive && !this.moving && this.queuedSends.length > 0) {
@@ -1791,6 +1952,18 @@ class GeminiRealtimeSession {
1791
1952
  send?.();
1792
1953
  }
1793
1954
  }
1955
+ flushPendingMemoryTranscripts(role) {
1956
+ if ((!role || role === 'user') && this.pendingUserTranscript.trim().length > 0) {
1957
+ const text = this.pendingUserTranscript;
1958
+ this.pendingUserTranscript = '';
1959
+ this.conversationMemory.Record({ Kind: 'user', Text: text });
1960
+ }
1961
+ if ((!role || role === 'assistant') && this.pendingAssistantTranscript.trim().length > 0) {
1962
+ const text = this.pendingAssistantTranscript;
1963
+ this.pendingAssistantTranscript = '';
1964
+ this.conversationMemory.Record({ Kind: 'assistant', Text: text });
1965
+ }
1966
+ }
1794
1967
  // ── Turn tracking (see IsTurnOpen) ─────────────────────────────────────────
1795
1968
  /**
1796
1969
  * Whether a server content frame is a sign of a turn: the user's transcribed words (outside
@@ -1823,9 +1996,8 @@ class GeminiRealtimeSession {
1823
1996
  }
1824
1997
  /** A turn started or continued: a planned move waits until it ends. */
1825
1998
  markTurnOpen() {
1826
- this.turnOpen = true;
1999
+ this.NotifyTurnStarted();
1827
2000
  this.turnEndAwaitsToolResults = false;
1828
- this.resumption?.TurnStarted();
1829
2001
  }
1830
2002
  /** The turn's `turnComplete`: it ends now, or once the results of the tool calls still pending go out. */
1831
2003
  endTurnUnlessToolCallPending() {
@@ -1836,22 +2008,24 @@ class GeminiRealtimeSession {
1836
2008
  this.endTurn();
1837
2009
  }
1838
2010
  /** A tool result went out: a turn whose `turnComplete` waited on the pending calls ends once none is left. */
1839
- endTurnIfToolResultsIn() {
1840
- if (this.turnEndAwaitsToolResults && this.pendingToolCallNames.size === 0) {
1841
- this.endTurn();
2011
+ endTurnIfToolResultsIn(expectsReply = true) {
2012
+ if (this.pendingToolCallNames.size > 0) {
2013
+ return;
2014
+ }
2015
+ this.NotifyToolCallsDrained(expectsReply);
2016
+ if (this.turnEndAwaitsToolResults || (!expectsReply && !this.responseActive)) {
2017
+ this.endTurn(expectsReply);
1842
2018
  }
1843
2019
  }
1844
2020
  /** The turn is over: a planned move happens at the next resumable handle Google issues. */
1845
- endTurn() {
1846
- this.turnOpen = false;
2021
+ endTurn(keepPostToolTurnWait = false) {
2022
+ this.flushPendingMemoryTranscripts();
1847
2023
  this.turnEndAwaitsToolResults = false;
1848
- this.resumption?.TurnEnded();
2024
+ this.NotifyTurnEnded(keepPostToolTurnWait);
1849
2025
  }
1850
2026
  /** @inheritdoc */
1851
2027
  async Close() {
1852
- this.closedByConsumer = true;
1853
- // Stop resuming before the socket closes, and drop events still in flight from it.
1854
- this.resumption?.Dispose();
2028
+ this.DisposeReconnectTimers();
1855
2029
  this.currentConnection = 0;
1856
2030
  // A closed session's sends fail as before (no live connection), rather than wait for a move.
1857
2031
  this.moving = false;
@@ -1873,10 +2047,11 @@ class GeminiRealtimeSession {
1873
2047
  // an update without the flag is treated as resumable.
1874
2048
  if (message.sessionResumptionUpdate) {
1875
2049
  const update = message.sessionResumptionUpdate;
1876
- this.resumption?.RecordHandle(update.newHandle, update.resumable !== false);
2050
+ this.RecordResumptionHandle(update.newHandle, update.resumable !== false);
1877
2051
  }
1878
2052
  if (message.goAway) {
1879
- this.resumption?.ConnectionEnding(ParseDurationToMs(message.goAway.timeLeft));
2053
+ const timeLeftMs = ParseDurationToMs(message.goAway.timeLeft);
2054
+ this.NotifyConnectionEnding(timeLeftMs);
1880
2055
  }
1881
2056
  if (message.serverContent) {
1882
2057
  this.handleServerContent(message.serverContent);
@@ -1919,6 +2094,12 @@ class GeminiRealtimeSession {
1919
2094
  if (content.generationComplete) {
1920
2095
  this.avatarOutput?.GenerationComplete();
1921
2096
  }
2097
+ if (content.inputTranscription) {
2098
+ this.emitTranscript('user', content.inputTranscription.text, content.inputTranscription.finished, 'normal');
2099
+ }
2100
+ if (content.outputTranscription) {
2101
+ this.emitTranscript('assistant', content.outputTranscription.text, content.outputTranscription.finished, 'normal');
2102
+ }
1922
2103
  if (content.turnComplete) {
1923
2104
  this.avatarOutput?.TurnComplete();
1924
2105
  // Before the drain: a queued send that starts a new turn opens it again, and a queued note opens a client turn.
@@ -1926,12 +2107,6 @@ class GeminiRealtimeSession {
1926
2107
  this.openClientTurn = false; // the model's turn took in any note that left the client turn open
1927
2108
  this.completeTurn();
1928
2109
  }
1929
- if (content.inputTranscription) {
1930
- this.emitTranscript('user', content.inputTranscription.text, content.inputTranscription.finished, 'normal');
1931
- }
1932
- if (content.outputTranscription) {
1933
- this.emitTranscript('assistant', content.outputTranscription.text, content.outputTranscription.finished, 'normal');
1934
- }
1935
2110
  }
1936
2111
  /** The model is generating: sends wait for the turn's boundary instead of interrupting it. */
1937
2112
  markGenerating() {
@@ -2020,10 +2195,43 @@ class GeminiRealtimeSession {
2020
2195
  * Emits a transcript event, defaulting missing text to empty and `finished` to a partial update.
2021
2196
  */
2022
2197
  emitTranscript(role, text, finished, kind) {
2198
+ const isFinal = finished ?? false;
2199
+ const normalizedText = text ?? '';
2200
+ if (kind !== 'narration') {
2201
+ if (role === 'assistant' && normalizedText.length > 0) {
2202
+ this.flushPendingMemoryTranscripts('user');
2203
+ }
2204
+ if (role === 'user') {
2205
+ this.pendingUserTranscript += normalizedText;
2206
+ if (isFinal) {
2207
+ const finalText = this.pendingUserTranscript.trim().length > 0 ? this.pendingUserTranscript : normalizedText;
2208
+ this.pendingUserTranscript = '';
2209
+ if (finalText.trim().length > 0) {
2210
+ this.conversationMemory.Record({
2211
+ Kind: 'user',
2212
+ Text: finalText,
2213
+ });
2214
+ }
2215
+ }
2216
+ }
2217
+ else {
2218
+ this.pendingAssistantTranscript += normalizedText;
2219
+ if (isFinal) {
2220
+ const finalText = this.pendingAssistantTranscript.trim().length > 0 ? this.pendingAssistantTranscript : normalizedText;
2221
+ this.pendingAssistantTranscript = '';
2222
+ if (finalText.trim().length > 0) {
2223
+ this.conversationMemory.Record({
2224
+ Kind: 'assistant',
2225
+ Text: finalText,
2226
+ });
2227
+ }
2228
+ }
2229
+ }
2230
+ }
2023
2231
  if (!this.transcriptHandler) {
2024
2232
  return;
2025
2233
  }
2026
- const t = { Role: role, Text: text ?? '', IsFinal: finished ?? false };
2234
+ const t = { Role: role, Text: normalizedText, IsFinal: isFinal };
2027
2235
  if (kind === 'narration') {
2028
2236
  t.Kind = 'narration';
2029
2237
  }
@@ -2037,6 +2245,7 @@ class GeminiRealtimeSession {
2037
2245
  if (!functionCalls) {
2038
2246
  return;
2039
2247
  }
2248
+ this.flushPendingMemoryTranscripts();
2040
2249
  // The model has yielded the floor pending the tool result — clear the busy flag (without
2041
2250
  // draining the queue; queued sends flush at the next real turn boundary) so the eventual
2042
2251
  // SendToolResult and any fresh context note are not deferred behind a turn that will not
@@ -2047,16 +2256,22 @@ class GeminiRealtimeSession {
2047
2256
  for (const call of functionCalls) {
2048
2257
  const callID = call.id ?? '';
2049
2258
  const toolName = call.name ?? '';
2259
+ const argsJson = JSON.stringify(call.args ?? {});
2050
2260
  // Cache the call's name (regardless of whether a tool-call handler is registered) so
2051
2261
  // SendToolResult can supply it to Gemini's sendToolResponse, which requires the function
2052
2262
  // name the Core contract does not carry.
2053
2263
  this.pendingToolCallNames.set(callID, toolName);
2264
+ this.conversationMemory.Record({
2265
+ Kind: 'toolCall',
2266
+ Name: toolName,
2267
+ ArgumentsJson: argsJson,
2268
+ });
2054
2269
  // A pending call keeps its turn open until its result goes out (see IsTurnOpen).
2055
2270
  this.markTurnOpen();
2056
2271
  this.toolCallHandler?.({
2057
2272
  CallID: callID,
2058
2273
  ToolName: toolName,
2059
- Arguments: JSON.stringify(call.args ?? {}),
2274
+ Arguments: argsJson,
2060
2275
  });
2061
2276
  }
2062
2277
  }
@@ -2104,11 +2319,15 @@ class GeminiRealtimeSession {
2104
2319
  this.toolCallHandler = null;
2105
2320
  this.interruptionHandler = null;
2106
2321
  this.usageHandler = null;
2322
+ this.errorHandler = null;
2107
2323
  this.pendingToolCallNames.clear();
2324
+ this.callsFromBeforeReseed.clear();
2108
2325
  this.queuedSends = [];
2109
2326
  this.responseActive = false;
2110
2327
  this.openClientTurn = false;
2111
2328
  this.pendingThoughtText = '';
2329
+ this.pendingUserTranscript = '';
2330
+ this.pendingAssistantTranscript = '';
2112
2331
  }
2113
2332
  /** Returns the bound live session or throws if it was never attached / already closed. */
2114
2333
  requireLive() {