npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@centralchat/voice-conference

v0.3.2

Published

Voice-only WebRTC call library for Botmaker signaling servers (headless core + React hooks)

Readme

voice-conference

Voice WebRTC call library for Botmaker calls with an AI agent or a person. It also covers screen sharing (one side at a time), an in-call chat (text, images, files) and the bot's requests for attachments. It succeeds the conference package and is rebuilt as a headless core + React hooks for final users. There is no built-in UI and no agent features: recording, hold and transfer were removed on purpose. It runs on web (the default) and React Native (@centralchat/voice-conference/react-native + react-native-webrtc). Everything host-specific sits behind an injectable Platform.

Signaling is a single HTTP POST (/join: SDP offer in, answer out, vanilla ICE). All in-call events travel over a WebRTC data channel; there is no WebSocket. Auth is invisible to the consumer: <VoiceCallProvider> needs only the widget's webchat chatChannelId, plus an optional customerId for returning callers. It mints the call JWT itself from the web_call_token endpoint during init().

You need React 18 or newer and the webchat chatChannelId, which Botmaker provides. On web, the page must be served over HTTPS, because browsers allow the mic only in a secure context. On React Native, see React Native for the setup.

Install · Quick start · Creating a session · Lifecycle · Methods · State · Warnings and logs · Chat attachments · Limits and constants · React bindings · React Native · Other exports · Network endpoints · End-to-end example · Development

Install

npm install @centralchat/voice-conference

| Dependency | Version | Notes | | -------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | react (peer) | >=18 | Required. The state layer uses useSyncExternalStore, and the main entry also exports the React layer. | | react-native-webrtc (optional peer) | >=124.0.7 | React Native only. It needs a development build, not Expo Go. | | jwt-decode | ^4.0.0 | The only runtime dependency. |

Entry points

| Import | Exports | | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | @centralchat/voice-conference | Everything listed below, with the web platform as the default. | | @centralchat/voice-conference/react-native | Everything from the main entry, plus createReactNativePlatform and ReactNativePlatformOptions. Its VoiceCallProvider and JwtVoiceCallProvider come pre-wired with the RN platform. |

Both entries ship ESM (import), CJS (require) and TypeScript types.

| Group | Exports | | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | React | VoiceCallProvider, JwtVoiceCallProvider, VoiceCallSessionContext, useCallSelector, useCallActions, useVoiceCallSession, useVolumeFromStream, useStreamLevelReader; types VoiceCallProviderProps, VoiceCallAdvancedOptions, JwtVoiceCallProviderProps, JwtVoiceCallAdvancedOptions, VoiceCallActions, UseVolumeFromStreamOptions | | Core session | VoiceCallSession, INITIAL_CALL_STATE; types VoiceCallConfig, VoiceCallState, CallStatus, EndReason, WarningCode, TranscriptEntry, TranscriptKind, ChatAttachmentInfo, AttachmentRequest | | Chat limits | MAX_CHAT_MESSAGE_LENGTH, MAX_CHAT_IMAGE_BYTES, MAX_CHAT_IMAGE_INPUT_BYTES, MAX_CHAT_FILE_BYTES, CHAT_IMAGE_TYPES, CHAT_IMAGE_SENT_TYPES, CHAT_FILE_TYPES; types ChatAttachmentFile, ChatFileTypes | | Platform | webPlatform; types Platform, AudioOutput, PlaybackCallbacks, DecodedImage | | Token and sharding | fetchWebCallToken, TokenError, businessIdFromChannelId, computeBusinessGroup, opsvcUrl; types WebCallTokenRequest, WebCallTokenResult, JwtContext | | Negotiation | createHttpNegotiator, SignalingError; types Negotiator, JoinRequest, JoinResult | | Frame crypto (E2EE) | frameCryptoSupport; types FrameCryptoProvider, FrameCryptoSupport | | Peer calls | toPeerCallOutcome; type PeerCallOutcome | | Audio level | createStreamLevelReader; types StreamLevelReader, StreamLevelReaderOptions | | Protocol types | AttachmentKind, AttachmentRequestEvent, ChatAttachment, ChatLink, ChatMessageEvent, ClientMessage, ConferenceStatus, CurrentParticipants, QosChange, RemoteParticipantStateChange, RemoteTrackStateChange, ServerEventMap, ServerEventName, TrackKind, TrackSource, TrackStateChange, TranscriptEvent, TranscriptRole |

Quick start (React)

Mounting the provider warms everything up: the mic, the peer connection, ICE gathering and the token mint. The call server itself is not contacted yet. status === 'ready' (or onReady) is the signal to enable the start button. The start click then pays only one HTTP round-trip (POST /join) plus the DTLS handshake.

import { VoiceCallProvider, useCallSelector, useCallActions } from '@centralchat/voice-conference';

function MyCall({ onClose }: { onClose: () => void }) {
    return (
        <VoiceCallProvider chatChannelId="myBusiness-webchat" onEnded={onClose}>
            <MyCallUI />
        </VoiceCallProvider>
    );
}

function MyCallUI() {
    const status = useCallSelector(s => s.status);
    const isMicMuted = useCallSelector(s => s.isMicMuted);
    const { start, toggleMic, hangUp } = useCallActions();
    // The library plays the remote audio itself: there is nothing to render for it.
    return (
        <div>
            {status !== 'in-call' && (
                <button onClick={start} disabled={status !== 'ready'}>
                    Start call
                </button>
            )}
            <button onClick={toggleMic}>{isMicMuted ? 'Unmute' : 'Mute'}</button>
            <button onClick={hangUp}>Hang up</button>
        </div>
    );
}

The end-to-end example adds the transcript, the chat, images and attachment requests.

Creating a session

There are three ways to get a session. All of them share the same session class, state and hooks.

| Path | Identity | Who owns init() / destroy() | | ----------------------------------- | ------------------------------------------------------------------ | ----------------------------------------------------------------- | | <VoiceCallProvider chatChannelId> | The library mints the JWT from the webchat channel ("call us"). | The provider, with one session per mount. | | <JwtVoiceCallProvider jwt> | Your backend minted the JWT. | The provider, with one session per mount. | | new VoiceCallSession(config) | config.jwt or config.tokenRequest. | You. Hand it to the hooks through VoiceCallSessionContext. |

The provider props are in React bindings. This section covers the core.

new VoiceCallSession(config: VoiceCallConfig)

The constructor throws Error('VoiceCallConfig requires either jwt or tokenRequest') when neither one is set. It makes no network requests and does not touch media. It only decodes a given jwt and registers the platform's app-terminating listener (on web, pagehide).

Sessions are single-use. Once a session is ended or destroyed, a new call needs a new instance. Always call destroy() when you are done with a session.

import { VoiceCallSession } from '@centralchat/voice-conference';

const session = new VoiceCallSession({ tokenRequest: { chatChannelId: 'myBusiness-webchat' }, chat: true });
const unsubscribe = session.store.subscribe(() => render(session.store.getSnapshot()));

await session.init(); // 'ready', or 'ended' when the warm-up failed
await session.start(); // the answer is applied; 'in-call' follows when the server confirms
session.sendChatMessage('hola');
session.hangUp();
unsubscribe();
session.destroy(); // always, even after 'ended'

VoiceCallConfig

| Option | Type | Default | What it does | | ----------------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | jwt | string | — | A pre-minted call JWT. You must set either jwt or tokenRequest; jwt wins when both are set. | | tokenRequest | WebCallTokenRequest ({ chatChannelId, customerId? }) | — | Mints the JWT during init() through web_call_token. If the token is within 30 s of expiry at start(), it is silently re-minted (minted tokens live 60 min). | | tokenUrl | string | https://go.botmaker.com/opsvc/sg<G>/web_call_token, where G comes from the channel's business | Overrides the token endpoint. | | platform | Platform | webPlatform | The host adapter. See Platform adapter. | | server | string | The JWT's recordingServer claim, else r0.botmaker.com | The signaling host. | | insecure | boolean | false | Uses http:// instead of https:// for join and rejoin (local development). | | joinUrl | string | <scheme>://<server>/join | Overrides the join endpoint. | | rejoinUrl | string | <scheme>://<server>/rejoin | Overrides the rejoin endpoint. | | source | string | unset | Sent as source in the join and rejoin bodies. 'web-demo' (the demo page) runs the bot on the realtime model alone, without the business engine. Leave it unset in production. | | chat | boolean | false | Tells the server that the UI renders the transcript as a chat (the chat capability). The bot then writes links and codes as chat lines, and sendChatMessage() works. Leave it off when there is no chat UI. | | chatImages | boolean | false | Requires chat and is ignored without it. Declares chat-image, which enables sendChatImage() and image requests. | | chatFiles | boolean | false | Requires chat and is ignored without it. Declares chat-file, which enables sendChatFile() and file requests. | | uploadUrl | string | https://go.botmaker.com/rest/file-upload/voice/<businessId>, using the JWT's businessId claim | The base URL for attachment uploads. Images are POSTed to it and files to <uploadUrl>/file. | | negotiate | Negotiator | The HTTP negotiator | Replaces the offer→answer exchange. See Negotiation. | | iceServers | RTCIceServer[] | stun:stun.l.google.com:19302, stun:stun1.l.google.com:19302 | The STUN servers. TURN is deliberately unsupported. | | iceGatheringTimeoutMs | number | 2000 | The longest the client waits for ICE gathering before it sends an offer (vanilla ICE). | | acquireMicOnInit | boolean | true | Asks for the mic in init(). With false, the permission prompt waits until start(). | | warmOfferMaxAgeMs | number | 30000 | A warm offer older than this is re-gathered with an ICE restart at start(), because NAT bindings go stale in the lobby. | | joinTimeoutMs | number | 15000 | Aborts the token, join and rejoin POSTs after this long. It applies to the built-in transports only. | | setupTimeoutMs | number | 30000 | Ends the call with connection_failed if the event channel isn't open this long after start(). It also bounds each rejoin attempt. | | frameCrypto | FrameCryptoProvider | unset | End-to-end transforms for audio frames. See Frame crypto. | | requireFrameCrypto | boolean | false | Used with frameCrypto. Ends the call with frame_crypto_unavailable instead of continuing with transport encryption only. | | maxRejoinAttempts | number | 2 | Rejoin attempts after a transport failure. 0 disables rejoin. | | rejoinBackoffMs | number | 2000 | The wait between attempts, multiplied by the attempt number. | | disconnectedGraceMs | number | 5000 | How long an RTC disconnected state may last before the client forces a rejoin. | | loggingUrl | string | https://go.botmaker.com/opsvc/sg<G>/voice_log, where G comes from the JWT's business | The remote log sink. '' disables it. |

When you pass a custom negotiate, the session ignores server, insecure, joinUrl and rejoinUrl, and joinTimeoutMs applies only to the token mint. It also sends neither source nor the chat capabilities, because the negotiator receives only { offer, rejoin? }.

Platform adapter

A Platform provides everything the core needs from the host. The core never touches browser globals.

| Member | Required | webPlatform | createReactNativePlatform() | Used for | | ------------------------------------------- | -------- | ----------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | name | yes | 'web' | 'react-native' | An identifier for the platform. | | createPeerConnection(configuration) | yes | new RTCPeerConnection | react-native-webrtc's RTCPeerConnection | The call's connection. | | getUserMedia(constraints) | yes | navigator.mediaDevices | react-native-webrtc's mediaDevices | The mic, with echo cancellation, noise suppression and auto gain on. | | enumerateDevices() | yes | ✓ | ✓ | Fills mics and speakers. | | createAudioOutput(callbacks) | yes | A hidden <audio> element with setSinkId | A no-op, because the OS session plays the audio. options.createAudioOutput replaces it. | Remote playback, speaker selection and autoplay detection. | | subscribeDeviceChange?(listener) | no | devicechange | — | Refreshes mics and speakers. | | subscribeAppTerminating?(listener) | no | pagehide, except when the page enters the bfcache | — (backgrounding must not hang up) | Sends leave, so closing the tab hangs up. | | getDisplayMedia?(constraints) | no | ✓ | ✓ | Screen share. Without it, canScreenShare stays false. | | createMediaStream?(tracks?) | no | ✓ | ✓ | Without it, no screen-share m-line is negotiated. | | getReceiverCapabilities?(kind) | no | RTCRtpReceiver.getCapabilities | — | Puts VP8 first on the screen-share m-line. | | createObjectUrl?(blob), revokeObjectUrl?(url) | no | URL.createObjectURL / URL.revokeObjectURL | — | The previewUrl of a Blob image. React Native images preview from their uri. | | openImage?(blob) | no | createImageBitmap + canvas, with EXIF orientation applied | — | Re-encoding chat images. Without it, only PNG/JPEG pictures that already fit MAX_CHAT_IMAGE_BYTES can be sent. |

interface AudioOutput {
    attachRemoteStream(stream: MediaStream | null): void;
    resumePlayback(): Promise<boolean>; // called from a user gesture; true once audible
    setSpeaker(deviceId: string): Promise<boolean>; // false where unsupported
    destroy(): void;
}
type PlaybackCallbacks = { onPlaybackBlockedChange: (blocked: boolean) => void };
type DecodedImage = {
    width: number;
    height: number;
    encode(o: { width: number; height: number; type: 'image/jpeg' | 'image/png'; quality?: number }): Promise<Blob | null>;
    close(): void;
};

createReactNativePlatform(options?: ReactNativePlatformOptions) takes createAudioOutput?: (callbacks: PlaybackCallbacks) => AudioOutput for custom audio routing, such as an earpiece/speaker toggle. Both platforms are plain objects, so you can extend one, for example { ...createReactNativePlatform(), openImage }.

Lifecycle

Status

CallStatus is 'idle' | 'initializing' | 'ready' | 'connecting' | 'joining' | 'in-call' | 'reconnecting' | 'ended'.

| From | To | When | | -------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------- | | idle | initializing | init() is called, or start(), which runs it. | | initializing | ready | The token is minted (tokenRequest mode), the mic is acquired (unless deferred), the connection and data channel are built and ICE has gathered. Enable the start button. | | ready | connecting | start(). | | connecting | joining | The event channel opened; the client sends joined. | | joining | in-call | The server confirmed the join (joined-ok). | | joining, in-call | reconnecting | RTC reported disconnected, or the transport failed (ICE or RTC failed, channel closed) while a rejoin is possible. | | reconnecting | the status before | The disconnect healed within disconnectedGraceMs. | | reconnecting | in-call | A rejoin completed, with joined-ok on the new transport. | | any | ended | Terminal. endReason says why. |

Warm-up: init()

init() prepares everything on the client: the mic prompt (unless acquireMicOnInit: false), the peer connection, the events data channel and ICE gathering. It never contacts the call server. In tokenRequest mode it also POSTs web_call_token, at the same time as the mic prompt. Minting registers the call server-side, so call init() only when a call is intended.

  • It resolves when the status is ready, or when the warm-up ended the session. It is idempotent and returns the same promise each time. On an ended or destroyed session it resolves at once.
  • Failures end the session:
    • The mint fails: token_failed.
    • The mic fails: the warning media_devices_error, then media_error.
    • The offer fails: connection_failed.
    • requireFrameCrypto is set and frame crypto is unsupported: frame_crypto_unavailable.

Start: start()

start() pays only for the join round-trip. It POSTs /join with the warm offer and applies the answer. When the channel opens, it sends joined automatically; there is no separate join call.

  • It runs init() first if needed, and continues only if the status is then ready. Only the first call counts; later calls do nothing.
  • It re-gathers a stale offer (older than warmOfferMaxAgeMs), re-mints a token that is about to expire (tokenRequest mode only) and acquires a deferred mic.
  • It resolves once the answer is applied, or when the call ends. in-call arrives later, with joined-ok.
  • Failures end the session:
    • The join answers 401 or 403: link_exhausted.
    • The join fails for any other reason: connection_failed.
    • The re-mint fails: token_failed.
    • The deferred mic fails: media_error.
    • The channel is not open setupTimeoutMs after start(): connection_failed.

Reconnection

The join answer carries a callId, which is the handle for rejoining.

  • An RTC disconnected state during joining or in-call moves the status to reconnecting. If the connection heals within disconnectedGraceMs, the status goes back to what it was. Otherwise it counts as a transport failure.

  • A transport failure is ICE or RTC failed, a closed data channel, or a disconnect that outlived the grace period. If there is a callId and maxRejoinAttempts > 0, the client rejoins:

    1. It builds a new peer connection and data channel, keeping the mic track.
    2. It POSTs /rejoin with { sdp, callId }.
    3. It waits up to setupTimeoutMs for the channel, then re-sends joined.
    4. It returns to in-call on joined-ok.

    Between attempts it waits rejoinBackoffMs × attempt.

  • The call ends with connection_failed right away when there is no callId, when rejoin is disabled, or when the failure happens during connecting. It also ends with connection_failed when every attempt fails. A 401 or 403 on rejoin ends it with link_exhausted, without retrying.

  • An ICE failure also raises the warning ice_connection_error.

  • A local screen share carries over to the new connection. If the new connection can't carry it, the share stops with screen_share_unavailable. The other side's share comes back on the new connection.

  • The event channel is closed while reconnecting, so chat sends return false.

  • Rejoin needs a server that implements POST /rejoin. Against a server without it, a transport failure costs maxRejoinAttempts failed requests before the call ends with connection_failed.

End and teardown

  • hangUp() ends the call with hangup. The server or the room can also end it (see the table below).

  • Ending the call:

    • sends leave when the channel is open;
    • aborts uploads;
    • releases the mic, the audio sink, the listeners, the timers and the connection;
    • clears attachmentRequest, the streams and the screen-share fields.

    transcript, jwtContext and tokenResult stay, so a summary screen can still read them.

  • destroy() is final and idempotent. It first ends a live session with hangup, then revokes image preview URLs. Every method does nothing afterwards: methods that return booleans return false, and promises resolve. Standalone-core consumers must call destroy() even after ended. The providers call it on unmount.

  • Closing the tab (web pagehide, except when the page enters the bfcache) sends leave, so the server hangs up. Backgrounding a React Native app does not.

End reasons (EndReason)

These are codes, not text: map them to your own copy. The last column is the result of toPeerCallOutcome(reason).

| Code | Cause | Peer outcome | | --------------------------- | -------------------------------------------------------------------------------------------------- | ----------------- | | hangup | hangUp(), or destroy() on a live session. | ended | | agent_left | A console user (an agent) left. | ended | | customer_left | A participant who isn't a console user left and did not return within 5 s. | ended | | call_ended | The server ended the call (conference-status call-ended). | ended | | conference_already_closed | The server reported conference-already-closed. | unavailable | | link_exhausted | The join or rejoin answered 401 or 403 (a used or expired JWT), or the server reported link-exhausted. | unavailable | | too_many_participants | The server reported too-many-participants. | unavailable | | too_many_connections | The server reported too-many-connections. | unavailable | | token_failed | The web_call_token mint failed (validation, unknown channel, 429 rate limit, network). | unavailable | | frame_crypto_unavailable | requireFrameCrypto is set on a browser without frame transforms. | unavailable | | connection_failed | The join failed, setup timed out, the transport died without a rejoin, or every rejoin attempt failed. | connection_lost | | media_error | No usable microphone (denied or missing). | mic_error | | qos_critical | Never emitted. It is kept so that exhaustive switches compile. | connection_lost |

The session does not expose the TokenError behind a token_failed. To read the HTTP status or Retry-After, call fetchWebCallToken yourself.

Methods (VoiceCallSession)

Every method does nothing after destroy().

| Method | Returns | Behavior | Failure | | ----------------------------------------------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | init() | Promise<void> | The warm-up. See Warm-up. | Ends the session. | | start() | Promise<void> | The join. See Start. | Ends the session. | | hangUp() | void | Ends the call with hangup. Does nothing once the call has ended. | — | | destroy() | void | The final teardown. See End and teardown. | — | | setMicMuted(muted: boolean) | void | Turns the mic track off or on, announces the change (track-state-change) and sets isMicMuted. It works in the lobby: the state is announced when the channel opens and applies to a mic acquired later. | — | | toggleMic() | void | Same as setMicMuted(!isMicMuted). | — | | setMic(deviceId: string) | Promise<void> | Switches to the mic with that exact device id without renegotiating, and updates micId and localStream. | Raises the warning media_devices_error; the current mic stays. | | setSpeaker(deviceId: string) | Promise<void> | Routes the remote audio with setSinkId and updates speakerId. Where that is unsupported (Safari, the React Native default output), nothing changes. | Raises the warning media_devices_error when the sink rejects the device. | | pressDialpad(key: string) | void | Sends dialpad-press { key }, a DTMF key for IVR menus ('0'–'9', '*', '#'). The key isn't validated. | Dropped silently while the channel is closed. | | sendChatMessage(text: string) | boolean | Trims the text, sends chat-message { text } and appends the caller's chat line to the transcript. | Returns false and sends nothing, adds no line and raises no warning when: chat is off, the text is empty or longer than MAX_CHAT_MESSAGE_LENGTH, or the channel is closed (before joining, while reconnecting, after the end). Keep the draft. | | sendChatImage(file: ChatAttachmentFile, text = '') | Promise<boolean> | Sends a picture the bot looks at, with an optional caption. See Chat attachments. | Resolves false. See Chat attachments. | | sendChatFile(file: ChatAttachmentFile, text = '') | Promise<boolean> | Sends a file the bot gets as a link, with an optional caption. See Chat attachments. | Resolves false. See Chat attachments. | | dismissAttachmentRequest() | void | Clears attachmentRequest when the caller declines. Does nothing when there is no request. | — | | startScreenShare() | Promise<void> | Opens the platform's picker, so call it from a user gesture. The capture is sent on the video m-line negotiated at join, and isScreenSharing and localScreenStream are set. Does nothing while a share is running or starting. | Raises a warning and changes nothing. screen_share_e2ee_unsupported: frame crypto is active. screen_share_unavailable: canScreenShare is false, there is no getDisplayMedia, or attaching the track failed. screen_share_denied: the picker was cancelled or failed. | | stopScreenShare() | Promise<void> | Stops sharing and releases the capture. The browser's own "Stop sharing" bar and hanging up do the same. Idempotent. | — | | resumeAudio() | Promise<void> | Retries the remote playback after isPlaybackBlocked. Call it from a tap. isPlaybackBlocked turns false once the audio plays. | The audio stays blocked. | | store | read-only property | The state snapshot store. See State. | — |

State

Reading and subscribing

| session.store member | Signature | Notes | | ---------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------- | | getSnapshot | () => VoiceCallState | The current snapshot. Every change creates a new object; fields that didn't change keep their reference. | | subscribe | (listener: () => void) => () => void | The listener is called with no arguments after every change. Returns the unsubscribe function. |

Both are bound functions, so you can pass them straight to useSyncExternalStore. The store also has an update() method. It is how the session writes its state and is not part of the consumer API. In React, use useCallSelector.

There is no event emitter: everything is state, the end and the warnings included. Watch status/endReason for the end (the providers' onEnded does this for you) and warning.seq for warnings.

VoiceCallState

| Field | Type | Initial | Meaning | | ----------------------- | -------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | status | CallStatus | 'idle' | See Status. | | endReason | EndReason \| null | null | Set when status becomes ended. | | warning | { code: WarningCode; seq: number } \| null | null | The latest transient warning. seq grows on every emission. It is never reset: it stays until the next warning replaces it. | | isEventChannelOpen | boolean | false | The events data channel is open, so chat messages and attachments can be sent. | | isPlaybackBlocked | boolean | false | Web: the browser's autoplay policy blocked the remote audio. Bind a tap to resumeAudio(). It is never true on React Native. | | isMicMuted | boolean | false | The local mic is muted. | | isRemoteMicMuted | boolean | false | The other side muted its mic. | | isFrameCryptoActive | boolean | false | E2EE frame transforms are attached to the current connection. | | isAlone | boolean | true | No other participant is in the call. | | hasLocalQosIssue | boolean | false | The server rated this side's connection CRITICAL. It clears when the server reports a better level. | | hasRemoteQosIssue | boolean | false | The server rated a remote participant CRITICAL. It is not cleared afterwards. | | mics | MediaDeviceInfo[] | [] | The audio inputs. Filled after the mic is acquired and refreshed when devices change. | | speakers | MediaDeviceInfo[] | [] | The audio outputs. | | micId | string | '' | The selected mic. Defaults to the first one listed. | | speakerId | string | '' | The selected speaker. Defaults to the first one listed. | | localStream | MediaStream \| null | null | The mic stream, for volume meters. null after the end. | | remoteStream | MediaStream \| null | null | The remote audio. The library plays it, so you don't need to render it. null after the end. | | canScreenShare | boolean | false | The server accepted the screen-share m-line, the platform can capture the screen and frame crypto is off. Set after the join answer. | | isScreenSharing | boolean | false | This side is sharing its screen. | | localScreenStream | MediaStream \| null | null | The capture being sent. Don't render a self-view of it. | | isRemoteScreenSharing | boolean | false | The other side says it is sharing. | | remoteScreenStream | MediaStream \| null | null | The other side's share. It is set while the other side shares, possibly before the first frame arrives. Render it in a <video autoPlay playsInline muted> (on React Native, an RTCView). | | isRemoteScreenLive | boolean | false | Frames are arriving on remoteScreenStream. | | jwtContext | JwtContext \| null | null | The decoded claims of the call JWT. Set at construction (jwt) or after the mint. | | tokenResult | WebCallTokenResult \| null | null | In tokenRequest mode, the mint result. Persist its customerId to recognize returning callers. | | transcript | TranscriptEntry[] | [] | The live transcript and the chat, oldest first. It is a new array on every change, is kept after the end and holds the last 500 lines. It stays empty on calls the server doesn't transcribe. | | attachmentRequest | AttachmentRequest \| null | null | The bot is waiting for an image or a file. |

INITIAL_CALL_STATE holds the initial values. It is also what useCallSelector reads before a session exists.

TranscriptEntry

| Field | Type | Meaning | | ------------ | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | id | number | Stays the same across partial updates of a line. Use it as the render key. | | role | 'user' \| 'bot' | The caller or the bot. | | kind | 'speech' \| 'chat' | Transcribed audio, or a written chat message. | | text | string | For speech, the text so far. For chat, the trimmed message. It may contain URLs (linkify only http(s)), and it may be empty on an attachment line. | | links | ChatLink[] ({ url, label? }) | Only on the bot's chat lines: links beyond those in text. Only http(s):, mailto: and tel: links are kept. Render them with target="_blank" rel="noopener noreferrer". | | attachment | ChatAttachmentInfo | Only on the caller's lines sent with sendChatImage() or sendChatFile(). | | final | boolean | false while a speech line is still being transcribed. Chat lines are always final. | | at | number | Date.now() when the line, or its first partial, arrived. |

Speech lines stream. A line that isn't final yet grows in place, keeping its id, until its final text arrives. The caller's line opens with an empty text as soon as the server detects speech, so render it as a "listening" indicator. If that turn transcribes to nothing, the line is removed. Chat lines don't take part in this matching, so a chat line that arrives mid-utterance doesn't split the spoken line. A bot chat message with neither text nor a kept link is dropped.

ChatAttachmentInfo

| Field | Type | Meaning | | ------------ | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | kind | 'image' \| 'file' | What was sent: a picture or a file. | | name | string | The name the picker gave, or 'image'/'file' when it gave none. | | mime | string | The type as picked, before any re-encoding. For files, it is the accepted type, read from the extension when the picked type was empty or generic. | | size | number (optional) | The size in bytes as picked. Absent when the platform doesn't report it, as with some React Native pickers. | | previewUrl | string (optional) | Images only: a local preview of the original picture. On web it is an object URL, revoked by destroy(); on React Native it is the picker's uri. Absent where the platform can't make one. | | status | 'sending' \| 'sent' \| 'failed' | Starts as sending, then becomes sent or failed. |

AttachmentRequest

{ kind: 'image' | 'file'; text?: string; seq: number; at: number }: the bot asks the caller for a picture or a file.

  • text is an optional short hint, such as "El frente de tu DNI". It is trimmed and capped at 200 characters, and the bot also says it aloud.
  • seq grows with every request, so you can tell a repeated request apart. at is Date.now() when the request arrived. A new request replaces the previous one.
  • A request appears only for kinds this call enabled (chat plus chatImages or chatFiles). Requests for other kinds are ignored.
  • It is cleared when the caller sends an attachment of that kind (as soon as its line is added), when you call dismissAttachmentRequest(), and when the call ends.
  • When a request arrives, open the camera or the file picker, or highlight the matching button.

JwtContext

The JWT is decoded on the client and not verified. Its fields are id, name, businessId, isAudioOnly (boolean), meetId, channelId, recordingServer, lang and exp?. lang is the call's locale, such as 'es'; the library has no strings of its own. exp is in seconds since the epoch. Other claims are ignored.

WebCallTokenResult

{ jwt, callId, roomNumber, recordingServer, businessId, customerId, customerCreated }. Every field is a string except customerCreated, which is a boolean. Pass customerId back on the next call (the customerId prop or tokenRequest.customerId) to keep the same customer across calls.

Warnings and logs

Warnings (WarningCode)

Warnings arrive as state.warning.code, and the call goes on. Show them as toasts. They are codes, not text.

| Code | Source | Meaning | | ------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | customer_left | server | A participant who isn't a console user left. The call ends with customer_left in 5 s unless they return. | | qos_critical | server | This side's connection is CRITICAL (hasLocalQosIssue). It never ends the call. | | qos_remote_warning | server | The other side's connection is CRITICAL (hasRemoteQosIssue). | | qos_remote_error | server | The other side's connection FAILED. | | ice_connection_error | transport | ICE failed. A rejoin follows, or the call ends with connection_failed. | | mic_lost | mic | The mic track ended (Bluetooth dropped, the device was unplugged, permission was revoked). The library re-acquires the default mic. | | media_devices_error | mic, devices | The mic could not be acquired (then the call ends with media_error), could not be re-acquired after mic_lost (the call stays up and inbound audio works) or could not be switched. Also raised when the speaker could not be set. | | screen_share_unavailable | startScreenShare(), rejoin | This call or platform cannot carry a screen share. | | screen_share_denied | startScreenShare() | The user cancelled the picker. | | screen_share_e2ee_unsupported | startScreenShare() | Frame crypto is on, and it doesn't cover video. | | chat_upload_unsupported | sendChatImage(), sendChatFile() | The type isn't accepted: by the client check, because the platform can't decode the image, or because the upload answered 415. | | chat_upload_too_large | sendChatImage(), sendChatFile() | An image over MAX_CHAT_IMAGE_INPUT_BYTES, or one that can't be brought under MAX_CHAT_IMAGE_BYTES. A file over MAX_CHAT_FILE_BYTES. Or the upload answered 413. | | chat_upload_expired | sendChatImage(), sendChatFile() | The upload answered 401: the call token expired (minted tokens live 60 min).