SDKsWeb SDK

Events

Lifecycle callbacks, session status, and the incoming data your client receives

The SDK tells you what happens during a session through callbacks you pass in the config. To send messages and commands the other way, see Messaging.

Lifecycle callbacks

Register these in the config object. All are optional.

const instance = await NapsterCompanionApiSdk.init(getToken, {
  onReady: () => console.log("Widget mounted"),
  onError: (error) => console.error("SDK error:", error),
  onAvatarReady: (isReady) => console.log("Session live:", isReady),
  onSessionStatusChange: (status) => console.log("Status:", status),
  onInactivityStatusChange: (isInactive) => console.log("Inactive:", isInactive),
  onFeaturesUpdate: (features) => console.log("Features:", features),
  onScreenShareStateChange: (isSharing) => console.log("Sharing:", isSharing),
  onDestroy: () => console.log("Session torn down"),
  onData: (data) => console.log("Data:", data),
});
CallbackSignatureFires when
onReady() => voidThe SDK has mounted the widget. Nothing is connected yet.
onError(error: Error) => voidA runtime, network, or server error occurs. See Handling errors.
onAvatarReady(isReady?: boolean) => voidtrue once per session, when it's live and ready for commands. false when it's torn down.
onSessionStatusChange(status: SessionStatus) => voidThe session moves to a new stage. See Session status.
onInactivityStatusChange(isInactive: boolean) => voidThe SDK's inactivity timer runs out or restarts. Pairs with the inactivity timeout feature.
onDestroy() => voidThe session is torn down, for any reason. See below.
onData(data: EventMessage) => voidA message arrives over the data channel. See Incoming data.
onFeaturesUpdate(features: FeatureConfig) => voidFeature configuration changes at runtime.
onScreenShareStateChange(isSharing: boolean) => voidScreen sharing starts or stops.

onAvatarReady(true) waits until the data channel is open, so it's the safe place to send your first command, such as a greeting. With the launcher, it fires once for each session the visitor starts. onAvatarReady(false) fires whenever a session is torn down, including an attempt that never went live.

Under deferred video, the session goes live on audio first and the video follows. onAvatarReady(true) fires when the audio is live, not when the video appears. To react to the video, wait for onSessionStatusChange to report readyVideo.

onDestroy fires on every teardown: destroy(), the End button, the inactivity countdown, a session the server ends, a fatal connection error, or a failed getToken. When getToken fails, onDestroy fires before onError. It doesn't fire when an ignored microphone prompt returns the launcher to entry.

onInactivityStatusChange(true) fires when the SDK's own inactivity timer shows the Still there? warning. onInactivityStatusChange(false) fires each time the idle timer restarts, for example after every completed message. Treat it as the current state, not as a change. The server's idle warning, avatar_connection_warning, shows the same card but doesn't fire this callback. To catch it, watch for that event in onData.

Session status

onSessionStatusChange reports each stage the session goes through. Use it when you want to drive your own UI from the same state the widget uses.

StatusMeaning
entryNothing is connected. With the launcher, the launcher card or your own button is showing.
loadingThe session is starting.
permissionPendingThe browser's microphone prompt is still open after half a second. Not used on touch devices.
permissionBlockedThe microphone is blocked. The SDK shows a card asking the visitor to allow it in the browser's site settings, with a Check again button.
permissionDismissedLauncher mode only. The visitor didn't answer the microphone prompt within 30 seconds. The status then returns to entry.
readyAudioThe session is live with audio. The video isn't showing yet.
readyVideoThe video is showing.

A typical session goes from loading to readyVideo, then back to entry when it ends. Under deferred video, or when the first video frame is slow to arrive, readyAudio comes before readyVideo, so handle both.

Every teardown reports entry, with or without the launcher. Without the launcher, entry is the starting state, so it isn't reported when the session starts. The first status you receive is loading, permissionPending, or permissionBlocked. With the launcher, a click moves the status from entry to loading. If the microphone prompt stays open, you get permissionPending, then loading again once the visitor allows the microphone.

onSessionStatusChange: (status) => {
  if (status === "permissionBlocked") {
    showHelp("Allow microphone access to talk to the agent.");
  }
},

The package doesn't export a SessionStatus type. Derive it from the exported NapsterCompanionApiConfig type, so it stays in sync with the SDK:

import type { NapsterCompanionApiConfig } from "@touchcastllc/napster-companion-api";

type SessionStatus = Parameters<NonNullable<NapsterCompanionApiConfig["onSessionStatusChange"]>>[0];

Incoming data

onData receives each message the avatar sends over the data channel as an EventMessage:

interface EventMessage {
  event: string;
  data?: {
    state?: string;
    message?: { action?: string; content?: string; role?: string };
    details?: { mode?: string; stage?: string; video_type?: string };
    [key: string]: unknown;
  };
}

The package doesn't export this type either. Derive it the same way:

type EventMessage = Parameters<NonNullable<NapsterCompanionApiConfig["onData"]>>[0];

The event field names the message type, for example avatar_state_changed or message_received, and data carries the payload. For the full protocol, including how transcripts and state changes are shaped, see Server events.

One event doesn't come from the platform: ui_update carries JSON that your own functions server pushed to the client. Use it to update your page from your backend in step with the conversation.

Handling errors

onError receives problems on the visitor's side, such as a blocked microphone or a failed getToken, and errors the server reports during the session. A blocked microphone is reported on the first denial only, not when a Check again retry is refused.

An error doesn't always end the session. Use onDestroy to know when it has.

Server errors

These server events reach onError.

EventWhat onError receivesWhat happens next
session_expiredA ConnectionErrorThe SDK ends the session, and onDestroy fires.
no_credits_leftA ConnectionErrorThe SDK ends the session, and onDestroy fires.
provider_connection_abortedA WebRTCError with the provider's message, then a ConnectionErrorThe SDK ends the session, and onDestroy fires.
avatar_state_changed with failedA WebRTCError with the server's messageThe server closes the session, and onDestroy fires.
avatar_state_changed with video_failedA WebRTCError with the server's messageThe session continues on audio.
errorA WebRTCError with the message Received "error" event. The server's message is in context.serverMessage.data.message.Depends on the cause.

onData receives these events too. For session_expired, no_credits_left, and provider_connection_aborted, though, it receives them only after the SDK has torn down the session. Handle the end of the session in onError or onDestroy instead.

The package doesn't export the error classes. To tell which event caused an error, check the error's name, then its context:

  • For a ConnectionError, context.reason holds the event name.
  • For a WebRTCError, context.event holds it.

For example, to show a message when your organization runs out of credits:

onError: (error) => {
  const reason = (error as { context?: { reason?: string } }).context?.reason;
  if (error.name === "ConnectionError" && reason === "no_credits_left") {
    showHelp("The agent isn't available right now.");
  }
},

Next steps

On this page