modern-winter-66316
12/02/2025, 8:29 PMtall-airline-16756
12/02/2025, 8:29 PMtall-airline-16756
12/02/2025, 8:29 PMmodern-winter-66316
12/02/2025, 8:29 PMuser-${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.tall-airline-16756
12/02/2025, 8:30 PMroomConfig 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 docsmodern-winter-66316
12/02/2025, 8:32 PMtall-airline-16756
12/02/2025, 8:32 PMroomConfig, sensible defaults, and improved diagnostics).
Save as e.g. api/connect.js and adapt environment variable names and logging to your needs.
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.modern-winter-66316
12/02/2025, 8:34 PMmodern-winter-66316
12/02/2025, 8:35 PMtall-airline-16756
12/02/2025, 8:35 PMroomConfig 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?modern-winter-66316
12/02/2025, 8:42 PMtall-airline-16756
12/02/2025, 8:42 PMttl (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?modern-winter-66316
12/02/2025, 8:42 PMtall-airline-16756
12/02/2025, 8:43 PMroomConfig 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.
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.modern-winter-66316
12/02/2025, 8:50 PMtall-airline-16756
12/02/2025, 8:51 PMroomConfig.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.modern-winter-66316
12/02/2025, 8:53 PMtall-airline-16756
12/02/2025, 8:53 PMimport 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.modern-winter-66316
12/02/2025, 8:54 PMtall-airline-16756
12/02/2025, 8:55 PMFROM 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
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.modern-winter-66316
12/02/2025, 9:00 PMmodern-winter-66316
12/02/2025, 9:01 PMtall-airline-16756
12/02/2025, 9:01 PMroom.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?modern-winter-66316
12/02/2025, 9:05 PMtall-airline-16756
12/02/2025, 9:05 PMroomConfig, iat, exp) for debugging. Save as api/connect-debug.js and use in place of your current endpoint.
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:
// 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?modern-winter-66316
12/02/2025, 9:07 PMroomConfig, iat, exp) for debugging. Save as api/connect-debug.js and use in place of your current endpoint.
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:
// 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.tall-airline-16756
12/02/2025, 9:07 PM<!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.