Member Junction
    Preparing search index...

    Google Gemini implementation of BaseRealtimeClient: a browser-direct Gemini Live websocket session authenticated with the server-minted ephemeral auth token (v1alpha auth_tokens mechanism — the token is passed as the SDK apiKey).

    Registered with the ClassFactory under the key 'gemini' — the Provider string the server's GeminiRealtime driver stamps on its ClientRealtimeSessionConfig — so hosts resolve it without referencing this class directly.

    Owns ALL Gemini wire concerns (the behavioral twin of OpenAIRealtimeClient, adapted to Gemini's client-owned audio plane — there is no WebRTC here):

    • Audio in: mic PCM16 @ 16 kHz captured via an inline-Blob AudioWorklet (createMicCapture seam) and streamed with sendRealtimeInput.
    • Audio out: model PCM16 @ 24 kHz chunks scheduled through GeminiPcmPlayback (createPlayback seam); IsAudioPlaying is computed from the playout clock.
    • Avatar out: when the minted config grants an avatar and the host shows it (the outbound video track is live), fragmented MP4 parts play through a VideoPlayout (CreateVideoPlayout seam) handed to the host at connect, whose audio routes into the PCM playback's graph; PCM follows the avatar's voice rule (see GeminiAvatarOutput). A host that shows no avatar gets an audio-only session.
    • Event translation (Gemini → contract): inputTranscription → User deltas/finals, outputTranscription → Assistant deltas/finals (accumulated like the OpenAI driver), toolCall.functionCalls → OnToolCall (callID→name cached for SendToolResult), interrupted → playback flush + 'listening', turnComplete → busy cleared + queued sends flushed, usageMetadata → OnUsage (per-turn prompt/response token deltas with their modality split — see handleUsageMetadata). An avatar's generated video seconds go to OnUsage in updates of their own (OutputTokenDetails.VideoSeconds) at each turn boundary.
    • Busy mapping: Gemini has no response.created frame, so IsBusy is set EAGERLY when this client triggers a response (text / narration / tool result) and on the first model output of a turn (audio part or output-transcription delta); cleared on turnComplete, and on a toolCall frame (the model has yielded the floor pending the tool result — so a slow turnComplete can never deadlock the queued result). In an avatar session, video sets it only while the model's answer is under way: Vertex AI streams the avatar's video between answers too, and that idle video plays without marking the agent speaking or busy.
    • Collision safety: ANY sendClientContent interrupts in-flight Gemini generation (per the Live API contract), so text / narration / context-note / tool-result sends issued while a turn is in flight are queued and flushed in order on turnComplete (the flush stops at the first send that starts a new response).
    • Moving to a new connection: Google ends a connection after about 10 minutes, announcing it with goAway, and the session resumes on a new one with Google's handle (RealtimeSessionResumption). A planned move waits until no turn is in progress (IsTurnOpen). A connection is put to use only once Google confirms its setup (setupComplete): input that reaches it earlier is dropped. During a move, sends queue and the latest 2 s of mic audio are held; both go out on the new connection once it is ready.
    • Open-turn commit: context notes ride as turnComplete: false client content, which tells the Live API MORE INPUT IS COMING — the server holds ALL generation (including the normally-automatic continuation after a tool response) until a turnComplete: true commit. SendToolResult therefore follows sendToolResponse with an empty-turn commit whenever a note left the turn open, so the model speaks the result immediately (the behavioral equivalent of the OpenAI driver's explicit response.create).
    • Triggering turns ride realtime text: typed text (SendText) and narration triggers (RequestSpokenUpdate) are sent via sendRealtimeInput({ text }) — the Live API's documented in-conversation text path. Native-audio Live models treat sendClientContent as initial-history seeding only: a mid-call turnComplete: true client turn appends to history WITHOUT starting generation (the model stays silent until the user's next spoken turn), while realtime text triggers an immediate response on every model generation. Context notes stay on sendClientContent (turnComplete: false) — the silent history-append is exactly the contract they want.
    • Narration tagging: RequestSpokenUpdate has no per-response-instructions equivalent on Gemini, so it is emulated as a realtime-text user turn carrying the instructions; the response kind is stamped 'narration' at send time (sends ARE the turn triggers on Gemini, unlike OpenAI where response.created confirms) and reset to 'normal' when the turn completes.

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    inputAudioMeter: IRealtimeAudioMeter = null

    Meter over the USER's microphone, when the driver attached one.

    outputAudioMeter: IRealtimeAudioMeter = null

    Meter over the AGENT's audio output, when the driver attached one.

    tracks: RealtimeTrack[] = []

    Tracks requested, established, or denied on this session.

    videoFramesSent: number = 0
    ASSISTANT_SAFETY_BACKSTOP_MS: 15000

    Accessors

    • get InboundVideoRate(): number

      The frame rate (frames per second) the live inbound video track was negotiated at — the model's ceiling or the session's request, whichever is lower — or undefined when no inbound video track is live or none declared a rate. Anything pacing a video feed reads THIS, never a constant of its own.

      Returns number

    • get IsAudioPlaying(): boolean

      Returns boolean

      directly from the playout engine's playhead clock — this client OWNS the output buffer (no WebRTC playback events exist on Gemini), so "audibly playing" is precisely "scheduled audio extends beyond the audio context's current time". In an avatar session the avatar's video counts too, while some of an answer's media is still ahead of its playhead: its MP4 usually carries the voice. The idle video that follows an answer does not count.

    • get IsTurnOpen(): boolean

      Whether a turn is in progress. A turn opens at its first sign: the user's first transcribed words, a turn this client sends (typed text, a spoken update), or the model's output (a transcription delta, a thought, a tool call, an audio part, which in an avatar session must play as the voice, or, on an interactionStatus model, the IN_PROGRESS status; the video an avatar streams between turns never opens one). It closes at the turn's turnComplete (the true idle signal on an interactionStatus model) once no tool call is pending, or when the last pending call's result goes out after that; and at a resume. The session moves to a new connection only between turns.

      Returns boolean

    • get MaxInboundVideoStreams(): number

      How many concurrent inbound video streams the model accepts: the ceiling the driver declared when it negotiated tracks, else 1 when an inbound video track is live and 0 when it is not.

      A source arbiter reads this to decide whether several live video sources must be narrowed to one (with a note to the model on each switch) or passed through untouched.

      Returns number

    • get SupportsInboundVideo(): boolean

      Whether the model takes inbound video on this session: the driver declared an inbound video track it supports when it negotiated tracks, and a stream limit above zero. No video track need be live; one is added when a capture starts (AddTrack). false before tracks are negotiated, and for a driver that does not negotiate them.

      Returns boolean

    • get SupportsRelayTransport(): boolean

      Whether this driver can open a relay session (ClientRealtimeSessionConfig.Transport 'relay'): connect to MJAPI's realtime relay at the session's RelayUrl rather than to its provider. false here; a driver that speaks its provider's protocol through the relay opts in by overriding it (the Gemini Enterprise client does).

      Returns boolean

    • get VideoSeconds(): number

      Returns the cumulative active video duration in seconds across sent video frames. Represents the wall-clock span between first and last sent frames (span-not-sum) for stream telemetry. Provider-reported ImageTokens remains the authoritative financial billing basis.

      Returns number

    Methods

    • Adds a track to a running session, such as inbound video when the user starts their camera, resolved against what the driver supported when it negotiated at connect. The new track is 'live', or 'unsupported' with the reason (the model takes no such track, or no more inbound video streams). A live track with the same direction, modality and source is returned as it is. Other tracks keep their ids.

      The base re-negotiates locally, which is all a driver needs when its provider accepts the media without a setup change (Gemini Live takes video frames at any time). A driver whose wire must change overrides this and calls it.

      Parameters

      Returns RealtimeTrack

      The track, or null when the session has not negotiated tracks: before it connects, or with a driver that does not negotiate them (only the Gemini driver does today).

    • Returns void

      has no explicit cancel frame — the client OWNS the audio plane, so cancelling means: flush the local playout queue (GeminiPcmPlayback) so speech stops immediately, mark the in-flight turn inactive, and drain queued sends (a queued tool result or context note takes the floor next — tool-result delivery is never dropped by a cancel). Server-side, the next client content sent naturally interrupts any residual generation per the Live API contract. The interrupted turn's accumulated transcript is kept — the provider's trailing frames finalize what WAS spoken. No-op when nothing is active. An avatar's video stops with the voice.

    • Opens the client-direct Gemini Live session: creates the playout engine, connects with the ephemeral token + the server-built SessionConfig ({ model, config } — the same values the server LOCKED into the token, so tampering is ignored by the API), negotiates tracks, then wires the mic-capture worklet and optional video capture. Reports 'connected' once Google confirms the session's setup (setupComplete): input sent before that is dropped, so nothing goes out on the connection, and the microphone does not start, until then. Reports 'listening' once audio is flowing.

      When the server granted an avatar (the minted avatar block) and the host shows it (the outbound video track is live), the avatar's video goes to the host once the connection is open. When the host doesn't show it, the session connects audio only.

      Parameters

      Returns Promise<void>

      When the connection closes or fails before Google confirms its setup, or no confirmation comes in time (see RealtimeConnectionSetup).

    • Creation seam for the mic-capture pipeline. Production delegates to the shared createPcmMicCapture (a 16 kHz AudioContext, inline-Blob capture worklet, and a zero-gain tail; each worklet block is PCM16-encoded and handed to onPcmChunk as base64). Unit tests override this with a no-op fake (and may capture onPcmChunk to simulate mic frames).

      Parameters

      • micStream: MediaStream
      • onPcmChunk: (base64Pcm16: string) => void

      Returns Promise<IPcmMicCapture>

    • Returns the AGENT's remote-audio MediaStream when this driver owns a tappable agent-audio plane (a WebRTC driver's remote track, or a PCM driver's playout output), or null otherwise. Hosts use it to MIX the agent's voice into a browser-side recording alongside the mic; null (drivers with no tappable plane, or before the stream lands) degrades gracefully to mic-only capture. Hosts may still call it as client.GetRemoteMediaStream?.(). Pure read — never mutates.

      Returns MediaStream

    • Registers the (single) interruption handler.

      True barge-in only: fires ONLY when USER INPUT CUT OFF ACTIVE MODEL OUTPUT — a model response in flight or audio audibly playing when the user took the floor. A user simply taking their normal turn while the model is idle is NOT an interruption, and drivers must not report it as one (e.g. a raw "speech started" frame must be gated on whether a response is actually active or audio is playing).

      On interruption, drivers must also flush locally-owned playback and report IsAudioPlaying === false promptly (driver obligation #3). Hosts typically use this hook to abort in-flight delegated work so a stale result is never narrated into a conversation that has moved on.

      Parameters

      • handler: () => void

      Returns void

    • Registers a handler invoked when the agent's remote-audio stream becomes available — IMMEDIATELY (synchronously) if it has already landed, otherwise when the driver publishes it (a WebRTC track typically lands AFTER Connect resolves). Lets a host attach the agent voice to a recording that began before the stream landed. Handler errors are isolated (logged) so a host bug never disturbs the call. Handlers are session-scoped: clearRemoteMediaStream (called from Disconnect) drops them.

      Parameters

      • handler: (stream: MediaStream) => void

      Returns void

    • Registers the (single) remote-VIDEO handler — the model/avatar's video for a VIDEO session (a talking-head the host renders, e.g. as the agent's tile). Invoked once the provider's video is available.

      The video is a MediaVideoSource: a live stream (a WebRTC track), or a player that must own the <video> element (MSE or WebCodecs playout of encoded avatar video). Hosts show either with AttachVideoSource.

      Optional capability: audio-only drivers (the default) never emit — registering is always safe, but hosts must not assume video arrives. A driver whose model sends video (the server driver declares an outbound video track in its session's Capabilities.SupportedOutboundTracks, or renders an avatar, BaseRealtimeModel.SupportsAvatarOutput) calls emitRemoteVideo when it is live.

      Parameters

      • handler: (video: MediaVideoSource) => void

        Invoked with the remote video when it becomes available.

      Returns void

    • Registers the (single) usage handler.

      Emissions carry token deltas for the response/turn that just completed (see RealtimeClientUsage — deltas preferred; cumulative-only providers must convert in the driver). Hosts accumulate and relay/persist on their own cadence (e.g. the voice session service debounces a RelayRealtimeUsage mutation onto the co-agent prompt run).

      Optional capability: drivers whose provider exposes no usage telemetry simply never emit — registering a handler is always safe, but hosts must not assume emissions arrive. See RealtimeClientUsage for per-driver availability.

      Parameters

      Returns void

    • Triggers ONE short spoken update. Gemini has no per-response instructions (OpenAI's response.create.instructions), so this is EMULATED: the instructions ride as a realtime-text user turn (sendRealtimeInput({ text }) — the path that triggers generation on native-audio models, where mid-call sendClientContent is inert), and the resulting turn is stamped Kind: 'narration' at send time (reset on turnComplete) — mirroring the OpenAI driver's narration semantics. Queued behind any in-flight turn so it can never interrupt a pending reply.

      Parameters

      • instructions: string

      Returns void

    • Opens a replacement connection that resumes the session from handle, switches to it once Google confirms its setup, and closes the old one. Until then the old connection stays in use, so what it still sends (the rest of a turn the deadline cut, its usage) is handled. Mic capture and playout carry over untouched. Rejects when the connection can't be opened or its setup fails, so RealtimeSessionResumption can retry.

      The resume reuses the session's ephemeral token, which Google accepts until the token's expireTime (the server driver mints 30 minutes). After that every attempt fails and the session ends with a fatal error.

      Parameters

      • handle: string

        The resumption handle Google issued.

      • attempt: RealtimeResumeAttempt

        Marks the attempt abandoned after a timeout or a consumer close; a connection that opens after that is closed instead of used.

      Returns Promise<void>

    • Injects background context as a user turn with turnComplete: false — appended to the conversation WITHOUT starting generation, so the model draws on it the next time it speaks. Gemini Live turns have no system role, so the user role carries it (the host owns prefixing policy). Queued while a turn is in flight because ANY client content interrupts in-flight generation on Gemini (a divergence from the OpenAI driver, which can inject items mid-response safely).

      SIDE EFFECT: turnComplete: false leaves the client content turn OPEN — the server holds generation until a turnComplete: true commit arrives. openClientTurn tracks this so SendToolResult can commit the turn and unblock the spoken reply.

      Parameters

      • text: string

      Returns void

    • Injects typed text as a realtime-text user turn (sendRealtimeInput({ text }) — Gemini's "respond now" trigger on every Live model generation, including native-audio models that ignore mid-call sendClientContent). No-op when the session is not open.

      SendText implies barge-in (base-contract rule): an active spoken response is cancelled via CancelActiveResponse first — playback flushed, turn marked inactive, queued sends drained — so the typed turn takes the floor immediately. If a drained queued send (e.g. a pending tool result) starts a new turn, the text queues behind it, preserving the tool-result delivery invariant. On the wire, sending the user turn itself interrupts any residual server-side generation (Gemini Live's any-client-content-interrupts contract), so no explicit cancel frame exists or is needed.

      Parameters

      • text: string

      Returns void

    • Feeds an executed tool's result back via sendToolResponse, supplying the function name cached from the originating tool call (Gemini requires it; the contract only carries the callID). Sent immediately when idle — Gemini speaks the result as its next turn — otherwise queued until the in-flight turn (e.g. a progress narration) completes.

      If context notes left a client content turn OPEN (turnComplete: false), the tool response is followed by an empty-turn commit (sendClientContent({ turnComplete: true })) — without it the server keeps waiting for more client input and NEVER starts the spoken reply (observed live as the model staying silent after a delegated agent's result).

      Parameters

      • callID: string
      • outputJson: string

      Returns void

    • Streams one base64 image frame over the established inbound video track.

      Enforces a minimum inter-frame spacing as a backstop with deliberate jitter headroom for the upstream pacers (the source arbiter, ChannelInboundVideoBridge, frameCapture, channel-level gates such as OnScreencastFrame). The spacing is derived from the rate the track NEGOTIATED (MinVideoFrameSpacingMs of BaseRealtimeClient.InboundVideoRate), so it follows the model's profile rather than a constant: at the 1 fps every Live model accepts today it is the 750 ms gate this driver has always applied, and a faster model needs no change here. Upstream generators are the primary enforcers of the nominal rate; this gate absorbs event-loop and async dispatch jitter without dropping intended frames, while preventing an unpaced caller from bursting.

      Gemini accepts ONE inbound video stream, so sourceId is ignored: choosing which source feeds that stream is the arbiter's job, and by the time a frame arrives here the choice is made.

      If inbound video is not established, returns false without error or frame sends (fallback). A frame that comes while no connection is ready (before Google confirms the setup, or while the session moves to a new connection) is dropped too: the source sends the next one at the track's rate.

      Parameters

      • base64Image: string
      • mimeType: string = 'image/jpeg'
      • Optional_sourceId: string

      Returns boolean

      true if the frame was dispatched to the session; false if dropped (throttled, track unestablished, or no connection ready).

    • Mutes / unmutes by toggling the mic tracks' enabled flag: the capture pipeline stays up and streams SILENCE while muted (chosen over gating the worklet send so the provider's VAD sees a continuous stream and the un-mute is glitch-free — same policy as the OpenAI client driver).

      Parameters

      • muted: boolean

      Returns void