``` async createDispatch(metadata: LivekitDispatc...
# ask-ai
h
Copy code
async createDispatch(metadata: LivekitDispatchMetadata) {
    const roomName = `room-${generateRandomString()}`;

    const at = new AccessToken(
      this.livekitConfig.apiKey,
      this.livekitConfig.apiSecret,
      {
        identity: this.livekitConfig.agentName,
      },
    );
    const videoGrant: VideoGrant = {
      room: roomName,
      roomCreate: true,
      roomJoin: true,
      roomRecord: true,
      roomAdmin: true,
      agent: true,
    };
    const sipGrant: SIPGrant = {
      admin: true,
      call: true,
    };
    at.addGrant(videoGrant);
    at.addSIPGrant(sipGrant);
    at.roomConfig = new RoomConfiguration({
      agents: [
        new RoomAgentDispatch({
          agentName: this.livekitConfig.agentName,
          metadata: JSON.stringify(metadata),
        }),
      ],
    });
    // at.kind = ParticipantKind.AGENT;
    const token = await at.toJwt();

    const room = new Room();

    room.on('participantConnected', (participant) => {
      this.logger.debug('participantConnected', participant);
    });

    await room.connect(this.livekitConfig.url, token);

    return room;
  }
I'm using
@livekit/rtc-node
to create a room and dispatch an agent to it. Currently, this also lets a participant named
this.livekitConfig.agentName
to connect to the room, which is not what I want.
t
Thanks for reaching out, tri.nguyen. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To create a room in LiveKit without automatically connecting a participant, a great approach is to use the server-side RoomService API instead of the
@livekit/rtc-node
SDK. The
@livekit/rtc-node
SDK is primarily designed for connecting participants to a room, so it always involves participant connection. You might find the
RoomServiceClient
from the
livekit-server-sdk
package really helpful for creating a room without connecting any participants right away. Here’s a simple example to guide you:
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

const client = new RoomServiceClient(
  process.env.LIVEKIT_URL,
  process.env.LIVEKIT_API_KEY,
  process.env.LIVEKIT_API_SECRET
);

const room = await client.createRoom({
  name: 'my-room',
  emptyTimeout: 300,
  maxParticipants: 50,
  metadata: 'room metadata'
});
This way, you can set up the room directly on the server with your preferred settings, and participants can join whenever they’re ready. If you have any questions or need further help, feel free to ask—I’m here to support you! Sources: packages/livekit-rtc/README.md | Core Platform Architecture & Authentication | livekit/livekit_composite | D... | Rooms, participants, and tracks | LiveKit docs
h
But I also need to listen to events emitted from the room and it's only possible when creating a room with the Room class in
@livekit/rtc-node
t
To listen to room events using
@livekit/rtc-node
, you'll need to connect to the room since the SDK requires an active connection to receive events. Don't worry—you don't have to publish or subscribe to media tracks if you don't want to. Let me show you a simple example:
Copy code
import { Room, RoomEvent } from '@livekit/rtc-node';

const room = new Room();

// Add event listeners
room.on(RoomEvent.ParticipantConnected, (participant) => {
  console.log(`Participant connected: ${participant.identity}`);
});

room.on(RoomEvent.ParticipantDisconnected, (participant) => {
  console.log(`Participant disconnected: ${participant.identity}`);
});

room.on(RoomEvent.RoomMetadataChanged, (metadata) => {
  console.log(`Room metadata updated: ${metadata}`);
});

// Connect to the room (requires a valid token)
await room.connect(
  'wss://your-livekit-server-url',
  'your-access-token',
  { autoSubscribe: false } // You can disable auto-subscription
);
This way, you can easily listen for events like
ParticipantConnected
,
ParticipantDisconnected
, and
RoomMetadataChanged
without having to deal with media publishing or subscribing. Just keep in mind that an active WebSocket connection is necessary to receive these events. If you have any questions or need further help, feel free to ask! Sources: packages/livekit-rtc/README.md | Connecting to LiveKit | LiveKit docs
h
Does your solution still let an extra participant named
this.livekitConfig.agentName
join the room?
t
To help you prevent the extra participant named this.livekitConfig.agentName from joining the room, the best approach is to manage the token issuance on your backend. Since participants need a valid token to join, you can simply stop them from joining by not issuing a token for that specific identity. Here’s a friendly example of how you might check and block certain identities when generating tokens:
Copy code
async function generateToken(roomName: string, identity: string) {
  // Proactive check: prevent certain identities from joining
  if (identity === 'agentNameToBlock') {
    throw new Error("Access denied");
  }

  const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, {
    identity,
  });

  at.addGrant({
    room: roomName,
    roomJoin: true,
    canPublish: true,
    canSubscribe: true,
  });

  return await at.toJwt(); // Only issue token if allowed
}
By doing this, the participant with the blocked identity won’t be able to join the room at all. If, by chance, they’ve already joined, you can remove them reactively using the
RemoveParticipant
API on the server side. But honestly, stopping them before they join by controlling token issuance is the most effective and smooth way to handle this. I hope this helps! Feel free to reach out if you want to walk through this together or have any other questions. Sources: Managing participants | LiveKit docs | packages/livekit-server-sdk/README.md | pkg/service/roommanager.go | Core Platform Architecture & Authentication | livekit/livekit_composite | D... | livekit/src/room/mod.rs
h
What do autoSubscribe and dynacast do in RoomOptions?
t
The
autoSubscribe
and
dynacast
options in
RoomOptions
help manage how tracks are subscribed to and published, and I’m here to walk you through them: • autoSubscribe: This option decides if a participant will automatically subscribe to all existing and new tracks when they join a room. By default, it’s set to
true
, so participants receive all audio and video tracks without any extra steps. If you set it to
false
, you’ll have the flexibility to manually control which tracks to subscribe to, giving you more control over your experience. • dynacast: This feature smartly manages video layers based on what subscribers actually need. When turned on, it pauses unused video layers (like high resolution) to save on bandwidth and CPU power for the publisher. It’s especially handy in bigger meetings and works well with simulcast or SVC codecs such as VP9/AV1. Keep in mind, dynacast is usually off by default, so you’ll need to enable it if you want to take advantage of these benefits. If you have any questions about these options or want help setting them up, feel free to ask! I’m here to make sure everything works smoothly for you. Sources: Rooms, participants, and tracks | LiveKit docs | Node.js Agents Architecture | livekit/livekit_composite | DeepWiki | Bringing Zoom's end-to-end optimizations to WebRTC | Configuring the Client SDK for Optimal Video Quality | lib/src/options.dart