@memberjunction/ai-gemini 6.2.0-edge.3 → 6.2.0-edge.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/geminiAvatarVideoBitrate.d.ts +29 -0
- package/dist/geminiAvatarVideoBitrate.d.ts.map +1 -0
- package/dist/geminiAvatarVideoBitrate.js +58 -0
- package/dist/geminiAvatarVideoBitrate.js.map +1 -0
- package/dist/geminiBridgedAvatar.d.ts +119 -0
- package/dist/geminiBridgedAvatar.d.ts.map +1 -0
- package/dist/geminiBridgedAvatar.js +196 -0
- package/dist/geminiBridgedAvatar.js.map +1 -0
- package/dist/geminiEmbedding.d.ts +11 -0
- package/dist/geminiEmbedding.d.ts.map +1 -1
- package/dist/geminiEmbedding.js +34 -12
- package/dist/geminiEmbedding.js.map +1 -1
- package/dist/geminiImage.d.ts +10 -3
- package/dist/geminiImage.d.ts.map +1 -1
- package/dist/geminiImage.js +84 -14
- package/dist/geminiImage.js.map +1 -1
- package/dist/geminiLiveProfiles.d.ts +111 -4
- package/dist/geminiLiveProfiles.d.ts.map +1 -1
- package/dist/geminiLiveProfiles.js +169 -4
- package/dist/geminiLiveProfiles.js.map +1 -1
- package/dist/geminiLiveRelayPolicy.d.ts +87 -0
- package/dist/geminiLiveRelayPolicy.d.ts.map +1 -0
- package/dist/geminiLiveRelayPolicy.js +425 -0
- package/dist/geminiLiveRelayPolicy.js.map +1 -0
- package/dist/geminiLiveSetup.d.ts +79 -0
- package/dist/geminiLiveSetup.d.ts.map +1 -0
- package/dist/geminiLiveSetup.js +287 -0
- package/dist/geminiLiveSetup.js.map +1 -0
- package/dist/geminiRealtime.d.ts +171 -12
- package/dist/geminiRealtime.d.ts.map +1 -1
- package/dist/geminiRealtime.js +957 -141
- package/dist/geminiRealtime.js.map +1 -1
- package/dist/geminiSampling.d.ts +30 -0
- package/dist/geminiSampling.d.ts.map +1 -0
- package/dist/geminiSampling.js +44 -0
- package/dist/geminiSampling.js.map +1 -0
- package/dist/geminiThinking.d.ts +54 -0
- package/dist/geminiThinking.d.ts.map +1 -0
- package/dist/geminiThinking.js +107 -0
- package/dist/geminiThinking.js.map +1 -0
- package/dist/index.d.ts +60 -43
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +177 -309
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
- package/readme.md +66 -1
package/dist/geminiRealtime.js
CHANGED
|
@@ -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.
|
|
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
|
-
|
|
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
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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
|
|
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.
|
|
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
|
|
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
|
-
//
|
|
187
|
-
//
|
|
188
|
-
SessionConfig:
|
|
189
|
-
|
|
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
|
|
@@ -229,18 +298,33 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
|
|
|
229
298
|
* boundary is the *only* thing tests need to replace.
|
|
230
299
|
*
|
|
231
300
|
* @param args Resolved model, connect config, and the server-message callback.
|
|
232
|
-
* @returns A promise resolving to the live session handle
|
|
301
|
+
* @returns A promise resolving to the live session handle; it rejects if the socket errors or
|
|
302
|
+
* closes before Gemini acknowledges the setup.
|
|
233
303
|
*/
|
|
234
304
|
async connectLiveSession(args) {
|
|
235
305
|
const client = this.ensureClient();
|
|
236
|
-
return client.live.connect({
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
306
|
+
return this.connectUntilSetup(args, (callbacks) => client.live.connect({ model: args.Model, config: args.Config, callbacks }));
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Opens a Live connection with `connect`, which passes the given callbacks to `live.connect`, and rejects if the
|
|
310
|
+
* socket errors or closes before Gemini acknowledges the setup. `live.connect` (@google/genai 2.11+) resolves only on
|
|
311
|
+
* the server's setupComplete frame and never rejects when the socket errors or closes first (a rejected key, model or
|
|
312
|
+
* setup field), so without this the connect waits forever. A promise settles once, so callbacks after a successful
|
|
313
|
+
* connect only reach the handlers. Every {@link connectLiveSession} override should open through this.
|
|
314
|
+
*/
|
|
315
|
+
connectUntilSetup(args, connect) {
|
|
316
|
+
return new Promise((resolve, reject) => {
|
|
317
|
+
connect({
|
|
240
318
|
onmessage: args.OnMessage,
|
|
241
|
-
onerror:
|
|
242
|
-
|
|
243
|
-
|
|
319
|
+
onerror: (event) => {
|
|
320
|
+
reject(new Error(`Gemini Live connection failed: ${event?.message ?? 'websocket error'}`));
|
|
321
|
+
args.OnError?.(event);
|
|
322
|
+
},
|
|
323
|
+
onclose: (event) => {
|
|
324
|
+
reject(new Error(`Gemini Live closed during setup (code ${event?.code ?? 'unknown'}${event?.reason ? `: ${event.reason}` : ''})`));
|
|
325
|
+
args.OnClose?.(event);
|
|
326
|
+
},
|
|
327
|
+
}).then(resolve, reject);
|
|
244
328
|
});
|
|
245
329
|
}
|
|
246
330
|
/**
|
|
@@ -259,6 +343,13 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
|
|
|
259
343
|
* there — `systemInstruction`, `tools`, and the transcription configs are NOT, and their
|
|
260
344
|
* presence 400s the entire mint. Only defined fields are copied (an absent key must stay
|
|
261
345
|
* absent so it doesn't enter the mask).
|
|
346
|
+
*
|
|
347
|
+
* `contextWindowCompression` is left out on purpose. No test or doc shows the mask accepts
|
|
348
|
+
* it, and a rejected mask would fail every client-direct session. The browser applies it from
|
|
349
|
+
* `SessionConfig`, like the other server-built keys the token cannot lock.
|
|
350
|
+
*
|
|
351
|
+
* `sessionResumption: {}` is locked as in Google's ephemeral-token example. The browser adds
|
|
352
|
+
* the handle when it resumes, and Google accepts the same token for that until `expireTime`.
|
|
262
353
|
*/
|
|
263
354
|
static BuildConstraintConfig(config) {
|
|
264
355
|
const constraint = {};
|
|
@@ -336,23 +427,121 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
|
|
|
336
427
|
MalformedExisting: malformedExisting,
|
|
337
428
|
};
|
|
338
429
|
}
|
|
430
|
+
/**
|
|
431
|
+
* Consumes the driver-NEUTRAL `transcriptionLanguages` bag key (BCP-47 codes) into `languageCodes`
|
|
432
|
+
* hints on both caption streams. Without a hint Gemini auto-detects each utterance's language for
|
|
433
|
+
* the captions, and can caption English speech in another script.
|
|
434
|
+
*
|
|
435
|
+
* @param cfg The open config bag; the key is always deleted from it.
|
|
436
|
+
* @param config The connect config receiving the hints.
|
|
437
|
+
*/
|
|
438
|
+
static applyTranscriptionLanguages(cfg, config) {
|
|
439
|
+
const raw = cfg.transcriptionLanguages;
|
|
440
|
+
delete cfg.transcriptionLanguages;
|
|
441
|
+
const languageCodes = Array.isArray(raw)
|
|
442
|
+
? raw.filter((c) => typeof c === 'string' && c.trim().length > 0).map((c) => c.trim())
|
|
443
|
+
: [];
|
|
444
|
+
if (languageCodes.length > 0) {
|
|
445
|
+
config.inputAudioTranscription = { languageCodes };
|
|
446
|
+
config.outputAudioTranscription = { languageCodes };
|
|
447
|
+
}
|
|
448
|
+
else if (raw !== undefined) {
|
|
449
|
+
console.warn('[GeminiRealtime] Ignored the session config bag\'s `transcriptionLanguages` because it holds no language codes '
|
|
450
|
+
+ '— expected an array of BCP-47 codes such as ["en-US"].');
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Deletes every key in {@link REALTIME_SHARED_CONFIG_KEYS} from the copy of the config bag that is merged into the
|
|
455
|
+
* connect config, so none reaches the Live SDK raw, and logs what the session will not apply:
|
|
456
|
+
*
|
|
457
|
+
* - the keys Gemini Live has no use for, in one line;
|
|
458
|
+
* - a key the driver applies after the merge ({@link GEMINI_SHARED_KEYS_APPLIED_AFTER_MERGE}) whose value is of a
|
|
459
|
+
* type it cannot read, one line each. `null` reads as unset, the way a config layer clears an inherited value.
|
|
460
|
+
*
|
|
461
|
+
* A key the driver applies, with a value it can read, gets no line here: `applyModelLegality` applies it and logs a
|
|
462
|
+
* value the model or endpoint doesn't accept (a turn coverage, a thinking level).
|
|
463
|
+
*
|
|
464
|
+
* @param cfg The copy of the session config bag that is merged into the connect config. The keys are deleted from it.
|
|
465
|
+
*/
|
|
466
|
+
static scrubSharedKeys(cfg) {
|
|
467
|
+
const notApplied = [];
|
|
468
|
+
for (const key of REALTIME_SHARED_CONFIG_KEYS) {
|
|
469
|
+
if (!(key in cfg)) {
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
const value = cfg[key];
|
|
473
|
+
delete cfg[key];
|
|
474
|
+
const shape = GEMINI_SHARED_KEYS_APPLIED_AFTER_MERGE.get(key);
|
|
475
|
+
if (shape === undefined) {
|
|
476
|
+
notApplied.push(key);
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
const unset = value === null || value === undefined;
|
|
480
|
+
const readable = shape === 'object' ? GeminiRealtime_1.readObject(value) !== undefined : typeof value === 'string';
|
|
481
|
+
if (!unset && !readable) {
|
|
482
|
+
const expected = shape === 'object' ? 'an object' : 'a named effort such as "medium"';
|
|
483
|
+
console.warn(`[GeminiRealtime] Ignored the session config bag's \`${key}\` because it is not ${expected} (got ${Array.isArray(value) ? 'array' : typeof value}).`);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if (notApplied.length > 0) {
|
|
487
|
+
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.`);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Keeps a config-bag `contextWindowCompression` only when it is an object. The bag is untyped
|
|
492
|
+
* JSON, so a string, array or null would otherwise reach the wire and fail the session at
|
|
493
|
+
* connect. A malformed value is replaced by the default and reported; a well-formed one wins
|
|
494
|
+
* over the default, like every other bag key.
|
|
495
|
+
*/
|
|
496
|
+
static ensureContextWindowCompression(config) {
|
|
497
|
+
const compression = config.contextWindowCompression;
|
|
498
|
+
if (GeminiRealtime_1.readObject(compression)) {
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
const got = compression === null ? 'null' : Array.isArray(compression) ? 'array' : typeof compression;
|
|
502
|
+
console.warn(`[GeminiRealtime] Ignored the session config bag's \`contextWindowCompression\` because it is not an object (got ${got}); using the default sliding window.`);
|
|
503
|
+
config.contextWindowCompression = GeminiRealtime_1.DefaultContextWindowCompression();
|
|
504
|
+
}
|
|
339
505
|
/** Narrows an unenforced config-bag value to a real object — not a string, array, or null. */
|
|
340
506
|
static isPlainObject(value) {
|
|
341
507
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
342
508
|
}
|
|
509
|
+
/**
|
|
510
|
+
* The context-window compression every Gemini Live session gets unless the config bag sets
|
|
511
|
+
* its own: a server-side sliding window with Google's default trigger and target sizes.
|
|
512
|
+
*
|
|
513
|
+
* Without compression, Google ends a session when its context fills: about 15 minutes for
|
|
514
|
+
* audio only and about 2 minutes for audio plus video (Google's Live API session-management
|
|
515
|
+
* docs). With compression the server drops the oldest turns and the session continues.
|
|
516
|
+
* Session resumption handles a different limit (a single connection lasts about 10 minutes)
|
|
517
|
+
* and does not lift this one.
|
|
518
|
+
*
|
|
519
|
+
* Returns a new object on each call so no session shares mutable config with another.
|
|
520
|
+
*/
|
|
521
|
+
static DefaultContextWindowCompression() {
|
|
522
|
+
return { slidingWindow: {} };
|
|
523
|
+
}
|
|
343
524
|
/**
|
|
344
525
|
* Builds the {@link LiveConnectConfig} from the Core session params: audio response modality,
|
|
345
|
-
* input/output transcription, system instruction,
|
|
346
|
-
*
|
|
347
|
-
*
|
|
526
|
+
* input/output transcription, system instruction, sliding-window context compression
|
|
527
|
+
* ({@link GeminiRealtime.DefaultContextWindowCompression}), session resumption (unless the
|
|
528
|
+
* session is zero-data-retention), mapped tools, the neutral `voice` key mapped via
|
|
529
|
+
* {@link GeminiRealtime.buildSpeechConfig}, plus any provider-specific overrides from the open
|
|
530
|
+
* config bag.
|
|
348
531
|
*/
|
|
349
|
-
|
|
532
|
+
BuildConnectConfig(params) {
|
|
350
533
|
const config = {
|
|
351
534
|
responseModalities: [Modality.AUDIO],
|
|
352
535
|
inputAudioTranscription: {},
|
|
353
536
|
outputAudioTranscription: {},
|
|
354
537
|
systemInstruction: params.SystemPrompt,
|
|
538
|
+
contextWindowCompression: GeminiRealtime_1.DefaultContextWindowCompression(),
|
|
355
539
|
};
|
|
540
|
+
// Resumption handles let a session continue across Gemini's ~10-minute connection limit.
|
|
541
|
+
// Zero-data-retention sessions never get them; see applyZeroDataRetention.
|
|
542
|
+
if (!params.ZeroDataRetention) {
|
|
543
|
+
config.sessionResumption = {};
|
|
544
|
+
}
|
|
356
545
|
if (params.Tools && params.Tools.length > 0) {
|
|
357
546
|
const bag = params.Config ?? {};
|
|
358
547
|
const tooling = GeminiRealtime_1.readObject(bag['tooling']);
|
|
@@ -393,14 +582,17 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
|
|
|
393
582
|
const reason = typeof rawVoice === 'string' ? 'blank' : `not a string (got ${typeof rawVoice})`;
|
|
394
583
|
console.warn(`[GeminiRealtime] Ignored the session config bag's \`voice\` because it is ${reason} — expected a Gemini prebuilt voice name.`);
|
|
395
584
|
}
|
|
396
|
-
//
|
|
397
|
-
|
|
398
|
-
//
|
|
399
|
-
//
|
|
400
|
-
//
|
|
401
|
-
// The
|
|
402
|
-
//
|
|
403
|
-
//
|
|
585
|
+
// Consumed before the merge below, so a provider-native transcription config in the bag still wins.
|
|
586
|
+
GeminiRealtime_1.applyTranscriptionLanguages(cfg, config);
|
|
587
|
+
// Scrub the MJ-side keys shared across the realtime driver family. None is a Live config
|
|
588
|
+
// field — a co-agent config carrying e.g. `effortLevel` or `mcpTools` must not break a
|
|
589
|
+
// Gemini session by being spread raw into the Live SDK, where strictness varies by version.
|
|
590
|
+
// The keys this driver applies after the merge (`turnDetection`, `reasoning`,
|
|
591
|
+
// `effortLevel`, `reasoningEffort`) are read from params.Config by applyModelLegality, so
|
|
592
|
+
// the scrub reports one only when its value is of a type the driver cannot read; the
|
|
593
|
+
// rest are diag-logged so config typos and cross-provider keys stop being silent. The
|
|
594
|
+
// keys consumed above (`disableAutoResponse`, `voice`, `tooling`, `toolBehavior`,
|
|
595
|
+
// `transcriptionLanguages`) never reach it.
|
|
404
596
|
//
|
|
405
597
|
// This scrub NARROWS the silent-drop class of #3721; it does not close it. The list is an
|
|
406
598
|
// allowlist of MJ-SHARED keys, not of non-Gemini keys, so anything outside it still rides
|
|
@@ -409,17 +601,9 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
|
|
|
409
601
|
// deprecated but deliberately kept authorable in the agent-type ConfigSchema. Closing the
|
|
410
602
|
// class means inverting this check to warn on any key that is not a known
|
|
411
603
|
// `LiveConnectConfig` field — tracked separately rather than widened here.
|
|
412
|
-
|
|
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
|
-
}
|
|
604
|
+
GeminiRealtime_1.scrubSharedKeys(cfg);
|
|
422
605
|
Object.assign(config, cfg);
|
|
606
|
+
GeminiRealtime_1.ensureContextWindowCompression(config);
|
|
423
607
|
// Captured BEFORE the mapping below replaces or deletes it, so the warning can report the
|
|
424
608
|
// type that was actually rejected rather than the type that replaced it.
|
|
425
609
|
const rawSpeechConfig = config.speechConfig;
|
|
@@ -454,11 +638,147 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
|
|
|
454
638
|
// config bag must not be able to reintroduce a key the target model has retired. Anything the
|
|
455
639
|
// merge above put back is removed here.
|
|
456
640
|
this.applyModelLegality(config, params);
|
|
641
|
+
GeminiRealtime_1.applyZeroDataRetention(config, params);
|
|
642
|
+
this.applyAvatarOutput(config, params);
|
|
457
643
|
return config;
|
|
458
644
|
}
|
|
459
645
|
/**
|
|
460
|
-
*
|
|
461
|
-
*
|
|
646
|
+
* Renders the requested avatar when the model can on this endpoint: video output and the avatar's name, at the
|
|
647
|
+
* bitrate the deployment asks for (`MJ_GEMINI_AVATAR_VIDEO_BITRATE_BPS`, 2 Mbps by default; `0` leaves the field out).
|
|
648
|
+
* Otherwise the session stays audio-only and one line says why. Either way a VIDEO modality or an `avatarConfig` from
|
|
649
|
+
* the config bag is removed: an avatar comes only from the session's avatar request. Applied last, like the legality
|
|
650
|
+
* rules. Every session's setup comes from here: the browser mint, the relay's setup and server-side sessions.
|
|
651
|
+
*/
|
|
652
|
+
applyAvatarOutput(config, params) {
|
|
653
|
+
const request = params.Avatar;
|
|
654
|
+
const reason = request ? this.avatarUnavailableReason(request, params.Model) : undefined;
|
|
655
|
+
if (request && !reason) {
|
|
656
|
+
const videoBitrateBps = ResolveGeminiAvatarVideoBitrateBps();
|
|
657
|
+
config.responseModalities = [Modality.VIDEO];
|
|
658
|
+
config.avatarConfig = videoBitrateBps === null ? { avatarName: request.AvatarID.trim() } : { avatarName: request.AvatarID.trim(), videoBitrateBps };
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
GeminiRealtime_1.removeVideoOutput(config, params.Model);
|
|
662
|
+
if (request && reason) {
|
|
663
|
+
console.warn(this.avatarUnavailableMessage(request, params.Model, reason));
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
/** Why this session can't render the requested avatar, or `undefined` when it can. */
|
|
667
|
+
avatarUnavailableReason(request, model) {
|
|
668
|
+
if ((request.Kind ?? 'preset') === 'custom') {
|
|
669
|
+
return 'custom-disabled';
|
|
670
|
+
}
|
|
671
|
+
if (!ResolveGeminiLiveProfile(model, this.Endpoint).SupportsAvatarOutput) {
|
|
672
|
+
return 'endpoint';
|
|
673
|
+
}
|
|
674
|
+
return request.AvatarID?.trim() ? undefined : 'unknown-avatar';
|
|
675
|
+
}
|
|
676
|
+
/** The one log line for an avatar the session asked for and won't render. */
|
|
677
|
+
avatarUnavailableMessage(request, model, reason) {
|
|
678
|
+
const why = {
|
|
679
|
+
endpoint: `${model} on ${GEMINI_ENDPOINT_NAMES[this.Endpoint]} renders no avatar`,
|
|
680
|
+
bridged: "a session on the server whose host can't publish video into a room",
|
|
681
|
+
phone: 'a phone caller sees no video',
|
|
682
|
+
'custom-disabled': 'custom avatars are not enabled',
|
|
683
|
+
'unknown-avatar': 'the request names no avatar',
|
|
684
|
+
'no-binding': 'the persona has no avatar on this vendor',
|
|
685
|
+
host: 'the app showing the call asks for no agent video',
|
|
686
|
+
browser: 'the browser cannot play the avatar',
|
|
687
|
+
'decoder-missing': 'the meeting host has no usable video decoder',
|
|
688
|
+
'decoder-failed': "the meeting bot's decoders kept failing",
|
|
689
|
+
'publish-failed': 'the meeting room refused the video track',
|
|
690
|
+
'video-off': "the agent's video setting is off",
|
|
691
|
+
};
|
|
692
|
+
const persona = request.PersonaName ? ` (persona ${request.PersonaName})` : '';
|
|
693
|
+
return `[GeminiRealtime] Avatar "${request.AvatarID}"${persona} not used: ${why[reason]}. The call is audio only. Reason: ${reason}.`;
|
|
694
|
+
}
|
|
695
|
+
/** Removes a VIDEO response modality and any `avatarConfig` that came from somewhere other than an avatar request. */
|
|
696
|
+
static removeVideoOutput(config, model) {
|
|
697
|
+
if (config.avatarConfig !== undefined) {
|
|
698
|
+
delete config.avatarConfig;
|
|
699
|
+
console.warn(`[GeminiRealtime] Dropped \`avatarConfig\` from the session config for ${model}: an avatar comes only from the session's avatar request.`);
|
|
700
|
+
}
|
|
701
|
+
const modalities = config.responseModalities ?? [];
|
|
702
|
+
if (modalities.includes(Modality.VIDEO)) {
|
|
703
|
+
const rest = modalities.filter((m) => m !== Modality.VIDEO);
|
|
704
|
+
config.responseModalities = rest.length > 0 ? rest : [Modality.AUDIO];
|
|
705
|
+
console.warn(`[GeminiRealtime] Dropped the VIDEO response modality for ${model}: video output comes only from an avatar request the model can render.`);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* A server-side session (a meeting bot) asks for an avatar only when its host publishes the video into a room
|
|
710
|
+
* (`Delivery: 'room'`, a bot that decodes it). Anywhere else nothing on the server can show it: returns the params
|
|
711
|
+
* without the request, logging the reason once. A phone call never gets here with a request: its session prep asks
|
|
712
|
+
* for none (`'phone'`).
|
|
713
|
+
*/
|
|
714
|
+
withoutAvatarOnServer(params) {
|
|
715
|
+
if (!params.Avatar || params.Avatar.Delivery === 'room') {
|
|
716
|
+
return params;
|
|
717
|
+
}
|
|
718
|
+
console.warn(this.avatarUnavailableMessage(params.Avatar, params.Model, 'bridged'));
|
|
719
|
+
return { ...params, Avatar: undefined };
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* What the mint tells the call about the avatar the session asked for: granted, or audio only and why. `undefined` when
|
|
723
|
+
* it asked for none. Read from the connect config {@link BuildConnectConfig} built, so it says what the session does:
|
|
724
|
+
* an `avatarConfig` there is the grant. Every Gemini driver returns it on its minted config.
|
|
725
|
+
*
|
|
726
|
+
* @param params The session parameters (the avatar request).
|
|
727
|
+
* @param config The connect config the session was built with.
|
|
728
|
+
*/
|
|
729
|
+
AvatarStatusFor(params, config) {
|
|
730
|
+
const request = params.Avatar;
|
|
731
|
+
if (!request) {
|
|
732
|
+
return undefined;
|
|
733
|
+
}
|
|
734
|
+
if (config.avatarConfig) {
|
|
735
|
+
return { Requested: true, Granted: true };
|
|
736
|
+
}
|
|
737
|
+
const reason = this.avatarUnavailableReason(request, params.Model);
|
|
738
|
+
return reason ? { Requested: true, Granted: false, Reason: reason } : { Requested: true, Granted: false };
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* What became of a server-side session's avatar request: {@link AvatarStatusFor}, except that a session whose host
|
|
742
|
+
* can't publish the avatar (no `Delivery: 'room'`) is audio only as `bridged`. `undefined` without a request.
|
|
743
|
+
*
|
|
744
|
+
* @param params The session parameters as the host passed them (the avatar request included).
|
|
745
|
+
* @param config The connect config the session was built with.
|
|
746
|
+
*/
|
|
747
|
+
serverAvatarStatus(params, config) {
|
|
748
|
+
const status = this.AvatarStatusFor(params, config);
|
|
749
|
+
if (!status || status.Granted || params.Avatar?.Delivery === 'room') {
|
|
750
|
+
return status;
|
|
751
|
+
}
|
|
752
|
+
return { ...status, Reason: 'bridged' };
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* The minted session config's avatar block: present only when this session renders an avatar, so the browser driver
|
|
756
|
+
* knows to expect video parts, their encoding, and whether they carry the voice.
|
|
757
|
+
*
|
|
758
|
+
* @param config The connect config the session was built with.
|
|
759
|
+
* @param profile The model's profile on this driver's endpoint.
|
|
760
|
+
*/
|
|
761
|
+
AvatarPactFor(config, profile) {
|
|
762
|
+
if (!config.avatarConfig) {
|
|
763
|
+
return {};
|
|
764
|
+
}
|
|
765
|
+
return { avatar: { output: true, encoding: profile.AvatarOutputEncoding ?? null, audioMuxed: profile.AvatarAudioMuxed ?? true } };
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Keeps session resumption off a zero-data-retention session, even when the config bag asks
|
|
769
|
+
* for it: Google stores resumable session state, which such a model promises not to do.
|
|
770
|
+
* Applied after the bag merge, like the legality rules, so the bag cannot turn it back on.
|
|
771
|
+
*/
|
|
772
|
+
static applyZeroDataRetention(config, params) {
|
|
773
|
+
if (!params.ZeroDataRetention || config.sessionResumption === undefined) {
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
delete config.sessionResumption;
|
|
777
|
+
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.`);
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* Enforces what the TARGET model, on the session's endpoint, actually accepts, and states what MJ
|
|
781
|
+
* wants rather than inheriting a provider default.
|
|
462
782
|
*
|
|
463
783
|
* Every rule here fails at SESSION MINT if broken — upstream of all UI code, the same failure
|
|
464
784
|
* class as an illegal tool name — so none of it can be left to discover at connect time. Facts
|
|
@@ -466,10 +786,12 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
|
|
|
466
786
|
* `plans/realtime/gemini-3-8-live.md` §3 for their sourcing.
|
|
467
787
|
*/
|
|
468
788
|
applyModelLegality(config, params) {
|
|
469
|
-
const profile = ResolveGeminiLiveProfile(params.Model);
|
|
789
|
+
const profile = ResolveGeminiLiveProfile(params.Model, this.Endpoint);
|
|
470
790
|
// The catalog's ModelConfiguration.Realtime reaches a driver folded into the session Config
|
|
471
791
|
// BAG as neutral keys (the same route `turnDetection` already travels), not as a field on
|
|
472
|
-
// RealtimeSessionParams — so read it from there.
|
|
792
|
+
// RealtimeSessionParams — so read it from there. A shared key read here belongs in
|
|
793
|
+
// GEMINI_SHARED_KEYS_APPLIED_AFTER_MERGE; otherwise the scrub logs it as a key Gemini Live
|
|
794
|
+
// does not apply.
|
|
473
795
|
const bag = params.Config ?? {};
|
|
474
796
|
const reasoning = GeminiRealtime_1.readObject(bag['reasoning']);
|
|
475
797
|
const turnDetection = GeminiRealtime_1.readObject(bag['turnDetection']);
|
|
@@ -522,18 +844,7 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
|
|
|
522
844
|
else {
|
|
523
845
|
delete config.thinkingConfig;
|
|
524
846
|
}
|
|
525
|
-
|
|
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
|
-
};
|
|
847
|
+
GeminiRealtime_1.applyTurnCoverage(config, coverageSetting, profile, params.Model);
|
|
537
848
|
// C5 / C5a / C5b — state behavior on every declaration, whatever its origin.
|
|
538
849
|
// Drops the !SupportsBlockingExecution gate so 3.8-live bag tools are stated too.
|
|
539
850
|
if (config.tools) {
|
|
@@ -575,6 +886,38 @@ let GeminiRealtime = class GeminiRealtime extends BaseRealtimeModel {
|
|
|
575
886
|
}
|
|
576
887
|
}
|
|
577
888
|
}
|
|
889
|
+
/**
|
|
890
|
+
* C4 — turn coverage is STATED, never inherited. The SDK's enum doc says coverage defaults to
|
|
891
|
+
* TURN_INCLUDES_ONLY_ACTIVITY while the 3.8 model page says the default includes all video; sending it explicitly
|
|
892
|
+
* makes that contradiction irrelevant. Absent config means audio only, because video frames are billed and consume
|
|
893
|
+
* context, so the expensive option must be asked for rather than inherited. Only a coverage the session's endpoint
|
|
894
|
+
* accepts is sent ({@link ResolveGeminiTurnCoverage}): Gemini Enterprise closes the setup on
|
|
895
|
+
* TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO, so a session there that asks for it gets audio only, and one line names
|
|
896
|
+
* what was asked for and what was sent. The setup the relay writes and a bridged session's both come from here.
|
|
897
|
+
*
|
|
898
|
+
* @param config The connect config being built.
|
|
899
|
+
* @param requested The bag's `turnDetection.Coverage`, if any.
|
|
900
|
+
* @param profile The model's profile on the session's endpoint.
|
|
901
|
+
* @param model The model id, for the log line.
|
|
902
|
+
*/
|
|
903
|
+
static applyTurnCoverage(config, requested, profile, model) {
|
|
904
|
+
const coverage = ResolveGeminiTurnCoverage(requested, profile);
|
|
905
|
+
const wire = GeminiRealtime_1.mapTurnCoverage(coverage.Coverage);
|
|
906
|
+
if (coverage.Refused !== undefined) {
|
|
907
|
+
console.warn(`[GeminiRealtime] Turn coverage ${JSON.stringify(coverage.Refused)} is not one ${GEMINI_ENDPOINT_NAMES[profile.Endpoint]} ` +
|
|
908
|
+
`accepts for ${model} (it accepts ${profile.AcceptedTurnCoverages.join(', ')}); sent "${coverage.Coverage}" (${wire}) instead.`);
|
|
909
|
+
}
|
|
910
|
+
config.realtimeInputConfig = { ...(config.realtimeInputConfig ?? {}), turnCoverage: wire };
|
|
911
|
+
}
|
|
912
|
+
/** Maps MJ's turn coverage onto the SDK's {@link TurnCoverage} wire value. */
|
|
913
|
+
static mapTurnCoverage(coverage) {
|
|
914
|
+
switch (coverage) {
|
|
915
|
+
case 'audioActivityOnly':
|
|
916
|
+
return TurnCoverage.TURN_INCLUDES_ONLY_ACTIVITY;
|
|
917
|
+
case 'audioActivityAndAllVideo':
|
|
918
|
+
return TurnCoverage.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
578
921
|
/**
|
|
579
922
|
* Narrows a bag value to a plain object, or `undefined`.
|
|
580
923
|
*
|
|
@@ -701,6 +1044,7 @@ class GeminiRealtimeSession {
|
|
|
701
1044
|
this.OutputSampleRate = 24000;
|
|
702
1045
|
this.live = null;
|
|
703
1046
|
this.outputHandler = null;
|
|
1047
|
+
this.videoFrameHandler = null;
|
|
704
1048
|
this.transcriptHandler = null;
|
|
705
1049
|
this.toolCallHandler = null;
|
|
706
1050
|
this.interruptionHandler = null;
|
|
@@ -717,6 +1061,10 @@ class GeminiRealtimeSession {
|
|
|
717
1061
|
this.pendingToolCallNames = new Map();
|
|
718
1062
|
/** Accumulates in-flight thought text deltas until finalized on turn completion. */
|
|
719
1063
|
this.pendingThoughtText = '';
|
|
1064
|
+
/** MIME types of model output this session dropped, so each is reported once. */
|
|
1065
|
+
this.droppedOutputTypes = new Set();
|
|
1066
|
+
/** Reports the input frames {@link SendInput} drops, once per kind and type. */
|
|
1067
|
+
this.droppedInput = new RealtimeDroppedInputReporter('GeminiRealtime', 'Gemini Live takes PCM audio and JPEG or PNG video frames');
|
|
720
1068
|
/**
|
|
721
1069
|
* Fingerprint of the tool set bound at connect time (set via {@link SetConnectTimeTools});
|
|
722
1070
|
* {@link RegisterTools} compares against it to no-op identical re-registrations.
|
|
@@ -726,11 +1074,13 @@ class GeminiRealtimeSession {
|
|
|
726
1074
|
/**
|
|
727
1075
|
* Whether a model turn is currently being generated. Minimal turn tracking mirroring the
|
|
728
1076
|
* client driver: set when model output arrives (Gemini has no `response.created`-style frame,
|
|
729
|
-
* so the first `modelTurn` content is the signal
|
|
730
|
-
*
|
|
731
|
-
*
|
|
732
|
-
*
|
|
733
|
-
*
|
|
1077
|
+
* so the first `modelTurn` content is the signal; an avatar's video sets it only while the
|
|
1078
|
+
* model's answer is under way, since Vertex AI streams it between answers too) and eagerly
|
|
1079
|
+
* when this session itself sends a turn-triggering client content; cleared on `turnComplete`,
|
|
1080
|
+
* `interrupted`, and a tool-call frame (the model yields the floor pending the result).
|
|
1081
|
+
* Consumed by {@link enqueueOrRun}: on Gemini Live ANY client content sent mid-turn
|
|
1082
|
+
* INTERRUPTS the in-flight generation, so interim-update sends are deferred rather than sent
|
|
1083
|
+
* into an active turn.
|
|
734
1084
|
*/
|
|
735
1085
|
this.responseActive = false;
|
|
736
1086
|
/**
|
|
@@ -739,6 +1089,13 @@ class GeminiRealtimeSession {
|
|
|
739
1089
|
* {@link Close} so a closed session never replays stale sends.
|
|
740
1090
|
*/
|
|
741
1091
|
this.queuedSends = [];
|
|
1092
|
+
/**
|
|
1093
|
+
* Whether a context note left the client turn open. {@link SendContextNote} sends `turnComplete: false`, which tells
|
|
1094
|
+
* Gemini more input is coming, and Gemini then holds all generation, the continuation after a tool result included,
|
|
1095
|
+
* until a `turnComplete: true` arrives. Set when a note goes out; cleared when {@link SendToolResult} closes the
|
|
1096
|
+
* turn, at the model's `turnComplete` (its generation took the note in), and on {@link Close}.
|
|
1097
|
+
*/
|
|
1098
|
+
this.openClientTurn = false;
|
|
742
1099
|
/**
|
|
743
1100
|
* Whether this session runs in MEETING mode — Gemini's automatic activity detection is disabled, so the
|
|
744
1101
|
* model never auto-responds to room audio. The bridge drives turns manually instead: an `activityStart`
|
|
@@ -748,13 +1105,107 @@ class GeminiRealtimeSession {
|
|
|
748
1105
|
this.meetingMode = false;
|
|
749
1106
|
/** In meeting mode, whether a manual input window (`activityStart` … pending `activityEnd`) is open. */
|
|
750
1107
|
this.manualActivityOpen = false;
|
|
1108
|
+
/** Opens this session's Live connections; set by the driver before {@link Open}. */
|
|
1109
|
+
this.connector = null;
|
|
1110
|
+
/**
|
|
1111
|
+
* Routes model parts, turn boundaries and avatar usage when the driver granted an avatar to a host that publishes it
|
|
1112
|
+
* into a room; null on every other session, whose output is PCM only.
|
|
1113
|
+
*/
|
|
1114
|
+
this.avatarOutput = null;
|
|
1115
|
+
/**
|
|
1116
|
+
* Moves the session to a new connection with Google's resumption handle: when Google announces
|
|
1117
|
+
* the connection is ending (`goAway`, with the time left; on Vertex AI it came about 9 minutes
|
|
1118
|
+
* into a connection, with 30 s left) and after an unexpected drop. A planned move waits until
|
|
1119
|
+
* no turn is in progress ({@link IsTurnOpen}). Created by {@link Open}.
|
|
1120
|
+
*/
|
|
1121
|
+
this.resumption = null;
|
|
1122
|
+
/**
|
|
1123
|
+
* Whether the session is moving to a new connection: from the start of a move until Google
|
|
1124
|
+
* confirms the new connection's setup (`setupComplete`). Input waits meanwhile, in
|
|
1125
|
+
* {@link queuedSends} and {@link heldAudio}: the connection being replaced resumes from a handle
|
|
1126
|
+
* issued before the move, so what it receives never reaches the new one, and Google drops input
|
|
1127
|
+
* that reaches the new one before its setup completes. The first connection needs no flag:
|
|
1128
|
+
* {@link Open} returns only once its setup is confirmed.
|
|
1129
|
+
*/
|
|
1130
|
+
this.moving = false;
|
|
1131
|
+
/** Input audio that came during a move, sent on the new connection once it is ready. */
|
|
1132
|
+
this.heldAudio = [];
|
|
1133
|
+
/** Bytes in {@link heldAudio}, kept under {@link MAX_HELD_INPUT_AUDIO_BYTES}. */
|
|
1134
|
+
this.heldAudioBytes = 0;
|
|
1135
|
+
/** See {@link IsTurnOpen}. */
|
|
1136
|
+
this.turnOpen = false;
|
|
1137
|
+
/** A turn's `turnComplete` came while a tool call was pending: the turn ends once the last pending call's result goes out. */
|
|
1138
|
+
this.turnEndAwaitsToolResults = false;
|
|
1139
|
+
/** Last connection number handed out by {@link openConnection}. */
|
|
1140
|
+
this.issuedConnections = 0;
|
|
1141
|
+
/**
|
|
1142
|
+
* Number of the connection in use. Callbacks from any other connection (one that was replaced,
|
|
1143
|
+
* closed, or is still opening) are ignored, so a replaced socket's close can't end the session
|
|
1144
|
+
* that replaced it. `0` while no connection is in use.
|
|
1145
|
+
*/
|
|
1146
|
+
this.currentConnection = 0;
|
|
751
1147
|
this.profile = profile ?? GEMINI_LIVE_FALLBACK_PROFILE;
|
|
752
1148
|
}
|
|
1149
|
+
/** Sets how this session opens its Live connections. Called by the driver before {@link Open}. */
|
|
1150
|
+
SetConnector(connector) {
|
|
1151
|
+
this.connector = connector;
|
|
1152
|
+
}
|
|
753
1153
|
/**
|
|
754
|
-
*
|
|
1154
|
+
* Records what became of the session's avatar request. A granted one (a server-side session whose host publishes the
|
|
1155
|
+
* avatar into a room) sends the model's MP4 pieces as frames to {@link OnVideoFrame} (marked `Idle` outside an
|
|
1156
|
+
* answer), keeps PCM to turns without video, marks the model generating for its answer's media only, and reports the
|
|
1157
|
+
* avatar's video seconds through {@link OnUsage}. Called by the driver before {@link Open}.
|
|
1158
|
+
*
|
|
1159
|
+
* @param status The avatar status, or `undefined` when the session asked for no avatar.
|
|
1160
|
+
* @param encoding The avatar's MSE type from the model's profile.
|
|
1161
|
+
*/
|
|
1162
|
+
SetAvatar(status, encoding) {
|
|
1163
|
+
this.AvatarStatus = status;
|
|
1164
|
+
this.avatarEncoding = encoding;
|
|
1165
|
+
this.avatarOutput = status?.Granted
|
|
1166
|
+
? new GeminiBridgedAvatarOutput({
|
|
1167
|
+
OnVideoFrame: (frame) => this.videoFrameHandler?.(frame),
|
|
1168
|
+
OnPcm: (pcm) => this.outputHandler?.(pcm),
|
|
1169
|
+
OnVideoSeconds: (seconds) => this.usageHandler?.({ InputTokens: 0, OutputTokens: 0, OutputTokenDetails: { VideoSeconds: seconds } }),
|
|
1170
|
+
OnAnswer: () => this.markAnswering(),
|
|
1171
|
+
Report: (message) => console.warn(message),
|
|
1172
|
+
})
|
|
1173
|
+
: null;
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* Opens the first connection and puts it to use once Google confirms its setup (`setupComplete`): input sent before
|
|
1177
|
+
* that is dropped, so nothing (the initial context, the first audio) goes out until then. Called by the driver once
|
|
1178
|
+
* the session is configured.
|
|
1179
|
+
*
|
|
1180
|
+
* @throws When the connection closes or fails before Google confirms its setup, or no confirmation comes in time.
|
|
1181
|
+
*/
|
|
1182
|
+
async Open() {
|
|
1183
|
+
this.resumption = new RealtimeSessionResumption({
|
|
1184
|
+
Reconnect: (handle, attempt) => this.resume(handle, attempt),
|
|
1185
|
+
OnReconnecting: (reason) => {
|
|
1186
|
+
RealtimeDiagLog(`[GeminiRealtime] Resuming the session on a new connection (${reason})`);
|
|
1187
|
+
// From the moment a move starts, input waits for the new connection.
|
|
1188
|
+
this.moving = true;
|
|
1189
|
+
},
|
|
1190
|
+
OnReconnected: () => this.handleResumed(),
|
|
1191
|
+
OnReconnectFailed: (error) => this.handleResumeFailed(error),
|
|
1192
|
+
Log: (message) => RealtimeDiagLog(message),
|
|
1193
|
+
});
|
|
1194
|
+
const opened = await this.openConnection(undefined);
|
|
1195
|
+
await GeminiRealtimeSession.awaitSetup(opened);
|
|
1196
|
+
this.useConnection(opened);
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* Whether a turn is in progress. A turn opens at its first sign: the user's first transcribed words (outside meeting
|
|
1200
|
+
* mode, where room speech is no turn until the bridge commits one), a spoken update this session sends, or the
|
|
1201
|
+
* model's output (a transcription delta, a thought, a tool call, or an audio part, which in an avatar session must
|
|
1202
|
+
* play as the voice; the video an avatar streams between turns never opens one). It closes at the turn's
|
|
1203
|
+
* `turnComplete` once no tool call is pending, or when the last pending call's result goes out after that; at a
|
|
1204
|
+
* meeting-mode commit that produced no turn; and at a resume. The session moves to a new connection only between
|
|
1205
|
+
* turns.
|
|
755
1206
|
*/
|
|
756
|
-
|
|
757
|
-
this.
|
|
1207
|
+
get IsTurnOpen() {
|
|
1208
|
+
return this.turnOpen;
|
|
758
1209
|
}
|
|
759
1210
|
/** Sets MEETING mode (manual turn-taking). Called by the driver from the connect config at start. */
|
|
760
1211
|
SetMeetingMode(on) {
|
|
@@ -773,11 +1224,17 @@ class GeminiRealtimeSession {
|
|
|
773
1224
|
Modality: 'video',
|
|
774
1225
|
Direction: 'inbound',
|
|
775
1226
|
Encoding: 'image/jpeg',
|
|
776
|
-
|
|
1227
|
+
// The model's own ceiling from the profile table; a bridged host paces frames to it.
|
|
1228
|
+
Rate: this.profile.MaxInboundVideoRate,
|
|
777
1229
|
UsageBasis: ['tokens', 'frames'],
|
|
778
1230
|
RequiresConsent: true,
|
|
779
1231
|
});
|
|
780
1232
|
}
|
|
1233
|
+
const outbound = [{ Modality: 'audio', Direction: 'outbound' }];
|
|
1234
|
+
if (this.avatarOutput) {
|
|
1235
|
+
// A granted avatar: its MP4 pieces reach the host as frames through OnVideoFrame.
|
|
1236
|
+
outbound.push({ Modality: 'video', Direction: 'outbound', ...(this.avatarEncoding ? { Encoding: this.avatarEncoding } : {}) });
|
|
1237
|
+
}
|
|
781
1238
|
return {
|
|
782
1239
|
CanReconfigureTurnMode: false,
|
|
783
1240
|
// Proactive audio is permanently on for the 3.8 line: the model listens while speaking and decides
|
|
@@ -785,7 +1242,8 @@ class GeminiRealtimeSession {
|
|
|
785
1242
|
FullDuplex: this.profile.ProactiveAudioAlwaysOn && !this.meetingMode,
|
|
786
1243
|
SupportsDynamicToolSet: GeminiRealtime.SupportsDynamicToolSet,
|
|
787
1244
|
SupportedInboundTracks: inbound,
|
|
788
|
-
|
|
1245
|
+
MaxInboundVideoStreams: ResolveGeminiMaxInboundVideoStreams(this.profile),
|
|
1246
|
+
SupportedOutboundTracks: outbound,
|
|
789
1247
|
ProvidesThoughtSummaries: this.profile.SupportsThoughtSummaries,
|
|
790
1248
|
SupportsAsynchronousReasoning: !this.profile.Tooling.SupportsBlockingExecution,
|
|
791
1249
|
UsageBases: this.profile.SupportsInboundVideo ? ['tokens', 'seconds', 'frames'] : ['tokens', 'seconds'],
|
|
@@ -799,22 +1257,74 @@ class GeminiRealtimeSession {
|
|
|
799
1257
|
const turns = [{ role: 'user', parts: [{ text: context }] }];
|
|
800
1258
|
this.requireLive().sendClientContent({ turns, turnComplete: false });
|
|
801
1259
|
}
|
|
802
|
-
/**
|
|
803
|
-
|
|
1260
|
+
/**
|
|
1261
|
+
* @inheritdoc
|
|
1262
|
+
*
|
|
1263
|
+
* Audio goes out as `audio` in the frame's PCM format (16 kHz PCM when the frame names none).
|
|
1264
|
+
* Video goes out as `video` when the frame is a JPEG or PNG image, the types Gemini Live accepts.
|
|
1265
|
+
* Anything else is dropped and reported once per type, never sent as the wrong kind.
|
|
1266
|
+
*
|
|
1267
|
+
* While the session moves to a new connection, audio is held (the latest 2 s) and goes out on
|
|
1268
|
+
* the new connection once it is ready; a video frame is dropped, as the next one follows.
|
|
1269
|
+
*/
|
|
1270
|
+
SendInput(frame) {
|
|
1271
|
+
if (frame.Kind === 'video') {
|
|
1272
|
+
if (!this.moving) {
|
|
1273
|
+
this.sendVideoInput(frame);
|
|
1274
|
+
}
|
|
1275
|
+
return;
|
|
1276
|
+
}
|
|
1277
|
+
if (this.moving) {
|
|
1278
|
+
this.holdAudio(frame);
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
1281
|
+
this.sendAudioInput(frame);
|
|
1282
|
+
}
|
|
1283
|
+
/**
|
|
1284
|
+
* Holds an audio frame during a move, keeping the latest {@link MAX_HELD_INPUT_AUDIO_BYTES}; older audio goes first.
|
|
1285
|
+
* The bytes are copied, so a host that reuses its buffers can't change what is held.
|
|
1286
|
+
*/
|
|
1287
|
+
holdAudio(frame) {
|
|
1288
|
+
this.heldAudio.push({ ...frame, Data: frame.Data.slice(0) });
|
|
1289
|
+
this.heldAudioBytes += frame.Data.byteLength;
|
|
1290
|
+
while (this.heldAudioBytes > MAX_HELD_INPUT_AUDIO_BYTES && this.heldAudio.length > 1) {
|
|
1291
|
+
this.heldAudioBytes -= this.heldAudio.shift()?.Data.byteLength ?? 0;
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
/** Sends the audio held during a move on the connection now in use, oldest first. */
|
|
1295
|
+
sendHeldAudio() {
|
|
1296
|
+
const held = this.heldAudio;
|
|
1297
|
+
this.heldAudio = [];
|
|
1298
|
+
this.heldAudioBytes = 0;
|
|
1299
|
+
for (const frame of held) {
|
|
1300
|
+
this.sendAudioInput(frame);
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
sendAudioInput(frame) {
|
|
1304
|
+
const mimeType = frame.MimeType ?? GEMINI_INPUT_AUDIO_MIME_TYPE;
|
|
1305
|
+
if (!IsPcmAudioMimeType(mimeType)) {
|
|
1306
|
+
this.droppedInput.Report(frame);
|
|
1307
|
+
return;
|
|
1308
|
+
}
|
|
804
1309
|
const live = this.requireLive();
|
|
805
1310
|
// Meeting mode: automatic activity detection is OFF, so audio is only processed inside an explicit
|
|
806
1311
|
// activity window. Open one lazily on the first audio after the last turn was committed — the window
|
|
807
1312
|
// stays open (accumulating what the agent hears) until RequestSpokenUpdate sends `activityEnd`.
|
|
1313
|
+
// Only audio opens it: a video frame is not speech.
|
|
808
1314
|
if (this.meetingMode && !this.manualActivityOpen) {
|
|
809
1315
|
live.sendRealtimeInput({ activityStart: {} });
|
|
810
1316
|
this.manualActivityOpen = true;
|
|
811
1317
|
RealtimeDiagLog('[GeminiRealtime][diag] meeting: activityStart — opened input window on first audio (now accumulating room audio)');
|
|
812
1318
|
}
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
1319
|
+
live.sendRealtimeInput({ audio: { data: GeminiRealtimeSession.arrayBufferToBase64(frame.Data), mimeType } });
|
|
1320
|
+
}
|
|
1321
|
+
sendVideoInput(frame) {
|
|
1322
|
+
const mimeType = frame.MimeType?.trim().toLowerCase();
|
|
1323
|
+
if (!mimeType || !GEMINI_VIDEO_INPUT_MIME_TYPES.has(mimeType)) {
|
|
1324
|
+
this.droppedInput.Report(frame);
|
|
1325
|
+
return;
|
|
1326
|
+
}
|
|
1327
|
+
this.requireLive().sendRealtimeInput({ video: { data: GeminiRealtimeSession.arrayBufferToBase64(frame.Data), mimeType } });
|
|
818
1328
|
}
|
|
819
1329
|
/**
|
|
820
1330
|
* @inheritdoc
|
|
@@ -854,6 +1364,10 @@ class GeminiRealtimeSession {
|
|
|
854
1364
|
this.outputHandler = handler;
|
|
855
1365
|
}
|
|
856
1366
|
/** @inheritdoc */
|
|
1367
|
+
OnVideoFrame(handler) {
|
|
1368
|
+
this.videoFrameHandler = handler;
|
|
1369
|
+
}
|
|
1370
|
+
/** @inheritdoc */
|
|
857
1371
|
OnTranscript(handler) {
|
|
858
1372
|
this.transcriptHandler = handler;
|
|
859
1373
|
}
|
|
@@ -875,22 +1389,142 @@ class GeminiRealtimeSession {
|
|
|
875
1389
|
/**
|
|
876
1390
|
* Surfaces a websocket-level failure as a FATAL session error — the transport is gone,
|
|
877
1391
|
* so the consumer (e.g. the session runner) should finalize cleanly instead of idling.
|
|
1392
|
+
* When the session can be resumed, the error is only logged: a websocket `error` is always
|
|
1393
|
+
* followed by a `close`, and {@link HandleTransportClose} resumes from there.
|
|
878
1394
|
*/
|
|
879
1395
|
HandleTransportError(message) {
|
|
1396
|
+
if (this.resumption?.Handle) {
|
|
1397
|
+
RealtimeDiagLog(`[GeminiRealtime] Transport error, resuming on close: ${message}`);
|
|
1398
|
+
return;
|
|
1399
|
+
}
|
|
880
1400
|
this.errorHandler?.({ Message: message, Fatal: true });
|
|
881
1401
|
}
|
|
882
1402
|
/**
|
|
883
|
-
*
|
|
884
|
-
*
|
|
885
|
-
*
|
|
1403
|
+
* Handles a close of the current connection that the consumer did not ask for. When Google
|
|
1404
|
+
* issued a resumption handle, the session reconnects with it; otherwise the close surfaces as a
|
|
1405
|
+
* fatal error, as before (expected closes, after {@link Close}, stay silent).
|
|
886
1406
|
*/
|
|
887
1407
|
HandleTransportClose(code, reason) {
|
|
888
1408
|
if (this.closedByConsumer) {
|
|
889
1409
|
return;
|
|
890
1410
|
}
|
|
1411
|
+
if (this.resumption?.ConnectionLost()) {
|
|
1412
|
+
return;
|
|
1413
|
+
}
|
|
891
1414
|
const detail = [code != null ? `code ${code}` : null, reason || null].filter(Boolean).join(' — ');
|
|
892
1415
|
this.errorHandler?.({ Message: `Gemini Live session closed unexpectedly${detail ? ` (${detail})` : ''}`, Fatal: true });
|
|
893
1416
|
}
|
|
1417
|
+
/**
|
|
1418
|
+
* Opens a connection through the driver's connector. Its callbacks act only while it is the
|
|
1419
|
+
* connection in use, so events from one that was replaced, closed, or is still opening are
|
|
1420
|
+
* dropped; its `setupComplete`, and a close or error before it, settle its
|
|
1421
|
+
* {@link GeminiOpenedConnection.Setup} whether or not it is in use yet. It becomes the
|
|
1422
|
+
* connection in use through {@link useConnection}, which lets the old connection keep
|
|
1423
|
+
* delivering events while a planned move is in progress.
|
|
1424
|
+
*/
|
|
1425
|
+
async openConnection(handle) {
|
|
1426
|
+
if (!this.connector) {
|
|
1427
|
+
throw new Error('Gemini realtime session has no connector; the driver must call SetConnector before Open.');
|
|
1428
|
+
}
|
|
1429
|
+
const number = ++this.issuedConnections;
|
|
1430
|
+
const isCurrent = () => number === this.currentConnection;
|
|
1431
|
+
const setup = new RealtimeConnectionSetup();
|
|
1432
|
+
const live = await this.connector(handle, {
|
|
1433
|
+
OnMessage: (message) => {
|
|
1434
|
+
if (message.setupComplete) {
|
|
1435
|
+
setup.Confirm();
|
|
1436
|
+
}
|
|
1437
|
+
if (isCurrent()) {
|
|
1438
|
+
this.HandleServerMessage(message);
|
|
1439
|
+
}
|
|
1440
|
+
},
|
|
1441
|
+
OnError: (event) => {
|
|
1442
|
+
setup.Fail(new Error(`Gemini Live connection failed before confirming its setup: ${event?.message ?? 'websocket error'}`));
|
|
1443
|
+
if (isCurrent()) {
|
|
1444
|
+
this.HandleTransportError(event?.message ?? 'Gemini Live websocket error');
|
|
1445
|
+
}
|
|
1446
|
+
},
|
|
1447
|
+
OnClose: (event) => {
|
|
1448
|
+
setup.Fail(new Error(`Gemini Live closed the connection before confirming its setup (${event?.code}): ${event?.reason || 'no reason given'}`));
|
|
1449
|
+
if (isCurrent()) {
|
|
1450
|
+
this.HandleTransportClose(event?.code, event?.reason);
|
|
1451
|
+
}
|
|
1452
|
+
},
|
|
1453
|
+
});
|
|
1454
|
+
return { Live: live, ConnectionNumber: number, Setup: setup };
|
|
1455
|
+
}
|
|
1456
|
+
/** Waits for Google to confirm a new connection's setup. On failure the connection is closed and the error rethrown. */
|
|
1457
|
+
static async awaitSetup(opened) {
|
|
1458
|
+
try {
|
|
1459
|
+
await opened.Setup.Wait();
|
|
1460
|
+
}
|
|
1461
|
+
catch (error) {
|
|
1462
|
+
GeminiRealtimeSession.closeQuietly(opened.Live);
|
|
1463
|
+
throw error;
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
/** Makes an opened connection the one in use. */
|
|
1467
|
+
useConnection(opened) {
|
|
1468
|
+
this.live = opened.Live;
|
|
1469
|
+
this.currentConnection = opened.ConnectionNumber;
|
|
1470
|
+
}
|
|
1471
|
+
/**
|
|
1472
|
+
* Opens a replacement connection that resumes the session from `handle`, switches to it once
|
|
1473
|
+
* Google confirms its setup, and closes the old one. Until then the old connection stays in
|
|
1474
|
+
* use, so what it still sends (the rest of a turn the deadline cut, its usage) is handled.
|
|
1475
|
+
* Rejects when the connection can't be opened or its setup fails, so
|
|
1476
|
+
* {@link RealtimeSessionResumption} can retry. A connection that opens after the attempt was
|
|
1477
|
+
* abandoned (timeout, or {@link Close}) is closed instead of used.
|
|
1478
|
+
*/
|
|
1479
|
+
async resume(handle, attempt) {
|
|
1480
|
+
const opened = await this.openConnection(handle);
|
|
1481
|
+
await GeminiRealtimeSession.awaitSetup(opened);
|
|
1482
|
+
if (attempt.Abandoned || this.closedByConsumer) {
|
|
1483
|
+
GeminiRealtimeSession.closeQuietly(opened.Live);
|
|
1484
|
+
return;
|
|
1485
|
+
}
|
|
1486
|
+
const previous = this.live;
|
|
1487
|
+
this.useConnection(opened);
|
|
1488
|
+
if (previous) {
|
|
1489
|
+
GeminiRealtimeSession.closeQuietly(previous);
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* The session continues on a new connection, whose setup Google has confirmed. It has no open
|
|
1494
|
+
* meeting-mode activity window, and a turn cut off by a drop or the deadline never completes
|
|
1495
|
+
* there, so the turn is ended the way `turnComplete` ends one: thought text emitted, the busy
|
|
1496
|
+
* flag cleared. The audio held during the move goes out, then the queued sends.
|
|
1497
|
+
*/
|
|
1498
|
+
handleResumed() {
|
|
1499
|
+
this.manualActivityOpen = false;
|
|
1500
|
+
this.avatarOutput?.Resumed();
|
|
1501
|
+
this.endTurn();
|
|
1502
|
+
this.moving = false;
|
|
1503
|
+
this.sendHeldAudio();
|
|
1504
|
+
this.completeTurn();
|
|
1505
|
+
}
|
|
1506
|
+
/**
|
|
1507
|
+
* Every resume attempt failed: the session ends with a fatal error. Input no longer waits for a new connection; the
|
|
1508
|
+
* audio held for one is dropped.
|
|
1509
|
+
*/
|
|
1510
|
+
handleResumeFailed(error) {
|
|
1511
|
+
this.moving = false;
|
|
1512
|
+
this.heldAudio = [];
|
|
1513
|
+
this.heldAudioBytes = 0;
|
|
1514
|
+
if (this.closedByConsumer) {
|
|
1515
|
+
return;
|
|
1516
|
+
}
|
|
1517
|
+
this.errorHandler?.({ Message: `Gemini Live connection was lost and could not be resumed: ${error.message}`, Fatal: true });
|
|
1518
|
+
}
|
|
1519
|
+
/** Closes a connection the session no longer uses; it may already be closed. */
|
|
1520
|
+
static closeQuietly(live) {
|
|
1521
|
+
try {
|
|
1522
|
+
live.close();
|
|
1523
|
+
}
|
|
1524
|
+
catch (err) {
|
|
1525
|
+
RealtimeDiagLog(`[GeminiRealtime] Closing a replaced connection failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
894
1528
|
/**
|
|
895
1529
|
* @inheritdoc
|
|
896
1530
|
*
|
|
@@ -898,7 +1532,12 @@ class GeminiRealtimeSession {
|
|
|
898
1532
|
* *name*, which the Core contract does not pass — so the name is looked up from the
|
|
899
1533
|
* {@link pendingToolCallNames} cache populated when the originating tool call arrived. The
|
|
900
1534
|
* `output` JSON string is parsed into the structured response object Gemini expects, and the
|
|
901
|
-
* cache entry is cleared once the response is sent.
|
|
1535
|
+
* cache entry is cleared once the response is sent. While the session moves to a new
|
|
1536
|
+
* connection, the result waits and goes out on the new one.
|
|
1537
|
+
*
|
|
1538
|
+
* When a context note left the client turn open, the result is followed by a bare
|
|
1539
|
+
* `turnComplete: true` that closes it (see {@link closeOpenClientTurn}): Gemini holds the
|
|
1540
|
+
* continuation after a tool result while that turn is open, and the model stays silent.
|
|
902
1541
|
*
|
|
903
1542
|
* @param callID The originating tool call's id.
|
|
904
1543
|
* @param output The tool's result as a JSON-stringified string.
|
|
@@ -913,8 +1552,31 @@ class GeminiRealtimeSession {
|
|
|
913
1552
|
response: parsed,
|
|
914
1553
|
...(sched ? { scheduling: sched } : {}),
|
|
915
1554
|
};
|
|
916
|
-
|
|
917
|
-
|
|
1555
|
+
const send = () => {
|
|
1556
|
+
const live = this.requireLive();
|
|
1557
|
+
live.sendToolResponse({ functionResponses: [functionResponse] });
|
|
1558
|
+
this.closeOpenClientTurn(live);
|
|
1559
|
+
this.pendingToolCallNames.delete(callID);
|
|
1560
|
+
this.endTurnIfToolResultsIn();
|
|
1561
|
+
};
|
|
1562
|
+
if (this.moving) {
|
|
1563
|
+
this.queuedSends.push(send);
|
|
1564
|
+
return;
|
|
1565
|
+
}
|
|
1566
|
+
send();
|
|
1567
|
+
}
|
|
1568
|
+
/**
|
|
1569
|
+
* Closes the client turn a context note left open, right after a tool result, so the model speaks the result. Not
|
|
1570
|
+
* while an answer is being generated: a `turnComplete: true` would cut it off, and that turn takes the note in at its
|
|
1571
|
+
* own `turnComplete`. Not on a model whose tools never block (Extended Thinking): it may still be reasoning when the
|
|
1572
|
+
* result arrives, which this session can't see, and the close would cut that off too.
|
|
1573
|
+
*/
|
|
1574
|
+
closeOpenClientTurn(live) {
|
|
1575
|
+
if (!this.openClientTurn || !this.profile.Tooling.SupportsBlockingExecution || this.responseActive) {
|
|
1576
|
+
return;
|
|
1577
|
+
}
|
|
1578
|
+
live.sendClientContent({ turnComplete: true });
|
|
1579
|
+
this.openClientTurn = false;
|
|
918
1580
|
}
|
|
919
1581
|
/**
|
|
920
1582
|
* Parses a JSON-stringified tool result into the structured object Gemini's function-response
|
|
@@ -947,11 +1609,15 @@ class GeminiRealtimeSession {
|
|
|
947
1609
|
* **Collision behavior: queue.** Any client content sent mid-turn interrupts in-flight
|
|
948
1610
|
* generation on Gemini Live, so the send is deferred until the active turn completes.
|
|
949
1611
|
*
|
|
1612
|
+
* `turnComplete: false` leaves the client turn open: Gemini holds the continuation after a
|
|
1613
|
+
* tool result until the turn is closed, which {@link SendToolResult} does.
|
|
1614
|
+
*
|
|
950
1615
|
* @param text The context note to append to the conversation.
|
|
951
1616
|
*/
|
|
952
1617
|
SendContextNote(text) {
|
|
953
1618
|
this.enqueueOrRun(() => {
|
|
954
1619
|
this.requireLive().sendClientContent({ turns: [{ role: 'user', parts: [{ text }] }], turnComplete: false });
|
|
1620
|
+
this.openClientTurn = true;
|
|
955
1621
|
});
|
|
956
1622
|
}
|
|
957
1623
|
/**
|
|
@@ -982,8 +1648,11 @@ class GeminiRealtimeSession {
|
|
|
982
1648
|
return false;
|
|
983
1649
|
}
|
|
984
1650
|
let committed = false;
|
|
1651
|
+
// During a move the update waits for the new connection and commits there, so it counts as committed.
|
|
1652
|
+
const waitsForConnection = this.moving;
|
|
985
1653
|
this.enqueueOrRun(() => {
|
|
986
1654
|
this.responseActive = true;
|
|
1655
|
+
this.markTurnOpen();
|
|
987
1656
|
const live = this.requireLive();
|
|
988
1657
|
if (this.meetingMode) {
|
|
989
1658
|
// MEETING mode: the agent has been heard accumulating audio inside the open activity window
|
|
@@ -1010,7 +1679,7 @@ class GeminiRealtimeSession {
|
|
|
1010
1679
|
});
|
|
1011
1680
|
// Meeting mode: report whether we actually committed a turn (so the bridge can release the floor if
|
|
1012
1681
|
// not). Non-meeting (narration) always reports sent — it queues rather than wedges a floor.
|
|
1013
|
-
return this.meetingMode ? committed : true;
|
|
1682
|
+
return this.meetingMode ? committed || waitsForConnection : true;
|
|
1014
1683
|
}
|
|
1015
1684
|
/**
|
|
1016
1685
|
* Watchdog for the manual-activity meeting trigger: if Gemini produces NO turn after an `activityEnd`
|
|
@@ -1026,6 +1695,7 @@ class GeminiRealtimeSession {
|
|
|
1026
1695
|
this.meetingResponseWatchdog = undefined;
|
|
1027
1696
|
if (this.responseActive) {
|
|
1028
1697
|
RealtimeDiagLog('[GeminiRealtime][diag] meeting WATCHDOG fired — no turn produced after activityEnd; clearing responseActive so the agent isn’t stuck silent');
|
|
1698
|
+
this.endTurnUnlessToolCallPending();
|
|
1029
1699
|
this.completeTurn();
|
|
1030
1700
|
}
|
|
1031
1701
|
}, GEMINI_MEETING_RESPONSE_WATCHDOG_MS);
|
|
@@ -1034,11 +1704,12 @@ class GeminiRealtimeSession {
|
|
|
1034
1704
|
* Runs a client-content send immediately when no turn is in flight; otherwise queues it for
|
|
1035
1705
|
* the next turn boundary. Gemini-specific collision rule: ANY client content interrupts
|
|
1036
1706
|
* in-flight generation on the Live API, so deferral (not skipping) is the safe default.
|
|
1707
|
+
* A send also waits while the session moves to a new connection, and goes out on the new one.
|
|
1037
1708
|
*/
|
|
1038
1709
|
enqueueOrRun(send) {
|
|
1039
|
-
if (this.responseActive) {
|
|
1710
|
+
if (this.responseActive || this.moving) {
|
|
1040
1711
|
this.queuedSends.push(send);
|
|
1041
|
-
RealtimeDiagLog(`[GeminiRealtime][diag] send QUEUED
|
|
1712
|
+
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`);
|
|
1042
1713
|
return;
|
|
1043
1714
|
}
|
|
1044
1715
|
send();
|
|
@@ -1046,7 +1717,8 @@ class GeminiRealtimeSession {
|
|
|
1046
1717
|
/**
|
|
1047
1718
|
* Turn boundary (`turnComplete` or `interrupted`): releases the busy flag and drains queued
|
|
1048
1719
|
* sends in order, stopping at the first send that itself starts a new turn (a queued
|
|
1049
|
-
* {@link RequestSpokenUpdate} re-sets {@link responseActive}).
|
|
1720
|
+
* {@link RequestSpokenUpdate} re-sets {@link responseActive}). Nothing drains during a move:
|
|
1721
|
+
* {@link handleResumed} drains onto the new connection.
|
|
1050
1722
|
*/
|
|
1051
1723
|
completeTurn() {
|
|
1052
1724
|
if (this.meetingResponseWatchdog) {
|
|
@@ -1066,16 +1738,82 @@ class GeminiRealtimeSession {
|
|
|
1066
1738
|
}
|
|
1067
1739
|
RealtimeDiagLog(`[GeminiRealtime][diag] turn boundary — clearing responseActive (was ${this.responseActive}), draining ${this.queuedSends.length} queued send(s)`);
|
|
1068
1740
|
this.responseActive = false;
|
|
1069
|
-
while (!this.responseActive && this.queuedSends.length > 0) {
|
|
1741
|
+
while (!this.responseActive && !this.moving && this.queuedSends.length > 0) {
|
|
1070
1742
|
const send = this.queuedSends.shift();
|
|
1071
1743
|
send?.();
|
|
1072
1744
|
}
|
|
1073
1745
|
}
|
|
1746
|
+
// ── Turn tracking (see IsTurnOpen) ─────────────────────────────────────────
|
|
1747
|
+
/**
|
|
1748
|
+
* Whether a server content frame is a sign of a turn: the user's transcribed words (outside
|
|
1749
|
+
* meeting mode), the model's transcribed words, a thought, or (in a session without an avatar)
|
|
1750
|
+
* the model's audio. An avatar's video never is: Vertex AI streams it between turns too.
|
|
1751
|
+
*/
|
|
1752
|
+
contentOpensTurn(content) {
|
|
1753
|
+
if (!this.meetingMode && GeminiRealtimeSession.hasText(content.inputTranscription?.text)) {
|
|
1754
|
+
return true;
|
|
1755
|
+
}
|
|
1756
|
+
if (GeminiRealtimeSession.hasText(content.outputTranscription?.text)) {
|
|
1757
|
+
return true;
|
|
1758
|
+
}
|
|
1759
|
+
return (content.modelTurn?.parts ?? []).some((part) => this.partOpensTurn(part));
|
|
1760
|
+
}
|
|
1761
|
+
/**
|
|
1762
|
+
* Whether a model part is a sign of a turn: a thought, or audio (as this session plays it) in a session without an
|
|
1763
|
+
* avatar. In an avatar session, a voice part opens the turn once it plays (the avatar output's `OnAnswer`).
|
|
1764
|
+
*/
|
|
1765
|
+
partOpensTurn(part) {
|
|
1766
|
+
if (part.thought) {
|
|
1767
|
+
return GeminiRealtimeSession.hasText(part.text);
|
|
1768
|
+
}
|
|
1769
|
+
const inline = part.inlineData;
|
|
1770
|
+
return !this.avatarOutput && !!inline?.data && (!inline.mimeType || IsPcmAudioMimeType(inline.mimeType));
|
|
1771
|
+
}
|
|
1772
|
+
/** Whether a transcription or thought carries words (whitespace alone does not count). */
|
|
1773
|
+
static hasText(text) {
|
|
1774
|
+
return (text?.trim().length ?? 0) > 0;
|
|
1775
|
+
}
|
|
1776
|
+
/** A turn started or continued: a planned move waits until it ends. */
|
|
1777
|
+
markTurnOpen() {
|
|
1778
|
+
this.turnOpen = true;
|
|
1779
|
+
this.turnEndAwaitsToolResults = false;
|
|
1780
|
+
this.resumption?.TurnStarted();
|
|
1781
|
+
}
|
|
1782
|
+
/** The turn's `turnComplete`: it ends now, or once the results of the tool calls still pending go out. */
|
|
1783
|
+
endTurnUnlessToolCallPending() {
|
|
1784
|
+
if (this.pendingToolCallNames.size > 0) {
|
|
1785
|
+
this.turnEndAwaitsToolResults = this.turnOpen;
|
|
1786
|
+
return;
|
|
1787
|
+
}
|
|
1788
|
+
this.endTurn();
|
|
1789
|
+
}
|
|
1790
|
+
/** A tool result went out: a turn whose `turnComplete` waited on the pending calls ends once none is left. */
|
|
1791
|
+
endTurnIfToolResultsIn() {
|
|
1792
|
+
if (this.turnEndAwaitsToolResults && this.pendingToolCallNames.size === 0) {
|
|
1793
|
+
this.endTurn();
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
/** The turn is over: a planned move happens at the next resumable handle Google issues. */
|
|
1797
|
+
endTurn() {
|
|
1798
|
+
this.turnOpen = false;
|
|
1799
|
+
this.turnEndAwaitsToolResults = false;
|
|
1800
|
+
this.resumption?.TurnEnded();
|
|
1801
|
+
}
|
|
1074
1802
|
/** @inheritdoc */
|
|
1075
1803
|
async Close() {
|
|
1076
1804
|
this.closedByConsumer = true;
|
|
1805
|
+
// Stop resuming before the socket closes, and drop events still in flight from it.
|
|
1806
|
+
this.resumption?.Dispose();
|
|
1807
|
+
this.currentConnection = 0;
|
|
1808
|
+
// A closed session's sends fail as before (no live connection), rather than wait for a move.
|
|
1809
|
+
this.moving = false;
|
|
1810
|
+
this.heldAudio = [];
|
|
1811
|
+
this.heldAudioBytes = 0;
|
|
1812
|
+
this.turnOpen = false;
|
|
1813
|
+
this.turnEndAwaitsToolResults = false;
|
|
1077
1814
|
this.live?.close();
|
|
1078
1815
|
this.live = null;
|
|
1816
|
+
this.avatarOutput?.Close(); // reports the avatar seconds generated and not yet reported, while the handler is set
|
|
1079
1817
|
this.clearHandlers();
|
|
1080
1818
|
}
|
|
1081
1819
|
/**
|
|
@@ -1083,6 +1821,15 @@ class GeminiRealtimeSession {
|
|
|
1083
1821
|
* per-concern handlers so each translation unit stays small and testable.
|
|
1084
1822
|
*/
|
|
1085
1823
|
HandleServerMessage(message) {
|
|
1824
|
+
// Session continuity. `resumable: false` (mid-turn, mid-tool-call) arrives with no handle;
|
|
1825
|
+
// an update without the flag is treated as resumable.
|
|
1826
|
+
if (message.sessionResumptionUpdate) {
|
|
1827
|
+
const update = message.sessionResumptionUpdate;
|
|
1828
|
+
this.resumption?.RecordHandle(update.newHandle, update.resumable !== false);
|
|
1829
|
+
}
|
|
1830
|
+
if (message.goAway) {
|
|
1831
|
+
this.resumption?.ConnectionEnding(ParseDurationToMs(message.goAway.timeLeft));
|
|
1832
|
+
}
|
|
1086
1833
|
if (message.serverContent) {
|
|
1087
1834
|
this.handleServerContent(message.serverContent);
|
|
1088
1835
|
}
|
|
@@ -1095,24 +1842,40 @@ class GeminiRealtimeSession {
|
|
|
1095
1842
|
}
|
|
1096
1843
|
/**
|
|
1097
1844
|
* Translates a {@link LiveServerContent} frame: model audio output, input/output transcription,
|
|
1098
|
-
* and interruption.
|
|
1845
|
+
* and interruption. What the frame carries opens the turn before its `turnComplete` ends it.
|
|
1099
1846
|
*/
|
|
1100
1847
|
handleServerContent(content) {
|
|
1848
|
+
if (this.contentOpensTurn(content)) {
|
|
1849
|
+
this.markTurnOpen();
|
|
1850
|
+
}
|
|
1851
|
+
if (this.avatarOutput && GeminiRealtimeSession.hasText(content.outputTranscription?.text)) {
|
|
1852
|
+
// The model speaks: the avatar's video is its answer's from here, this message's parts included.
|
|
1853
|
+
this.avatarOutput.AnswerStarted();
|
|
1854
|
+
}
|
|
1101
1855
|
if (content.interrupted) {
|
|
1856
|
+
this.avatarOutput?.Interrupted(); // before the parts of this message: the turn's late media is dropped
|
|
1102
1857
|
this.interruptionHandler?.();
|
|
1103
1858
|
this.completeTurn();
|
|
1104
1859
|
}
|
|
1105
1860
|
if (content.modelTurn) {
|
|
1106
1861
|
// First model output of a turn marks generation in flight (Gemini emits no explicit
|
|
1107
|
-
// "response started" frame), so interim-update sends defer instead of interrupting.
|
|
1108
|
-
|
|
1109
|
-
|
|
1862
|
+
// "response started" frame), so interim-update sends defer instead of interrupting. In an
|
|
1863
|
+
// avatar session the avatar output marks it for the answer's media (OnAnswer): the video
|
|
1864
|
+
// Vertex AI streams between answers is not generation.
|
|
1865
|
+
if (!this.avatarOutput || GeminiRealtimeSession.carriesMoreThanMedia(content.modelTurn)) {
|
|
1866
|
+
this.markGenerating();
|
|
1110
1867
|
}
|
|
1111
|
-
this.
|
|
1112
|
-
this.emitAudioOutput(content.modelTurn);
|
|
1868
|
+
this.emitModelMedia(content.modelTurn);
|
|
1113
1869
|
this.emitThoughtOutput(content.modelTurn);
|
|
1114
1870
|
}
|
|
1871
|
+
if (content.generationComplete) {
|
|
1872
|
+
this.avatarOutput?.GenerationComplete();
|
|
1873
|
+
}
|
|
1115
1874
|
if (content.turnComplete) {
|
|
1875
|
+
this.avatarOutput?.TurnComplete();
|
|
1876
|
+
// Before the drain: a queued send that starts a new turn opens it again, and a queued note opens a client turn.
|
|
1877
|
+
this.endTurnUnlessToolCallPending();
|
|
1878
|
+
this.openClientTurn = false; // the model's turn took in any note that left the client turn open
|
|
1116
1879
|
this.completeTurn();
|
|
1117
1880
|
}
|
|
1118
1881
|
if (content.inputTranscription) {
|
|
@@ -1122,25 +1885,68 @@ class GeminiRealtimeSession {
|
|
|
1122
1885
|
this.emitTranscript('assistant', content.outputTranscription.text, content.outputTranscription.finished, 'normal');
|
|
1123
1886
|
}
|
|
1124
1887
|
}
|
|
1888
|
+
/** The model is generating: sends wait for the turn's boundary instead of interrupting it. */
|
|
1889
|
+
markGenerating() {
|
|
1890
|
+
if (!this.responseActive) {
|
|
1891
|
+
RealtimeDiagLog('[GeminiRealtime][diag] modelTurn — model is GENERATING output (the activityEnd worked)');
|
|
1892
|
+
}
|
|
1893
|
+
this.responseActive = true;
|
|
1894
|
+
}
|
|
1895
|
+
/** A part of the avatar session's answer is about to reach the host: the turn is open and the model generating. */
|
|
1896
|
+
markAnswering() {
|
|
1897
|
+
this.markTurnOpen();
|
|
1898
|
+
this.markGenerating();
|
|
1899
|
+
}
|
|
1125
1900
|
/**
|
|
1126
|
-
*
|
|
1127
|
-
*
|
|
1128
|
-
* not synthesized audio.
|
|
1901
|
+
* Whether a model turn carries something besides media parts (a thought, a part without inline data) or nothing at
|
|
1902
|
+
* all: generation in an avatar session, whatever its media turn out to be.
|
|
1129
1903
|
*/
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1904
|
+
static carriesMoreThanMedia(modelTurn) {
|
|
1905
|
+
const parts = modelTurn.parts ?? [];
|
|
1906
|
+
return parts.length === 0 || parts.some((part) => part.thought || !part.inlineData?.data);
|
|
1907
|
+
}
|
|
1908
|
+
/**
|
|
1909
|
+
* Forwards the model turn's inline media parts. Thought parts (`part.thought === true`) are skipped — thoughts are
|
|
1910
|
+
* reasoning summaries, not synthesized media. A session with a granted avatar routes each part through its avatar
|
|
1911
|
+
* output (MP4 pieces to the host, PCM only before the turn's video; the answer's parts mark the model generating);
|
|
1912
|
+
* every other session plays PCM only.
|
|
1913
|
+
*/
|
|
1914
|
+
emitModelMedia(modelTurn) {
|
|
1915
|
+
for (const part of modelTurn.parts ?? []) {
|
|
1916
|
+
const inline = part.inlineData;
|
|
1917
|
+
if (part.thought || !inline?.data) {
|
|
1136
1918
|
continue;
|
|
1137
1919
|
}
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1920
|
+
if (this.avatarOutput) {
|
|
1921
|
+
this.avatarOutput.Accept(inline.mimeType, GeminiRealtimeSession.base64ToArrayBuffer(inline.data));
|
|
1922
|
+
}
|
|
1923
|
+
else {
|
|
1924
|
+
this.emitAudioOutput(inline.mimeType, inline.data);
|
|
1141
1925
|
}
|
|
1142
1926
|
}
|
|
1143
1927
|
}
|
|
1928
|
+
/**
|
|
1929
|
+
* Forwards one inline part as raw PCM. A part that names a non-PCM type (e.g. video/mp4 avatar frames) must never
|
|
1930
|
+
* reach the audio output, where it would play as noise. A part with no type plays, as it always has.
|
|
1931
|
+
*/
|
|
1932
|
+
emitAudioOutput(mimeType, data) {
|
|
1933
|
+
if (!this.outputHandler) {
|
|
1934
|
+
return;
|
|
1935
|
+
}
|
|
1936
|
+
if (mimeType && !IsPcmAudioMimeType(mimeType)) {
|
|
1937
|
+
this.reportDroppedOutput(mimeType);
|
|
1938
|
+
return;
|
|
1939
|
+
}
|
|
1940
|
+
this.outputHandler(GeminiRealtimeSession.base64ToArrayBuffer(data));
|
|
1941
|
+
}
|
|
1942
|
+
/** Reports each MIME type of dropped model output once per session, not once per part. */
|
|
1943
|
+
reportDroppedOutput(mimeType) {
|
|
1944
|
+
if (this.droppedOutputTypes.has(mimeType)) {
|
|
1945
|
+
return;
|
|
1946
|
+
}
|
|
1947
|
+
this.droppedOutputTypes.add(mimeType);
|
|
1948
|
+
console.warn(`[GeminiRealtime] Dropped model output of type ${mimeType}: only PCM audio is played on this session.`);
|
|
1949
|
+
}
|
|
1144
1950
|
/**
|
|
1145
1951
|
* Extracts thought parts (`part.thought === true`) from the model turn and emits each
|
|
1146
1952
|
* as an interim narration transcript (`Kind: 'narration'`).
|
|
@@ -1187,7 +1993,9 @@ class GeminiRealtimeSession {
|
|
|
1187
1993
|
// draining the queue; queued sends flush at the next real turn boundary) so the eventual
|
|
1188
1994
|
// SendToolResult and any fresh context note are not deferred behind a turn that will not
|
|
1189
1995
|
// complete until after the result is sent. Mirrors the client driver's deadlock guard.
|
|
1996
|
+
// The answer stops at the call: the avatar's video until the model speaks again is idle.
|
|
1190
1997
|
this.responseActive = false;
|
|
1998
|
+
this.avatarOutput?.ToolCalled();
|
|
1191
1999
|
for (const call of functionCalls) {
|
|
1192
2000
|
const callID = call.id ?? '';
|
|
1193
2001
|
const toolName = call.name ?? '';
|
|
@@ -1195,6 +2003,8 @@ class GeminiRealtimeSession {
|
|
|
1195
2003
|
// SendToolResult can supply it to Gemini's sendToolResponse, which requires the function
|
|
1196
2004
|
// name the Core contract does not carry.
|
|
1197
2005
|
this.pendingToolCallNames.set(callID, toolName);
|
|
2006
|
+
// A pending call keeps its turn open until its result goes out (see IsTurnOpen).
|
|
2007
|
+
this.markTurnOpen();
|
|
1198
2008
|
this.toolCallHandler?.({
|
|
1199
2009
|
CallID: callID,
|
|
1200
2010
|
ToolName: toolName,
|
|
@@ -1203,40 +2013,45 @@ class GeminiRealtimeSession {
|
|
|
1203
2013
|
}
|
|
1204
2014
|
}
|
|
1205
2015
|
/**
|
|
1206
|
-
* Emits an incremental usage update, defaulting missing token counts to zero,
|
|
1207
|
-
*
|
|
2016
|
+
* Emits an incremental usage update, defaulting missing token counts to zero, with the per-modality breakdown
|
|
2017
|
+
* (text, audio, image, video) of the prompt and of the response when Google reports one. A generated avatar's tokens
|
|
2018
|
+
* arrive as the response's VIDEO.
|
|
1208
2019
|
*/
|
|
1209
2020
|
handleUsage(usageMetadata) {
|
|
1210
2021
|
if (!usageMetadata) {
|
|
1211
2022
|
return;
|
|
1212
2023
|
}
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
for (const detail of usageMetadata.promptTokensDetails) {
|
|
1216
|
-
if (typeof detail.tokenCount === 'number') {
|
|
1217
|
-
inputDetails = inputDetails ?? {};
|
|
1218
|
-
const mod = String(detail.modality ?? '').toUpperCase();
|
|
1219
|
-
if (mod === 'AUDIO') {
|
|
1220
|
-
inputDetails.AudioTokens = (inputDetails.AudioTokens ?? 0) + detail.tokenCount;
|
|
1221
|
-
}
|
|
1222
|
-
else if (mod === 'TEXT') {
|
|
1223
|
-
inputDetails.TextTokens = (inputDetails.TextTokens ?? 0) + detail.tokenCount;
|
|
1224
|
-
}
|
|
1225
|
-
else if (mod === 'IMAGE') {
|
|
1226
|
-
inputDetails.ImageTokens = (inputDetails.ImageTokens ?? 0) + detail.tokenCount;
|
|
1227
|
-
}
|
|
1228
|
-
}
|
|
1229
|
-
}
|
|
1230
|
-
}
|
|
2024
|
+
const inputDetails = this.modalityTokenDetails(usageMetadata.promptTokensDetails);
|
|
2025
|
+
const outputDetails = this.modalityTokenDetails(usageMetadata.responseTokensDetails);
|
|
1231
2026
|
this.usageHandler?.({
|
|
1232
2027
|
InputTokens: usageMetadata.promptTokenCount ?? 0,
|
|
1233
2028
|
OutputTokens: usageMetadata.responseTokenCount ?? 0,
|
|
1234
2029
|
...(inputDetails ? { InputTokenDetails: inputDetails } : {}),
|
|
2030
|
+
...(outputDetails ? { OutputTokenDetails: outputDetails } : {}),
|
|
1235
2031
|
});
|
|
1236
2032
|
}
|
|
2033
|
+
/**
|
|
2034
|
+
* Sums a usage report's per-modality token counts into the fields {@link GEMINI_MODALITY_TOKEN_FIELDS} names.
|
|
2035
|
+
* `undefined` when the report has no count for a modality the table names.
|
|
2036
|
+
*/
|
|
2037
|
+
modalityTokenDetails(counts) {
|
|
2038
|
+
if (!Array.isArray(counts)) {
|
|
2039
|
+
return undefined;
|
|
2040
|
+
}
|
|
2041
|
+
let details;
|
|
2042
|
+
for (const count of counts) {
|
|
2043
|
+
const field = GEMINI_MODALITY_TOKEN_FIELDS[String(count.modality ?? '').toUpperCase()];
|
|
2044
|
+
if (field && typeof count.tokenCount === 'number') {
|
|
2045
|
+
details = details ?? {};
|
|
2046
|
+
details[field] = (details[field] ?? 0) + count.tokenCount;
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
return details;
|
|
2050
|
+
}
|
|
1237
2051
|
/** Drops all registered handlers so a closed session can't fire stale callbacks. */
|
|
1238
2052
|
clearHandlers() {
|
|
1239
2053
|
this.outputHandler = null;
|
|
2054
|
+
this.videoFrameHandler = null;
|
|
1240
2055
|
this.transcriptHandler = null;
|
|
1241
2056
|
this.toolCallHandler = null;
|
|
1242
2057
|
this.interruptionHandler = null;
|
|
@@ -1244,6 +2059,7 @@ class GeminiRealtimeSession {
|
|
|
1244
2059
|
this.pendingToolCallNames.clear();
|
|
1245
2060
|
this.queuedSends = [];
|
|
1246
2061
|
this.responseActive = false;
|
|
2062
|
+
this.openClientTurn = false;
|
|
1247
2063
|
this.pendingThoughtText = '';
|
|
1248
2064
|
}
|
|
1249
2065
|
/** Returns the bound live session or throws if it was never attached / already closed. */
|