dispatch issues
# ask-ai
m
dispatch issues
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.
I’m here to help with your dispatch issues. To diagnose quickly, can you tell me: 1. Are these inbound SIP calls, outbound calls, or agent-to-agent dispatches? 2. What exactly is happening (agents not answering, calls not routed, agents failing to join rooms, auth errors)? 3. Any error codes or messages (e.g., 403, 404) or timestamps of recent failures? 4. Are your dispatch rules using explicit
roomConfig.agents
and do agent names match the agent server config? Share logs or a short example of your dispatch rule if possible. I’ll use those details to suggest targeted troubleshooting steps. Sources: SIP troubleshooting guide | LiveKit docs | Agent dispatch | LiveKit docs
m
const startBtn = document.getElementById("startBtn"); const status = document.getElementById("status"); const controls = document.getElementById("controls"); const muteBtn = document.getElementById("muteBtn"); const endBtn = document.getElementById("endBtn"); const personaSelect = document.getElementById("persona"); const diagnosticsLog = document.getElementById("diagnosticsLog"); const transcriptLog = document.getElementById("transcriptLog"); const soundTestBtn = document.getElementById("soundTestBtn"); const pingStatus = document.getElementById("pingStatus"); const hardRefreshBtn = document.getElementById("hardRefreshBtn"); let room = null; let isMuted = false; function appendLog(target, message) { if (!target) return; const timestamp = new Date().toLocaleTimeString(); const entry = document.createElement("div"); entry.className = "log-entry"; entry.textContent = `[${timestamp}] ${message}`; target.prepend(entry); // Keep only last 20 entries while (target.children.length > 20) { target.removeChild(target.lastChild); } } function appendTranscript(message, tone = "neutral") { if (!transcriptLog) return; const entry = document.createElement("div"); entry.className = `transcript-line ${tone}`; entry.textContent = message; transcriptLog.prepend(entry); // Keep only last 30 entries while (transcriptLog.children.length > 30) { transcriptLog.removeChild(transcriptLog.lastChild); } } function setStatus(message) { status.textContent = message; appendLog(diagnosticsLog, message); } // Sound test (ping chime) soundTestBtn.addEventListener("click", async () => { pingStatus.textContent = "Playing test chime..."; try { const AudioCtx = window.AudioContext || window.webkitAudioContext; const ctx = new AudioCtx(); const oscillator = ctx.createOscillator(); const gain = ctx.createGain(); oscillator.type = "sine"; oscillator.frequency.value = 880; gain.gain.value = 0.15; oscillator.connect(gain).connect(ctx.destination); oscillator.start(); oscillator.stop(ctx.currentTime + 0.4); oscillator.onended = () => { ctx.close(); pingStatus.textContent = "Chime finished. If you didn't hear it, check your output device."; appendLog(diagnosticsLog, "Sound test chime played."); }; } catch (error) { pingStatus.textContent = `Unable to play test chime: ${error.message}`; appendLog(diagnosticsLog,
Sound test failed: ${error.message}
); } }); // Hard refresh if (hardRefreshBtn) { hardRefreshBtn.addEventListener("click", () => { appendLog(diagnosticsLog, "Hard refresh requested. Reloading page and bypassing cache."); // Force reload bypassing cache window.location.reload(true); }); } // Start lesson startBtn.addEventListener("click", async () => { const persona = personaSelect.value; setStatus("Connecting..."); startBtn.disabled = true; try { // Check if LiveKit SDK is loaded if (typeof window.LivekitClient === 'undefined') { throw new Error('LiveKit SDK not loaded. Please refresh the page.'); } const { Room } = window.LivekitClient; const endpoint = "/api/start-lesson"; const response = await fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ persona }), }); if (!response.ok) { throw new Error(
Failed to start lesson: ${response.statusText}
); } const data = await response.json(); const { token, room_name, url } = data; console.log("API Response:", data); appendLog(diagnosticsLog,
Token received for room: ${room_name}
); appendLog(diagnosticsLog,
Persona: ${persona}
); if (data.agent_status) { appendLog(diagnosticsLog,
Agent dispatch: ${data.agent_status}
); } room = new Room(); // Log all room events for debugging room.on("connected", () => { setStatus("Connected to room"); console.log("✅ Connected to room"); appendLog(diagnosticsLog, "Connected to LiveKit room"); appendLog(diagnosticsLog,
Local participant: ${room.localParticipant.identity}
); appendTranscript("Connected to room. Waiting for agent...", "neutral"); }); room.on("disconnected", () => { setStatus("Disconnected"); appendLog(diagnosticsLog, "Disconnected from room"); appendTranscript("Disconnected", "neutral"); startBtn.disabled = false; controls.style.display = "none"; }); room.on("participantConnected", (participant) => { const who = participant.identity || "Unknown"; console.log("👤 Participant connected:", who, participant); appendLog(diagnosticsLog,
Participant connected: ${who}
); appendLog(diagnosticsLog,
- Metadata: ${participant.metadata || 'none'}
); appendTranscript(
${who} joined
, "neutral"); }); room.on("trackPublished", (publication, participant) => { const who = participant.identity || "Unknown"; console.log("🎵 Track published:", publication.trackName, "from", who); appendLog(diagnosticsLog,
Track published: ${publication.trackName} from ${who}
); }); room.on("trackSubscribed", (track, publication, participant) => { const who = participant.identity || "Unknown"; console.log("🔊 Track subscribed:", track.kind, "from", who); appendLog(diagnosticsLog,
Track subscribed: ${track.kind} from ${who}
); if (track.kind === "audio") { const audioElement = track.attach(); audioElement.style.display = "none"; audioElement.volume = 1.0; // Ensure volume is at max document.body.appendChild(audioElement); console.log("🔊 Audio element attached:", audioElement); appendLog(diagnosticsLog, "Audio track attached and playing"); // Play the audio element explicitly audioElement.play().catch(e => { console.error("Audio play error:", e); appendLog(diagnosticsLog,
Audio play failed: ${e.message}
); }); } }); room.on("dataReceived", (payload, participant) => { try { const text = new TextDecoder().decode(payload); const who = participant.identity || "Agent"; appendTranscript(
${who}: ${text}
, "agent"); appendLog(diagnosticsLog,
Data received from ${who}: ${text}
); } catch (error) { console.warn("data decode error", error); } }); console.log("🔗 Connecting to:", url); console.log("🎫 Token (first 50 chars):", token.substring(0, 50) + "..."); await room.connect(url, token, { autoSubscribe: true }); console.log("✅ Room.connect() completed"); console.log("🤖 Agent explicitly dispatched - should join shortly"); appendLog(diagnosticsLog, "Room connection initiated"); appendLog(diagnosticsLog, "Agent dispatched to room - waiting for agent to join..."); // Wait a moment for participants to be available setTimeout(() => { if (room && room.participants) { appendLog(diagnosticsLog,
Participants in room: ${room.participants.size}
); // List existing participants room.participants.forEach((participant, identity) => { console.log("👥 Existing participant:", identity); appendLog(diagnosticsLog,
Existing participant: ${identity}
); }); } }, 1000); // Request microphone access and publish try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); await room.localParticipant.publishTrack(stream.getTracks()[0]); appendLog(diagnosticsLog, "Microphone track published"); controls.style.display = "flex"; } catch (error) { appendLog(diagnosticsLog,
Microphone access failed: ${error.message}
); setStatus(
Microphone error: ${error.message}
); } } catch (error) { console.error(error); setStatus(
Error: ${error.message}
); appendLog(diagnosticsLog,
Connection failed: ${error.message}
); startBtn.disabled = false; } }); // Mute toggle muteBtn.addEventListener("click", async () => { if (!room) return; try { if (isMuted) { await room.localParticipant.setMicrophoneEnabled(true); isMuted = false; muteBtn.textContent = "🔇 Mute"; appendLog(diagnosticsLog, "Microphone unmuted"); } else { await room.localParticipant.setMicrophoneEnabled(false); isMuted = true; muteBtn.textContent = "🎤 Unmute"; appendLog(diagnosticsLog, "Microphone muted"); } } catch (error) { appendLog(diagnosticsLog,
Mute toggle failed: ${error.message}
); } }); // End call endBtn.addEventListener("click", async () => { if (room) { await room.disconnect(); room = null; setStatus("Call ended"); controls.style.display = "none"; } }); // Health check on load window.addEventListener("load", async () => { try { const endpoint = "/api/health"; const response = await fetch(endpoint); if (response.ok) { appendLog(diagnosticsLog, "Backend health check: OK"); } else { appendLog(diagnosticsLog, "Backend health check: FAILED"); } } catch (error) { appendLog(diagnosticsLog,
Health check error: ${error.message}
); } }); [212256] Call ended [212256] Disconnected from room [212256] Disconnected [212124] Microphone track published [212124] Agent dispatched to room - waiting for agent to join... [212124] Room connection initiated [212124] Local participant: student-1f809e57 [212124] Connected to LiveKit room [212124] Connected to room [212123] Agent dispatch: dispatched - AD_dfbsieirHmn3 [212123] Persona: English Teacher [212123] Token received for room: lesson-13526ae6 [212121] Connecting... [212120] Sound test chime played. [212117] Backend health check: OK Waiting for events...
t
Thanks — I reviewed your code and logs. You're connecting, publishing audio, and the API returned "Agent dispatch: dispatched - AD_dfbsieirHmn3", but no agent participant appears in the room logs. To narrow this down, please confirm the following so I can give targeted steps: 1. When you say "dispatch issues," do agents sometimes join, or never join after "dispatched"? 2. Does the agent service show any logs around the same timestamp (212123 → 212124)? If so, any error or join attempts? 3. Are your dispatch rules using explicit
roomConfig.agents
with agent identities that exactly match the agent server config? (Case-sensitive.) 4. Is the agent expected to join via SIP trunk or via a LiveKit client/service using the
AD_...
dispatch ID? If SIP, are trunk credentials and routing configured correctly? 5. Any 403/401 or network errors in agent-side logs or in your backend that generates the token? Meanwhile try these quick checks: • Confirm the agent service can use the same LiveKit URL + token pattern (log the connect attempt and errors on agent side). • On the backend that returns token/agent_status, log the dispatch request body and the exact room name used (
lesson-13526ae6
) to ensure the agent dispatcher targets that room. • Increase your client-side logging window: after connect, list participants immediately and after 5–10s (you already check after 1s — try 5s) to catch delayed joins. • Verify agent identity strings exactly match dispatch rule entries (no metadata/name mismatch). Tell me which of the above you can check or paste the agent-side logs around the timestamps and the dispatch rule JSON — I’ll then give precise next steps.
m
1. never join
t
Thanks — since agents never join after dispatch, let’s focus on the highest-probability causes and gather a few quick logs. Please provide or check the following (in this order): 1. Agent worker status • Run:
lk agent status --id <agent_id>
and paste the output (or confirm worker shows as ACTIVE). • If not active, run
lk agent logs --id <agent_id> --log-type=deploy
and paste recent errors. 1. Agent-side connection logs (most important) • From the agent process around the dispatch timestamp (212123), share logs showing: ◦ Job creation / JobContext entries ◦ Any attempt to call
Room.connect()
or errors (ICE/DTLS, token, network, timeouts) ◦ Any message like "Room connection not established within 10 seconds" If you can’t share full logs, paste the last ~50 lines. 1. Confirm agent registration name • Show the code snippet where the agent registers its
agent_name
(e.g.,
rtc_session(agent_name="my-agent")
or WorkerOptions). The dispatch
agent_name
must match exactly (case-sensitive). 1. Dispatch method & token • Which method dispatched the agent: API dispatch, token RoomConfiguration, or SIP dispatch rule? • If dispatch via token/room config, paste the token-generation snippet (no secret keys) or the JSON for the room config showing
agents: [...]
. 1. Quick checks you can run now • Verify token grants include
roomJoin: true
and
RoomAgentDispatch
for the correct room. • Increase delay in your client logs: after connect, call and log room.participants immediately, at 5s, and at 10s. Paste outputs. • Confirm backend dispatched to the exact room name
lesson-13526ae6
(log the dispatch body). What I will do once you share the above: • Diagnose whether the failure is worker availability, agent name mismatch, token/permission issue, or agent-side connection/network error and provide exact next steps or a code fix. Which of the items above can you fetch first? Sources: Agents Framework | livekit/livekit_composite | DeepWiki | Quotas and limits | LiveKit docs | Log collection | LiveKit Docs | Agent dispatch | LiveKit docs | server-sdk-ruby | livekit/livekit_composite | DeepWiki
m
does tis hekp ? : Still only 1 participant (student) - agent never joins. The logs show "Agent dispatched to room - waiting for agent to join..." but it never arrives. The issue: The agent is deployed but not receiving dispatch requests. Check agent logs for the latest session: Still no logs - the agent container isn't even starting. The problem is the 1.3.x decorator pattern isn't working with LiveKit Cloud's deployment system. Let me check if the agent needs a different structure for cloud deployment: C:\Users\samdu\Projects\agent-stack\agent\livekit.toml The livekit.toml still has the old entrypoint = "main:entrypoint" but we changed the code to use server.run(). For 1.3.x with decorator pattern, the entrypoint needs to be the server instance: Deployed with entrypoint = "main:server". Test now - the agent should finally start and accept dispatch requests!
t
Good find — that likely fixes it. Your summary: agent container never started because the deployment entrypoint still pointed to the old entry (entrypoint = "main:entrypoint") while your code now uses the 1.3.x decorator pattern and exposes the server instance. Changing livekit.toml to entrypoint = "main:server" makes the deployed container start the server so it can register workers and accept dispatches. Next steps to verify: 1. Update livekit.toml to: entrypoint = "main:server" 2. Redeploy the agent to LiveKit Cloud. 3. Check deployment logs: run
lk agent logs --id <agent_id> --log-type=deploy
and confirm the container starts and you see server startup logs. 4. After startup, trigger a dispatch and watch
lk agent logs
for JobContext creation and
Room.connect()
attempts. Also confirm
lk agent status --id <agent_id>
shows ACTIVE. 5. Verify the room now receives the agent (your client-side logs should show participantConnected). If you want, paste the first ~50 lines of the deploy logs after redeploy and I’ll verify the startup sequence and the expected log lines to confirm the fix.
m
1. API Response: _{token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiU…Q1OH0.7aDCe_5PyzQlRejWDyn6UCDbIQhBaELRYwx7B8c8Gx4', room_name: 'lesson-d0347cfa', url: 'wss://turbo-ms4yz8cm.livekit.cloud', persona: 'English Teacher', agent_status: 'dispatched - AD_WTZBYWUrMM7z'}_ 2. agent_status 3. : a. "dispatched - AD_WTZBYWUrMM7z" 4. persona 5. : a. "English Teacher" 6. room_name 7. : a. "lesson-d0347cfa" 8. token 9. : a. "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiU3R1ZGVudCIsInZpZGVvIjp7InJvb21Kb2luIjp0cnVlLCJyb29tIjoibGVzc29uLWQwMzQ3Y2ZhIiwiY2FuUHVibGlzaCI6dHJ1ZSwiY2FuU3Vic2NyaWJlIjp0cnVlLCJjYW5QdWJsaXNoRGF0YSI6dHJ1ZX0sInN1YiI6InN0dWRlbnQtNTBhMmZmZDQiLCJpc3MiOiJBUElpSzJYUldyblBFWksiLCJuYmYiOjE3NjUwMDk4NTgsImV4cCI6MTc2NTAzMTQ1OH0.7aDCe_5PyzQlRejWDyn6UCDbIQhBaELRYwx7B8c8Gx4" 10. url 11. : a. "wss://turbo-ms4yz8cm.livekit.cloud" 12. [[Prototype]] 13. : a. Object
t
Thanks — your API response shows the token, room, and an agent_status of "dispatched - AD_WTZBYWUrMM7z", so dispatch was created but the agent still hasn't joined. Next steps to confirm the deployment fix and verify the agent starts and accepts dispatches: 1. Redeploy with updated livekit.toml • Ensure entrypoint = "main:server" and redeploy the agent container. 1. Confirm the agent container starts • Run: lk agent logs --id <agent_id> --log-type=deploy • Paste the first ~50 lines here. I’m looking for server startup logs (server listening, worker registration, or similar). 1. Verify agent is active • Run: lk agent status --id <agent_id> • Paste the output (should show ACTIVE). If not ACTIVE, paste any status text. 1. Trigger a dispatch and watch runtime logs • After agent shows ACTIVE, trigger another lesson and immediately run: lk agent logs --id <agent_id> (stream runtime logs) to capture JobContext creation and Room.connect() attempts. Paste any errors or timeouts. 1. Quick checks if agent still fails to start • Confirm the agent container entrypoint file exports
server
(e.g., in main.py there is a
server
variable referencing the server instance). • Confirm agent image was built after the entrypoint change (no stale image). • If using LiveKit Cloud Build plan, cold-start may add 10–20s delay — check deploy logs for process start delays. If you paste the deploy logs and
lk agent status
output now, I’ll verify the startup sequence and point to the exact next fix if it still fails.
m
do we need to create rooms incororating agent name ?
t
No — rooms do not need to include the agent name. What matters is how you dispatch the agent: • Dispatch via token/RoomConfiguration: the token must include a room config with an agents entry that references the exact
agent_name
you registered in your agent code. Example: include RoomConfiguration with
agents: [ { agent_name: "my-agent" } ]
when generating the token for
lesson-d0347cfa
. • Explicit API dispatch or SIP dispatch rules: the dispatch request or SIP rule must reference the same
agent_name
. Key checks to make sure dispatch works: • The
agent_name
in the dispatch (token, API, or SIP rule) exactly matches the agent registration (case-sensitive). • The agent process is actually running and registered (deployment entrypoint must start the server so workers register). • Tokens used by the agent to connect include roomJoin grants and any required room config (if the agent connects using a token). • Watch agent runtime logs for JobContext creation and Room.connect() attempts after dispatch. If you want, paste your token-generation snippet or your dispatch JSON and the agent registration line (the
agent_name
) and I’ll confirm they match and show the exact fields you need.
m
MATCH CONFIRMED: • API Dispatch (line 46): agent_name="cloud-english-teacher" • Agent Registration (line 16): AGENT_NAME = "cloud-english-teacher" • Decorator (line 204): @server.rtc_session(agent_name=AGENT_NAME) Names match exactly. The problem must be that the agent server isn't actually starting/registering. Let me check if there's an issue with how AgentServer is being initialized. The agent might need to export the server instance at module level BEFORE the if name block:
t
You're on the right track — if the agent server instance isn't exposed at module level the cloud deploy won't register workers. Do the following: 1) Export the server instance at module level • Ensure
server
is created at top-level (not only inside
if __name__ == "__main__":
) so the platform can import it. Example pattern:
Copy code
# main.py
from livekit_agent import AgentServer

server = AgentServer()

@server.rtc_session(agent_name=AGENT_NAME)
async def handler(ctx: JobContext):
    ...
2) livekit.toml entrypoint • Set: entrypoint = "main:server" 3) Rebuild & redeploy • Rebuild your image, push, then redeploy so the cloud uses the updated image with the exported
server
. 4) Verify startup • After deploy, run: ◦
lk agent logs --id <agent_id> --log-type=deploy
— paste the first ~50 lines here. ◦
lk agent status --id <agent_id>
— confirm it shows ACTIVE. 5) If it still fails, paste: • The first ~50 lines of deploy logs • The top of your main.py (showing
server
creation) — no secrets I’ll review the logs and confirm the exact startup/registration issue.
m
how do we access logs with cli ? asd we cant seem to access won dahsvboard ?
t
You're right to pull logs from the CLI if the dashboard isn't available. Here are the exact lk CLI commands and what to look for. 1) List agents to get the agent_id • lk agent list ◦ Note the agent's ID and name from the output. 2) Check agent status • lk agent status --id <agent_id> ◦ Look for state: ACTIVE (or error/status text). 3) View deployment logs (container startup) • lk agent logs --id <agent_id> --log-type=deploy --follow ◦ This shows the build/container start logs. Look for server startup, any import errors, or messages indicating the entrypoint executed. 4) View runtime logs (worker / agent process) • lk agent logs --id <agent_id> --log-type=runtime --follow ◦ This streams the agent process logs: JobContext creation, Room.connect() attempts, token errors, timeouts, ICE/DTLS errors. 5) Tail recent logs without follow • lk agent logs --id <agent_id> --log-type=deploy --lines=100 • lk agent logs --id <agent_id> --log-type=runtime --lines=200 6) If you don't see logs or the agent isn't listed • Confirm the image was rebuilt and redeployed after changing entrypoint. • Confirm livekit.toml has entrypoint = "main:server" and that
server
is a top-level object in main.py. • Re-run: lk agent list (new deployment should appear) and then check deploy logs. What to paste here • Output of
lk agent list
• First ~50 lines from
lk agent logs --id <agent_id> --log-type=deploy --lines=50
• Output of
lk agent status --id <agent_id>
Paste those and I’ll confirm whether the container started and whether the server registered workers.
m
can you create a simple file of CLI LK log type rewuest s please
t
Below is a simple bash script file you can save as fetch_lk_logs.sh. It lists agents, prompts for an agent ID, then fetches deploy and runtime logs (tail or follow). Make it executable with
chmod +x fetch_lk_logs.sh
and run it from a shell where
lk
CLI is configured.
Copy code
#!/usr/bin/env bash
set -e

echo "Listing LiveKit agents..."
lk agent list
echo
read -p "Enter agent ID to fetch logs for: " AGENT_ID

if [ -z "$AGENT_ID" ]; then
  echo "No agent ID provided. Exiting."
  exit 1
fi

echo
echo "=== Agent status ==="
lk agent status --id "$AGENT_ID" || true

echo
echo "Fetch last 50 lines of deploy logs:"
lk agent logs --id "$AGENT_ID" --log-type=deploy --lines=50 || true

echo
echo "Fetch last 200 lines of runtime logs:"
lk agent logs --id "$AGENT_ID" --log-type=runtime --lines=200 || true

echo
read -p "Follow deploy logs? (y/N): " FOLLOW_DEPLOY
if [[ "$FOLLOW_DEPLOY" =~ ^([yY][eE][sS]|[yY])$ ]]; then
  echo "Following deploy logs (Ctrl+C to stop)..."
  lk agent logs --id "$AGENT_ID" --log-type=deploy --follow || true
fi

echo
read -p "Follow runtime logs? (y/N): " FOLLOW_RUNTIME
if [[ "$FOLLOW_RUNTIME" =~ ^([yY][eE][sS]|[yY])$ ]]; then
  echo "Following runtime logs (Ctrl+C to stop)..."
  lk agent logs --id "$AGENT_ID" --log-type=runtime --follow || true
fi

echo "Done."
If you want, I can also provide a one-liner version for quick use.
m
The CLI doesn't support --lines or --follow flags! It only supports --log-type (deploy or build). The script won't work as written. The lk agent logs command just tails all logs without line limits. Since we can't control log output, and previous runs showed empty logs, this means: 1. Deploy logs are not being generated (container starts silently or crashes immediately) 2. Runtime logs are empty (no dispatch jobs executed) The agent shows "Running" but 0 CPU/Memory usage confirms the Python process never started. This is a LiveKit Cloud container execution issue that requires their support to investigate why entrypoint = "main:server" isn't executing the Python module. Summary for LiveKit Support: • Agent ID: CA_e7hLTus66nKZ • Status: Running, but 0 CPU/0 Memory • Code: server = agents.AgentServer() at module level, @server.rtc_session(agent_name="cloud-english-teacher") • Config: entrypoint = "main:server" in livekit.toml • Issue: Container runs but Python process doesn't start; no logs generated; dispatches fail
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!