Events & State

Event subscription and state monitoring for embedded agents

Subscribe to agent events to monitor connection state, agent activity, and errors in real time. Use event callbacks to update your UI, log analytics, or trigger custom behavior.

Available Events

The API exposes three event types for monitoring agent state.

EventPayloadDescription
connection{ state }Connection state changes throughout lifecycle
agentActivity{ state }Agent activity status changes
error{ error }Errors and exceptions

Event Subscription

Use window.DID_AGENTS_API.events.on() to subscribe to events. All subscriptions return an unsubscribe function.

Basic Pattern

const api = window.DID_AGENTS_API;

// Subscribe to an event
const unsubscribe = api.events.on("connection", ({ state }) => {
  console.log("Connection state:", state);
});

// Later, clean up
unsubscribe();

connection Event

Tracks the WebRTC connection lifecycle from initialization to closure.

Connection States

StateDescription
newConnection initialized, not yet started
connectingAttempting to establish connection
connectedSuccessfully connected and ready
disconnectedConnection lost (may reconnect automatically)
disconnectingClosing connection gracefully
closedConnection closed normally
failConnection failed (check error event)
completedConnection completed successfully

Example: Complete Connection Handling

const api = window.DID_AGENTS_API;

const unsubscribe = api.events.on("connection", ({ state }) => {
  console.log("Connection state:", state);

  switch (state) {
    case "new":
      console.log("Connection initialized");
      break;

    case "connecting":
      console.log("Connecting to agent...");
      showLoadingIndicator();
      break;

    case "connected":
      console.log("Connected successfully!");
      hideLoadingIndicator();
      showAgentInterface();
      break;

    case "disconnected":
      console.log("Connection lost");
      showReconnectingMessage();
      break;

    case "disconnecting":
      console.log("Closing connection...");
      break;

    case "closed":
      console.log("Connection closed");
      hideAgentInterface();
      break;

    case "fail":
      console.error("Connection failed");
      showErrorMessage("Unable to connect to agent");
      break;

    case "completed":
      console.log("Connection completed");
      break;
  }
});

agentActivity Event

Tracks what the agent is currently doing.

Agent Activity States

StateDescription
IDLEAgent is waiting and ready to interact
TALKINGAgent is currently speaking
LOADINGAgent is processing (LLM generating response)
BUFFERINGAgent is buffering audio/video

Example: Activity Monitoring

api.events.on("agentActivity", ({ state }) => {
  console.log("Agent activity:", state);

  const statusElement = document.querySelector(".agent-status");

  switch (state) {
    case "IDLE":
      statusElement.textContent = "Ready to chat";
      statusElement.className = "agent-status idle";
      break;

    case "TALKING":
      statusElement.textContent = "Speaking...";
      statusElement.className = "agent-status talking";
      break;

    case "LOADING":
      statusElement.textContent = "Thinking...";
      statusElement.className = "agent-status loading";
      break;

    case "BUFFERING":
      statusElement.textContent = "Buffering...";
      statusElement.className = "agent-status buffering";
      break;
  }
});

Multiple Event Subscriptions

Subscribe to multiple events and manage cleanup.

const api = window.DID_AGENTS_API;

// Store unsubscribe functions
const subscriptions = [];

// Connection monitoring
subscriptions.push(
  api.events.on("connection", ({ state }) => {
    updateConnectionStatus(state);
  }),
);

// Activity monitoring
subscriptions.push(
  api.events.on("agentActivity", ({ state }) => {
    updateAgentActivity(state);
  }),
);

// Error handling
subscriptions.push(
  api.events.on("error", ({ error }) => {
    handleError(error);
  }),
);

// Clean up all subscriptions
window.addEventListener("beforeunload", () => {
  subscriptions.forEach((unsubscribe) => unsubscribe());
});

FAQ

Subscribe to events after the API loads, typically in a window.addEventListener("load", ...) callback. Events will fire as soon as state changes occur.

Yes, always unsubscribe when you no longer need the event listener to prevent memory leaks. This is especially important for single-page applications. Store the unsubscribe function and call it during cleanup.

Yes. Each subscription is independent and receives its own callback. However, this is rarely needed and can lead to duplicate processing. Usually one callback per event type is sufficient.

You'll receive connection state updates: disconnectedconnectingconnected. Your event listeners remain active and will receive all state changes during reconnection.

Check the error.code or error.type property in the error event payload. Common codes include NETWORK_ERROR, AUTH_ERROR, and TIMEOUT_ERROR. Log the error object to see all available properties.