m
hi
t
Thanks for reaching out, aigentzi. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi — how can I help you today? If you have an issue, please include what you're trying to do (app, SDK/language, room or participant IDs if relevant) and any errors or unexpected behavior you're seeing.
m
woudl you sugest any chages to his script to ensure our livkeit clud agent joins the room ? const { AccessToken, RoomServiceClient } = require('livekit-server-sdk'); const { AccessToken, AgentDispatchClient, RoomServiceClient } = require('livekit-server-sdk'); /** * POST /api/connect * Body: { scenario, level, voice_provider, voice } * * Fixes applied: * - Sets token TTL (seconds) to avoid "token is expired" errors * - Ensures
roomConfig
is set on the AccessToken instance * - Logs
iat
and
exp
for debugging * - Uses HTTP(S) admin URL for RoomServiceClient and returns WS(S) URL to client * - Basic input validation and improved error handling */ const REQUIRED_ENVS = ['LIVEKIT_URL', 'LIVEKIT_API_KEY', 'LIVEKIT_API_SECRET']; const DEFAULT_TTL = 60 * 10; // 10 minutes function missingEnv() { return REQUIRED_ENVS.filter((k) => !process.env[k]); } function adminUrlFromLivekit(url) { if (!url) return url; return url.replace('ws://', 'http://').replace('wss://', 'https://'); } @@ -46,93 +46,111 @@ module.exports = async function handler(req, res) { const missing = missingEnv(); if (missing.length > 0) { res.status(500).json({ error: 'Server misconfiguration: missing environment variables', missing, }); return; } try { const LIVEKIT_URL = process.env.LIVEKIT_URL; const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY; const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET; const AGENT_NAME = process.env.AGENT_NAME || 'CA_4T2cvqbL6JwH'; const TOKEN_TTL = Number(process.env.TOKEN_TTL_SECONDS) || DEFAULT_TTL; const body = req.body || {}; const scenario = typeof body.scenario === 'string' ? body.scenario : 'taxi'; const level = typeof body.level === 'string' ? body.level : 'basic'; const voice_provider = typeof body.voice_provider === 'string' ? body.voice_provider : 'livekit'; const voice = typeof body.voice === 'string' ? body.voice : 'default'; const roomName = `english-teacher-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`; const metadata = { scenario, level, voice_provider, voice }; const agentDispatch = { agentName: AGENT_NAME, metadata: JSON.stringify(metadata), }; // Create RoomServiceClient (admin API uses HTTP(S)) const adminUrl = adminUrlFromLivekit(LIVEKIT_URL); const roomService = new RoomServiceClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET); const dispatchClient = new AgentDispatchClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET); let dispatchId = null; // Create room (ignore if fails due to race/exists) try { await roomService.createRoom({ name: roomName, emptyTimeout: 300, // 5 minutes - longer timeout for debugging maxParticipants: 2, metadata: JSON.stringify(metadata), agents: [agentDispatch], }); } catch (err) { // Log warning but continue - room names are unique so this should be rare console.warn('createRoom warning:', err && err.message ? err.message : err); } // Explicitly dispatch the agent to the room to avoid relying solely on implicit triggers try { const dispatch = await dispatchClient.createDispatch(roomName, AGENT_NAME, { metadata: JSON.stringify(metadata), }); dispatchId = dispatch?.id || null; console.info('Agent dispatch created', { dispatchId: dispatch?.id, agentName: AGENT_NAME, room: roomName, }); } catch (dispatchErr) { console.error('Failed to create agent dispatch', dispatchErr?.message || dispatchErr); } // Build AccessToken const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, { identity:
user-${Date.now()}
, name: 'English Teacher Student', ttl: TOKEN_TTL, // TTL in seconds }); // Video grant (only permissions) const videoGrant = { room: roomName, roomJoin: true, canPublish: true, canSubscribe: true, canPublishData: true, }; at.addGrant(videoGrant); // Correct: attach roomConfig to AccessToken (top-level) to dispatch agent at.roomConfig = { agents: [ { agentName: AGENT_NAME, // optional: metadata: JSON.stringify({ scenario, level, ... }) }, ], agents: [agentDispatch], }; const token = await at.toJwt(); // Decode token payload for debugging (iat/exp/roomConfig) try { const payloadPart = token.split('.')[1]; const decoded = JSON.parse(Buffer.from(payloadPart, 'base64').toString('utf8')); const iat = decoded.iat || null; const exp = decoded.exp || null; const roomConfig = decoded.roomConfig || null; const now = Math.floor(Date.now() / 1000); const timeUntilExpiry = exp - now; console.info('=== TOKEN GENERATION DEBUG ==='); console.info('Token timestamps:', { iat, exp, now, server_time_utc: new Date().toISOString(), ttl_seconds: exp - iat, time_until_expiry_seconds: timeUntilExpiry, token_valid: timeUntilExpiry > 0 ? 'YES' : 'NO (EXPIRED!)', }); @@ -149,41 +167,43 @@ module.exports = async function handler(req, res) { } else if (roomConfig.agents[0].agentName !== AGENT_NAME) { console.error(
:x: CRITICAL: agentName mismatch! Expected: ${AGENT_NAME}, Got: ${roomConfig.agents[0].agentName}
); } else { console.info(
:white_check_mark: Token contains correct agentName: ${AGENT_NAME}
); } // Check for token expiry issues if (timeUntilExpiry <= 0) { console.error('❌ CRITICAL: Token is already expired! Check server clock.'); } else if (timeUntilExpiry < 60) { console.warn('⚠️ WARNING: Token expires in less than 60 seconds!'); } console.info('=== END TOKEN DEBUG ==='); } catch (err) { console.error('❌ Could not decode token payload for logging:', err && err.message ? err.message : err); console.error('Error stack:', err.stack); } // Log response for debugging console.info('Returning token response:', { room: roomName, url: wsUrlFromLivekit(LIVEKIT_URL), agentName: AGENT_NAME, tokenLength: token.length, dispatchId, }); res.status(200).json({ token, url: wsUrlFromLivekit(LIVEKIT_URL), room: roomName, metadata, dispatchId, }); } catch (error) { console.error('Error in /api/connect:', error && error.stack ? error.stack : error); res.status(500).json({ error: 'Failed to generate access token or create room', message: error && error.message ? error.message : String(error), }); }
t
Thanks — I reviewed your script and it’s very close. Focused suggestions to ensure the LiveKit cloud agent reliably joins: 1) Fix duplicate
agents
in
roomConfig
• You currently set
agents
twice; the latter overwrites the former. Use a single array that contains the full agent object (name + metadata). Example:
Copy code
at.roomConfig = {
  agents: [agentDispatch], // agentDispatch has agentName and metadata
};
2) Pick one dispatch mechanism (don’t mix three) • You create the room with
agents
, call
createDispatch()
, and include
roomConfig
in the token. That can cause race conditions or duplicate dispatches. Choose one: ◦ Use
roomConfig
in the token -> agent joins when participant connects. ◦ Or call
AgentDispatchClient.createDispatch()
-> agent joins immediately or on your schedule. ◦ Or set
agents
in
createRoom()
-> agent may be dispatched at room creation. Remove the others to avoid conflicts. For "join when user connects", remove
agents
from
createRoom()
and remove the explicit
createDispatch()
. 3) Ensure
AGENT_NAME
exactly matches the registered agent ID (case-sensitive). 4) Keep token TTL sufficient and verify token contains
roomConfig
• Your TTL logic and JWT decoding are good; also log/validate
roomConfig.agents
exists in the decoded token:
Copy code
if (!roomConfig || !Array.isArray(roomConfig.agents) || roomConfig.agents.length === 0) {
  console.warn('No agents in roomConfig');
}
5) Ensure agent process connects as kind=AGENT (agent framework handles this) so it can accept dispatches. Minimal patch summary: • Replace the duplicate
roomConfig
block with a single
agents: [agentDispatch]
. • Remove
agents
from
createRoom()
if you want on-join behavior. • Remove
createDispatch()
unless you need pre-dispatch. If you tell me which dispatch behavior you want (on-join, pre-dispatch, or on-room-create), I’ll produce the exact cleaned-up code snippet. Sources: Authentication | LiveKit docs | Agent dispatch | LiveKit docs
m
thsi agent is an engliosh teacher who will join thephone call or room andf usesr will be espectinga gent to welecome them when they noin room eg when the call connecst ( phone) or when buution start is pressed on web app so whatever you recomened
t
Use the token-based on-join dispatch (
roomConfig.agents
) so the agent joins exactly when the user connects (phone call connects or user presses start). That matches your goal (agent greets user on join) and avoids pre-dispatch or duplicate joins. Changes to make: • Remove
agents
from
createRoom()
and remove the explicit
dispatchClient.createDispatch()
call. • Ensure
at.roomConfig
contains a single
agents
array with the agent object (name + metadata). • Keep token TTL > 60s and verify the decoded JWT contains
roomConfig.agents
. Minimal code changes: 1) When creating the room, do NOT include agents:
Copy code
await roomService.createRoom({
  name: roomName,
  emptyTimeout: 300,
  maxParticipants: 2,
  metadata: JSON.stringify(metadata),
  // agents: [agentDispatch], // remove this
});
2) Remove explicit dispatch block:
Copy code
// remove dispatchClient.createDispatch(...) unless you want pre-dispatch
3) Set
roomConfig
on the AccessToken once, using the
agentDispatch
object:
Copy code
at.roomConfig = {
  agents: [agentDispatch],
};
4) Verify in logs the token contains roomConfig and agentName:
Copy code
console.info('RoomConfig in token:', roomConfig);
if (!roomConfig || !Array.isArray(roomConfig.agents) || roomConfig.agents.length === 0) {
  console.warn('No agents in roomConfig');
}
5) Confirm
AGENT_NAME
exactly matches the registered agent ID and that the agent process runs as kind=AGENT. If you want, I can return a fully cleaned handler function with these edits applied. Which do you prefer: a full patched file or just the minimal snippets above?
m
share a ciomplete sugegsted replacemnts for tghios : const { AccessToken, RoomServiceClient } = require('livekit-server-sdk'); const { AccessToken, AgentDispatchClient, RoomServiceClient } = require('livekit-server-sdk'); /** * POST /api/connect * Body: { scenario, level, voice_provider, voice } * * Fixes applied: * - Sets token TTL (seconds) to avoid "token is expired" errors * - Ensures
roomConfig
is set on the AccessToken instance * - Logs
iat
and
exp
for debugging * - Uses HTTP(S) admin URL for RoomServiceClient and returns WS(S) URL to client * - Basic input validation and improved error handling */ const REQUIRED_ENVS = ['LIVEKIT_URL', 'LIVEKIT_API_KEY', 'LIVEKIT_API_SECRET']; const DEFAULT_TTL = 60 * 10; // 10 minutes function missingEnv() { return REQUIRED_ENVS.filter((k) => !process.env[k]); } function adminUrlFromLivekit(url) { if (!url) return url; return url.replace('ws://', 'http://').replace('wss://', 'https://'); } @@ -46,93 +46,111 @@ module.exports = async function handler(req, res) { const missing = missingEnv(); if (missing.length > 0) { res.status(500).json({ error: 'Server misconfiguration: missing environment variables', missing, }); return; } try { const LIVEKIT_URL = process.env.LIVEKIT_URL; const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY; const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET; const AGENT_NAME = process.env.AGENT_NAME || 'CA_4T2cvqbL6JwH'; const TOKEN_TTL = Number(process.env.TOKEN_TTL_SECONDS) || DEFAULT_TTL; const body = req.body || {}; const scenario = typeof body.scenario === 'string' ? body.scenario : 'taxi'; const level = typeof body.level === 'string' ? body.level : 'basic'; const voice_provider = typeof body.voice_provider === 'string' ? body.voice_provider : 'livekit'; const voice = typeof body.voice === 'string' ? body.voice : 'default'; const roomName = `english-teacher-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`; const metadata = { scenario, level, voice_provider, voice }; const agentDispatch = { agentName: AGENT_NAME, metadata: JSON.stringify(metadata), }; // Create RoomServiceClient (admin API uses HTTP(S)) const adminUrl = adminUrlFromLivekit(LIVEKIT_URL); const roomService = new RoomServiceClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET); const dispatchClient = new AgentDispatchClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET); let dispatchId = null; // Create room (ignore if fails due to race/exists) try { await roomService.createRoom({ name: roomName, emptyTimeout: 300, // 5 minutes - longer timeout for debugging maxParticipants: 2, metadata: JSON.stringify(metadata), agents: [agentDispatch], }); } catch (err) { // Log warning but continue - room names are unique so this should be rare console.warn('createRoom warning:', err && err.message ? err.message : err); } // Explicitly dispatch the agent to the room to avoid relying solely on implicit triggers try { const dispatch = await dispatchClient.createDispatch(roomName, AGENT_NAME, { metadata: JSON.stringify(metadata), }); dispatchId = dispatch?.id || null; console.info('Agent dispatch created', { dispatchId: dispatch?.id, agentName: AGENT_NAME, room: roomName, }); } catch (dispatchErr) { console.error('Failed to create agent dispatch', dispatchErr?.message || dispatchErr); } // Build AccessToken const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, { identity:
user-${Date.now()}
, name: 'English Teacher Student', ttl: TOKEN_TTL, // TTL in seconds }); // Video grant (only permissions) const videoGrant = { room: roomName, roomJoin: true, canPublish: true, canSubscribe: true, canPublishData: true, }; at.addGrant(videoGrant); // Correct: attach roomConfig to AccessToken (top-level) to dispatch agent at.roomConfig = { agents: [ { agentName: AGENT_NAME, // optional: metadata: JSON.stringify({ scenario, level, ... }) }, ], agents: [agentDispatch], }; const token = await at.toJwt(); // Decode token payload for debugging (iat/exp/roomConfig) try { const payloadPart = token.split('.')[1]; const decoded = JSON.parse(Buffer.from(payloadPart, 'base64').toString('utf8')); const iat = decoded.iat || null; const exp = decoded.exp || null; const roomConfig = decoded.roomConfig || null; const now = Math.floor(Date.now() / 1000); const timeUntilExpiry = exp - now; console.info('=== TOKEN GENERATION DEBUG ==='); console.info('Token timestamps:', { iat, exp, now, server_time_utc: new Date().toISOString(), ttl_seconds: exp - iat, time_until_expiry_seconds: timeUntilExpiry, token_valid: timeUntilExpiry > 0 ? 'YES' : 'NO (EXPIRED!)', }); @@ -149,41 +167,43 @@ module.exports = async function handler(req, res) { } else if (roomConfig.agents[0].agentName !== AGENT_NAME) { console.error(
:x: CRITICAL: agentName mismatch! Expected: ${AGENT_NAME}, Got: ${roomConfig.agents[0].agentName}
); } else { console.info(
:white_check_mark: Token contains correct agentName: ${AGENT_NAME}
); } // Check for token expiry issues if (timeUntilExpiry <= 0) { console.error('❌ CRITICAL: Token is already expired! Check server clock.'); } else if (timeUntilExpiry < 60) { console.warn('⚠️ WARNING: Token expires in less than 60 seconds!'); } console.info('=== END TOKEN DEBUG ==='); } catch (err) { console.error('❌ Could not decode token payload for logging:', err && err.message ? err.message : err); console.error('Error stack:', err.stack); } // Log response for debugging console.info('Returning token response:', { room: roomName, url: wsUrlFromLivekit(LIVEKIT_URL), agentName: AGENT_NAME, tokenLength: token.length, dispatchId, }); res.status(200).json({ token, url: wsUrlFromLivekit(LIVEKIT_URL), room: roomName, metadata, dispatchId, }); } catch (error) { console.error('Error in /api/connect:', error && error.stack ? error.stack : error); res.status(500).json({ error: 'Failed to generate access token or create room', message: error && error.message ? error.message : String(error), }); }
t
Below is a complete, cleaned replacement for your handler that implements token-based on-join dispatch (
roomConfig.agents
) so the English-teacher agent joins only when the user connects. It removes
agents
from room creation and removes the explicit
createDispatch()
call. Comments highlight key points.
Copy code
const { AccessToken, AgentDispatchClient, RoomServiceClient } = require('livekit-server-sdk');

/**
 * POST /api/connect
 * Body: { scenario, level, voice_provider, voice }
 *
 * - Uses token-based on-join dispatch via at.roomConfig
 * - Removes agents from createRoom and removes explicit createDispatch()
 * - Sets token TTL and logs token payload for debugging
 */

const REQUIRED_ENVS = ['LIVEKIT_URL', 'LIVEKIT_API_KEY', 'LIVEKIT_API_SECRET'];
const DEFAULT_TTL = 60 * 10; // 10 minutes

function missingEnv() {
  return REQUIRED_ENVS.filter((k) => !process.env[k]);
}

function adminUrlFromLivekit(url) {
  if (!url) return url;
  return url.replace('ws://', 'http://').replace('wss://', 'https://');
}

function wsUrlFromLivekit(url) {
  if (!url) return url;
  return url.replace('http://', 'ws://').replace('https://', 'wss://');
}

module.exports = async function handler(req, res) {
  const missing = missingEnv();
  if (missing.length > 0) {
    res.status(500).json({
      error: 'Server misconfiguration: missing environment variables',
      missing,
    });
    return;
  }

  try {
    const LIVEKIT_URL = process.env.LIVEKIT_URL;
    const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY;
    const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET;
    const AGENT_NAME = process.env.AGENT_NAME || 'CA_4T2cvqbL6JwH';
    const TOKEN_TTL = Number(process.env.TOKEN_TTL_SECONDS) || DEFAULT_TTL;

    const body = req.body || {};
    const scenario = typeof body.scenario === 'string' ? body.scenario : 'taxi';
    const level = typeof body.level === 'string' ? body.level : 'basic';
    const voice_provider = typeof body.voice_provider === 'string' ? body.voice_provider : 'livekit';
    const voice = typeof body.voice === 'string' ? body.voice : 'default';

    const roomName = `english-teacher-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
    const metadata = { scenario, level, voice_provider, voice };

    // agentDispatch object contains the agentName and metadata
    const agentDispatch = {
      agentName: AGENT_NAME,
      metadata: JSON.stringify(metadata),
    };

    // Admin clients use HTTP(S) admin URL
    const adminUrl = adminUrlFromLivekit(LIVEKIT_URL);
    const roomService = new RoomServiceClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);
    // dispatchClient kept in case you want to programmatically dispatch later (not used here)
    const dispatchClient = new AgentDispatchClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);

    // Create room (do NOT include agents here to avoid early dispatch)
    try {
      await roomService.createRoom({
        name: roomName,
        emptyTimeout: 300, // 5 minutes
        maxParticipants: 2,
        metadata: JSON.stringify(metadata),
        // agents: [agentDispatch], // ← removed for on-join dispatch
      });
    } catch (err) {
      // Log and continue; room may already exist due to race conditions
      console.warn('createRoom warning:', err && err.message ? err.message : err);
    }

    // Build AccessToken for the client user
    const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, {
      identity: `user-${Date.now()}`,
      name: 'English Teacher Student',
      ttl: TOKEN_TTL, // TTL in seconds
    });

    // Grant participant permissions
    const videoGrant = {
      room: roomName,
      roomJoin: true,
      canPublish: true,
      canSubscribe: true,
      canPublishData: true,
    };
    at.addGrant(videoGrant);

    // Set roomConfig to dispatch agent when this participant joins
    at.roomConfig = {
      agents: [agentDispatch], // single agents array with agentName + metadata
    };

    const token = await at.toJwt();

    // Decode token payload for debugging (iat/exp/roomConfig)
    try {
      const payloadPart = token.split('.')[1];
      const decoded = JSON.parse(Buffer.from(payloadPart, 'base64').toString('utf8'));
      const iat = decoded.iat || null;
      const exp = decoded.exp || null;
      const roomConfig = decoded.roomConfig || null;
      const now = Math.floor(Date.now() / 1000);
      const timeUntilExpiry = exp - now;

      console.info('=== TOKEN GENERATION DEBUG ===');
      console.info('Token timestamps:', {
        iat,
        exp,
        now,
        server_time_utc: new Date().toISOString(),
        ttl_seconds: exp - iat,
        time_until_expiry_seconds: timeUntilExpiry,
        token_valid: timeUntilExpiry > 0 ? 'YES' : 'NO (EXPIRED!)',
      });

      console.info('RoomConfig in token:', roomConfig);
      if (!roomConfig || !Array.isArray(roomConfig.agents) || roomConfig.agents.length === 0) {
        console.warn('⚠️ No agents found in roomConfig of token!');
      } else if (roomConfig.agents[0].agentName !== AGENT_NAME) {
        console.error(`❌ CRITICAL: agentName mismatch! Expected: ${AGENT_NAME}, Got: ${roomConfig.agents[0].agentName}`);
      } else {
        console.info(`✅ Token contains correct agentName: ${AGENT_NAME}`);
      }

      if (timeUntilExpiry <= 0) {
        console.error('❌ CRITICAL: Token is already expired! Check server clock.');
      } else if (timeUntilExpiry < 60) {
        console.warn('⚠️ WARNING: Token expires in less than 60 seconds!');
      }
      console.info('=== END TOKEN DEBUG ===');
    } catch (err) {
      console.error('❌ Could not decode token payload for logging:', err && err.message ? err.message : err);
    }

    console.info('Returning token response:', {
      room: roomName,
      url: wsUrlFromLivekit(LIVEKIT_URL),
      agentName: AGENT_NAME,
      tokenLength: token.length,
    });

    res.status(200).json({
      token,
      url: wsUrlFromLivekit(LIVEKIT_URL),
      room: roomName,
      metadata,
    });
  } catch (error) {
    console.error('Error in /api/connect:', error && error.stack ? error.stack : error);
    res.status(500).json({
      error: 'Failed to generate access token or create room',
      message: error && error.message ? error.message : String(error),
    });
  }
};
If you want, I can: • Return a version that also returns a pre-created agent dispatchId (keeping explicit dispatch) — useful only if you want the agent to join before the participant connects. • Add stricter validation for incoming body fields. Which would you prefer?
m
would you make cgages to this : nnect-debug.js +25 -6 const { AccessToken, RoomServiceClient } = require('livekit-server-sdk'); const { AccessToken, AgentDispatchClient, RoomServiceClient } = require('livekit-server-sdk'); const REQUIRED_ENVS = ['LIVEKIT_URL', 'LIVEKIT_API_KEY', 'LIVEKIT_API_SECRET']; const DEFAULT_TTL = 60 * 10; // 10 minutes function missingEnv() { return REQUIRED_ENVS.filter((k) => !process.env[k]); } function adminUrlFromLivekit(url) { if (!url) return url; return url.replace('ws://', 'http://').replace('wss://', 'https://'); } function wsUrlFromLivekit(url) { if (!url) return url; return url.replace('http://', 'ws://').replace('https://', 'wss://'); } module.exports = async function handler(req, res) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); if (req.method === 'OPTIONS') { res.status(200).end(); @@ -33,89 +33,108 @@ module.exports = async function handler(req, res) { const missing = missingEnv(); if (missing.length > 0) { res.status(500).json({ error: 'Server misconfiguration: missing environment variables', missing, }); return; } try { const LIVEKIT_URL = process.env.LIVEKIT_URL; const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY; const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET; const AGENT_NAME = process.env.AGENT_NAME || 'CA_4T2cvqbL6JwH'; const TOKEN_TTL = Number(process.env.TOKEN_TTL_SECONDS) || DEFAULT_TTL; const body = req.body || {}; const scenario = typeof body.scenario === 'string' ? body.scenario : 'taxi'; const level = typeof body.level === 'string' ? body.level : 'basic'; const voice_provider = typeof body.voice_provider === 'string' ? body.voice_provider : 'livekit'; const voice = typeof body.voice === 'string' ? body.voice : 'default'; const roomName = `english-teacher-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`; const metadata = { scenario, level, voice_provider, voice }; const agentDispatch = { agentName: AGENT_NAME, metadata: JSON.stringify(metadata), }; const adminUrl = adminUrlFromLivekit(LIVEKIT_URL); const roomService = new RoomServiceClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET); const dispatchClient = new AgentDispatchClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET); let dispatchId = null; try { await roomService.createRoom({ name: roomName, emptyTimeout: 120, maxParticipants: 2, metadata: JSON.stringify(metadata), agents: [agentDispatch], }); } catch (err) { console.warn('createRoom warning:', err && err.message ? err.message : err); } try { const dispatch = await dispatchClient.createDispatch(roomName, AGENT_NAME, { metadata: JSON.stringify(metadata), }); dispatchId = dispatch?.id || null; console.info('Agent dispatch created (debug)', { dispatchId: dispatch?.id, agentName: AGENT_NAME, room: roomName, }); } catch (dispatchErr) { console.error('Failed to create agent dispatch (debug)', dispatchErr?.message || dispatchErr); } const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, { identity:
user-${Date.now()}
, name: 'English Teacher Student', ttl: TOKEN_TTL, }); const videoGrant = { room: roomName, roomJoin: true, canPublish: true, canSubscribe: true, canPublishData: true, }; at.addGrant(videoGrant); at.roomConfig = { agents: [ { agentName: AGENT_NAME, }, ], agents: [agentDispatch], }; const token = await at.toJwt(); // Decode payload for debugging (safe: this is only returned for dev debugging) let decoded = null; try { const payloadPart = token.split('.')[1]; decoded = JSON.parse(Buffer.from(payloadPart, 'base64').toString('utf8')); } catch (err) { console.warn('Could not decode token payload for logging:', err && err.message ? err.message : err); } res.status(200).json({ token, url: wsUrlFromLivekit(LIVEKIT_URL), room: roomName, metadata, dispatchId, token_debug: decoded, // includes iat, exp, roomConfig if present }); } catch (error) { console.error('Error in /api/connect-debug:', error && error.stack ? error.stack : error); res.status(500).json({ error: 'Failed to generate access token or create room', message: error && error.message ? error.message : String(error), }); } };
t
Thanks — I updated your connect-debug.js to use token-based on-join dispatch, remove duplicate
agents
entries, and avoid redundant explicit dispatching. Replace your current file with the code below.
Copy code
const { AccessToken, AgentDispatchClient, RoomServiceClient } = require('livekit-server-sdk');

/**
 * POST /api/connect-debug
 * Body: { scenario, level, voice_provider, voice }
 *
 * - Uses token-based on-join dispatch via at.roomConfig so the agent joins when the user connects
 * - Removes agents from createRoom and removes explicit createDispatch() (optional: kept but not required)
 * - Sets token TTL and returns token debug info for development
 */

const REQUIRED_ENVS = ['LIVEKIT_URL', 'LIVEKIT_API_KEY', 'LIVEKIT_API_SECRET'];
const DEFAULT_TTL = 60 * 10; // 10 minutes

function missingEnv() {
  return REQUIRED_ENVS.filter((k) => !process.env[k]);
}

function adminUrlFromLivekit(url) {
  if (!url) return url;
  return url.replace('ws://', 'http://').replace('wss://', 'https://');
}

function wsUrlFromLivekit(url) {
  if (!url) return url;
  return url.replace('http://', 'ws://').replace('https://', 'wss://');
}

module.exports = async function handler(req, res) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  if (req.method === 'OPTIONS') {
    res.status(200).end();
    return;
  }

  const missing = missingEnv();
  if (missing.length > 0) {
    res.status(500).json({
      error: 'Server misconfiguration: missing environment variables',
      missing,
    });
    return;
  }

  try {
    const LIVEKIT_URL = process.env.LIVEKIT_URL;
    const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY;
    const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET;
    const AGENT_NAME = process.env.AGENT_NAME || 'CA_4T2cvqbL6JwH';
    const TOKEN_TTL = Number(process.env.TOKEN_TTL_SECONDS) || DEFAULT_TTL;

    const body = req.body || {};
    const scenario = typeof body.scenario === 'string' ? body.scenario : 'taxi';
    const level = typeof body.level === 'string' ? body.level : 'basic';
    const voice_provider = typeof body.voice_provider === 'string' ? body.voice_provider : 'livekit';
    const voice = typeof body.voice === 'string' ? body.voice : 'default';

    const roomName = `english-teacher-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
    const metadata = { scenario, level, voice_provider, voice };

    const agentDispatch = {
      agentName: AGENT_NAME,
      metadata: JSON.stringify(metadata),
    };

    const adminUrl = adminUrlFromLivekit(LIVEKIT_URL);
    const roomService = new RoomServiceClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);
    const dispatchClient = new AgentDispatchClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);

    let dispatchId = null;

    // Create room WITHOUT agents to avoid early dispatch. Use token roomConfig for on-join dispatch.
    try {
      await roomService.createRoom({
        name: roomName,
        emptyTimeout: 120,
        maxParticipants: 2,
        metadata: JSON.stringify(metadata),
        // agents: [agentDispatch], // removed for on-join behavior
      });
    } catch (err) {
      console.warn('createRoom warning:', err && err.message ? err.message : err);
    }

    // OPTIONAL: if you want to pre-dispatch the agent (not required for on-join), uncomment below.
    // try {
    //   const dispatch = await dispatchClient.createDispatch(roomName, AGENT_NAME, { metadata: JSON.stringify(metadata) });
    //   dispatchId = dispatch?.id || null;
    //   console.info('Agent dispatch created (debug)', { dispatchId, agentName: AGENT_NAME, room: roomName });
    // } catch (dispatchErr) {
    //   console.error('Failed to create agent dispatch (debug)', dispatchErr?.message || dispatchErr);
    // }

    // Build AccessToken for the client participant
    const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, {
      identity: `user-${Date.now()}`,
      name: 'English Teacher Student',
      ttl: TOKEN_TTL,
    });

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

    // Single agents array with agentName + metadata to dispatch when this participant joins
    at.roomConfig = {
      agents: [agentDispatch],
    };

    const token = await at.toJwt();

    // Decode payload for debugging (development only)
    let decoded = null;
    try {
      const payloadPart = token.split('.')[1];
      decoded = JSON.parse(Buffer.from(payloadPart, 'base64').toString('utf8'));
    } catch (err) {
      console.warn('Could not decode token payload for logging:', err && err.message ? err.message : err);
    }

    res.status(200).json({
      token,
      url: wsUrlFromLivekit(LIVEKIT_URL),
      room: roomName,
      metadata,
      dispatchId,
      token_debug: decoded, // includes iat, exp, roomConfig if present
    });
  } catch (error) {
    console.error('Error in /api/connect-debug:', error && error.stack ? error.stack : error);
    res.status(500).json({
      error: 'Failed to generate access token or create room',
      message: error && error.message ? error.message : String(error),
    });
  }
};
Notes: • This version uses token-based on-join dispatch so the English-teacher joins when the participant connects (phone connects or user presses start). • I left an optional commented block showing how to call
createDispatch()
if you later need pre-dispatch behavior. • Confirm your environment variables and that
AGENT_NAME
exactly matches the registered agent ID. Want me to produce a version that returns a short-lived client token for the agent itself as well (for local testing)?
m
debig reult :
Copy code
[DebugClient] Requesting token from /api/connect-debug
[DebugClient] Token endpoint response: {
  "token": "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFjaGVyIFN0dWRlbnQiLCJ2aWRlbyI6eyJyb29tIjoiZW5nbGlzaC10ZWFjaGVyLTE3NjQ3MTU5NjcxNDgtazBkNHQ0YSIsInJvb21Kb2luIjp0cnVlLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwicm9vbUNvbmZpZyI6eyJhZ2VudHMiOlt7ImFnZW50TmFtZSI6IkNBXzRUMmN2cWJMNkp3SCIsIm1ldGFkYXRhIjoie1wic2NlbmFyaW9cIjpcImRlYnVnXCIsXCJsZXZlbFwiOlwiZGVidWdcIixcInZvaWNlX3Byb3ZpZGVyXCI6XCJsaXZla2l0XCIsXCJ2b2ljZVwiOlwiZGVmYXVsdFwifSJ9XX0sImlzcyI6IkFQSUxGSzY0V3JWTmVXTCIsImV4cCI6MTc2NDcxNjU2NywibmJmIjowLCJzdWIiOiJ1c2VyLTE3NjQ3MTU5Njc1MTcifQ.4OmMeqpLbh6ifWaGWbmmTXqyd9-9I4vbVa5gCah6Qy0",
  "url": "wss://englishlive-3qjapr2j.livekit.cloud",
  "room": "english-teacher-1764715967148-k0d4t4a",
  "metadata": {
    "scenario": "debug",
    "level": "debug",
    "voice_provider": "livekit",
    "voice": "default"
  },
  "dispatchId": null,
  "agentName": "CA_4T2cvqbL6JwH",
  "token_debug": {
    "name": "English Teacher Student",
    "video": {
      "room": "english-teacher-1764715967148-k0d4t4a",
      "roomJoin": true,
      "canPublish": true,
      "canSubscribe": true,
      "canPublishData": true
    },
    "roomConfig": {
      "agents": [
        {
          "agentName": "CA_4T2cvqbL6JwH",
          "metadata": "{\"scenario\":\"debug\",\"level\":\"debug\",\"voice_provider\":\"livekit\",\"voice\":\"default\"}"
        }
      ]
    },
    "iss": "APILFK64WrVNeWL",
    "exp": 1764716567,
    "nbf": 0,
    "sub": "user-1764715967517"
  }
}
[DebugClient] Decoded token payload: {
  "name": "English Teacher Student",
  "video": {
    "room": "english-teacher-1764715967148-k0d4t4a",
    "roomJoin": true,
    "canPublish": true,
    "canSubscribe": true,
    "canPublishData": true
  },
  "roomConfig": {
    "agents": [
      {
        "agentName": "CA_4T2cvqbL6JwH",
        "metadata": "{\"scenario\":\"debug\",\"level\":\"debug\",\"voice_provider\":\"livekit\",\"voice\":\"default\"}"
      }
    ]
  },
  "iss": "APILFK64WrVNeWL",
  "exp": 1764716567,
  "nbf": 0,
  "sub": "user-1764715967517"
}
[DebugClient] Unexpected error: TypeError: Cannot destructure property 'Room' of 'window.LiveKit' as it is undefined.
    at HTMLButtonElement.runDebug (https://englishlive.xtrius.com/debug.html:51:17)
t
Thanks — your server token looks correct and the debug shows the token includes
roomConfig.agents
, so the agent should be dispatched on participant join. The remaining problem is the client-side error: Error: "Cannot destructure property 'Room' of 'window.LiveKit' as it is undefined." What to do (quick fixes) • Add the LiveKit client script to your HTML before any code that uses `LiveKit`:
Copy code
<script src="https://cdn.jsdelivr.net/npm/livekit-client@2.16.0/dist/livekit-client.umd.min.js"></script>
• In your client JS, destructure from the global
LiveKit
(not
window.LiveKit
if using bundlers) after the script loads:
Copy code
const { Room } = LiveKit;
• Then connect using the token and URL returned by your /api/connect-debug response:
Copy code
const room = new Room({ adaptiveStream: true, dynacast: true });
  await room.connect(wsUrl, token, { autoSubscribe: true });
Why this fixes it • Your server token already contains: "roomConfig": { "agents":[{ "agentName":"CA_4T2cvqbL6JwH", "metadata":"..." }] } which triggers on-join dispatch. The client error prevents the participant from connecting, so the agent never gets the trigger. Small checklist to confirm • HTML includes the CDN script above (or you import
livekit-client
properly in your build). • Client code destructures
Room
from
LiveKit
after the script loads. • Use the
url
and
token
returned by your API to call
room.connect(...)
. •
AGENT_NAME
exactly matches your agent registration and the agent process is running. If you want, paste your debug.html (or the portion that imports LiveKit and calls
runDebug
) and I’ll give the exact corrected snippet for your page. Sources: Agent dispatch | LiveKit docs | server-sdk-js | livekit/livekit_composite | DeepWiki | Python SDKs | livekit/livekit_composite | DeepWiki | Client SDKs | livekit/livekit_composite | DeepWiki | Agents telephony integration | LiveKit docs
m
Copy code
[DebugClient] Requesting token from /api/connect-debug
[DebugClient] Token endpoint response: {
  "token": "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFjaGVyIFN0dWRlbnQiLCJ2aWRlbyI6eyJyb29tIjoiZW5nbGlzaC10ZWFjaGVyLTE3NjQ3MTYxMDQ3MTgtcmNmd240eCIsInJvb21Kb2luIjp0cnVlLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwicm9vbUNvbmZpZyI6eyJhZ2VudHMiOlt7ImFnZW50TmFtZSI6IkNBXzRUMmN2cWJMNkp3SCIsIm1ldGFkYXRhIjoie1wic2NlbmFyaW9cIjpcImRlYnVnXCIsXCJsZXZlbFwiOlwiZGVidWdcIixcInZvaWNlX3Byb3ZpZGVyXCI6XCJsaXZla2l0XCIsXCJ2b2ljZVwiOlwiZGVmYXVsdFwifSJ9XX0sImlzcyI6IkFQSUxGSzY0V3JWTmVXTCIsImV4cCI6MTc2NDcxNjcwNSwibmJmIjowLCJzdWIiOiJ1c2VyLTE3NjQ3MTYxMDUxMzMifQ.9JGGlZCdIRI5AahTYx4m0_IndbERqlLTfgpW97BNEJs",
  "url": "wss://englishlive-3qjapr2j.livekit.cloud",
  "room": "english-teacher-1764716104718-rcfwn4x",
  "metadata": {
    "scenario": "debug",
    "level": "debug",
    "voice_provider": "livekit",
    "voice": "default"
  },
  "dispatchId": null,
  "agentName": "CA_4T2cvqbL6JwH",
  "token_debug": {
    "name": "English Teacher Student",
    "video": {
      "room": "english-teacher-1764716104718-rcfwn4x",
      "roomJoin": true,
      "canPublish": true,
      "canSubscribe": true,
      "canPublishData": true
    },
    "roomConfig": {
      "agents": [
        {
          "agentName": "CA_4T2cvqbL6JwH",
          "metadata": "{\"scenario\":\"debug\",\"level\":\"debug\",\"voice_provider\":\"livekit\",\"voice\":\"default\"}"
        }
      ]
    },
    "iss": "APILFK64WrVNeWL",
    "exp": 1764716705,
    "nbf": 0,
    "sub": "user-1764716105133"
  }
}
[DebugClient] Decoded token payload: {
  "name": "English Teacher Student",
  "video": {
    "room": "english-teacher-1764716104718-rcfwn4x",
    "roomJoin": true,
    "canPublish": true,
    "canSubscribe": true,
    "canPublishData": true
  },
  "roomConfig": {
    "agents": [
      {
        "agentName": "CA_4T2cvqbL6JwH",
        "metadata": "{\"scenario\":\"debug\",\"level\":\"debug\",\"voice_provider\":\"livekit\",\"voice\":\"default\"}"
      }
    ]
  },
  "iss": "APILFK64WrVNeWL",
  "exp": 1764716705,
  "nbf": 0,
  "sub": "user-1764716105133"
}
[DebugClient] Unexpected error: TypeError: Cannot destructure property 'Room' of 'window.LiveKit' as it is undefined.
    at HTMLButtonElement.runDebug (https://englishlive.xtrius.com/debug.html:51:17)
1. [DebugClient] Token endpoint response: _{token: 'eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFja…zMifQ.9JGGlZCdIRI5AahTYx4m0_IndbERqlLTfgpW97BNEJs', url: 'wss://englishlive-3qjapr2j.livekit.cloud', room: 'english-teacher-1764716104718-rcfwn4x', metadata: {…}, dispatchId: null, …}_ 2. agentName 3. : a. "CA_4T2cvqbL6JwH" 4. dispatchId 5. : a. null 6. metadata a. : 7. level 8. : i. "debug" 9. scenario 10. : i. "debug" 11. voice 12. : i. "default" 13. voice_provider 14. : i. "livekit" 15. [[Prototype]] 16. : i. Object 17. room 18. : a. "english-teacher-1764716104718-rcfwn4x" 19. token 20. : a. "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFjaGVyIFN0dWRlbnQiLCJ2aWRlbyI6eyJyb29tIjoiZW5nbGlzaC10ZWFjaGVyLTE3NjQ3MTYxMDQ3MTgtcmNmd240eCIsInJvb21Kb2luIjp0cnVlLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwicm9vbUNvbmZpZyI6eyJhZ2VudHMiOlt7ImFnZW50TmFtZSI6IkNBXzRUMmN2cWJMNkp3SCIsIm1ldGFkYXRhIjoie1wic2NlbmFyaW9cIjpcImRlYnVnXCIsXCJsZXZlbFwiOlwiZGVidWdcIixcInZvaWNlX3Byb3ZpZGVyXCI6XCJsaXZla2l0XCIsXCJ2b2ljZVwiOlwiZGVmYXVsdFwifSJ9XX0sImlzcyI6IkFQSUxGSzY0V3JWTmVXTCIsImV4cCI6MTc2NDcxNjcwNSwibmJmIjowLCJzdWIiOiJ1c2VyLTE3NjQ3MTYxMDUxMzMifQ.9JGGlZCdIRI5AahTYx4m0_IndbERqlLTfgpW97BNEJs" 21. token_debug 22. : a. {name: 'English Teacher Student', video: {…}, roomConfig: {…}, iss: 'APILFK64WrVNeWL', exp: 1764716705, …} 23. url 24. : a. "wss://englishlive-3qjapr2j.livekit.cloud" 25. [[Prototype]] 26. : a. Object 27. [DebugClient] Decoded token payload: {name: 'English Teacher Student', video: {…}, roomConfig: {…}, iss: 'APILFK64WrVNeWL', exp: 1764716705, …} 28. exp 29. : a. 1764716705 30. iss 31. : a. "APILFK64WrVNeWL" 32. name 33. : a. "English Teacher Student" 34. nbf 35. : a. 0 36. roomConfig 37. : a. {agents: Array(1)} 38. sub 39. : a. "user-1764716105133" 40. video 41. : a. {room: 'english-teacher-1764716104718-rcfwn4x', roomJoin: true, canPublish: true, canSubscribe: true, canPublishData: true} 42. [[Prototype]] 43. : a. Object <!doctype html> <html> <head> <meta charset="utf-8" /> <title>LiveKit Debug Client</title> <script src="https://cdn.jsdelivr.net/npm/livekit-client@1.15.0/dist/livekit-client.umd.min.js"></script> </head> <body> <h1>LiveKit Debug Client</h1> <button id="startBtn">Start Debug Session</button> <pre id="log" style="white-space:pre-wrap; background:#f7f7f7; padding:12px; border:1px solid #ddd; height:400px; overflow:auto;"></pre> <script> const API_PATH = '/api/connect-debug'; // adjust if different const STAY_MS = 30000; function log(...args) { console.log('[DebugClient]', ...args); const el = document.getElementById('log'); el.textContent += '[DebugClient] ' + args.map(a => { try { return typeof a === 'object' ? JSON.stringify(a, null, 2) : String(a); } catch { return String(a); } }).join(' ') + '\n'; el.scrollTop = el.scrollHeight; } async function runDebug() { try { log('Requesting token from', API_PATH); const resp = await fetch(API_PATH, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ scenario: 'debug', level: 'debug' }), }); const data = await resp.json(); if (!resp.ok) { log('Token endpoint error:', data); return; } log('Token endpoint response:', data); const token = data.token; const url = data.url; if (!token || !url) { log('Missing token or url in response'); return; } if (data.token_debug) { log('Decoded token payload:', data.token_debug); } const { Room } = window.LiveKit; const room = new Room(); room.on('stateChanged', (s) => log('room stateChanged', s)); room.on('disconnected', (r) => log('room disconnected', r)); room.on('participantConnected', (p) => log('participantConnected', p.identity)); room.on('participantDisconnected', (p) => log('participantDisconnected', p.identity)); room.on('trackPublished', (pub, p) => log('trackPublished', pub.trackName, p?.identity)); room.on('trackSubscribed', (track, pub, p) => log('trackSubscribed', track.kind, p?.identity)); room.on('connectionQualityChanged', (q, p) => log('connectionQualityChanged', q, p?.identity)); room.on('participantUpdated', (p) => log('participantUpdated', p.identity)); log('Connecting to', url); await room.connect(url, token, { autoSubscribe: true }); log('Connected. Local participant identity:', room.localParticipant?.identity); // publish mic try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); const [track] = stream.getAudioTracks(); const localTrack = await window.LiveKit.createLocalAudioTrack({ track }); await room.localParticipant.publishTrack(localTrack); log('Published local audio track'); } catch (err) { log('Could not publish mic:', err?.message ?? err); } log(
Staying connected for ${STAY_MS}ms to allow agent dispatch
); await new Promise((r) => setTimeout(r, STAY_MS)); log('Disconnecting now'); room.disconnect(); log('Disconnected (done)'); } catch (err) { log('Unexpected error:', err?.stack ?? err); } } document.getElementById('startBtn').addEventListener('click', runDebug); </script> </body> </html>
Copy code
[DebugClient] Requesting token from /api/connect-debug
[DebugClient] Token endpoint response: {
  "token": "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFjaGVyIFN0dWRlbnQiLCJ2aWRlbyI6eyJyb29tIjoiZW5nbGlzaC10ZWFjaGVyLTE3NjQ3MTYxMDQ3MTgtcmNmd240eCIsInJvb21Kb2luIjp0cnVlLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwicm9vbUNvbmZpZyI6eyJhZ2VudHMiOlt7ImFnZW50TmFtZSI6IkNBXzRUMmN2cWJMNkp3SCIsIm1ldGFkYXRhIjoie1wic2NlbmFyaW9cIjpcImRlYnVnXCIsXCJsZXZlbFwiOlwiZGVidWdcIixcInZvaWNlX3Byb3ZpZGVyXCI6XCJsaXZla2l0XCIsXCJ2b2ljZVwiOlwiZGVmYXVsdFwifSJ9XX0sImlzcyI6IkFQSUxGSzY0V3JWTmVXTCIsImV4cCI6MTc2NDcxNjcwNSwibmJmIjowLCJzdWIiOiJ1c2VyLTE3NjQ3MTYxMDUxMzMifQ.9JGGlZCdIRI5AahTYx4m0_IndbERqlLTfgpW97BNEJs",
  "url": "wss://englishlive-3qjapr2j.livekit.cloud",
  "room": "english-teacher-1764716104718-rcfwn4x",
  "metadata": {
    "scenario": "debug",
    "level": "debug",
    "voice_provider": "livekit",
    "voice": "default"
  },
  "dispatchId": null,
  "agentName": "CA_4T2cvqbL6JwH",
  "token_debug": {
    "name": "English Teacher Student",
    "video": {
      "room": "english-teacher-1764716104718-rcfwn4x",
      "roomJoin": true,
      "canPublish": true,
      "canSubscribe": true,
      "canPublishData": true
    },
    "roomConfig": {
      "agents": [
        {
          "agentName": "CA_4T2cvqbL6JwH",
          "metadata": "{\"scenario\":\"debug\",\"level\":\"debug\",\"voice_provider\":\"livekit\",\"voice\":\"default\"}"
        }
      ]
    },
    "iss": "APILFK64WrVNeWL",
    "exp": 1764716705,
    "nbf": 0,
    "sub": "user-1764716105133"
  }
}
[DebugClient] Decoded token payload: {
  "name": "English Teacher Student",
  "video": {
    "room": "english-teacher-1764716104718-rcfwn4x",
    "roomJoin": true,
    "canPublish": true,
    "canSubscribe": true,
    "canPublishData": true
  },
  "roomConfig": {
    "agents": [
      {
        "agentName": "CA_4T2cvqbL6JwH",
        "metadata": "{\"scenario\":\"debug\",\"level\":\"debug\",\"voice_provider\":\"livekit\",\"voice\":\"default\"}"
      }
    ]
  },
  "iss": "APILFK64WrVNeWL",
  "exp": 1764716705,
  "nbf": 0,
  "sub": "user-1764716105133"
}
[DebugClient] Unexpected error: TypeError: Cannot destructure property 'Room' of 'window.LiveKit' as it is undefined.
    at HTMLButtonElement.runDebug (https://englishlive.xtrius.com/debug.html:51:17)
1. [DebugClient] Token endpoint response: _{token: 'eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFja…zMifQ.9JGGlZCdIRI5AahTYx4m0_IndbERqlLTfgpW97BNEJs', url: 'wss://englishlive-3qjapr2j.livekit.cloud', room: 'english-teacher-1764716104718-rcfwn4x', metadata: {…}, dispatchId: null, …}_ 2. agentName 3. : a. "CA_4T2cvqbL6JwH" 4. dispatchId 5. : a. null 6. metadata a. : 7. level 8. : i. "debug" 9. scenario 10. : i. "debug" 11. voice 12. : i. "default" 13. voice_provider 14. : i. "livekit" 15. [[Prototype]] 16. : i. Object 17. room 18. : a. "english-teacher-1764716104718-rcfwn4x" 19. token 20. : a. "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFjaGVyIFN0dWRlbnQiLCJ2aWRlbyI6eyJyb29tIjoiZW5nbGlzaC10ZWFjaGVyLTE3NjQ3MTYxMDQ3MTgtcmNmd240eCIsInJvb21Kb2luIjp0cnVlLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwicm9vbUNvbmZpZyI6eyJhZ2VudHMiOlt7ImFnZW50TmFtZSI6IkNBXzRUMmN2cWJMNkp3SCIsIm1ldGFkYXRhIjoie1wic2NlbmFyaW9cIjpcImRlYnVnXCIsXCJsZXZlbFwiOlwiZGVidWdcIixcInZvaWNlX3Byb3ZpZGVyXCI6XCJsaXZla2l0XCIsXCJ2b2ljZVwiOlwiZGVmYXVsdFwifSJ9XX0sImlzcyI6IkFQSUxGSzY0V3JWTmVXTCIsImV4cCI6MTc2NDcxNjcwNSwibmJmIjowLCJzdWIiOiJ1c2VyLTE3NjQ3MTYxMDUxMzMifQ.9JGGlZCdIRI5AahTYx4m0_IndbERqlLTfgpW97BNEJs" 21. token_debug 22. : a. {name: 'English Teacher Student', video: {…}, roomConfig: {…}, iss: 'APILFK64WrVNeWL', exp: 1764716705, …} 23. url 24. : a. "wss://englishlive-3qjapr2j.livekit.cloud" 25. [[Prototype]] 26. : a. Object 27. [DebugClient] Decoded token payload: {name: 'English Teacher Student', video: {…}, roomConfig: {…}, iss: 'APILFK64WrVNeWL', exp: 1764716705, …} 28. exp 29. : a. 1764716705 30. iss 31. : a. "APILFK64WrVNeWL" 32. name 33. : a. "English Teacher Student" 34. nbf 35. : a. 0 36. roomConfig 37. : a. {agents: Array(1)} 38. sub 39. : a. "user-1764716105133" 40. video 41. : a. {room: 'english-teacher-1764716104718-rcfwn4x', roomJoin: true, canPublish: true, canSubscribe: true, canPublishData: true} 42. [[Prototype]] 43. : a. Object <!doctype html> <html> <head> <meta charset="utf-8" /> <title>LiveKit Debug Client</title> <script src="https://cdn.jsdelivr.net/npm/livekit-client@1.15.0/dist/livekit-client.umd.min.js"></script> </head> <body> <h1>LiveKit Debug Client</h1> <button id="startBtn">Start Debug Session</button> <pre id="log" style="white-space:pre-wrap; background:#f7f7f7; padding:12px; border:1px solid #ddd; height:400px; overflow:auto;"></pre> <script> const API_PATH = '/api/connect-debug'; // adjust if different const STAY_MS = 30000; function log(...args) { console.log('[DebugClient]', ...args); const el = document.getElementById('log'); el.textContent += '[DebugClient] ' + args.map(a => { try { return typeof a === 'object' ? JSON.stringify(a, null, 2) : String(a); } catch { return String(a); } }).join(' ') + '\n'; el.scrollTop = el.scrollHeight; } async function runDebug() { try { log('Requesting token from', API_PATH); const resp = await fetch(API_PATH, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ scenario: 'debug', level: 'debug' }), }); const data = await resp.json(); if (!resp.ok) { log('Token endpoint error:', data); return; } log('Token endpoint response:', data); const token = data.token; const url = data.url; if (!token || !url) { log('Missing token or url in response'); return; } if (data.token_debug) { log('Decoded token payload:', data.token_debug); } const { Room } = window.LiveKit; const room = new Room(); room.on('stateChanged', (s) => log('room stateChanged', s)); room.on('disconnected', (r) => log('room disconnected', r)); room.on('participantConnected', (p) => log('participantConnected', p.identity)); room.on('participantDisconnected', (p) => log('participantDisconnected', p.identity)); room.on('trackPublished', (pub, p) => log('trackPublished', pub.trackName, p?.identity)); room.on('trackSubscribed', (track, pub, p) => log('trackSubscribed', track.kind, p?.identity)); room.on('connectionQualityChanged', (q, p) => log('connectionQualityChanged', q, p?.identity)); room.on('participantUpdated', (p) => log('participantUpdated', p.identity)); log('Connecting to', url); await room.connect(url, token, { autoSubscribe: true }); log('Connected. Local participant identity:', room.localParticipant?.identity); // publish mic try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); const [track] = stream.getAudioTracks(); const localTrack = await window.LiveKit.createLocalAudioTrack({ track }); await room.localParticipant.publishTrack(localTrack); log('Published local audio track'); } catch (err) { log('Could not publish mic:', err?.message ?? err); } log(
Staying connected for ${STAY_MS}ms to allow agent dispatch
); await new Promise((r) => setTimeout(r, STAY_MS)); log('Disconnecting now'); room.disconnect(); log('Disconnected (done)'); } catch (err) { log('Unexpected error:', err?.stack ?? err); } } document.getElementById('startBtn').addEventListener('click', runDebug); </script> </body> </html>
t
Thanks — your token and roomConfig look correct. The client error shows the LiveKit client SDK isn't available as
window.LiveKit
, so the page can't construct
Room
. Quick fixes: 1) Replace the script tag with a recent LiveKit UMD build (2.x):
Copy code
<script src="https://cdn.jsdelivr.net/npm/livekit-client@2.16.0/dist/livekit-client.umd.min.js"></script>
2) In your client JS, use the global LiveKit after that script loads:
Copy code
const { Room, createLocalAudioTrack } = LiveKit;
const room = new Room();
await room.connect(url, token, { autoSubscribe: true });
const track = await createLocalAudioTrack({ deviceId: /* optional */ });
await room.localParticipant.publishTrack(track);
3) If you must keep the old 1.x script, the API surface differs; upgrade to 2.x or adjust code to that older API. Using 2.x is recommended. 4) Confirm agent is running and
AGENT_NAME
matches exactly (CA_4T2cvqbL6JwH). Your token shows the correct
roomConfig.agents
, so once the client connects the agent will be dispatched. If you paste your current HTML (with the exact script tag) I’ll provide a ready-to-drop corrected snippet.
m
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>AI English Teacher - Voice Testing</title> <link rel="stylesheet" href="style.css" /> <script src="https://cdn.jsdelivr.net/npm/livekit-client@1.15.0/dist/livekit-client.umd.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/livekit-client@2.16.0/dist/livekit-client.umd.min.js"></script> </head> <body> <div class="container"> <h1>🎓 AI English Teacher</h1> <p>Test different voice providers and models</p> <p class="micro-copy"> Need deeper diagnostics? <a class="debug-link" href="/debug.html" target="_blank">Open the LiveKit debug page</a>. </p> <div class="form-group"> <label for="voiceProvider">Voice Provider</label> <select id="voiceProvider"> <option value="livekit">LiveKit Inference (Default)</option> <option value="openai_realtime">OpenAI Realtime API</option> <option value="gemini_realtime">Google Gemini Realtime</option> </select> </div> <div class="form-group"> <label for="voice">Voice</label> <select id="voice"></select> </div> <div class="form-group"> <label for="scenario">Scenario</label> <select id="scenario"> <option value="taxi">Taxi Driver</option> <option value="hotel">Hotel Receptionist</option> <option value="restaurant">Waiter</option> <option value="airport">Check-in Agent</option> <option value="immigration">Border Officer</option> <option value="hospital">Nurse</option> <option value="train_station">Ticket Clerk</option> <option value="tourist_office">Information Agent</option> <option value="museum">Museum Front Desk</option> <option value="bar">Bartender</option> </select> </div> <div class="form-group"> <label>Select Level</label> <div class="radio-group"> <label><input type="radio" name="level" value="basic" checked /> Basic</label> <label><input type="radio" name="level" value="intermediate" /> Intermediate</label> <label><input type="radio" name="level" value="advanced" /> Advanced</label> </div> </div> <div class="cost-info" id="costInfo">Estimated cost: $0.00 per 5-minute session</div> <button id="startBtn" class="start-btn">🎤 START LESSON</button> <div id="status" class="status"></div> <div id="controls" class="controls" style="display: none;"> <button id="muteBtn">🔇 Mute</button> <button id="endBtn">📞 End Call</button> </div> <div class="panel"> <div class="panel-header"> <div> <h2>Connection check</h2> <p class="muted"> Confirm the page is wired up by playing a test chime and watching the connectivity log. </p> </div> <div class="badge">New</div> </div> <div class="inline-actions"> <button id="soundTestBtn" type="button">🔔 Play test chime</button> </div> <div id="pingStatus" class="micro-copy">Tap the button to verify your speakers.</div> <div class="log-window" id="diagnosticsLog"> <div class="log-entry">Waiting for events...</div> </div> </div> <div class="panel"> <div class="panel-header"> <div> <h2>Transcript monitor</h2> <p class="muted">Shows who is speaking and any messages sent by the agent.</p> </div> <div class="badge ghost">Live</div> </div> <div class="log-window transcript" id="transcriptLog"> <div class="transcript-line neutral">Waiting for conversation...</div> </div> </div> </div> <script src="app.js"></script> </body> </html>
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!