happy-diamond-58115
12/09/2025, 6:46 AMtall-airline-16756
12/09/2025, 6:46 AMtall-airline-16756
12/09/2025, 6:47 AMimport { RoomServiceClient, SipClient } from 'livekit-server-sdk';
const LIVEKIT_URL = process.env.LIVEKIT_URL!;
const API_KEY = process.env.LIVEKIT_API_KEY!;
const API_SECRET = process.env.LIVEKIT_API_SECRET!;
const roomService = new RoomServiceClient(LIVEKIT_URL, API_KEY, API_SECRET);
const sipClient = new SipClient(LIVEKIT_URL, API_KEY, API_SECRET);
// Inputs you provide:
const callerRoom = 'caller-room';
const callerIdentity = 'caller-123';
const outboundTrunkId = '<your-outbound-trunk-id>';
const transferNumber = '+15551234567';
async function warmTransferWithoutRefer() {
const transferRoom = `transfer-${Date.now()}`;
// 1) Create transfer room
await roomService.createRoom({
room: transferRoom,
empty_timeout: 300,
});
// 2) Dial transferee (outbound SIP call into transfer room)
const sipParticipant = await sipClient.createSIPParticipant({
sipTrunkId: outboundTrunkId,
sipCallTo: transferNumber,
roomName: transferRoom,
participantIdentity: `to-${transferNumber}`,
participantName: 'Transferee',
waitUntilAnswered: true,
});
// 3) Move caller into the transfer room to bridge audio
await roomService.moveParticipant({
room: callerRoom,
identity: callerIdentity,
destinationRoom: transferRoom,
});
// At this point caller + transferee are in the same room (warm transfer).
// Optionally have an agent/AI join to summarize, then remove if desired.
}
Notes and tips:
• Use waitUntilAnswered: true to ensure the transferee is connected before moving the caller.
• MoveParticipant is available in LiveKit Cloud; make sure your deployment supports it.
• You can optionally join an AI/agent to the transfer room to hand off context, then disconnect after the transfer completes.
Would you like a version that:
• Includes error handling and retries, or
• Shows how to add an AI agent to the transfer room before moving the caller? Sources: SIP APIs | LiveKit docs | Managing participants | LiveKit docs | Agent-assisted warm transfer | LiveKit docshappy-diamond-58115
12/09/2025, 6:49 AMtall-airline-16756
12/09/2025, 6:50 AMCreateSIPParticipant to dial the transferee and place them into the same room the caller is already in.
Below are the trade-offs and a concise TypeScript example.
Why you might add the transferee to the same room
• Simpler: fewer API calls and no room move.
• Faster cold transfer: dial transferee and once answered, you can disconnect any helper/agent and leave caller+transferee together.
Why you might prefer a separate transfer room
• Warm transfer control: let an agent or AI finish context/summarization in the transfer room before bridging the caller.
• Safer handoff: you can ensure the transferee is answered first (with waitUntilAnswered) and run any pre-transfer logic without the caller hearing it.
• Isolation: avoids exposing the caller to intermediate agents or diagnostics while the outbound call is ringing/connecting.
TypeScript example — add transferee into the caller's current room:
import { SipClient } from 'livekit-server-sdk';
const LIVEKIT_URL = process.env.LIVEKIT_URL!;
const API_KEY = process.env.LIVEKIT_API_KEY!;
const API_SECRET = process.env.LIVEKIT_API_SECRET!;
const sipClient = new SipClient(LIVEKIT_URL, API_KEY, API_SECRET);
// Inputs:
const callerRoom = 'caller-room';
const transferNumber = '+15551234567';
const outboundTrunkId = '<your-outbound-trunk-id>';
async function addTransfereeToCurrentRoom() {
// Dial the transferee and place them into the caller's room
const sipParticipant = await sipClient.createSIPParticipant({
sipTrunkId: outboundTrunkId,
sipCallTo: transferNumber,
roomName: callerRoom, // same room as caller
participantIdentity: `to-${transferNumber}`,
participantName: 'Transferee',
waitUntilAnswered: true, // ensures transferee answers before you act
});
// Once answered, transferee and caller share the same room
}
Which do you prefer for your flow:
• Cold transfer (dial transferee directly into caller's room), or
• Warm transfer (agent/AI needs time to add context before connecting caller)?
Tell me which and I’ll provide the next steps or a version with error handling and agent involvement.happy-diamond-58115
12/09/2025, 6:53 AMtall-airline-16756
12/09/2025, 6:54 AMCreateSIPParticipant with waitUntilAnswered: true. Do not keep the agent in the room after you initiate.
◦ Listen for participant disconnect events (via LiveKit webhooks or server-side room events). When you receive a disconnect for either the caller or the transferee, call the server API to remove the other participant from the room (or call DeleteSIPParticipant / remove participant) so the remaining side is also disconnected.
Concise TypeScript pattern (room-bridging + webhook-driven mutual hangup):
// 1) Dial transferee into caller's room
await sipClient.createSIPParticipant({
sipTrunkId: outboundTrunkId,
sipCallTo: transferNumber,
roomName: callerRoom,
participantIdentity: `to-${transferNumber}`,
participantName: 'Transferee',
waitUntilAnswered: true,
});
// 2) Webhook handler (or server event subscription) - pseudocode
// On participant disconnected event from LiveKit:
app.post('/webhook', async (req, res) => {
const evt = req.body; // LiveKit event payload
if (evt.type === 'participant_disconnected') {
const { room, identity } = evt.participant;
// find the peer identity to remove (caller <-> transferee mapping you maintain)
const otherIdentity = findPairedParticipant(room, identity);
if (otherIdentity) {
// remove the other participant so they also hang up
await roomService.removeParticipant({ room, identity: otherIdentity });
}
}
res.sendStatus(200);
});
Notes and implementation tips:
• Maintain a mapping on your server that pairs caller ↔️ transferee identities or transfer sessions so the webhook knows which participant to remove.
• Use waitUntilAnswered: true to avoid moving the caller into a half-connected state.
• Use removeParticipant / DeleteSIPParticipant (server API) to force the other side off the room; that triggers the SIP provider leg to hang up.
• Cold transfer via SIP REFER is simpler if your trunk supports it — it offloads mutual hangup to the SIP provider and requires no webhook pairing logic.
Which path do you want to implement? I can provide a full TypeScript example with:
• webhook signature verification and mapping logic, or
• a complete createSIPParticipant + moveParticipant warm-transfer flow with error handling. Sources: Call forwarding | LiveKit docs | Using Wavix to accept and make calls | LiveKit docs | SIP APIs | LiveKit docshappy-diamond-58115
12/09/2025, 6:56 AMtall-airline-16756
12/09/2025, 6:56 AMcreateSIPParticipant with waitUntilAnswered: true.
2. Backend records a transfer session mapping caller <-> transferee identities.
3. Agent leaves immediately.
4. Backend listens for LiveKit participant disconnect webhooks (or server events). When either side disconnects, backend removes the mapped peer programmatically so the remaining side is forced off the call.
Key pieces provided below:
• create transfer (dial transferee)
• simple in-memory mapping (replace with DB in prod)
• webhook handler that enforces mutual hangup
• removal using Room Service API
TypeScript example
import express from 'express';
import bodyParser from 'body-parser';
import { SipClient, RoomServiceClient } from 'livekit-server-sdk';
const LIVEKIT_URL = process.env.LIVEKIT_URL!;
const API_KEY = process.env.LIVEKIT_API_KEY!;
const API_SECRET = process.env.LIVEKIT_API_SECRET!;
const sipClient = new SipClient(LIVEKIT_URL, API_KEY, API_SECRET);
const roomService = new RoomServiceClient(LIVEKIT_URL, API_KEY, API_SECRET);
const app = express();
app.use(bodyParser.json());
// In-memory store for demo; use persistent DB in production
const transferMap = new Map<string, { callerIdentity: string; transfereeIdentity: string }>();
// key: roomName + ':' + callerIdentity
// 1) Initiate transfer: dial transferee into caller's room
export async function initiateTransfer({
roomName,
callerIdentity,
transferNumber,
outboundTrunkId,
}: {
roomName: string;
callerIdentity: string;
transferNumber: string;
outboundTrunkId: string;
}) {
const transfereeIdentity = `to-${transferNumber}-${Date.now()}`;
// Dial transferee into same room and wait until answered
await sipClient.createSIPParticipant({
sipTrunkId: outboundTrunkId,
sipCallTo: transferNumber,
roomName,
participantIdentity: transfereeIdentity,
participantName: 'Transferee',
waitUntilAnswered: true,
});
// Save mapping so webhook can lookup peer to remove later
const key = `${roomName}:${callerIdentity}`;
transferMap.set(key, { callerIdentity, transfereeIdentity });
// Agent can immediately leave now; transfer is live between caller + transferee
return { transfereeIdentity };
}
// 2) Webhook handler: enforce mutual hangup
app.post('/livekit-webhook', async (req, res) => {
const evt = req.body;
// Basic event handling; add signature verification in prod
if (!evt || !evt.type) {
return res.sendStatus(400);
}
// Handle participant disconnected events
if (evt.type === 'participant_disconnected' || evt.type === 'participant_left') {
const roomName = evt.room?.name || evt.roomName || evt.room;
const identity = evt.participant?.identity || evt.participantIdentity || evt.identity;
if (roomName && identity) {
// Find mapping by either caller or transferee identities
// Search keys and values in transferMap (simple linear search for demo)
for (const [key, pair] of transferMap.entries()) {
if (key.startsWith(`${roomName}:`) && (pair.callerIdentity === identity || pair.transfereeIdentity === identity)) {
const otherIdentity = pair.callerIdentity === identity ? pair.transfereeIdentity : pair.callerIdentity;
try {
// Remove the other participant to force hangup
await roomService.removeParticipant({ room: roomName, identity: otherIdentity });
} catch (err) {
// If removal fails (e.g., already gone), ignore or log
console.error('Failed to remove peer participant', otherIdentity, err);
}
// Clean up mapping
transferMap.delete(key);
break;
}
}
}
}
res.sendStatus(200);
});
// Example: express route to trigger transfer
app.post('/transfer', async (req, res) => {
const { roomName, callerIdentity, transferNumber, outboundTrunkId } = req.body;
try {
const result = await initiateTransfer({ roomName, callerIdentity, transferNumber, outboundTrunkId });
res.json(result);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'transfer_failed' });
}
});
app.listen(3000, () => console.log('Server listening 3000'));
Production considerations and best practices
• Persist transfer mappings in a DB (Redis, Postgres) so webhooks work after restarts.
• Verify LiveKit webhook signatures to prevent spoofing.
• Use waitUntilAnswered: true so the caller isn't exposed to ringing/failed calls.
• Gracefully handle race conditions: the peer might already be gone when you call removeParticipant — treat that as success.
• If your SIP provider supports early media or complex SIP behaviors, test hangup behavior to ensure forced removal results in provider hangup.
• Optionally add a short grace period (e.g., 1–2s) before removing peer to handle quick reconnect cases.
Would you like:
• the same flow but using a persistent Redis mapping example, or
• a version that also includes webhook signature verification code?happy-diamond-58115
12/09/2025, 7:00 AMtall-airline-16756
12/09/2025, 7:00 AM