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 — thanks for reaching out! How can I help you today? If you’re unsure where to start, you can tell me: • whether you’re integrating LiveKit into a web/mobile app or using our dashboard, • any error messages or unexpected behavior you’re seeing, • or what feature you want to implement (rooms, recordings, signaling, SDK questions, etc.). Pick one and I’ll guide you next.
m
can you help fix this code ? agent crashes > const { AccessToken, RoomServiceClient } = require('livekit-server-sdk'); /** * Generate LiveKit access token and create room with agent job * POST /api/connect _* Body: { scenario, level, voice_provider, voice }_ */ module.exports = async (req, res) => { // Set CORS headers 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; } if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }); } try { const { scenario, level, voice_provider, voice } = req.body; // Get LiveKit credentials from environment variables 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; if (!LIVEKIT_URL || !LIVEKIT_API_KEY || !LIVEKIT_API_SECRET) { return res.status(500).json({ error: 'LiveKit credentials not configured. Please set LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET environment variables.', }); } // Generate a unique room name const roomName = `english-teacher-${Date.now()}-${Math.random().toString(36).substring(7)}`; // Prepare metadata for the agent const metadata = { scenario: scenario || 'taxi', level: level || 'basic', voice_provider: voice_provider || 'livekit', voice: voice || 'default', }; // Create room service client const roomService = new RoomServiceClient( LIVEKIT_URL.replace('ws://', 'http://').replace('wss://', 'https://'), LIVEKIT_API_KEY, LIVEKIT_API_SECRET ); // Create room with metadata // Set emptyTimeout to 2 minutes (120 seconds) to save costs // Room will auto-close if no participants join within 2 minutes await roomService.createRoom({ name: roomName, emptyTimeout: 120, // 2 minutes - auto-close if empty maxParticipants: 2, metadata: JSON.stringify(metadata), }); // Create access token for user const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, { identity:
user-${Date.now()}
, name: 'English Teacher Student', }); // Grant permissions const grant = { room: roomName, roomJoin: true, canPublish: true, canSubscribe: true, canPublishData: true, // Add agent dispatch configuration for LiveKit Cloud // This tells LiveKit to automatically dispatch the agent when a participant joins roomConfig: { agents: [ { agentName: 'CA_4T2cvqbL6JwH', // Agent ID from livekit.toml }, ], }, }; at.addGrant(grant); const token = await at.toJwt(); // Return token and WebSocket URL res.status(200).json({ token, url: LIVEKIT_URL.replace('http://', 'ws://').replace('https://', 'wss://'), room: roomName, }); } catch (error) { console.error('Error generating token:', error); res.status(500).json({ error: 'Failed to generate access token', message: error.message, }); } }; Key changes: • Lines 72-89: Added roomConfig.agents to the grant to dispatch agent CA_4T2cvqbL6JwH when a participant joins. This should dispatch the agent when a user connects. The agent still needs to be fixed (it's crashing), but the dispatch configuration is in place.
t
Thanks — I reviewed your code and the likely cause is that
roomConfig
was added inside the grant object. That usage is incorrect and can cause token validation or dispatch issues that may lead to the agent crashing. I can help fix this. A few questions so I give the exact patch and next steps: 1. Do you want the minimal fix that moves
roomConfig
onto the AccessToken (recommended), or do you want a full cleaned-up endpoint with better error logging included? 2. Can you share the agent crash logs or the agent entrypoint code (or the crash error message)? That will tell us whether the token was malformed or the agent code itself is failing at runtime. If you want the quick fix now: move the
roomConfig
out of the grant and set it on the
AccessToken
instance, e.g. • keep the grant as the room/video grant (roomJoin, canPublish, etc.), then • set
at.roomConfig = { agents: [{ agentName: 'CA_4T2cvqbL6JwH' }] }
before
await at.toJwt()
. Tell me which option you prefer and share any agent logs or error text and I’ll provide the patched code and debugging steps. Sources: Authentication | LiveKit docs | Agent dispatch | LiveKit docs | Agent deployment CLI reference | LiveKit docs
m
share a complete file for best practice in your opiniion :
t
Below is a complete, production-ready Node.js endpoint file (CommonJS) that generates a LiveKit access token, creates a room, and correctly configures agent dispatch. It includes CORS handling, input validation, structured error logging, and recommended practices (separating grants from
roomConfig
, sensible defaults, and improved diagnostics). Save as e.g. api/connect.js and adapt environment variable names and logging to your needs.
Copy code
const { AccessToken, RoomServiceClient } = require('livekit-server-sdk');

/**
 * POST /api/connect
 * Body: { scenario, level, voice_provider, voice }
 *
 * Best-practice endpoint:
 * - Validates input and required env vars
 * - Creates a room with metadata via RoomServiceClient
 * - Builds a proper AccessToken with Video grant
 * - Applies `roomConfig` on the AccessToken (not inside the grant) to dispatch agents
 * - Returns token, room name, and ws url
 */

const requiredEnv = ['LIVEKIT_URL', 'LIVEKIT_API_KEY', 'LIVEKIT_API_SECRET'];

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

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

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

module.exports = async function handler(req, res) {
  // Basic CORS — adjust allowed origins in production
  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;
  }

  if (req.method !== 'POST') {
    res.status(405).json({ error: 'Method not allowed' });
    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;

    // Validate and parse JSON body
    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';

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

    // Create RoomServiceClient (use HTTP(S) admin endpoint)
    const adminUrl = normalizeLiveKitServiceUrl(LIVEKIT_URL);
    const roomService = new RoomServiceClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);

    // Create or ensure room exists. createRoom will fail if room exists by default; handle gracefully.
    try {
      await roomService.createRoom({
        name: roomName,
        emptyTimeout: 120, // auto-close if no participants within 2 minutes
        maxParticipants: 2,
        metadata: JSON.stringify(metadata),
      });
    } catch (err) {
      // If server responds that room already exists (unlikely with unique name) or transient error, log and continue or rethrow.
      // Keep the error for diagnostics but do not expose internal details to clients.
      console.warn('createRoom warning:', err.message || err.toString());
      // If you want to fail on createRoom error, uncomment next line:
      // throw err;
    }

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

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

    // Correct placement of roomConfig for agent dispatch:
    // Set the roomConfig on the AccessToken instance (top-level), not inside the grant.
    // Adjust agentName to your agent ID. You can also pass additional job metadata here if needed.
    at.roomConfig = {
      agents: [
        {
          agentName: 'CA_4T2cvqbL6JwH',
          // optional agentJobOverride: { ... } // if agent supports extra configuration
        },
      ],
    };

    // Optional: set token TTL (default may be short). TTLs are seconds.
    // Example: valid for 10 minutes
    at.ttl = 60 * 10;

    const token = await at.toJwt();

    res.status(200).json({
      token,
      url: wsUrlFromHttp(LIVEKIT_URL),
      room: roomName,
      metadata,
    });
  } catch (error) {
    // Log full error server-side for debugging, but return limited info to client
    console.error('Error in /api/connect:', error);
    res.status(500).json({
      error: 'Failed to generate access token or create room',
      message: error && error.message ? error.message : String(error),
    });
  }
};
Notes and best-practice tips: • Keep
roomConfig
on the AccessToken instance (not inside the grant). • Add robust logging on your agent side; check agent logs if dispatch still fails. • Use secure CORS in production — avoid wildcard origin. • Consider validating the agent ID exists and the agent is healthy (via your agent management tooling) before dispatching. • Short token TTL reduces risk if tokens leak; refresh tokens server-side when needed. If you want, I can: • Add TypeScript typings and an Express-compatible version. • Add example unit tests for this endpoint. • Help review the agent entrypoint if you paste the crashing code or logs.
m
yes share anything which may help :
anything esle ?
t
Great — here are concise, high-value items that will help prevent agent crashes and speed debugging. Pick which you want next and I’ll supply code or examples. 1) Quick checklist to prevent crashes • Ensure
roomConfig
is set on the AccessToken (not inside the grant). • Confirm agent ID exactly matches the agent registration (
agentName
). • Verify environment vars (API key/secret, LIVEKIT_URL) in both token server and agent. • Set short, appropriate token TTL and avoid leaking secrets. • Add robust try/catch and logging around agent entrypoint and async calls. • Validate and safely parse job metadata before use. 2) Agent-side best practices • Wrap main job handler in a top-level try/catch and log stack traces. • Validate
ctx.job
and
ctx.job.metadata
before accessing fields. • Wait for participant/media readiness (tracks, connections) before processing. • Protect external calls (LLM/TTS/STT) with timeouts and retries. • Gracefully handle unimplemented/unsupported job fields and return clear job errors. 3) Quick debugging actions to run now • Inspect agent deploy/start logs (startup errors, missing deps). • Re-run and capture the agent crash stack trace. • Test token with a simple client to confirm agent dispatch (no media): create token, join room, see agent logs for incoming job. • Try a minimal agent that just logs job metadata to confirm dispatch works. 4) Useful snippets I can provide (tell me which) • Hardened Node.js token endpoint (Express + TypeScript) — full file. • Minimal agent entrypoint that safely parses metadata and logs (Python or Node). • Example: safe job metadata parsing with validation. • Example: how to tail agent deploy logs and interpret common errors. 5) If you want I can: • Patch your exact endpoint file (I’ll return a single complete file). • Review agent entrypoint code or crash logs (paste them). • Provide an Express/TS or minimal Python agent example to replicate locally. Which of the above would you like next?
m
[App] Start button clicked app.js:119 [App] Fetching /api/connect... app.js:132 [App] Received API response: {token: 'eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFja…zMCJ9.HFB_8HRb7CbrF4Qn3ynCYA0UdUTOHeEjU1zZ-PRkCnY', url: 'wss://englishlive-3qjapr2j.livekit.cloud', room: 'english-teacher-1764708103128-bcac96j', metadata: {…}} app.js:141 [App] Checking for LiveKit: {window.LiveKit: 'object', window.LiveKitClient: 'object', window.LivekitClient: 'object', window.livekit: 'undefined'} app.js:155 [App] Connecting to LiveKit room... utils.ts:178 WebSocket connection to 'wss://englishlive-3qjapr2j.livekit.cloud/rtc?access_token=eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFjaGVyIFN0dWRlbnQiLCJ2aWRlbyI6eyJyb29tIjoiZW5nbGlzaC10ZWFjaGVyLTE3NjQ3MDgxMDMxMjgtYmNhYzk2aiIsInJvb21Kb2luIjp0cnVlLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwicm9vbUNvbmZpZyI6eyJhZ2VudHMiOlt7ImFnZW50TmFtZSI6IkNBXzRUMmN2cWJMNkp3SCJ9XX0sImlzcyI6IkFQSUxGSzY0V3JWTmVXTCIsImV4cCI6NjAwLCJuYmYiOjAsInN1YiI6InVzZXItMTc2NDcwODEwMzUzMCJ9.HFB_8HRb7CbrF4Qn3ynCYA0UdUTOHeEjU1zZ-PRkCnY&auto_subscribe=1&sdk=js&version=1.15.0&protocol=10' failed: (anonymous) @ utils.ts:178 (anonymous) @ utils.ts:178 Tt @ utils.ts:178 (anonymous) @ utils.ts:178 connect @ utils.ts:178 (anonymous) @ utils.ts:178 (anonymous) @ utils.ts:178 Tt @ utils.ts:178 join @ utils.ts:178 (anonymous) @ utils.ts:178 (anonymous) @ utils.ts:178 Tt @ utils.ts:178 join @ utils.ts:178 (anonymous) @ utils.ts:178 (anonymous) @ utils.ts:178 Tt @ utils.ts:178 Lo.connectSignal @ utils.ts:178 (anonymous) @ utils.ts:178 (anonymous) @ utils.ts:178 Tt @ utils.ts:178 Lo.attemptConnection @ utils.ts:178 (anonymous) @ utils.ts:178 (anonymous) @ utils.ts:178 Tt @ utils.ts:178 o @ utils.ts:178 (anonymous) @ utils.ts:178 (anonymous) @ utils.ts:178 (anonymous) @ utils.ts:178 Tt @ utils.ts:178 (anonymous) @ utils.ts:178 Hr @ utils.ts:178 (anonymous) @ utils.ts:178 o @ utils.ts:178Understand this error utils.ts:178 websocket closed {ev: CloseEvent} Tt.ws.onclose @ utils.ts:178Understand this warning utils.ts:178 GET https://englishlive-3qjapr2j.livekit.cloud/rtc/validate?access_token=eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFjaGVyIFN0dWRlbnQiLCJ2aWRlbyI6eyJyb29tIjoiZW5nbGlzaC10ZWFjaGVyLTE3NjQ3MDgxMDMxMjgtYmNhYzk2aiIsInJvb21Kb2luIjp0cnVlLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwicm9vbUNvbmZpZyI6eyJhZ2VudHMiOlt7ImFnZW50TmFtZSI6IkNBXzRUMmN2cWJMNkp3SCJ9XX0sImlzcyI6IkFQSUxGSzY0V3JWTmVXTCIsImV4cCI6NjAwLCJuYmYiOjAsInN1YiI6InVzZXItMTc2NDcwODEwMzUzMCJ9.HFB_8HRb7CbrF4Qn3ynCYA0UdUTOHeEjU1zZ-PRkCnY&auto_subscribe=1&sdk=js&version=1.15.0&protocol=10 401 (Unauthorized) (anonymous) @ utils.ts:178 (anonymous) @ utils.ts:178 Tt @ utils.ts:178 Tt.ws.onerror @ utils.ts:178Understand this error utils.ts:178 GET https://englishlive-3qjapr2j.livekit.cloud/settings/regions 401 (Unauthorized) (anonymous) @ utils.ts:178 (anonymous) @ utils.ts:178 Tt @ utils.ts:178 fetchRegionSettings @ utils.ts:178 (anonymous) @ utils.ts:178 o @ utils.ts:178 Promise.then c @ utils.ts:178 (anonymous) @ utils.ts:178 Tt @ utils.ts:178 Lo.connect @ utils.ts:178 (anonymous) @ app.js:189Understand this error utils.ts:178 could not fetch region settings {error: xn: Could not fetch region settings: at Ys.<anonymous> (https://cdn.jsdelivr.net/npm/livekit-c…} (anonymous) @ utils.ts:178 Promise.catch (anonymous) @ utils.ts:178 o @ utils.ts:178 Promise.then c @ utils.ts:178 (anonymous) @ utils.ts:178 Tt @ utils.ts:178 Lo.connect @ utils.ts:178 (anonymous) @ app.js:189Understand this warning app.js:165 [App] Room disconnected: undefined app.js:192 [App] Error connecting to room: xn: could not establish signal connection: invalid token: eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFjaGVyIFN0dWRlbnQiLCJ2aWRlbyI6eyJyb29tIjoiZW5nbGlzaC10ZWFjaGVyLTE3NjQ3MDgxMDMxMjgtYmNhYzk2aiIsInJvb21Kb2luIjp0cnVlLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwicm9vbUNvbmZpZyI6eyJhZ2VudHMiOlt7ImFnZW50TmFtZSI6IkNBXzRUMmN2cWJMNkp3SCJ9XX0sImlzcyI6IkFQSUxGSzY0V3JWTmVXTCIsImV4cCI6NjAwLCJuYmYiOjAsInN1YiI6InVzZXItMTc2NDcwODEwMzUzMCJ9.HFB_8HRb7CbrF4Qn3ynCYA0UdUTOHeEjU1zZ-PRkCnY, error: go-jose/go-jose/jwt: validation failed, token is expired (exp) at Lo.<anonymous> (utils.ts1781) at Generator.next (<anonymous>) at o (utils.ts1781) (anonymous) @ app.js:192Understand this error app.js:268 LiveKit detected, initializing app... app.js:40 App already initialized, skipping...
t
You're seeing two related problems: the client can't establish the WebSocket signal connection because the token is invalid/expired (401 + "token is expired"), and that prevents the room connect/agent dispatch — which can look like the agent "crashing" because it never receives a valid job. Here's a concise plan and targeted fixes. What the logs show • The client received a token and tried to open wss://.../rtc?access_token=... but the connection closed and the validate endpoint returned 401 Unauthorized. • The final error: "token is expired (exp)". The token's exp is already past when the client attempts to use it. Immediate fixes to try 1. Ensure server clock is correct ◦ Sync NTP/time on the machine generating tokens. JWT exp checks fail if server time is ahead/behind. 1. Set a reasonable token TTL when creating the AccessToken ◦ Example: set TTL to 10 minutes (600 seconds) or appropriate for your flow. In the AccessToken object set
ttl
(seconds) or set expiry when creating the token. ◦ Short TTL is good for security, but must be long enough to complete client flow. 1. Verify token generation flow ◦ Make sure you call
await at.toJwt()
after adding grants and setting
at.roomConfig
. ◦ Confirm you are not accidentally creating a token earlier and returning a stale value. 1. Confirm LIVEKIT_URL usage ◦ Use the HTTP(S) admin URL for RoomServiceClient and return the WS(S) URL to clients. ◦ The token must be issued with the same project/keys that the LiveKit host expects. 1. Recreate token and retry immediately from the client ◦ Generate a fresh token, then join within the token TTL to confirm validation succeeds. Agent / crash follow-ups • If agent still appears to crash after token issues are resolved: ◦ Share the agent logs (startup and job logs). Look for uncaught exceptions in the agent entrypoint. ◦ Add top-level try/catch in the agent job handler and log the full stack trace. ◦ Start with a minimal agent that just logs received
ctx.job.metadata
to confirm dispatch works. Debugging steps to run now (in order) 1. On the token server: log
Date.now()
and the token payload `exp`/`iat` right after
toJwt()
to confirm expiry. 2. Sync server time (ntp) if timestamps are off. 3. Generate a token with
ttl = 600
, immediately paste it into a client or curl the validate endpoint: ◦ GET https://<your-host>/rtc/validate?access_token=<token> ◦ Expect 200. If 401, inspect token
exp
vs server time. 1. If validate succeeds and client still fails, share the validate response and agent logs. If helpful, I can: • Post a single patched token endpoint file (Express/CommonJS or TypeScript) that sets TTL and logs iat/exp. • Show a minimal agent entrypoint that safely logs job metadata for verifying dispatch. Which would you like me to share next?
m
can you share fixing patch ?
t
Below is a ready-to-drop-in CommonJS Node.js endpoint that fixes the token expiry issue, places
roomConfig
on the AccessToken (not inside the grant), logs token timestamps, and includes safer error handling and sensible defaults. Save as e.g. api/connect.js and adapt env vars/agentName as needed.
Copy code
const { AccessToken, 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://');
}

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

module.exports = async function handler(req, res) {
  // Basic CORS - lock this down in production
  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;
  }
  if (req.method !== 'POST') {
    res.status(405).json({ error: 'Method not allowed' });
    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 };

    // Create RoomServiceClient (admin API uses HTTP(S))
    const adminUrl = adminUrlFromLivekit(LIVEKIT_URL);
    const roomService = new RoomServiceClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);

    // Create room (ignore if fails due to race/exists)
    try {
      await roomService.createRoom({
        name: roomName,
        emptyTimeout: 120,
        maxParticipants: 2,
        metadata: JSON.stringify(metadata),
      });
    } 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);
    }

    // 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, ... })
        },
      ],
    };

    const token = await at.toJwt();

    // Decode times for quick debugging (iat/exp are in seconds since epoch)
    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;
      console.info('Generated token iat:', iat, 'exp:', exp, 'now(s):', Math.floor(Date.now() / 1000));
    } 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,
    });
  } 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),
    });
  }
};
Small notes: • Set AGENT_NAME via env var if you want to change agent without code edits. • If you still see "token expired", verify system time on the token server (NTP sync) and that the client uses the returned token right away. • If you want, I can also provide an Express/TypeScript variant or a tiny script to validate tokens via the validate endpoint.
m
now LK cloud agent not joining ? (index):68 [LiveKit Loader] Script execution started (index):69 [LiveKit Loader] Document ready state: loading (index):73 [LiveKit Loader] Creating script element... (index):78 [LiveKit Loader] Script src set to: https://cdn.jsdelivr.net/npm/livekit-client@1.15.0/dist/livekit-client.umd.min.js (index):138 [LiveKit Loader] Appending script to document.head... (index):140 [LiveKit Loader] Script appended, waiting for load... app.js:4 [App] Script execution started app.js:5 [App] Document ready state: interactive app.js:315 [App] DOM already loaded app.js:318 [App] LiveKit not ready, setting up event listeners... (index):81 [LiveKit Loader] Script onload fired (index):86 [LiveKit Loader] Checking for window.LiveKit: undefined (index):87 [LiveKit Loader] Checking for window.LivekitClient: object (index):88 [LiveKit Loader] Checking for window.livekit: undefined (index):97 [LiveKit Loader] Found LivekitClient (lowercase k) (index):109 [LiveKit Loader] LiveKit client loaded successfully, aliases set app.js:321 [App] Received livekit-ready event Object app.js:49 Using window.LiveKit (index):114 [LiveKit Loader] Dispatched livekit-ready event app.js:109 [App] Start button clicked app.js:119 [App] Fetching /api/connect... app.js:132 [App] Received API response: Object app.js:141 [App] Checking for LiveKit: Object app.js:155 [App] Connecting to LiveKit room... app.js:160 [App] Room connected successfully app.js:190 [App] Room connect() completed app.js:200 [App] Checking microphone permission... app.js:205 [App] Microphone permission granted app.js:213 [App] Enabling microphone in LiveKit room... utils.ts:178 publishing track Object app.js:185 [App] Local track published: audio app.js:215 [App] Microphone enabled successfully app.js:268 LiveKit detected, initializing app... app.js:40 App already initialized, skipping... initApp @ app.js:40Understand this warning utils.ts:178 disconnect from room {identity: 'user-1764708463668'} app.js:165 [App] Room disconnected: 1
t
Thanks — you’re past the token/expiry step, so let’s focus on why the LiveKit Cloud agent isn’t joining. I’ll list quick checks and targeted actions you can run now. If you want, paste agent logs or your agent entrypoint and I’ll review them next. 1) Confirm token contains roomConfig • Immediately after creating the token, decode the JWT payload and confirm
roomConfig.agents
exists and contains the correct
agentName
. • You already log iat/exp — also log the decoded
roomConfig
to be sure it was embedded. 2) Verify agentName exact match • Ensure the agent ID in
at.roomConfig.agents[0].agentName
exactly matches the agent registration (case-sensitive). • If you use an env var, confirm it’s correct in the deployed token server. 3) Check LiveKit Cloud agent health • In LiveKit Cloud UI (Agents/Deploys) confirm the agent is deployed, healthy, and not in crash/restart loop. • If the UI shows it offline, the agent cannot join regardless of token. 4) Inspect agent startup & job logs • Tail agent deploy & session logs. Look for inbound job events or errors like missing env, dependency failures, uncaught exceptions. • If the agent never logs a received job, dispatch didn’t reach it (token/dispatch or control-plane issue). 5) Validate dispatch reached control plane • On token server, after room creation and token generation, call the validate endpoint: GET https://<LIVEKIT_HOST>/rtc/validate?access_token=<token> • Expect 200 and confirm response includes roomConfig (if available) or no errors. • If validate returns 200 but agent still doesn’t receive job, the control plane likely tried dispatch and agent failed during startup — check agent logs. 6) Confirm participant join timing • Agents dispatch when a participant joins the room. Ensure your client truly establishes the room connection (your logs show connect + publish then immediate disconnect). That disconnect may be too fast for dispatch. • Keep the client in the room for a short time (10–30s) to allow agent startup. 7) Look for immediate disconnect causes (client side) • Your logs show: "Room connected successfully" followed shortly by "Room disconnected". Check: ◦ Token TTL/clock skew (you already fixed TTL; confirm client system time). ◦ Network issues causing quick disconnect. ◦ Client code calling room.disconnect() or page navigation. • If client disconnects before agent startup, agent won’t join. 8) Add minimal agent job handler for testing • Deploy a tiny agent that only logs receipt of job metadata and immediately returns OK. This isolates dispatch from your full agent logic. • If the minimal agent receives jobs, the issue is in your main agent code. 9) Increase observability temporarily • Add extra logging on token server (log returned token roomConfig), agent (log every lifecycle event), and client (log full room state events). • Consider increasing token TTL during debugging to rule out timing issues. If you want, I can: • Provide a minimal agent entrypoint (Python or Node) that logs job receipt. • Patch your token endpoint to also return the decoded token payload (for debugging). • Review agent logs or your agent entrypoint if you paste them. Which do you want next? Paste agent logs (startup + session) or I’ll send a minimal agent example.
m
share a minimla example
t
Below is a minimal Python LiveKit agent entrypoint you can deploy to verify dispatch. It logs job receipt, job metadata, and lifecycle events, then quickly returns success. Use this to confirm the control plane is dispatching jobs to your agent. Save as agent.py (requires livekit-agents package and Python 3.8+):
Copy code
import json
import logging
import os
import sys
from livekit_agents import AgentServer, JobContext, JobResult

logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("minimal-agent")

AGENT_NAME = os.getenv("AGENT_NAME", "minimal-test-agent")
LISTEN_ADDR = os.getenv("AGENT_LISTEN_ADDR", "0.0.0.0")
LISTEN_PORT = int(os.getenv("AGENT_LISTEN_PORT", "8080"))

server = AgentServer(agent_name=AGENT_NAME, host=LISTEN_ADDR, port=LISTEN_PORT)

@server.rtc_session()
async def handle_job(ctx: JobContext) -> JobResult:
    try:
        logger.info("=== Received job ===")
        logger.info("job id: %s", getattr(ctx.job, "id", None))
        logger.info("room: %s", getattr(ctx.job, "room", None))
        # job.metadata may be a JSON string or dict depending on SDK usage
        raw_meta = getattr(ctx.job, "metadata", None)
        meta = {}
        if raw_meta:
            try:
                if isinstance(raw_meta, str):
                    meta = json.loads(raw_meta)
                else:
                    meta = raw_meta
            except Exception as e:
                logger.warning("failed to parse job.metadata: %s", e)
                meta = {"raw": str(raw_meta)}
        logger.info("job.metadata: %s", json.dumps(meta))

        # Log participant list if available
        try:
            participants = [p.identity for p in ctx.room.participants.values()] if ctx.room else []
            logger.info("participants at job start: %s", participants)
        except Exception as e:
            logger.warning("could not list participants: %s", e)

        # Minimal behavior: wait a short time to simulate startup, then succeed
        import asyncio
        await asyncio.sleep(1)

        logger.info("Job processed successfully, returning OK")
        return JobResult(success=True, detail="minimal agent OK")
    except Exception:
        logger.exception("Unhandled error in job handler")
        return JobResult(success=False, detail="handler error")

if __name__ == "__main__":
    logger.info("Starting minimal-test-agent: %s", AGENT_NAME)
    # If the agent framework supports a run() method:
    server.run()
Deployment & test tips • Set AGENT_NAME to match the
agentName
you use in
at.roomConfig.agents
. • Start this agent and ensure it's healthy in LiveKit Cloud. • Generate a token with
roomConfig
referencing that AGENT_NAME, join the room as a client, and keep the client connected for 10–30s. • Watch agent logs for the "Received job" messages. If you see them, dispatch works and the problem is in your full agent logic. • If no job arrives, check: agent health in UI, token payload contains roomConfig, and client stayed connected long enough. If you want, I can also provide a Node.js minimal agent example or a one-file Dockerfile to run this agent.
m
pls share diocker file
t
Below is a simple Docker setup to run the minimal Python agent I shared earlier. 1) Dockerfile
Copy code
FROM python:3.10-slim

# Install runtime deps
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy requirements and app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY agent.py .

# Expose default agent port (if used by AgentServer)
EXPOSE 8080

# Run the agent (adjust AGENT_NAME via env at run time)
CMD ["python", "agent.py"]
2) requirements.txt
Copy code
livekit-agents
livekit
3) Build and run • Build: docker build -t minimal-livekit-agent:latest . • Run (example): docker run --rm -e AGENT_NAME=minimal-test-agent \ -e AGENT_LISTEN_ADDR=0.0.0.0 -e AGENT_LISTEN_PORT=8080 \ -e LIVEKIT_API_KEY=your_key -e LIVEKIT_API_SECRET=your_secret \ -e LIVEKIT_URL=wss://your-livekit-host \ -p 8080:8080 minimal-livekit-agent:latest 4) Notes • Ensure
AGENT_NAME
matches the
agentName
used in
at.roomConfig
. • Provide LIVEKIT credentials and LIVEKIT_URL matching your project. • If your agent needs other libs (LLM/TTS/STT), add them to requirements.txt and adjust Dockerfile (watch image size). • Check container logs with
docker logs <container_id>
to see startup and job logs. • For production, use a smaller base image, pin package versions, and add healthchecks and restart policy.
m
[App] Microphone permission granted app.js:213 [App] Enabling microphone in LiveKit room... utils.ts:178 publishing track {localTrack: $s} app.js:268 LiveKit detected, initializing app... app.js:40 App already initialized, skipping... initApp @ app.js:40 tryInit @ app.js:269 (anonymous) @ app.js:342 setTimeout (anonymous) @ app.js:341 (anonymous) @ app.js:352Understand this warning app.js:185 [App] Local track published: audio app.js:215 [App] Microphone enabled successfully utils.ts:178 disconnect from room {identity: 'user-1764709178943'} app.js:165 [App] Room disconnected: 1 app.js:109 [App] Start button clicked app.js:119 [App] Fetching /api/connect... app.js:132 [App] Received API response: {token: 'eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFja…TgifQ.6v3H1GJoHwkQHev-jxWHoS8GaFDZFSdO9HMJ0vGTpe0', url: 'wss://englishlive-3qjapr2j.livekit.cloud', room: 'english-teacher-1764709221482-7hiz2vz', metadata: {…}} app.js:141 [App] Checking for LiveKit: {window.LiveKit: 'object', window.LiveKitClient: 'object', window.LivekitClient: 'object', window.livekit: 'undefined'} app.js:155 [App] Connecting to LiveKit room... app.js:160 [App] Room connected successfully app.js:190 [App] Room connect() completed app.js:200 [App] Checking microphone permission... app.js:205 [App] Microphone permission granted app.js:213 [App] Enabling microphone in LiveKit room... utils.ts:178 publishing track {localTrack: $s} app.js:185 [App] Local track published: audio app.js:215 [App] Microphone enabled successfully utils.ts:178 disconnect from room {identity: 'user-1764709221698'} app.js:165 [App] Room disconnected: 1
any ideas ?
t
Thanks — quick targeted steps to diagnose and fix the immediate disconnect (client connects, publishes, then disconnects quickly). Do these in order and tell me results or paste logs you see. 1) Confirm client isn’t disconnecting itself • Search your client code for any explicit
room.disconnect()
calls or navigation/unmount that runs after publish. Temporarily disable automatic disconnects and keep the client in the room for 20–30s. 2) Check token lifetime & clock skew one more time • Right after you call
toJwt()
log decoded
iat
and
exp
(seconds) and compare to server time:
Math.floor(Date.now()/1000)
. • If exp ≤ now, tokens will be rejected mid-flow. 3) Ensure client stays connected long enough for agent to start • Agents can take a few seconds to boot. Keep client connected 30s while testing. 4) Verify roomConfig actually reached LiveKit • Decode the returned token in your token server and log
roomConfig
before returning token. Ensure
agents: [{ agentName: "<exact-id>" }]
is present. 5) Confirm agent is healthy and deployed • Use your agent UI/CLI to confirm the agent is Active and not restarting. • Tail agent logs; look for incoming job logs. If nothing appears, dispatch didn’t reach the agent. 6) Run the minimal agent in Docker you deployed • Start the minimal agent container you built and watch logs for "Received job" messages when a client joins that room. • If minimal agent receives jobs, the issue is in your full agent code. 7) Check server-side room emptyTimeout and autoscaling • If room auto-closes too fast (emptyTimeout) or LiveKit Cloud scales down quickly, a brief disconnect can happen. Use longer emptyTimeout during debugging. 8) Inspect disconnect reason on client • Capture
room.on('disconnected', (reason) => console.log(reason))
and
room.on('connectionStateChanged')
events. Share those events if they show an error message or code. 9) Network and CORS checks • Ensure WebSocket and validate endpoints are reachable from client and not blocked by proxies/firewalls. • If using WSS, confirm TLS certs are valid and client time is correct. If you want, I can: • Patch your token endpoint to return the decoded payload (including roomConfig/iat/exp) for debugging. • Provide a tiny client script that connects, logs lifecycle events, and stays connected for 30s. • Review agent logs if you paste the startup/session output. Which would you like next?
m
• share this Pls: Patch your token endpoint to return the decoded payload (including roomConfig/iat/exp) for debugging. • Provide a tiny client script that connects, logs lifecycle events, and stays connected for 30s.
t
Below are two ready-to-use files. 1) Token endpoint patch (CommonJS) — returns decoded JWT payload (including
roomConfig
,
iat
,
exp
) for debugging. Save as api/connect-debug.js and use in place of your current endpoint.
Copy code
const { AccessToken, 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();
    return;
  }
  if (req.method !== 'POST') {
    res.status(405).json({ error: 'Method not allowed' });
    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 adminUrl = adminUrlFromLivekit(LIVEKIT_URL);
    const roomService = new RoomServiceClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);

    try {
      await roomService.createRoom({
        name: roomName,
        emptyTimeout: 120,
        maxParticipants: 2,
        metadata: JSON.stringify(metadata),
      });
    } catch (err) {
      console.warn('createRoom warning:', err && err.message ? err.message : err);
    }

    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,
        },
      ],
    };

    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,
      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: • Use this only for debugging. Remove the
token_debug
field in production (it exposes token internals). • Ensure server clock is synced (NTP) so
iat/exp
align with client. 2) Tiny client script (browser JS) — fetches token, connects with livekit-client, logs lifecycle events, publishes mic (if allowed), and stays connected ~30s before disconnect. Use in a page that includes livekit-client UMD (or adjust imports). Save as debug-client.js:
Copy code
// debug-client.js
// Assumes livekit-client is loaded as window.LiveKit (UMD) or adjust imports for module usage.

(async function () {
  const API_PATH = '/api/connect-debug'; // your debug endpoint
  const STAY_MS = 30000; // stay connected for 30s

  function log(...args) { console.log('[DebugClient]', ...args); }

  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;
    }

    // Log decoded token debug if present
    if (data.token_debug) {
      log('Decoded token payload:', data.token_debug);
    }

    // Create room and connect
    const { Room, ConnectOptions } = window.LiveKit;
    const room = new Room();

    room.on('stateChanged', (state) => log('room stateChanged', state));
    room.on('disconnected', (reason) => log('room disconnected', reason));
    room.on('participantConnected', (p) => log('participantConnected', p.identity));
    room.on('participantDisconnected', (p) => log('participantDisconnected', p.identity));
    room.on('trackPublished', (publication, participant) => log('trackPublished', publication.trackName, participant?.identity));
    room.on('trackSubscribed', (track, publication, participant) => log('trackSubscribed', track.kind, participant?.identity));
    room.on('connectionQualityChanged', (quality, participant) => log('connectionQualityChanged', quality, participant?.identity));

    log('Connecting to', url);
    await room.connect(url, token, { autoSubscribe: true });

    log('Connected. Local participant identity:', room.localParticipant?.identity);
    // Try to publish mic if available
    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 && err.message ? err.message : err);
    }

    // Keep connection open for STAY_MS then disconnect
    log(`Staying connected for ${STAY_MS}ms`);
    await new Promise((r) => setTimeout(r, STAY_MS));

    log('Disconnecting now');
    room.disconnect();
    log('Disconnected (done)');
  } catch (err) {
    log('Unexpected error:', err && err.stack ? err.stack : err);
  }
})();
How to use • Run your token server with the debug endpoint (ensure LIVEKIT envs set). • Host debug-client.js in a simple HTML page that loads livekit-client UMD (use same version you use in app, e.g. 1.15.0). • Open the page in browser, allow microphone, and watch console for logs: token_debug, connect lifecycle events,
participantConnected
, and any errors. • Keep the browser open for ~30s to allow agent dispatch and startup. If you want, I can: • Provide an HTML test page that includes the UMD script and this client script. • Patch your production endpoint to include optional debug flag (returns token_debug only when enabled). Which would you like next?
m
yes pls : 1) Token endpoint patch (CommonJS) — returns decoded JWT payload (including
roomConfig
,
iat
,
exp
) for debugging. Save as api/connect-debug.js and use in place of your current endpoint.
Copy code
const { AccessToken, 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();
    return;
  }
  if (req.method !== 'POST') {
    res.status(405).json({ error: 'Method not allowed' });
    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 adminUrl = adminUrlFromLivekit(LIVEKIT_URL);
    const roomService = new RoomServiceClient(adminUrl, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);

    try {
      await roomService.createRoom({
        name: roomName,
        emptyTimeout: 120,
        maxParticipants: 2,
        metadata: JSON.stringify(metadata),
      });
    } catch (err) {
      console.warn('createRoom warning:', err && err.message ? err.message : err);
    }

    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,
        },
      ],
    };

    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,
      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: • Use this only for debugging. Remove the
token_debug
field in production (it exposes token internals). • Ensure server clock is synced (NTP) so
iat/exp
align with client. 2) Tiny client script (browser JS) — fetches token, connects with livekit-client, logs lifecycle events, publishes mic (if allowed), and stays connected ~30s before disconnect. Use in a page that includes livekit-client UMD (or adjust imports). Save as debug-client.js:
Copy code
// debug-client.js
// Assumes livekit-client is loaded as window.LiveKit (UMD) or adjust imports for module usage.

(async function () {
  const API_PATH = '/api/connect-debug'; // your debug endpoint
  const STAY_MS = 30000; // stay connected for 30s

  function log(...args) { console.log('[DebugClient]', ...args); }

  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;
    }

    // Log decoded token debug if present
    if (data.token_debug) {
      log('Decoded token payload:', data.token_debug);
    }

    // Create room and connect
    const { Room, ConnectOptions } = window.LiveKit;
    const room = new Room();

    room.on('stateChanged', (state) => log('room stateChanged', state));
    room.on('disconnected', (reason) => log('room disconnected', reason));
    room.on('participantConnected', (p) => log('participantConnected', p.identity));
    room.on('participantDisconnected', (p) => log('participantDisconnected', p.identity));
    room.on('trackPublished', (publication, participant) => log('trackPublished', publication.trackName, participant?.identity));
    room.on('trackSubscribed', (track, publication, participant) => log('trackSubscribed', track.kind, participant?.identity));
    room.on('connectionQualityChanged', (quality, participant) => log('connectionQualityChanged', quality, participant?.identity));

    log('Connecting to', url);
    await room.connect(url, token, { autoSubscribe: true });

    log('Connected. Local participant identity:', room.localParticipant?.identity);
    // Try to publish mic if available
    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 && err.message ? err.message : err);
    }

    // Keep connection open for STAY_MS then disconnect
    log(`Staying connected for ${STAY_MS}ms`);
    await new Promise((r) => setTimeout(r, STAY_MS));

    log('Disconnecting now');
    room.disconnect();
    log('Disconnected (done)');
  } catch (err) {
    log('Unexpected error:', err && err.stack ? err.stack : err);
  }
})();
How to use • Run your token server with the debug endpoint (ensure LIVEKIT envs set). • Host debug-client.js in a simple HTML page that loads livekit-client UMD (use same version you use in app, e.g. 1.15.0). • Open the page in browser, allow microphone, and watch console for logs: token_debug, connect lifecycle events,
participantConnected
, and any errors. • Keep the browser open for ~30s to allow agent dispatch and startup.
t
Below is a simple HTML test page that loads the LiveKit UMD client and the debug client script you asked for. Save as debug.html, serve it from the same origin as your debug token endpoint (or allow CORS), open in the browser, allow microphone, and watch the console for lifecycle logs and the decoded token payload.
Copy code
<!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>
If you want, I can: • Update this page to accept a custom endpoint URL and agent name inputs, • Or patch your token endpoint to include extra debug fields only when a query flag is present.