@memberjunction/ai-gemini 6.2.0-edge.2 → 6.2.0-edge.4

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,8 +11,10 @@ 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, REALTIME_SHARED_CONFIG_KEYS, ExtractToolSchedulingHint, } from '@memberjunction/ai';
15
- import { ResolveGeminiLiveProfile, ResolveGeminiThinkingLevel, GEMINI_LIVE_FALLBACK_PROFILE, } from './geminiLiveProfiles.js';
14
+ import { BaseRealtimeModel, RealtimeDiagLog, RealtimeDroppedInputReporter, REALTIME_SHARED_CONFIG_KEYS, ExtractToolSchedulingHint, ParseDurationToMs, IsPcmAudioMimeType, RealtimeConnectionSetup, RealtimeSessionResumption, } from '@memberjunction/ai';
15
+ import { ResolveGeminiLiveProfile, ResolveGeminiMaxInboundVideoStreams, ResolveGeminiThinkingLevel, ResolveGeminiTurnCoverage, GEMINI_LIVE_FALLBACK_PROFILE, } from './geminiLiveProfiles.js';
16
+ import { GeminiBridgedAvatarOutput } from './geminiBridgedAvatar.js';
17
+ import { ResolveGeminiAvatarVideoBitrateBps } from './geminiAvatarVideoBitrate.js';
16
18
  import { RegisterClass } from '@memberjunction/global';
17
19
  /**
18
20
  * MIME type Gemini Live expects for client-streamed audio: 16-bit signed PCM at 16 kHz, mono.
@@ -20,8 +22,28 @@ import { RegisterClass } from '@memberjunction/global';
20
22
  * raw `ArrayBuffer` and leaves resampling/playback to the consumer.
21
23
  */
22
24
  const GEMINI_INPUT_AUDIO_MIME_TYPE = 'audio/pcm;rate=16000';
25
+ /** Image types Gemini Live accepts as video input frames. */
26
+ const GEMINI_VIDEO_INPUT_MIME_TYPES = new Set(['image/jpeg', 'image/png']);
27
+ /** The endpoints' names in log lines. */
28
+ const GEMINI_ENDPOINT_NAMES = { developer: 'the Gemini Developer API', enterprise: 'Gemini Enterprise' };
29
+ /**
30
+ * The keys in `REALTIME_SHARED_CONFIG_KEYS` that this driver applies after the config-bag merge, reading them from the
31
+ * original bag in `applyModelLegality`, with the value each must hold: `turnDetection` (its `Coverage` sets the turn
32
+ * coverage), `reasoning` (the thinking level and thought summaries), and `effortLevel` or `reasoningEffort` (a named
33
+ * thinking level). The scrub in `BuildConnectConfig` keeps them out of the merge without calling them non-Gemini
34
+ * (#5334). The other shared keys the driver applies (`voice`, `disableAutoResponse`, `tooling`, `toolBehavior`) are
35
+ * consumed before the scrub.
36
+ */
37
+ const GEMINI_SHARED_KEYS_APPLIED_AFTER_MERGE = new Map([
38
+ ['turnDetection', 'object'],
39
+ ['reasoning', 'object'],
40
+ ['effortLevel', 'named effort'],
41
+ ['reasoningEffort', 'named effort'],
42
+ ]);
23
43
  /** Meeting-mode watchdog: how long to wait for a turn after `activityEnd` before clearing a latched `responseActive` (shorter than the bridge's floor safety timer). */
24
44
  const GEMINI_MEETING_RESPONSE_WATCHDOG_MS = 5000;
45
+ /** The most input audio held while a session moves to a new connection: 2 s of 16-bit mono PCM at the 16 kHz input rate. */
46
+ const MAX_HELD_INPUT_AUDIO_BYTES = 16000 * 2 * 2;
25
47
  /**
26
48
  * Window (ms) within which a client-direct browser must OPEN its Live session using a minted
27
49
  * ephemeral token. After this the token can no longer start a NEW session (an already-open
@@ -33,6 +55,16 @@ const GEMINI_CLIENT_TOKEN_NEW_SESSION_WINDOW_MS = 10 * 60 * 1000;
33
55
  * authenticated with the token are rejected after this point.
34
56
  */
35
57
  const GEMINI_CLIENT_TOKEN_EXPIRY_MS = 30 * 60 * 1000;
58
+ /**
59
+ * The detail field each Gemini usage modality's token count goes into (the browser client keeps the same table); other
60
+ * modalities are not kept.
61
+ */
62
+ const GEMINI_MODALITY_TOKEN_FIELDS = {
63
+ TEXT: 'TextTokens',
64
+ AUDIO: 'AudioTokens',
65
+ IMAGE: 'ImageTokens',
66
+ VIDEO: 'VideoTokens',
67
+ };
36
68
  /**
37
69
  * Real-time, full-duplex driver for Google's **Gemini Live API**, implementing the Core
38
70
  * {@link BaseRealtimeModel} primitive.
@@ -99,20 +131,21 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
99
131
  * provider's frames and the MemberJunction realtime contract.
100
132
  */
101
133
  async StartSession(params) {
102
- const profile = ResolveGeminiLiveProfile(params.Model);
134
+ const profile = ResolveGeminiLiveProfile(params.Model, this.Endpoint);
103
135
  const session = new GeminiRealtimeSession(profile);
104
136
  session.SetConnectTimeTools(params.Tools ?? []);
105
- const config = this.buildConnectConfig(params);
137
+ const config = this.BuildConnectConfig(this.withoutAvatarOnServer(params));
138
+ session.SetAvatar(this.serverAvatarStatus(params, config), profile.AvatarOutputEncoding);
106
139
  // Meeting mode (auto activity detection disabled) → the session must drive turns manually.
107
140
  session.SetMeetingMode(config.realtimeInputConfig?.automaticActivityDetection?.disabled === true);
108
- const live = await this.connectLiveSession({
141
+ // The session opens its own connections through this seam, so it can resume on a new one
142
+ // with Google's handle when a connection ends (goAway) or drops.
143
+ session.SetConnector((handle, callbacks) => this.connectLiveSession({
109
144
  Model: params.Model,
110
- Config: config,
111
- OnMessage: (message) => session.HandleServerMessage(message),
112
- OnError: (event) => session.HandleTransportError(event?.message ?? 'Gemini Live websocket error'),
113
- OnClose: (event) => session.HandleTransportClose(event?.code, event?.reason),
114
- });
115
- session.AttachLiveSession(live);
145
+ Config: handle ? { ...config, sessionResumption: { ...config.sessionResumption, handle } } : config,
146
+ ...callbacks,
147
+ }));
148
+ await session.Open();
116
149
  // If the caller provided initial context, seed it as client content (without completing the
117
150
  // turn) so the model starts with the same history a loop agent would assemble.
118
151
  if (params.InitialContext && params.InitialContext.trim().length > 0) {
@@ -129,6 +162,23 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
129
162
  get SupportsClientDirect() {
130
163
  return true;
131
164
  }
165
+ /**
166
+ * The Gemini endpoint this driver talks to. The Developer API here; the Gemini Enterprise driver (Vertex AI)
167
+ * overrides it. Every profile lookup passes it, because what a model renders depends on the endpoint (live avatars
168
+ * are Enterprise only).
169
+ */
170
+ get Endpoint() {
171
+ return 'developer';
172
+ }
173
+ /**
174
+ * Whether the model renders a live avatar on this driver's endpoint, from its Live profile: never on the Developer
175
+ * API; on Gemini Enterprise for the models whose profile says so.
176
+ *
177
+ * @param model The model's API name.
178
+ */
179
+ SupportsAvatarOutput(model) {
180
+ return ResolveGeminiLiveProfile(model, this.Endpoint).SupportsAvatarOutput;
181
+ }
132
182
  /**
133
183
  * Gemini Live sessions accept dynamically-defined tools at connect/mint time.
134
184
  */
@@ -137,7 +187,7 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
137
187
  * Mints an ephemeral, server-scoped Live credential for a **client-direct** session.
138
188
  *
139
189
  * The connect config is built EXACTLY as {@link StartSession} builds it (same
140
- * {@link buildConnectConfig}: audio modality, input+output transcription, system instruction,
190
+ * {@link BuildConnectConfig}: audio modality, input+output transcription, system instruction,
141
191
  * mapped tools) and is **locked into the token** via `liveConnectConstraints` +
142
192
  * `lockAdditionalFields: []` — so the API ignores any attempt by the browser to change the
143
193
  * locked fields. The same config is ALSO carried in `SessionConfig` (as `{ model, config }`)
@@ -152,7 +202,7 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
152
202
  * @returns The minted {@link ClientRealtimeSessionConfig} the browser authenticates + applies.
153
203
  */
154
204
  async CreateClientSession(params) {
155
- const config = this.buildConnectConfig(params);
205
+ const config = this.BuildConnectConfig(params);
156
206
  const now = Date.now();
157
207
  const expireTime = new Date(now + GEMINI_CLIENT_TOKEN_EXPIRY_MS).toISOString();
158
208
  const newSessionExpireTime = new Date(now + GEMINI_CLIENT_TOKEN_NEW_SESSION_WINDOW_MS).toISOString();
@@ -177,29 +227,48 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
177
227
  if (!token.name) {
178
228
  throw new Error('Gemini auth-token mint returned no token name');
179
229
  }
180
- const profile = ResolveGeminiLiveProfile(params.Model);
230
+ const avatarStatus = this.AvatarStatusFor(params, config);
181
231
  return {
182
232
  Provider: 'gemini',
183
233
  Model: params.Model,
184
234
  EphemeralToken: token.name,
185
235
  ExpiresAt: expireTime,
186
- // Plain-JSON copy of what the browser passes to live.connect (model + config). The
187
- // token lock above makes these values authoritative even if a client tampers.
188
- SessionConfig: JSON.parse(JSON.stringify({
189
- model: params.Model,
190
- config,
191
- idleSignal: profile.IdleSignal,
192
- supportsScheduling: profile.Tooling.SupportsScheduling,
193
- supportsBlocking: profile.Tooling.SupportsBlockingExecution,
194
- // Per-model video legality travels with the mint so the browser driver never
195
- // has to infer it from the model id. The client cannot import this profile
196
- // table (@memberjunction/ai-realtime-client does not depend on the provider
197
- // package, by design), so the mint is the seam that carries it.
198
- supportsInboundVideo: profile.SupportsInboundVideo,
199
- maxInboundVideoRate: profile.MaxInboundVideoRate,
200
- })),
236
+ // The browser passes the full config to live.connect; the token lock above makes its
237
+ // values authoritative even if a client tampers.
238
+ SessionConfig: this.SessionPactFor(params.Model, config),
239
+ ...(avatarStatus ? { AvatarStatus: avatarStatus } : {}),
201
240
  };
202
241
  }
242
+ /**
243
+ * The minted session config, the private pact with the browser driver: a plain-JSON copy of the model and the config
244
+ * the browser passes to `live.connect`, plus the model's facts on this driver's endpoint (idle signal, tooling, inbound
245
+ * video limits, and the `avatar` block when the session renders one).
246
+ *
247
+ * @param model The model id.
248
+ * @param config The session's connect config, as {@link BuildConnectConfig} built it. It decides the avatar block.
249
+ * @param browserConfig The config the browser passes to `live.connect`: the full config here; a driver whose sessions
250
+ * go through MJAPI's relay, which writes the setup, passes a smaller one.
251
+ */
252
+ SessionPactFor(model, config, browserConfig = config) {
253
+ const profile = ResolveGeminiLiveProfile(model, this.Endpoint);
254
+ return JSON.parse(JSON.stringify({
255
+ model,
256
+ config: browserConfig,
257
+ idleSignal: profile.IdleSignal,
258
+ supportsScheduling: profile.Tooling.SupportsScheduling,
259
+ supportsBlocking: profile.Tooling.SupportsBlockingExecution,
260
+ // Per-model video legality travels with the mint so the browser driver never
261
+ // has to infer it from the model id. The client cannot import this profile
262
+ // table (@memberjunction/ai-realtime-client does not depend on the provider
263
+ // package, by design), so the mint is the seam that carries it.
264
+ supportsInboundVideo: profile.SupportsInboundVideo,
265
+ maxInboundVideoRate: profile.MaxInboundVideoRate,
266
+ // How many concurrent inbound video streams the model accepts (0 without video support).
267
+ // The browser's source arbiter maps live sources onto this many streams.
268
+ maxInboundVideoStreams: ResolveGeminiMaxInboundVideoStreams(profile),
269
+ ...this.AvatarPactFor(config, profile),
270
+ }));
271
+ }
203
272
  /**
204
273
  * Mint seam for the ephemeral auth token. Production routes through the SDK's
205
274
  * `authTokens.create` on a `v1alpha` client (ephemeral tokens are v1alpha-only); unit tests
@@ -259,6 +328,13 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
259
328
  * there — `systemInstruction`, `tools`, and the transcription configs are NOT, and their
260
329
  * presence 400s the entire mint. Only defined fields are copied (an absent key must stay
261
330
  * absent so it doesn't enter the mask).
331
+ *
332
+ * `contextWindowCompression` is left out on purpose. No test or doc shows the mask accepts
333
+ * it, and a rejected mask would fail every client-direct session. The browser applies it from
334
+ * `SessionConfig`, like the other server-built keys the token cannot lock.
335
+ *
336
+ * `sessionResumption: {}` is locked as in Google's ephemeral-token example. The browser adds
337
+ * the handle when it resumes, and Google accepts the same token for that until `expireTime`.
262
338
  */
263
339
  static BuildConstraintConfig(config) {
264
340
  const constraint = {};
@@ -336,23 +412,98 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
336
412
  MalformedExisting: malformedExisting,
337
413
  };
338
414
  }
415
+ /**
416
+ * Deletes every key in {@link REALTIME_SHARED_CONFIG_KEYS} from the copy of the config bag that is merged into the
417
+ * connect config, so none reaches the Live SDK raw, and logs what the session will not apply:
418
+ *
419
+ * - the keys Gemini Live has no use for, in one line;
420
+ * - a key the driver applies after the merge ({@link GEMINI_SHARED_KEYS_APPLIED_AFTER_MERGE}) whose value is of a
421
+ * type it cannot read, one line each. `null` reads as unset, the way a config layer clears an inherited value.
422
+ *
423
+ * A key the driver applies, with a value it can read, gets no line here: `applyModelLegality` applies it and logs a
424
+ * value the model or endpoint doesn't accept (a turn coverage, a thinking level).
425
+ *
426
+ * @param cfg The copy of the session config bag that is merged into the connect config. The keys are deleted from it.
427
+ */
428
+ static scrubSharedKeys(cfg) {
429
+ const notApplied = [];
430
+ for (const key of REALTIME_SHARED_CONFIG_KEYS) {
431
+ if (!(key in cfg)) {
432
+ continue;
433
+ }
434
+ const value = cfg[key];
435
+ delete cfg[key];
436
+ const shape = GEMINI_SHARED_KEYS_APPLIED_AFTER_MERGE.get(key);
437
+ if (shape === undefined) {
438
+ notApplied.push(key);
439
+ continue;
440
+ }
441
+ const unset = value === null || value === undefined;
442
+ const readable = shape === 'object' ? GeminiRealtime_1.readObject(value) !== undefined : typeof value === 'string';
443
+ if (!unset && !readable) {
444
+ const expected = shape === 'object' ? 'an object' : 'a named effort such as "medium"';
445
+ console.warn(`[GeminiRealtime] Ignored the session config bag's \`${key}\` because it is not ${expected} (got ${Array.isArray(value) ? 'array' : typeof value}).`);
446
+ }
447
+ }
448
+ if (notApplied.length > 0) {
449
+ console.warn(`[GeminiRealtime] Scrubbed non-Gemini config key(s) from the session bag: ${notApplied.join(', ')} — other realtime drivers use these; Gemini Live does not apply them.`);
450
+ }
451
+ }
452
+ /**
453
+ * Keeps a config-bag `contextWindowCompression` only when it is an object. The bag is untyped
454
+ * JSON, so a string, array or null would otherwise reach the wire and fail the session at
455
+ * connect. A malformed value is replaced by the default and reported; a well-formed one wins
456
+ * over the default, like every other bag key.
457
+ */
458
+ static ensureContextWindowCompression(config) {
459
+ const compression = config.contextWindowCompression;
460
+ if (GeminiRealtime_1.readObject(compression)) {
461
+ return;
462
+ }
463
+ const got = compression === null ? 'null' : Array.isArray(compression) ? 'array' : typeof compression;
464
+ console.warn(`[GeminiRealtime] Ignored the session config bag's \`contextWindowCompression\` because it is not an object (got ${got}); using the default sliding window.`);
465
+ config.contextWindowCompression = GeminiRealtime_1.DefaultContextWindowCompression();
466
+ }
339
467
  /** Narrows an unenforced config-bag value to a real object — not a string, array, or null. */
340
468
  static isPlainObject(value) {
341
469
  return typeof value === 'object' && value !== null && !Array.isArray(value);
342
470
  }
471
+ /**
472
+ * The context-window compression every Gemini Live session gets unless the config bag sets
473
+ * its own: a server-side sliding window with Google's default trigger and target sizes.
474
+ *
475
+ * Without compression, Google ends a session when its context fills: about 15 minutes for
476
+ * audio only and about 2 minutes for audio plus video (Google's Live API session-management
477
+ * docs). With compression the server drops the oldest turns and the session continues.
478
+ * Session resumption handles a different limit (a single connection lasts about 10 minutes)
479
+ * and does not lift this one.
480
+ *
481
+ * Returns a new object on each call so no session shares mutable config with another.
482
+ */
483
+ static DefaultContextWindowCompression() {
484
+ return { slidingWindow: {} };
485
+ }
343
486
  /**
344
487
  * Builds the {@link LiveConnectConfig} from the Core session params: audio response modality,
345
- * input/output transcription, system instruction, mapped tools, the neutral `voice` key mapped
346
- * via {@link GeminiRealtime.buildSpeechConfig}, plus any provider-specific overrides from the
347
- * open config bag.
488
+ * input/output transcription, system instruction, sliding-window context compression
489
+ * ({@link GeminiRealtime.DefaultContextWindowCompression}), session resumption (unless the
490
+ * session is zero-data-retention), mapped tools, the neutral `voice` key mapped via
491
+ * {@link GeminiRealtime.buildSpeechConfig}, plus any provider-specific overrides from the open
492
+ * config bag.
348
493
  */
349
- buildConnectConfig(params) {
494
+ BuildConnectConfig(params) {
350
495
  const config = {
351
496
  responseModalities: [Modality.AUDIO],
352
497
  inputAudioTranscription: {},
353
498
  outputAudioTranscription: {},
354
499
  systemInstruction: params.SystemPrompt,
500
+ contextWindowCompression: GeminiRealtime_1.DefaultContextWindowCompression(),
355
501
  };
502
+ // Resumption handles let a session continue across Gemini's ~10-minute connection limit.
503
+ // Zero-data-retention sessions never get them; see applyZeroDataRetention.
504
+ if (!params.ZeroDataRetention) {
505
+ config.sessionResumption = {};
506
+ }
356
507
  if (params.Tools && params.Tools.length > 0) {
357
508
  const bag = params.Config ?? {};
358
509
  const tooling = GeminiRealtime_1.readObject(bag['tooling']);
@@ -393,14 +544,15 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
393
544
  const reason = typeof rawVoice === 'string' ? 'blank' : `not a string (got ${typeof rawVoice})`;
394
545
  console.warn(`[GeminiRealtime] Ignored the session config bag's \`voice\` because it is ${reason} — expected a Gemini prebuilt voice name.`);
395
546
  }
396
- // Scrub the MJ-side keys shared across the realtime driver family (OpenAI-protocol
397
- // feature knobs + transport settings). They are NOT Gemini config keys — a co-agent
398
- // config carrying e.g. `effortLevel` or `mcpTools` must be SAFE on a Gemini session,
399
- // not spread raw into the Live SDK where strictness varies by version. Scrubbed keys
400
- // are diag-logged so config typos / cross-provider keys stop being silent.
401
- // The two keys Gemini translates natively (`disableAutoResponse`, `voice`) were already
402
- // consumed and deleted above, so the loop only ever sees keys with no Gemini mapping —
403
- // no per-key exemption needed here.
547
+ // Scrub the MJ-side keys shared across the realtime driver family. None is a Live config
548
+ // field — a co-agent config carrying e.g. `effortLevel` or `mcpTools` must not break a
549
+ // Gemini session by being spread raw into the Live SDK, where strictness varies by version.
550
+ // The keys this driver applies after the merge (`turnDetection`, `reasoning`,
551
+ // `effortLevel`, `reasoningEffort`) are read from params.Config by applyModelLegality, so
552
+ // the scrub reports one only when its value is of a type the driver cannot read; the
553
+ // rest are diag-logged so config typos and cross-provider keys stop being silent. The
554
+ // keys consumed above (`disableAutoResponse`, `voice`, `tooling`, `toolBehavior`) never
555
+ // reach it.
404
556
  //
405
557
  // This scrub NARROWS the silent-drop class of #3721; it does not close it. The list is an
406
558
  // allowlist of MJ-SHARED keys, not of non-Gemini keys, so anything outside it still rides
@@ -409,17 +561,9 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
409
561
  // deprecated but deliberately kept authorable in the agent-type ConfigSchema. Closing the
410
562
  // class means inverting this check to warn on any key that is not a known
411
563
  // `LiveConnectConfig` field — tracked separately rather than widened here.
412
- const scrubbed = [];
413
- for (const key of REALTIME_SHARED_CONFIG_KEYS) {
414
- if (key in cfg) {
415
- delete cfg[key];
416
- scrubbed.push(key);
417
- }
418
- }
419
- if (scrubbed.length > 0) {
420
- console.warn(`[GeminiRealtime] Scrubbed non-Gemini config key(s) from the session bag: ${scrubbed.join(', ')} — these are OpenAI-protocol/transport keys and do not apply to Gemini Live.`);
421
- }
564
+ GeminiRealtime_1.scrubSharedKeys(cfg);
422
565
  Object.assign(config, cfg);
566
+ GeminiRealtime_1.ensureContextWindowCompression(config);
423
567
  // Captured BEFORE the mapping below replaces or deletes it, so the warning can report the
424
568
  // type that was actually rejected rather than the type that replaced it.
425
569
  const rawSpeechConfig = config.speechConfig;
@@ -454,11 +598,147 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
454
598
  // config bag must not be able to reintroduce a key the target model has retired. Anything the
455
599
  // merge above put back is removed here.
456
600
  this.applyModelLegality(config, params);
601
+ GeminiRealtime_1.applyZeroDataRetention(config, params);
602
+ this.applyAvatarOutput(config, params);
457
603
  return config;
458
604
  }
459
605
  /**
460
- * Enforces what the TARGET model actually accepts, and states what MJ wants rather than
461
- * inheriting a provider default.
606
+ * Renders the requested avatar when the model can on this endpoint: video output and the avatar's name, at the
607
+ * bitrate the deployment asks for (`MJ_GEMINI_AVATAR_VIDEO_BITRATE_BPS`, 2 Mbps by default; `0` leaves the field out).
608
+ * Otherwise the session stays audio-only and one line says why. Either way a VIDEO modality or an `avatarConfig` from
609
+ * the config bag is removed: an avatar comes only from the session's avatar request. Applied last, like the legality
610
+ * rules. Every session's setup comes from here: the browser mint, the relay's setup and server-side sessions.
611
+ */
612
+ applyAvatarOutput(config, params) {
613
+ const request = params.Avatar;
614
+ const reason = request ? this.avatarUnavailableReason(request, params.Model) : undefined;
615
+ if (request && !reason) {
616
+ const videoBitrateBps = ResolveGeminiAvatarVideoBitrateBps();
617
+ config.responseModalities = [Modality.VIDEO];
618
+ config.avatarConfig = videoBitrateBps === null ? { avatarName: request.AvatarID.trim() } : { avatarName: request.AvatarID.trim(), videoBitrateBps };
619
+ return;
620
+ }
621
+ GeminiRealtime_1.removeVideoOutput(config, params.Model);
622
+ if (request && reason) {
623
+ console.warn(this.avatarUnavailableMessage(request, params.Model, reason));
624
+ }
625
+ }
626
+ /** Why this session can't render the requested avatar, or `undefined` when it can. */
627
+ avatarUnavailableReason(request, model) {
628
+ if ((request.Kind ?? 'preset') === 'custom') {
629
+ return 'custom-disabled';
630
+ }
631
+ if (!ResolveGeminiLiveProfile(model, this.Endpoint).SupportsAvatarOutput) {
632
+ return 'endpoint';
633
+ }
634
+ return request.AvatarID?.trim() ? undefined : 'unknown-avatar';
635
+ }
636
+ /** The one log line for an avatar the session asked for and won't render. */
637
+ avatarUnavailableMessage(request, model, reason) {
638
+ const why = {
639
+ endpoint: `${model} on ${GEMINI_ENDPOINT_NAMES[this.Endpoint]} renders no avatar`,
640
+ bridged: "a session on the server whose host can't publish video into a room",
641
+ phone: 'a phone caller sees no video',
642
+ 'custom-disabled': 'custom avatars are not enabled',
643
+ 'unknown-avatar': 'the request names no avatar',
644
+ 'no-binding': 'the persona has no avatar on this vendor',
645
+ host: 'the app showing the call asks for no agent video',
646
+ browser: 'the browser cannot play the avatar',
647
+ 'decoder-missing': 'the meeting host has no usable video decoder',
648
+ 'decoder-failed': "the meeting bot's decoders kept failing",
649
+ 'publish-failed': 'the meeting room refused the video track',
650
+ 'video-off': "the agent's video setting is off",
651
+ };
652
+ const persona = request.PersonaName ? ` (persona ${request.PersonaName})` : '';
653
+ return `[GeminiRealtime] Avatar "${request.AvatarID}"${persona} not used: ${why[reason]}. The call is audio only. Reason: ${reason}.`;
654
+ }
655
+ /** Removes a VIDEO response modality and any `avatarConfig` that came from somewhere other than an avatar request. */
656
+ static removeVideoOutput(config, model) {
657
+ if (config.avatarConfig !== undefined) {
658
+ delete config.avatarConfig;
659
+ console.warn(`[GeminiRealtime] Dropped \`avatarConfig\` from the session config for ${model}: an avatar comes only from the session's avatar request.`);
660
+ }
661
+ const modalities = config.responseModalities ?? [];
662
+ if (modalities.includes(Modality.VIDEO)) {
663
+ const rest = modalities.filter((m) => m !== Modality.VIDEO);
664
+ config.responseModalities = rest.length > 0 ? rest : [Modality.AUDIO];
665
+ console.warn(`[GeminiRealtime] Dropped the VIDEO response modality for ${model}: video output comes only from an avatar request the model can render.`);
666
+ }
667
+ }
668
+ /**
669
+ * A server-side session (a meeting bot) asks for an avatar only when its host publishes the video into a room
670
+ * (`Delivery: 'room'`, a bot that decodes it). Anywhere else nothing on the server can show it: returns the params
671
+ * without the request, logging the reason once. A phone call never gets here with a request: its session prep asks
672
+ * for none (`'phone'`).
673
+ */
674
+ withoutAvatarOnServer(params) {
675
+ if (!params.Avatar || params.Avatar.Delivery === 'room') {
676
+ return params;
677
+ }
678
+ console.warn(this.avatarUnavailableMessage(params.Avatar, params.Model, 'bridged'));
679
+ return { ...params, Avatar: undefined };
680
+ }
681
+ /**
682
+ * What the mint tells the call about the avatar the session asked for: granted, or audio only and why. `undefined` when
683
+ * it asked for none. Read from the connect config {@link BuildConnectConfig} built, so it says what the session does:
684
+ * an `avatarConfig` there is the grant. Every Gemini driver returns it on its minted config.
685
+ *
686
+ * @param params The session parameters (the avatar request).
687
+ * @param config The connect config the session was built with.
688
+ */
689
+ AvatarStatusFor(params, config) {
690
+ const request = params.Avatar;
691
+ if (!request) {
692
+ return undefined;
693
+ }
694
+ if (config.avatarConfig) {
695
+ return { Requested: true, Granted: true };
696
+ }
697
+ const reason = this.avatarUnavailableReason(request, params.Model);
698
+ return reason ? { Requested: true, Granted: false, Reason: reason } : { Requested: true, Granted: false };
699
+ }
700
+ /**
701
+ * What became of a server-side session's avatar request: {@link AvatarStatusFor}, except that a session whose host
702
+ * can't publish the avatar (no `Delivery: 'room'`) is audio only as `bridged`. `undefined` without a request.
703
+ *
704
+ * @param params The session parameters as the host passed them (the avatar request included).
705
+ * @param config The connect config the session was built with.
706
+ */
707
+ serverAvatarStatus(params, config) {
708
+ const status = this.AvatarStatusFor(params, config);
709
+ if (!status || status.Granted || params.Avatar?.Delivery === 'room') {
710
+ return status;
711
+ }
712
+ return { ...status, Reason: 'bridged' };
713
+ }
714
+ /**
715
+ * The minted session config's avatar block: present only when this session renders an avatar, so the browser driver
716
+ * knows to expect video parts, their encoding, and whether they carry the voice.
717
+ *
718
+ * @param config The connect config the session was built with.
719
+ * @param profile The model's profile on this driver's endpoint.
720
+ */
721
+ AvatarPactFor(config, profile) {
722
+ if (!config.avatarConfig) {
723
+ return {};
724
+ }
725
+ return { avatar: { output: true, encoding: profile.AvatarOutputEncoding ?? null, audioMuxed: profile.AvatarAudioMuxed ?? true } };
726
+ }
727
+ /**
728
+ * Keeps session resumption off a zero-data-retention session, even when the config bag asks
729
+ * for it: Google stores resumable session state, which such a model promises not to do.
730
+ * Applied after the bag merge, like the legality rules, so the bag cannot turn it back on.
731
+ */
732
+ static applyZeroDataRetention(config, params) {
733
+ if (!params.ZeroDataRetention || config.sessionResumption === undefined) {
734
+ return;
735
+ }
736
+ delete config.sessionResumption;
737
+ console.warn(`[GeminiRealtime] Dropped \`sessionResumption\` for ${params.Model}: the model is served under zero data retention, and resumption stores session data on Google's side.`);
738
+ }
739
+ /**
740
+ * Enforces what the TARGET model, on the session's endpoint, actually accepts, and states what MJ
741
+ * wants rather than inheriting a provider default.
462
742
  *
463
743
  * Every rule here fails at SESSION MINT if broken — upstream of all UI code, the same failure
464
744
  * class as an illegal tool name — so none of it can be left to discover at connect time. Facts
@@ -466,10 +746,12 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
466
746
  * `plans/realtime/gemini-3-8-live.md` §3 for their sourcing.
467
747
  */
468
748
  applyModelLegality(config, params) {
469
- const profile = ResolveGeminiLiveProfile(params.Model);
749
+ const profile = ResolveGeminiLiveProfile(params.Model, this.Endpoint);
470
750
  // The catalog's ModelConfiguration.Realtime reaches a driver folded into the session Config
471
751
  // BAG as neutral keys (the same route `turnDetection` already travels), not as a field on
472
- // RealtimeSessionParams — so read it from there.
752
+ // RealtimeSessionParams — so read it from there. A shared key read here belongs in
753
+ // GEMINI_SHARED_KEYS_APPLIED_AFTER_MERGE; otherwise the scrub logs it as a key Gemini Live
754
+ // does not apply.
473
755
  const bag = params.Config ?? {};
474
756
  const reasoning = GeminiRealtime_1.readObject(bag['reasoning']);
475
757
  const turnDetection = GeminiRealtime_1.readObject(bag['turnDetection']);
@@ -522,18 +804,7 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
522
804
  else {
523
805
  delete config.thinkingConfig;
524
806
  }
525
- // C4 — turn coverage is STATED, never inherited. The SDK's enum doc says coverage defaults to
526
- // TURN_INCLUDES_ONLY_ACTIVITY while the 3.8 model page says the default includes all video;
527
- // sending it explicitly makes that contradiction irrelevant. Absent config means audio-only,
528
- // because video frames are billed and consume context, so the expensive option must be asked
529
- // for rather than inherited.
530
- const coverage = coverageSetting ?? 'audioActivityOnly';
531
- config.realtimeInputConfig = {
532
- ...(config.realtimeInputConfig ?? {}),
533
- turnCoverage: coverage === 'audioActivityAndAllVideo'
534
- ? TurnCoverage.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO
535
- : TurnCoverage.TURN_INCLUDES_ONLY_ACTIVITY,
536
- };
807
+ GeminiRealtime_1.applyTurnCoverage(config, coverageSetting, profile, params.Model);
537
808
  // C5 / C5a / C5b — state behavior on every declaration, whatever its origin.
538
809
  // Drops the !SupportsBlockingExecution gate so 3.8-live bag tools are stated too.
539
810
  if (config.tools) {
@@ -575,6 +846,38 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
575
846
  }
576
847
  }
577
848
  }
849
+ /**
850
+ * C4 — turn coverage is STATED, never inherited. The SDK's enum doc says coverage defaults to
851
+ * TURN_INCLUDES_ONLY_ACTIVITY while the 3.8 model page says the default includes all video; sending it explicitly
852
+ * makes that contradiction irrelevant. Absent config means audio only, because video frames are billed and consume
853
+ * context, so the expensive option must be asked for rather than inherited. Only a coverage the session's endpoint
854
+ * accepts is sent ({@link ResolveGeminiTurnCoverage}): Gemini Enterprise closes the setup on
855
+ * TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO, so a session there that asks for it gets audio only, and one line names
856
+ * what was asked for and what was sent. The setup the relay writes and a bridged session's both come from here.
857
+ *
858
+ * @param config The connect config being built.
859
+ * @param requested The bag's `turnDetection.Coverage`, if any.
860
+ * @param profile The model's profile on the session's endpoint.
861
+ * @param model The model id, for the log line.
862
+ */
863
+ static applyTurnCoverage(config, requested, profile, model) {
864
+ const coverage = ResolveGeminiTurnCoverage(requested, profile);
865
+ const wire = GeminiRealtime_1.mapTurnCoverage(coverage.Coverage);
866
+ if (coverage.Refused !== undefined) {
867
+ console.warn(`[GeminiRealtime] Turn coverage ${JSON.stringify(coverage.Refused)} is not one ${GEMINI_ENDPOINT_NAMES[profile.Endpoint]} ` +
868
+ `accepts for ${model} (it accepts ${profile.AcceptedTurnCoverages.join(', ')}); sent "${coverage.Coverage}" (${wire}) instead.`);
869
+ }
870
+ config.realtimeInputConfig = { ...(config.realtimeInputConfig ?? {}), turnCoverage: wire };
871
+ }
872
+ /** Maps MJ's turn coverage onto the SDK's {@link TurnCoverage} wire value. */
873
+ static mapTurnCoverage(coverage) {
874
+ switch (coverage) {
875
+ case 'audioActivityOnly':
876
+ return TurnCoverage.TURN_INCLUDES_ONLY_ACTIVITY;
877
+ case 'audioActivityAndAllVideo':
878
+ return TurnCoverage.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO;
879
+ }
880
+ }
578
881
  /**
579
882
  * Narrows a bag value to a plain object, or `undefined`.
580
883
  *
@@ -701,6 +1004,7 @@ class GeminiRealtimeSession {
701
1004
  this.OutputSampleRate = 24000;
702
1005
  this.live = null;
703
1006
  this.outputHandler = null;
1007
+ this.videoFrameHandler = null;
704
1008
  this.transcriptHandler = null;
705
1009
  this.toolCallHandler = null;
706
1010
  this.interruptionHandler = null;
@@ -717,6 +1021,10 @@ class GeminiRealtimeSession {
717
1021
  this.pendingToolCallNames = new Map();
718
1022
  /** Accumulates in-flight thought text deltas until finalized on turn completion. */
719
1023
  this.pendingThoughtText = '';
1024
+ /** MIME types of model output this session dropped, so each is reported once. */
1025
+ this.droppedOutputTypes = new Set();
1026
+ /** Reports the input frames {@link SendInput} drops, once per kind and type. */
1027
+ this.droppedInput = new RealtimeDroppedInputReporter('GeminiRealtime', 'Gemini Live takes PCM audio and JPEG or PNG video frames');
720
1028
  /**
721
1029
  * Fingerprint of the tool set bound at connect time (set via {@link SetConnectTimeTools});
722
1030
  * {@link RegisterTools} compares against it to no-op identical re-registrations.
@@ -726,11 +1034,13 @@ class GeminiRealtimeSession {
726
1034
  /**
727
1035
  * Whether a model turn is currently being generated. Minimal turn tracking mirroring the
728
1036
  * client driver: set when model output arrives (Gemini has no `response.created`-style frame,
729
- * so the first `modelTurn` content is the signal) and eagerly when this session itself sends a
730
- * turn-triggering client content; cleared on `turnComplete`, `interrupted`, and a tool-call
731
- * frame (the model yields the floor pending the result). Consumed by {@link enqueueOrRun}:
732
- * on Gemini Live ANY client content sent mid-turn INTERRUPTS the in-flight generation, so
733
- * interim-update sends are deferred rather than sent into an active turn.
1037
+ * so the first `modelTurn` content is the signal; an avatar's video sets it only while the
1038
+ * model's answer is under way, since Vertex AI streams it between answers too) and eagerly
1039
+ * when this session itself sends a turn-triggering client content; cleared on `turnComplete`,
1040
+ * `interrupted`, and a tool-call frame (the model yields the floor pending the result).
1041
+ * Consumed by {@link enqueueOrRun}: on Gemini Live ANY client content sent mid-turn
1042
+ * INTERRUPTS the in-flight generation, so interim-update sends are deferred rather than sent
1043
+ * into an active turn.
734
1044
  */
735
1045
  this.responseActive = false;
736
1046
  /**
@@ -739,6 +1049,13 @@ class GeminiRealtimeSession {
739
1049
  * {@link Close} so a closed session never replays stale sends.
740
1050
  */
741
1051
  this.queuedSends = [];
1052
+ /**
1053
+ * Whether a context note left the client turn open. {@link SendContextNote} sends `turnComplete: false`, which tells
1054
+ * Gemini more input is coming, and Gemini then holds all generation, the continuation after a tool result included,
1055
+ * until a `turnComplete: true` arrives. Set when a note goes out; cleared when {@link SendToolResult} closes the
1056
+ * turn, at the model's `turnComplete` (its generation took the note in), and on {@link Close}.
1057
+ */
1058
+ this.openClientTurn = false;
742
1059
  /**
743
1060
  * Whether this session runs in MEETING mode — Gemini's automatic activity detection is disabled, so the
744
1061
  * model never auto-responds to room audio. The bridge drives turns manually instead: an `activityStart`
@@ -748,13 +1065,107 @@ class GeminiRealtimeSession {
748
1065
  this.meetingMode = false;
749
1066
  /** In meeting mode, whether a manual input window (`activityStart` … pending `activityEnd`) is open. */
750
1067
  this.manualActivityOpen = false;
1068
+ /** Opens this session's Live connections; set by the driver before {@link Open}. */
1069
+ this.connector = null;
1070
+ /**
1071
+ * Routes model parts, turn boundaries and avatar usage when the driver granted an avatar to a host that publishes it
1072
+ * into a room; null on every other session, whose output is PCM only.
1073
+ */
1074
+ this.avatarOutput = null;
1075
+ /**
1076
+ * Moves the session to a new connection with Google's resumption handle: when Google announces
1077
+ * the connection is ending (`goAway`, with the time left; on Vertex AI it came about 9 minutes
1078
+ * into a connection, with 30 s left) and after an unexpected drop. A planned move waits until
1079
+ * no turn is in progress ({@link IsTurnOpen}). Created by {@link Open}.
1080
+ */
1081
+ this.resumption = null;
1082
+ /**
1083
+ * Whether the session is moving to a new connection: from the start of a move until Google
1084
+ * confirms the new connection's setup (`setupComplete`). Input waits meanwhile, in
1085
+ * {@link queuedSends} and {@link heldAudio}: the connection being replaced resumes from a handle
1086
+ * issued before the move, so what it receives never reaches the new one, and Google drops input
1087
+ * that reaches the new one before its setup completes. The first connection needs no flag:
1088
+ * {@link Open} returns only once its setup is confirmed.
1089
+ */
1090
+ this.moving = false;
1091
+ /** Input audio that came during a move, sent on the new connection once it is ready. */
1092
+ this.heldAudio = [];
1093
+ /** Bytes in {@link heldAudio}, kept under {@link MAX_HELD_INPUT_AUDIO_BYTES}. */
1094
+ this.heldAudioBytes = 0;
1095
+ /** See {@link IsTurnOpen}. */
1096
+ this.turnOpen = false;
1097
+ /** A turn's `turnComplete` came while a tool call was pending: the turn ends once the last pending call's result goes out. */
1098
+ this.turnEndAwaitsToolResults = false;
1099
+ /** Last connection number handed out by {@link openConnection}. */
1100
+ this.issuedConnections = 0;
1101
+ /**
1102
+ * Number of the connection in use. Callbacks from any other connection (one that was replaced,
1103
+ * closed, or is still opening) are ignored, so a replaced socket's close can't end the session
1104
+ * that replaced it. `0` while no connection is in use.
1105
+ */
1106
+ this.currentConnection = 0;
751
1107
  this.profile = profile ?? GEMINI_LIVE_FALLBACK_PROFILE;
752
1108
  }
1109
+ /** Sets how this session opens its Live connections. Called by the driver before {@link Open}. */
1110
+ SetConnector(connector) {
1111
+ this.connector = connector;
1112
+ }
1113
+ /**
1114
+ * Records what became of the session's avatar request. A granted one (a server-side session whose host publishes the
1115
+ * avatar into a room) sends the model's MP4 pieces as frames to {@link OnVideoFrame} (marked `Idle` outside an
1116
+ * answer), keeps PCM to turns without video, marks the model generating for its answer's media only, and reports the
1117
+ * avatar's video seconds through {@link OnUsage}. Called by the driver before {@link Open}.
1118
+ *
1119
+ * @param status The avatar status, or `undefined` when the session asked for no avatar.
1120
+ * @param encoding The avatar's MSE type from the model's profile.
1121
+ */
1122
+ SetAvatar(status, encoding) {
1123
+ this.AvatarStatus = status;
1124
+ this.avatarEncoding = encoding;
1125
+ this.avatarOutput = status?.Granted
1126
+ ? new GeminiBridgedAvatarOutput({
1127
+ OnVideoFrame: (frame) => this.videoFrameHandler?.(frame),
1128
+ OnPcm: (pcm) => this.outputHandler?.(pcm),
1129
+ OnVideoSeconds: (seconds) => this.usageHandler?.({ InputTokens: 0, OutputTokens: 0, OutputTokenDetails: { VideoSeconds: seconds } }),
1130
+ OnAnswer: () => this.markAnswering(),
1131
+ Report: (message) => console.warn(message),
1132
+ })
1133
+ : null;
1134
+ }
1135
+ /**
1136
+ * Opens the first connection and puts it to use once Google confirms its setup (`setupComplete`): input sent before
1137
+ * that is dropped, so nothing (the initial context, the first audio) goes out until then. Called by the driver once
1138
+ * the session is configured.
1139
+ *
1140
+ * @throws When the connection closes or fails before Google confirms its setup, or no confirmation comes in time.
1141
+ */
1142
+ async Open() {
1143
+ this.resumption = new RealtimeSessionResumption({
1144
+ Reconnect: (handle, attempt) => this.resume(handle, attempt),
1145
+ OnReconnecting: (reason) => {
1146
+ RealtimeDiagLog(`[GeminiRealtime] Resuming the session on a new connection (${reason})`);
1147
+ // From the moment a move starts, input waits for the new connection.
1148
+ this.moving = true;
1149
+ },
1150
+ OnReconnected: () => this.handleResumed(),
1151
+ OnReconnectFailed: (error) => this.handleResumeFailed(error),
1152
+ Log: (message) => RealtimeDiagLog(message),
1153
+ });
1154
+ const opened = await this.openConnection(undefined);
1155
+ await GeminiRealtimeSession.awaitSetup(opened);
1156
+ this.useConnection(opened);
1157
+ }
753
1158
  /**
754
- * Binds the underlying live session. Called by the driver once `connect` resolves.
1159
+ * Whether a turn is in progress. A turn opens at its first sign: the user's first transcribed words (outside meeting
1160
+ * mode, where room speech is no turn until the bridge commits one), a spoken update this session sends, or the
1161
+ * model's output (a transcription delta, a thought, a tool call, or an audio part, which in an avatar session must
1162
+ * play as the voice; the video an avatar streams between turns never opens one). It closes at the turn's
1163
+ * `turnComplete` once no tool call is pending, or when the last pending call's result goes out after that; at a
1164
+ * meeting-mode commit that produced no turn; and at a resume. The session moves to a new connection only between
1165
+ * turns.
755
1166
  */
756
- AttachLiveSession(live) {
757
- this.live = live;
1167
+ get IsTurnOpen() {
1168
+ return this.turnOpen;
758
1169
  }
759
1170
  /** Sets MEETING mode (manual turn-taking). Called by the driver from the connect config at start. */
760
1171
  SetMeetingMode(on) {
@@ -773,16 +1184,26 @@ class GeminiRealtimeSession {
773
1184
  Modality: 'video',
774
1185
  Direction: 'inbound',
775
1186
  Encoding: 'image/jpeg',
776
- Rate: 1,
1187
+ // The model's own ceiling from the profile table; a bridged host paces frames to it.
1188
+ Rate: this.profile.MaxInboundVideoRate,
777
1189
  UsageBasis: ['tokens', 'frames'],
778
1190
  RequiresConsent: true,
779
1191
  });
780
1192
  }
1193
+ const outbound = [{ Modality: 'audio', Direction: 'outbound' }];
1194
+ if (this.avatarOutput) {
1195
+ // A granted avatar: its MP4 pieces reach the host as frames through OnVideoFrame.
1196
+ outbound.push({ Modality: 'video', Direction: 'outbound', ...(this.avatarEncoding ? { Encoding: this.avatarEncoding } : {}) });
1197
+ }
781
1198
  return {
782
1199
  CanReconfigureTurnMode: false,
1200
+ // Proactive audio is permanently on for the 3.8 line: the model listens while speaking and decides
1201
+ // for itself when to speak. A meeting-mode session (auto activity detection off) is turn-based.
1202
+ FullDuplex: this.profile.ProactiveAudioAlwaysOn && !this.meetingMode,
783
1203
  SupportsDynamicToolSet: GeminiRealtime.SupportsDynamicToolSet,
784
1204
  SupportedInboundTracks: inbound,
785
- SupportedOutboundTracks: [{ Modality: 'audio', Direction: 'outbound' }],
1205
+ MaxInboundVideoStreams: ResolveGeminiMaxInboundVideoStreams(this.profile),
1206
+ SupportedOutboundTracks: outbound,
786
1207
  ProvidesThoughtSummaries: this.profile.SupportsThoughtSummaries,
787
1208
  SupportsAsynchronousReasoning: !this.profile.Tooling.SupportsBlockingExecution,
788
1209
  UsageBases: this.profile.SupportsInboundVideo ? ['tokens', 'seconds', 'frames'] : ['tokens', 'seconds'],
@@ -796,22 +1217,74 @@ class GeminiRealtimeSession {
796
1217
  const turns = [{ role: 'user', parts: [{ text: context }] }];
797
1218
  this.requireLive().sendClientContent({ turns, turnComplete: false });
798
1219
  }
799
- /** @inheritdoc */
800
- SendInput(chunk) {
1220
+ /**
1221
+ * @inheritdoc
1222
+ *
1223
+ * Audio goes out as `audio` in the frame's PCM format (16 kHz PCM when the frame names none).
1224
+ * Video goes out as `video` when the frame is a JPEG or PNG image, the types Gemini Live accepts.
1225
+ * Anything else is dropped and reported once per type, never sent as the wrong kind.
1226
+ *
1227
+ * While the session moves to a new connection, audio is held (the latest 2 s) and goes out on
1228
+ * the new connection once it is ready; a video frame is dropped, as the next one follows.
1229
+ */
1230
+ SendInput(frame) {
1231
+ if (frame.Kind === 'video') {
1232
+ if (!this.moving) {
1233
+ this.sendVideoInput(frame);
1234
+ }
1235
+ return;
1236
+ }
1237
+ if (this.moving) {
1238
+ this.holdAudio(frame);
1239
+ return;
1240
+ }
1241
+ this.sendAudioInput(frame);
1242
+ }
1243
+ /**
1244
+ * Holds an audio frame during a move, keeping the latest {@link MAX_HELD_INPUT_AUDIO_BYTES}; older audio goes first.
1245
+ * The bytes are copied, so a host that reuses its buffers can't change what is held.
1246
+ */
1247
+ holdAudio(frame) {
1248
+ this.heldAudio.push({ ...frame, Data: frame.Data.slice(0) });
1249
+ this.heldAudioBytes += frame.Data.byteLength;
1250
+ while (this.heldAudioBytes > MAX_HELD_INPUT_AUDIO_BYTES && this.heldAudio.length > 1) {
1251
+ this.heldAudioBytes -= this.heldAudio.shift()?.Data.byteLength ?? 0;
1252
+ }
1253
+ }
1254
+ /** Sends the audio held during a move on the connection now in use, oldest first. */
1255
+ sendHeldAudio() {
1256
+ const held = this.heldAudio;
1257
+ this.heldAudio = [];
1258
+ this.heldAudioBytes = 0;
1259
+ for (const frame of held) {
1260
+ this.sendAudioInput(frame);
1261
+ }
1262
+ }
1263
+ sendAudioInput(frame) {
1264
+ const mimeType = frame.MimeType ?? GEMINI_INPUT_AUDIO_MIME_TYPE;
1265
+ if (!IsPcmAudioMimeType(mimeType)) {
1266
+ this.droppedInput.Report(frame);
1267
+ return;
1268
+ }
801
1269
  const live = this.requireLive();
802
1270
  // Meeting mode: automatic activity detection is OFF, so audio is only processed inside an explicit
803
1271
  // activity window. Open one lazily on the first audio after the last turn was committed — the window
804
1272
  // stays open (accumulating what the agent hears) until RequestSpokenUpdate sends `activityEnd`.
1273
+ // Only audio opens it: a video frame is not speech.
805
1274
  if (this.meetingMode && !this.manualActivityOpen) {
806
1275
  live.sendRealtimeInput({ activityStart: {} });
807
1276
  this.manualActivityOpen = true;
808
1277
  RealtimeDiagLog('[GeminiRealtime][diag] meeting: activityStart — opened input window on first audio (now accumulating room audio)');
809
1278
  }
810
- const audio = {
811
- data: GeminiRealtimeSession.arrayBufferToBase64(chunk),
812
- mimeType: GEMINI_INPUT_AUDIO_MIME_TYPE,
813
- };
814
- live.sendRealtimeInput({ audio });
1279
+ live.sendRealtimeInput({ audio: { data: GeminiRealtimeSession.arrayBufferToBase64(frame.Data), mimeType } });
1280
+ }
1281
+ sendVideoInput(frame) {
1282
+ const mimeType = frame.MimeType?.trim().toLowerCase();
1283
+ if (!mimeType || !GEMINI_VIDEO_INPUT_MIME_TYPES.has(mimeType)) {
1284
+ this.droppedInput.Report(frame);
1285
+ return;
1286
+ }
1287
+ this.requireLive().sendRealtimeInput({ video: { data: GeminiRealtimeSession.arrayBufferToBase64(frame.Data), mimeType } });
815
1288
  }
816
1289
  /**
817
1290
  * @inheritdoc
@@ -851,6 +1324,10 @@ class GeminiRealtimeSession {
851
1324
  this.outputHandler = handler;
852
1325
  }
853
1326
  /** @inheritdoc */
1327
+ OnVideoFrame(handler) {
1328
+ this.videoFrameHandler = handler;
1329
+ }
1330
+ /** @inheritdoc */
854
1331
  OnTranscript(handler) {
855
1332
  this.transcriptHandler = handler;
856
1333
  }
@@ -872,22 +1349,142 @@ class GeminiRealtimeSession {
872
1349
  /**
873
1350
  * Surfaces a websocket-level failure as a FATAL session error — the transport is gone,
874
1351
  * so the consumer (e.g. the session runner) should finalize cleanly instead of idling.
1352
+ * When the session can be resumed, the error is only logged: a websocket `error` is always
1353
+ * followed by a `close`, and {@link HandleTransportClose} resumes from there.
875
1354
  */
876
1355
  HandleTransportError(message) {
1356
+ if (this.resumption?.Handle) {
1357
+ RealtimeDiagLog(`[GeminiRealtime] Transport error, resuming on close: ${message}`);
1358
+ return;
1359
+ }
877
1360
  this.errorHandler?.({ Message: message, Fatal: true });
878
1361
  }
879
1362
  /**
880
- * Surfaces an UNEXPECTED socket close as a fatal error (expected closes — the consumer
881
- * called {@link Close} — are silent). Gemini hard-closes at token expiry, so this is
882
- * also how credential death reaches the consumer.
1363
+ * Handles a close of the current connection that the consumer did not ask for. When Google
1364
+ * issued a resumption handle, the session reconnects with it; otherwise the close surfaces as a
1365
+ * fatal error, as before (expected closes, after {@link Close}, stay silent).
883
1366
  */
884
1367
  HandleTransportClose(code, reason) {
885
1368
  if (this.closedByConsumer) {
886
1369
  return;
887
1370
  }
1371
+ if (this.resumption?.ConnectionLost()) {
1372
+ return;
1373
+ }
888
1374
  const detail = [code != null ? `code ${code}` : null, reason || null].filter(Boolean).join(' — ');
889
1375
  this.errorHandler?.({ Message: `Gemini Live session closed unexpectedly${detail ? ` (${detail})` : ''}`, Fatal: true });
890
1376
  }
1377
+ /**
1378
+ * Opens a connection through the driver's connector. Its callbacks act only while it is the
1379
+ * connection in use, so events from one that was replaced, closed, or is still opening are
1380
+ * dropped; its `setupComplete`, and a close or error before it, settle its
1381
+ * {@link GeminiOpenedConnection.Setup} whether or not it is in use yet. It becomes the
1382
+ * connection in use through {@link useConnection}, which lets the old connection keep
1383
+ * delivering events while a planned move is in progress.
1384
+ */
1385
+ async openConnection(handle) {
1386
+ if (!this.connector) {
1387
+ throw new Error('Gemini realtime session has no connector; the driver must call SetConnector before Open.');
1388
+ }
1389
+ const number = ++this.issuedConnections;
1390
+ const isCurrent = () => number === this.currentConnection;
1391
+ const setup = new RealtimeConnectionSetup();
1392
+ const live = await this.connector(handle, {
1393
+ OnMessage: (message) => {
1394
+ if (message.setupComplete) {
1395
+ setup.Confirm();
1396
+ }
1397
+ if (isCurrent()) {
1398
+ this.HandleServerMessage(message);
1399
+ }
1400
+ },
1401
+ OnError: (event) => {
1402
+ setup.Fail(new Error(`Gemini Live connection failed before confirming its setup: ${event?.message ?? 'websocket error'}`));
1403
+ if (isCurrent()) {
1404
+ this.HandleTransportError(event?.message ?? 'Gemini Live websocket error');
1405
+ }
1406
+ },
1407
+ OnClose: (event) => {
1408
+ setup.Fail(new Error(`Gemini Live closed the connection before confirming its setup (${event?.code}): ${event?.reason || 'no reason given'}`));
1409
+ if (isCurrent()) {
1410
+ this.HandleTransportClose(event?.code, event?.reason);
1411
+ }
1412
+ },
1413
+ });
1414
+ return { Live: live, ConnectionNumber: number, Setup: setup };
1415
+ }
1416
+ /** Waits for Google to confirm a new connection's setup. On failure the connection is closed and the error rethrown. */
1417
+ static async awaitSetup(opened) {
1418
+ try {
1419
+ await opened.Setup.Wait();
1420
+ }
1421
+ catch (error) {
1422
+ GeminiRealtimeSession.closeQuietly(opened.Live);
1423
+ throw error;
1424
+ }
1425
+ }
1426
+ /** Makes an opened connection the one in use. */
1427
+ useConnection(opened) {
1428
+ this.live = opened.Live;
1429
+ this.currentConnection = opened.ConnectionNumber;
1430
+ }
1431
+ /**
1432
+ * Opens a replacement connection that resumes the session from `handle`, switches to it once
1433
+ * Google confirms its setup, and closes the old one. Until then the old connection stays in
1434
+ * use, so what it still sends (the rest of a turn the deadline cut, its usage) is handled.
1435
+ * Rejects when the connection can't be opened or its setup fails, so
1436
+ * {@link RealtimeSessionResumption} can retry. A connection that opens after the attempt was
1437
+ * abandoned (timeout, or {@link Close}) is closed instead of used.
1438
+ */
1439
+ async resume(handle, attempt) {
1440
+ const opened = await this.openConnection(handle);
1441
+ await GeminiRealtimeSession.awaitSetup(opened);
1442
+ if (attempt.Abandoned || this.closedByConsumer) {
1443
+ GeminiRealtimeSession.closeQuietly(opened.Live);
1444
+ return;
1445
+ }
1446
+ const previous = this.live;
1447
+ this.useConnection(opened);
1448
+ if (previous) {
1449
+ GeminiRealtimeSession.closeQuietly(previous);
1450
+ }
1451
+ }
1452
+ /**
1453
+ * The session continues on a new connection, whose setup Google has confirmed. It has no open
1454
+ * meeting-mode activity window, and a turn cut off by a drop or the deadline never completes
1455
+ * there, so the turn is ended the way `turnComplete` ends one: thought text emitted, the busy
1456
+ * flag cleared. The audio held during the move goes out, then the queued sends.
1457
+ */
1458
+ handleResumed() {
1459
+ this.manualActivityOpen = false;
1460
+ this.avatarOutput?.Resumed();
1461
+ this.endTurn();
1462
+ this.moving = false;
1463
+ this.sendHeldAudio();
1464
+ this.completeTurn();
1465
+ }
1466
+ /**
1467
+ * Every resume attempt failed: the session ends with a fatal error. Input no longer waits for a new connection; the
1468
+ * audio held for one is dropped.
1469
+ */
1470
+ handleResumeFailed(error) {
1471
+ this.moving = false;
1472
+ this.heldAudio = [];
1473
+ this.heldAudioBytes = 0;
1474
+ if (this.closedByConsumer) {
1475
+ return;
1476
+ }
1477
+ this.errorHandler?.({ Message: `Gemini Live connection was lost and could not be resumed: ${error.message}`, Fatal: true });
1478
+ }
1479
+ /** Closes a connection the session no longer uses; it may already be closed. */
1480
+ static closeQuietly(live) {
1481
+ try {
1482
+ live.close();
1483
+ }
1484
+ catch (err) {
1485
+ RealtimeDiagLog(`[GeminiRealtime] Closing a replaced connection failed: ${err instanceof Error ? err.message : String(err)}`);
1486
+ }
1487
+ }
891
1488
  /**
892
1489
  * @inheritdoc
893
1490
  *
@@ -895,7 +1492,12 @@ class GeminiRealtimeSession {
895
1492
  * *name*, which the Core contract does not pass — so the name is looked up from the
896
1493
  * {@link pendingToolCallNames} cache populated when the originating tool call arrived. The
897
1494
  * `output` JSON string is parsed into the structured response object Gemini expects, and the
898
- * cache entry is cleared once the response is sent.
1495
+ * cache entry is cleared once the response is sent. While the session moves to a new
1496
+ * connection, the result waits and goes out on the new one.
1497
+ *
1498
+ * When a context note left the client turn open, the result is followed by a bare
1499
+ * `turnComplete: true` that closes it (see {@link closeOpenClientTurn}): Gemini holds the
1500
+ * continuation after a tool result while that turn is open, and the model stays silent.
899
1501
  *
900
1502
  * @param callID The originating tool call's id.
901
1503
  * @param output The tool's result as a JSON-stringified string.
@@ -910,8 +1512,31 @@ class GeminiRealtimeSession {
910
1512
  response: parsed,
911
1513
  ...(sched ? { scheduling: sched } : {}),
912
1514
  };
913
- this.requireLive().sendToolResponse({ functionResponses: [functionResponse] });
914
- this.pendingToolCallNames.delete(callID);
1515
+ const send = () => {
1516
+ const live = this.requireLive();
1517
+ live.sendToolResponse({ functionResponses: [functionResponse] });
1518
+ this.closeOpenClientTurn(live);
1519
+ this.pendingToolCallNames.delete(callID);
1520
+ this.endTurnIfToolResultsIn();
1521
+ };
1522
+ if (this.moving) {
1523
+ this.queuedSends.push(send);
1524
+ return;
1525
+ }
1526
+ send();
1527
+ }
1528
+ /**
1529
+ * Closes the client turn a context note left open, right after a tool result, so the model speaks the result. Not
1530
+ * while an answer is being generated: a `turnComplete: true` would cut it off, and that turn takes the note in at its
1531
+ * own `turnComplete`. Not on a model whose tools never block (Extended Thinking): it may still be reasoning when the
1532
+ * result arrives, which this session can't see, and the close would cut that off too.
1533
+ */
1534
+ closeOpenClientTurn(live) {
1535
+ if (!this.openClientTurn || !this.profile.Tooling.SupportsBlockingExecution || this.responseActive) {
1536
+ return;
1537
+ }
1538
+ live.sendClientContent({ turnComplete: true });
1539
+ this.openClientTurn = false;
915
1540
  }
916
1541
  /**
917
1542
  * Parses a JSON-stringified tool result into the structured object Gemini's function-response
@@ -944,11 +1569,15 @@ class GeminiRealtimeSession {
944
1569
  * **Collision behavior: queue.** Any client content sent mid-turn interrupts in-flight
945
1570
  * generation on Gemini Live, so the send is deferred until the active turn completes.
946
1571
  *
1572
+ * `turnComplete: false` leaves the client turn open: Gemini holds the continuation after a
1573
+ * tool result until the turn is closed, which {@link SendToolResult} does.
1574
+ *
947
1575
  * @param text The context note to append to the conversation.
948
1576
  */
949
1577
  SendContextNote(text) {
950
1578
  this.enqueueOrRun(() => {
951
1579
  this.requireLive().sendClientContent({ turns: [{ role: 'user', parts: [{ text }] }], turnComplete: false });
1580
+ this.openClientTurn = true;
952
1581
  });
953
1582
  }
954
1583
  /**
@@ -979,8 +1608,11 @@ class GeminiRealtimeSession {
979
1608
  return false;
980
1609
  }
981
1610
  let committed = false;
1611
+ // During a move the update waits for the new connection and commits there, so it counts as committed.
1612
+ const waitsForConnection = this.moving;
982
1613
  this.enqueueOrRun(() => {
983
1614
  this.responseActive = true;
1615
+ this.markTurnOpen();
984
1616
  const live = this.requireLive();
985
1617
  if (this.meetingMode) {
986
1618
  // MEETING mode: the agent has been heard accumulating audio inside the open activity window
@@ -1007,7 +1639,7 @@ class GeminiRealtimeSession {
1007
1639
  });
1008
1640
  // Meeting mode: report whether we actually committed a turn (so the bridge can release the floor if
1009
1641
  // not). Non-meeting (narration) always reports sent — it queues rather than wedges a floor.
1010
- return this.meetingMode ? committed : true;
1642
+ return this.meetingMode ? committed || waitsForConnection : true;
1011
1643
  }
1012
1644
  /**
1013
1645
  * Watchdog for the manual-activity meeting trigger: if Gemini produces NO turn after an `activityEnd`
@@ -1023,6 +1655,7 @@ class GeminiRealtimeSession {
1023
1655
  this.meetingResponseWatchdog = undefined;
1024
1656
  if (this.responseActive) {
1025
1657
  RealtimeDiagLog('[GeminiRealtime][diag] meeting WATCHDOG fired — no turn produced after activityEnd; clearing responseActive so the agent isn’t stuck silent');
1658
+ this.endTurnUnlessToolCallPending();
1026
1659
  this.completeTurn();
1027
1660
  }
1028
1661
  }, GEMINI_MEETING_RESPONSE_WATCHDOG_MS);
@@ -1031,11 +1664,12 @@ class GeminiRealtimeSession {
1031
1664
  * Runs a client-content send immediately when no turn is in flight; otherwise queues it for
1032
1665
  * the next turn boundary. Gemini-specific collision rule: ANY client content interrupts
1033
1666
  * in-flight generation on the Live API, so deferral (not skipping) is the safe default.
1667
+ * A send also waits while the session moves to a new connection, and goes out on the new one.
1034
1668
  */
1035
1669
  enqueueOrRun(send) {
1036
- if (this.responseActive) {
1670
+ if (this.responseActive || this.moving) {
1037
1671
  this.queuedSends.push(send);
1038
- RealtimeDiagLog(`[GeminiRealtime][diag] send QUEUED behind in-flight turn (responseActive=true, queueLen=${this.queuedSends.length}) — will not fire until a turn boundary clears the flag`);
1672
+ RealtimeDiagLog(`[GeminiRealtime][diag] send QUEUED (responseActive=${this.responseActive}, moving=${this.moving}, queueLen=${this.queuedSends.length}) — will not fire until a turn boundary clears the flag or the new connection is ready`);
1039
1673
  return;
1040
1674
  }
1041
1675
  send();
@@ -1043,7 +1677,8 @@ class GeminiRealtimeSession {
1043
1677
  /**
1044
1678
  * Turn boundary (`turnComplete` or `interrupted`): releases the busy flag and drains queued
1045
1679
  * sends in order, stopping at the first send that itself starts a new turn (a queued
1046
- * {@link RequestSpokenUpdate} re-sets {@link responseActive}).
1680
+ * {@link RequestSpokenUpdate} re-sets {@link responseActive}). Nothing drains during a move:
1681
+ * {@link handleResumed} drains onto the new connection.
1047
1682
  */
1048
1683
  completeTurn() {
1049
1684
  if (this.meetingResponseWatchdog) {
@@ -1063,16 +1698,82 @@ class GeminiRealtimeSession {
1063
1698
  }
1064
1699
  RealtimeDiagLog(`[GeminiRealtime][diag] turn boundary — clearing responseActive (was ${this.responseActive}), draining ${this.queuedSends.length} queued send(s)`);
1065
1700
  this.responseActive = false;
1066
- while (!this.responseActive && this.queuedSends.length > 0) {
1701
+ while (!this.responseActive && !this.moving && this.queuedSends.length > 0) {
1067
1702
  const send = this.queuedSends.shift();
1068
1703
  send?.();
1069
1704
  }
1070
1705
  }
1706
+ // ── Turn tracking (see IsTurnOpen) ─────────────────────────────────────────
1707
+ /**
1708
+ * Whether a server content frame is a sign of a turn: the user's transcribed words (outside
1709
+ * meeting mode), the model's transcribed words, a thought, or (in a session without an avatar)
1710
+ * the model's audio. An avatar's video never is: Vertex AI streams it between turns too.
1711
+ */
1712
+ contentOpensTurn(content) {
1713
+ if (!this.meetingMode && GeminiRealtimeSession.hasText(content.inputTranscription?.text)) {
1714
+ return true;
1715
+ }
1716
+ if (GeminiRealtimeSession.hasText(content.outputTranscription?.text)) {
1717
+ return true;
1718
+ }
1719
+ return (content.modelTurn?.parts ?? []).some((part) => this.partOpensTurn(part));
1720
+ }
1721
+ /**
1722
+ * Whether a model part is a sign of a turn: a thought, or audio (as this session plays it) in a session without an
1723
+ * avatar. In an avatar session, a voice part opens the turn once it plays (the avatar output's `OnAnswer`).
1724
+ */
1725
+ partOpensTurn(part) {
1726
+ if (part.thought) {
1727
+ return GeminiRealtimeSession.hasText(part.text);
1728
+ }
1729
+ const inline = part.inlineData;
1730
+ return !this.avatarOutput && !!inline?.data && (!inline.mimeType || IsPcmAudioMimeType(inline.mimeType));
1731
+ }
1732
+ /** Whether a transcription or thought carries words (whitespace alone does not count). */
1733
+ static hasText(text) {
1734
+ return (text?.trim().length ?? 0) > 0;
1735
+ }
1736
+ /** A turn started or continued: a planned move waits until it ends. */
1737
+ markTurnOpen() {
1738
+ this.turnOpen = true;
1739
+ this.turnEndAwaitsToolResults = false;
1740
+ this.resumption?.TurnStarted();
1741
+ }
1742
+ /** The turn's `turnComplete`: it ends now, or once the results of the tool calls still pending go out. */
1743
+ endTurnUnlessToolCallPending() {
1744
+ if (this.pendingToolCallNames.size > 0) {
1745
+ this.turnEndAwaitsToolResults = this.turnOpen;
1746
+ return;
1747
+ }
1748
+ this.endTurn();
1749
+ }
1750
+ /** A tool result went out: a turn whose `turnComplete` waited on the pending calls ends once none is left. */
1751
+ endTurnIfToolResultsIn() {
1752
+ if (this.turnEndAwaitsToolResults && this.pendingToolCallNames.size === 0) {
1753
+ this.endTurn();
1754
+ }
1755
+ }
1756
+ /** The turn is over: a planned move happens at the next resumable handle Google issues. */
1757
+ endTurn() {
1758
+ this.turnOpen = false;
1759
+ this.turnEndAwaitsToolResults = false;
1760
+ this.resumption?.TurnEnded();
1761
+ }
1071
1762
  /** @inheritdoc */
1072
1763
  async Close() {
1073
1764
  this.closedByConsumer = true;
1765
+ // Stop resuming before the socket closes, and drop events still in flight from it.
1766
+ this.resumption?.Dispose();
1767
+ this.currentConnection = 0;
1768
+ // A closed session's sends fail as before (no live connection), rather than wait for a move.
1769
+ this.moving = false;
1770
+ this.heldAudio = [];
1771
+ this.heldAudioBytes = 0;
1772
+ this.turnOpen = false;
1773
+ this.turnEndAwaitsToolResults = false;
1074
1774
  this.live?.close();
1075
1775
  this.live = null;
1776
+ this.avatarOutput?.Close(); // reports the avatar seconds generated and not yet reported, while the handler is set
1076
1777
  this.clearHandlers();
1077
1778
  }
1078
1779
  /**
@@ -1080,6 +1781,15 @@ class GeminiRealtimeSession {
1080
1781
  * per-concern handlers so each translation unit stays small and testable.
1081
1782
  */
1082
1783
  HandleServerMessage(message) {
1784
+ // Session continuity. `resumable: false` (mid-turn, mid-tool-call) arrives with no handle;
1785
+ // an update without the flag is treated as resumable.
1786
+ if (message.sessionResumptionUpdate) {
1787
+ const update = message.sessionResumptionUpdate;
1788
+ this.resumption?.RecordHandle(update.newHandle, update.resumable !== false);
1789
+ }
1790
+ if (message.goAway) {
1791
+ this.resumption?.ConnectionEnding(ParseDurationToMs(message.goAway.timeLeft));
1792
+ }
1083
1793
  if (message.serverContent) {
1084
1794
  this.handleServerContent(message.serverContent);
1085
1795
  }
@@ -1092,24 +1802,40 @@ class GeminiRealtimeSession {
1092
1802
  }
1093
1803
  /**
1094
1804
  * Translates a {@link LiveServerContent} frame: model audio output, input/output transcription,
1095
- * and interruption.
1805
+ * and interruption. What the frame carries opens the turn before its `turnComplete` ends it.
1096
1806
  */
1097
1807
  handleServerContent(content) {
1808
+ if (this.contentOpensTurn(content)) {
1809
+ this.markTurnOpen();
1810
+ }
1811
+ if (this.avatarOutput && GeminiRealtimeSession.hasText(content.outputTranscription?.text)) {
1812
+ // The model speaks: the avatar's video is its answer's from here, this message's parts included.
1813
+ this.avatarOutput.AnswerStarted();
1814
+ }
1098
1815
  if (content.interrupted) {
1816
+ this.avatarOutput?.Interrupted(); // before the parts of this message: the turn's late media is dropped
1099
1817
  this.interruptionHandler?.();
1100
1818
  this.completeTurn();
1101
1819
  }
1102
1820
  if (content.modelTurn) {
1103
1821
  // First model output of a turn marks generation in flight (Gemini emits no explicit
1104
- // "response started" frame), so interim-update sends defer instead of interrupting.
1105
- if (!this.responseActive) {
1106
- RealtimeDiagLog('[GeminiRealtime][diag] modelTurn — model is GENERATING output (the activityEnd worked)');
1822
+ // "response started" frame), so interim-update sends defer instead of interrupting. In an
1823
+ // avatar session the avatar output marks it for the answer's media (OnAnswer): the video
1824
+ // Vertex AI streams between answers is not generation.
1825
+ if (!this.avatarOutput || GeminiRealtimeSession.carriesMoreThanMedia(content.modelTurn)) {
1826
+ this.markGenerating();
1107
1827
  }
1108
- this.responseActive = true;
1109
- this.emitAudioOutput(content.modelTurn);
1828
+ this.emitModelMedia(content.modelTurn);
1110
1829
  this.emitThoughtOutput(content.modelTurn);
1111
1830
  }
1831
+ if (content.generationComplete) {
1832
+ this.avatarOutput?.GenerationComplete();
1833
+ }
1112
1834
  if (content.turnComplete) {
1835
+ this.avatarOutput?.TurnComplete();
1836
+ // Before the drain: a queued send that starts a new turn opens it again, and a queued note opens a client turn.
1837
+ this.endTurnUnlessToolCallPending();
1838
+ this.openClientTurn = false; // the model's turn took in any note that left the client turn open
1113
1839
  this.completeTurn();
1114
1840
  }
1115
1841
  if (content.inputTranscription) {
@@ -1119,25 +1845,68 @@ class GeminiRealtimeSession {
1119
1845
  this.emitTranscript('assistant', content.outputTranscription.text, content.outputTranscription.finished, 'normal');
1120
1846
  }
1121
1847
  }
1848
+ /** The model is generating: sends wait for the turn's boundary instead of interrupting it. */
1849
+ markGenerating() {
1850
+ if (!this.responseActive) {
1851
+ RealtimeDiagLog('[GeminiRealtime][diag] modelTurn — model is GENERATING output (the activityEnd worked)');
1852
+ }
1853
+ this.responseActive = true;
1854
+ }
1855
+ /** A part of the avatar session's answer is about to reach the host: the turn is open and the model generating. */
1856
+ markAnswering() {
1857
+ this.markTurnOpen();
1858
+ this.markGenerating();
1859
+ }
1122
1860
  /**
1123
- * Extracts inline audio parts from the model turn and forwards each as a raw `ArrayBuffer`.
1124
- * Thought parts (`part.thought === true`) are skipped — thoughts are reasoning summaries,
1125
- * not synthesized audio.
1861
+ * Whether a model turn carries something besides media parts (a thought, a part without inline data) or nothing at
1862
+ * all: generation in an avatar session, whatever its media turn out to be.
1126
1863
  */
1127
- emitAudioOutput(modelTurn) {
1128
- if (!this.outputHandler || !modelTurn.parts) {
1129
- return;
1130
- }
1131
- for (const part of modelTurn.parts) {
1132
- if (part.thought) {
1864
+ static carriesMoreThanMedia(modelTurn) {
1865
+ const parts = modelTurn.parts ?? [];
1866
+ return parts.length === 0 || parts.some((part) => part.thought || !part.inlineData?.data);
1867
+ }
1868
+ /**
1869
+ * Forwards the model turn's inline media parts. Thought parts (`part.thought === true`) are skipped — thoughts are
1870
+ * reasoning summaries, not synthesized media. A session with a granted avatar routes each part through its avatar
1871
+ * output (MP4 pieces to the host, PCM only before the turn's video; the answer's parts mark the model generating);
1872
+ * every other session plays PCM only.
1873
+ */
1874
+ emitModelMedia(modelTurn) {
1875
+ for (const part of modelTurn.parts ?? []) {
1876
+ const inline = part.inlineData;
1877
+ if (part.thought || !inline?.data) {
1133
1878
  continue;
1134
1879
  }
1135
- const data = part.inlineData?.data;
1136
- if (data) {
1137
- this.outputHandler(GeminiRealtimeSession.base64ToArrayBuffer(data));
1880
+ if (this.avatarOutput) {
1881
+ this.avatarOutput.Accept(inline.mimeType, GeminiRealtimeSession.base64ToArrayBuffer(inline.data));
1882
+ }
1883
+ else {
1884
+ this.emitAudioOutput(inline.mimeType, inline.data);
1138
1885
  }
1139
1886
  }
1140
1887
  }
1888
+ /**
1889
+ * Forwards one inline part as raw PCM. A part that names a non-PCM type (e.g. video/mp4 avatar frames) must never
1890
+ * reach the audio output, where it would play as noise. A part with no type plays, as it always has.
1891
+ */
1892
+ emitAudioOutput(mimeType, data) {
1893
+ if (!this.outputHandler) {
1894
+ return;
1895
+ }
1896
+ if (mimeType && !IsPcmAudioMimeType(mimeType)) {
1897
+ this.reportDroppedOutput(mimeType);
1898
+ return;
1899
+ }
1900
+ this.outputHandler(GeminiRealtimeSession.base64ToArrayBuffer(data));
1901
+ }
1902
+ /** Reports each MIME type of dropped model output once per session, not once per part. */
1903
+ reportDroppedOutput(mimeType) {
1904
+ if (this.droppedOutputTypes.has(mimeType)) {
1905
+ return;
1906
+ }
1907
+ this.droppedOutputTypes.add(mimeType);
1908
+ console.warn(`[GeminiRealtime] Dropped model output of type ${mimeType}: only PCM audio is played on this session.`);
1909
+ }
1141
1910
  /**
1142
1911
  * Extracts thought parts (`part.thought === true`) from the model turn and emits each
1143
1912
  * as an interim narration transcript (`Kind: 'narration'`).
@@ -1184,7 +1953,9 @@ class GeminiRealtimeSession {
1184
1953
  // draining the queue; queued sends flush at the next real turn boundary) so the eventual
1185
1954
  // SendToolResult and any fresh context note are not deferred behind a turn that will not
1186
1955
  // complete until after the result is sent. Mirrors the client driver's deadlock guard.
1956
+ // The answer stops at the call: the avatar's video until the model speaks again is idle.
1187
1957
  this.responseActive = false;
1958
+ this.avatarOutput?.ToolCalled();
1188
1959
  for (const call of functionCalls) {
1189
1960
  const callID = call.id ?? '';
1190
1961
  const toolName = call.name ?? '';
@@ -1192,6 +1963,8 @@ class GeminiRealtimeSession {
1192
1963
  // SendToolResult can supply it to Gemini's sendToolResponse, which requires the function
1193
1964
  // name the Core contract does not carry.
1194
1965
  this.pendingToolCallNames.set(callID, toolName);
1966
+ // A pending call keeps its turn open until its result goes out (see IsTurnOpen).
1967
+ this.markTurnOpen();
1195
1968
  this.toolCallHandler?.({
1196
1969
  CallID: callID,
1197
1970
  ToolName: toolName,
@@ -1200,40 +1973,45 @@ class GeminiRealtimeSession {
1200
1973
  }
1201
1974
  }
1202
1975
  /**
1203
- * Emits an incremental usage update, defaulting missing token counts to zero,
1204
- * and attributing modality breakdown (text, audio, image/video) when reported.
1976
+ * Emits an incremental usage update, defaulting missing token counts to zero, with the per-modality breakdown
1977
+ * (text, audio, image, video) of the prompt and of the response when Google reports one. A generated avatar's tokens
1978
+ * arrive as the response's VIDEO.
1205
1979
  */
1206
1980
  handleUsage(usageMetadata) {
1207
1981
  if (!usageMetadata) {
1208
1982
  return;
1209
1983
  }
1210
- let inputDetails;
1211
- if (usageMetadata.promptTokensDetails && Array.isArray(usageMetadata.promptTokensDetails)) {
1212
- for (const detail of usageMetadata.promptTokensDetails) {
1213
- if (typeof detail.tokenCount === 'number') {
1214
- inputDetails = inputDetails ?? {};
1215
- const mod = String(detail.modality ?? '').toUpperCase();
1216
- if (mod === 'AUDIO') {
1217
- inputDetails.AudioTokens = (inputDetails.AudioTokens ?? 0) + detail.tokenCount;
1218
- }
1219
- else if (mod === 'TEXT') {
1220
- inputDetails.TextTokens = (inputDetails.TextTokens ?? 0) + detail.tokenCount;
1221
- }
1222
- else if (mod === 'IMAGE') {
1223
- inputDetails.ImageTokens = (inputDetails.ImageTokens ?? 0) + detail.tokenCount;
1224
- }
1225
- }
1226
- }
1227
- }
1984
+ const inputDetails = this.modalityTokenDetails(usageMetadata.promptTokensDetails);
1985
+ const outputDetails = this.modalityTokenDetails(usageMetadata.responseTokensDetails);
1228
1986
  this.usageHandler?.({
1229
1987
  InputTokens: usageMetadata.promptTokenCount ?? 0,
1230
1988
  OutputTokens: usageMetadata.responseTokenCount ?? 0,
1231
1989
  ...(inputDetails ? { InputTokenDetails: inputDetails } : {}),
1990
+ ...(outputDetails ? { OutputTokenDetails: outputDetails } : {}),
1232
1991
  });
1233
1992
  }
1993
+ /**
1994
+ * Sums a usage report's per-modality token counts into the fields {@link GEMINI_MODALITY_TOKEN_FIELDS} names.
1995
+ * `undefined` when the report has no count for a modality the table names.
1996
+ */
1997
+ modalityTokenDetails(counts) {
1998
+ if (!Array.isArray(counts)) {
1999
+ return undefined;
2000
+ }
2001
+ let details;
2002
+ for (const count of counts) {
2003
+ const field = GEMINI_MODALITY_TOKEN_FIELDS[String(count.modality ?? '').toUpperCase()];
2004
+ if (field && typeof count.tokenCount === 'number') {
2005
+ details = details ?? {};
2006
+ details[field] = (details[field] ?? 0) + count.tokenCount;
2007
+ }
2008
+ }
2009
+ return details;
2010
+ }
1234
2011
  /** Drops all registered handlers so a closed session can't fire stale callbacks. */
1235
2012
  clearHandlers() {
1236
2013
  this.outputHandler = null;
2014
+ this.videoFrameHandler = null;
1237
2015
  this.transcriptHandler = null;
1238
2016
  this.toolCallHandler = null;
1239
2017
  this.interruptionHandler = null;
@@ -1241,6 +2019,7 @@ class GeminiRealtimeSession {
1241
2019
  this.pendingToolCallNames.clear();
1242
2020
  this.queuedSends = [];
1243
2021
  this.responseActive = false;
2022
+ this.openClientTurn = false;
1244
2023
  this.pendingThoughtText = '';
1245
2024
  }
1246
2025
  /** Returns the bound live session or throws if it was never attached / already closed. */