Member Junction
    Preparing search index...

    Class OpenAIProtocolWebSocketRealtimeClientAbstract

    The shared websocket + client-owned-PCM transport for OpenAI-protocol client drivers (xAI Grok Voice, self-hosted HuggingFace). Extends the protocol brain with everything the websocket drivers previously each owned:

    • The socket lifecycle: wire-up, open/created gating (profile-driven via waitsForSessionCreated), fatal error / unexpected-close handling.
    • The PCM audio plane: shared mic-capture worklet streaming input_audio_buffer.append frames up, shared playout engine scheduling base64 deltas down, audio meters both ways.
    • The transport implementations of the brain's seams: sendProtocolEvent / canSendEvents over the socket, stopAudioOutput → local playout flush, handleAudioDeltaFrame → playout enqueue, IsAudioPlaying → the playout clock.

    Concrete drivers supply only: the socket target (openProviderSocket), the session object + sample rate resolution from the server pact (resolveSessionObject / resolveSampleRate), and any provider behavior overrides (streamed user transcripts, close semantics).

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    activeResponseKind: "normal" | "narration" = 'normal'

    The kind of the response currently in flight. Event ordering (confirmed against the live OpenAI API): response.created → transcript deltas → *_audio_transcript.doneresponse.done. The transcript-done frame therefore arrives while the kind is still set, letting onAssistantDone classify the turn; response.done then resets it.

    closedByConsumer: boolean = false

    True once Disconnect ran — an expected socket close must not surface as fatal.

    confirmedResponseActive: boolean = false

    True while a response the provider has CONFIRMED (response.created seen, response.done not yet) is in flight. Distinct from responseActive, which is set EAGERLY before a local response.create is even sent: if the provider REJECTS that create (an error frame with no response.created), responseActive would otherwise stay stuck true forever. This flag lets onErrorFrame tell "the eager flag is a phantom for a rejected create" (no confirmed response) from "a real response is genuinely active" (e.g. a concurrent VAD turn), so it clears the phantom without disturbing a live turn. Set on response.created, cleared on response.done.

    currentState: RealtimeClientState = 'closed'

    The client's own view of the session state — mirrors what emitStateChange last reported, EXCEPT after a tool call is emitted: the host typically shows its own busy state then, so the client silently leaves 'speaking' (no emission) to preserve the host's indicator until the result reply starts (see onToolCallFrame).

    micCapture: IPcmMicCapture = null

    The mic-capture pipeline streaming PCM16 up to the provider.

    micStream: MediaStream = null

    The mic stream owned by the current connection (used by the shared SetMuted).

    pendingAssistantText: string = ''

    Accumulates the in-flight assistant transcript across delta frames.

    pendingLocalResponseCreates: number = 0

    Count of locally-initiated response.creates whose response.created echo has not arrived yet. While non-zero, a response.done belongs to an EARLIER (typically just-cancelled) response — it must not clear the busy flag, flush the queued trigger, or flip the state for the response we just started (usage is still emitted). Consumed by response.created.

    pendingNarrationKind: boolean = false

    Set by RequestSpokenUpdate just before it sends its response.create, and CONSUMED by the very next response.created frame, which stamps activeResponseKind for that turn. Narration is only requested while the model is idle (hosts gate on IsBusy), so under normal ordering the next response.created is ours.

    pendingResultResponse: boolean = false

    Set when a tool result is ready while a response is active; sent on the next response.done.

    playback: IRealtimePcmPlayback = null

    The local playout engine (client-owned audio plane).

    responseActive: boolean = false

    True while the model has a response in flight; gates narration + queues the tool result.

    sessionObject: JSONObject = {}

    The wire-shaped session object applied via session.update at the readiness boundary. Protected so test subclasses can seed it without a full Connect.

    The live socket (null when disconnected). Protected so test subclasses can inspect.

    socketOpen: boolean = false

    True while the socket is OPEN — gates every send so a CONNECTING socket never throws.

    Accessors

    • get connectTimeoutMs(): number

      Connect-phase deadline in milliseconds, covering socket-open AND (when the provider defers) the session.created wait. On expiry Connect rejects with a fatal error instead of hanging forever against a silent endpoint. Override per driver/deployment.

      Returns number

    • get IsAudioPlaying(): boolean

      Returns boolean

      directly from the playout engine's playhead clock — this client OWNS the output buffer, so "audibly playing" is precisely "scheduled audio extends beyond the audio context's current time".

    • get IsBusy(): boolean

      true while a model response is in flight (generation started and not yet done). Distinct from IsAudioPlaying: generation runs ahead of playback. Hosts use this to gate interim narration so it never interrupts a reply.

      Returns boolean

    • get providerDebugLabel(): string

      Debug label used in the shared console diagnostics.

      Returns string

    • get releasesBusyFlagOnToolCall(): boolean

      Returns boolean

      deadlock guard: compat endpoints may skip response.done after a tool call.

    • get unexpectedCloseMessage(): string

      The fatal-error message surfaced when the socket closes unexpectedly. Providers brand this.

      Returns string

    • get waitsForSessionCreated(): boolean

      Whether the readiness boundary waits for the endpoint's session.created frame before applying the session config (HuggingFace) or applies it on socket open (xAI — the protocol has no separate readiness ack there).

      Returns boolean

    Methods

    • Sends the server-controlled session config (instructions + tools) as a session.update so the co-agent's identity and tool set apply. Skipped when the pact carried no config (e.g. the host failed to parse the server payload — it already logged that; sending an EMPTY session.update would be wrong).

      Returns void

    • Returns void

      response.cancel (only when a response is actually in flight) and silences already-generated speech via the transport's stopAudioOutput. Resets the local response state machine (active flag, narration kind, accumulated transcript) but PRESERVES any queued tool-result trigger: delegated work is never affected by a floor-control cancel, and the queued trigger still fires on the cancelled response's trailing response.done. No-op when idle or when the transport is not open.

    • Creation seam for the mic-capture pipeline at the provider's rate. Production delegates to the shared createPcmMicCapture; unit tests override this with a no-op fake (and may capture onPcmChunk to simulate mic frames).

      Parameters

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

      Returns Promise<IPcmMicCapture>

    • Formats a socket-level error message for the host. Providers brand this (see xAI).

      Parameters

      • message: string

      Returns string

    • Returns the AGENT's remote-audio MediaStream when this driver owns a tappable remote-audio plane (e.g. a WebRTC peer-connection driver routes the model's audio track here), or null otherwise. Hosts use it to MIX the agent's voice into a browser-side recording alongside the mic; a null return (the default, and what every non-WebRTC driver gives) degrades gracefully to mic-only capture.

      Optional capability: the method itself is optional — call sites must use client.GetRemoteMediaStream?.() ?? null. Drivers that can't expose a remote stream simply don't implement it (or return null).

      Returns MediaStream

    • A socket close the CONSUMER didn't ask for. Default: FATAL — providers hard-close at token expiry and when they end the session themselves, so an unexpected close is how credential / session death reaches the host (obligation #6). Providers with benign close semantics (a self-hosted proxy hop) override.

      Returns void

    • Surfaces a fatal socket error and marks the session unusable (obligation #6).

      Parameters

      • message: string

      Returns void

    • 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

    • Optional capability: registers a handler invoked when the agent's remote-audio stream becomes available — immediately if it has already landed, otherwise when the WebRTC track arrives (typically AFTER Connect resolves). Lets a host attach the agent voice to a recording that began before the track landed. Call as client.OnRemoteMediaStream?.(cb); drivers without a remote stream simply don't implement it.

      Parameters

      • handler: (stream: MediaStream) => void

      Returns void

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

      Optional capability: audio-only drivers (the default) never emit — registering is always safe, but hosts must not assume a video track arrives. Video-capable drivers (BaseRealtimeModel.SupportsVideo) call emitRemoteVideo when the track is live.

      Parameters

      • handler: (stream: MediaStream) => void

        Invoked with the remote video MediaStream 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

    • Emits the user's spoken-input transcription. Default (OpenAI/HuggingFace): each .completed frame is one final caption. Providers that STREAM the completed event (Grok re-sends the full growing text each time) override to collapse the stream into a single in-place-updating bubble.

      Parameters

      • transcript: string

      Returns void

    • Asks the model to speak (a tool result or typed-text reply) — immediately if it's idle, otherwise queued until the current response finishes. An immediate trigger also CONSUMES any queued trigger debt: every payload item is already in the conversation, so one response.create voices everything (e.g. typed text barging in over a narration that had tool results queued behind it).

      Returns void

    • Triggers ONE short spoken update with the given instructions. Marks the upcoming response as 'narration' (flag consumed by the next response.created) so its transcripts are emitted with Kind: 'narration' — ephemeral by contract. Sets responseActive eagerly so a tool result landing mid-narration queues instead of colliding.

      Skips when busy (base-contract collision rule — drivers MUST queue or skip): a response.create sent while a response is in flight would be rejected/garbled by the provider, and narration is disposable by contract, so the update is dropped with a debug log rather than queued to come out late and stale. Hosts SHOULD still gate on IsBusy / IsAudioPlaying for timing quality.

      Parameters

      • instructions: string

      Returns void

    • Injects a system-role context item the model can draw on the next time it speaks, WITHOUT forcing a reply. Item creation is always safe mid-response.

      NOTE: role must be 'system' — gpt-realtime (and the compatible endpoints) reject 'developer' items ("Developer messages are only supported for quicksilver sessions").

      Parameters

      • text: string

      Returns void

    • Streams one base64 PCM16 mic chunk as an input_audio_buffer.append frame.

      Parameters

      • base64Pcm16: string

      Returns void

    • Injects typed text as a user-role message conversation item, then triggers a reply through the SAME collision-safe path tool results use (requestResultResponse). No-op when the transport isn't open.

      SendText implies barge-in (base-contract rule): an active spoken response is cancelled via CancelActiveResponse before the text is injected, so the typed turn takes the floor immediately instead of waiting behind stale speech. When nothing is active the cancel is a no-op and the reply triggers immediately.

      Parameters

      • text: string

      Returns void

    • Sends the tool result back as a function_call_output conversation item, then triggers a reply — immediately if the model is idle, otherwise queued until the current response (e.g. a progress narration) finishes. Without the queueing the result's response.create would collide with an in-flight narration and be dropped, leaving the model silent when delegated work comes back.

      Parameters

      • callID: string
      • outputJson: string

      Returns void

    • Mutes / unmutes by toggling the mic tracks' enabled flag: the transport stays up and streams SILENCE while muted (the provider's VAD sees a continuous stream and the un-mute is glitch-free — the same policy across the client driver family).

      Parameters

      • muted: boolean

      Returns void