My SIP trunk provider doesn't accept SIP REFER so ...
# ask-ai
h
My SIP trunk provider doesn't accept SIP REFER so forwarding a call using the method that LiveKit's docs suggests doesn't work Is there any other way? Your examples should be in TypeScript, not Python.
t
Thanks for reaching out, tri.nguyen. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're right — if your SIP trunk doesn't accept SIP REFER, you can do an outbound call + room-bridging (warm transfer) instead. That avoids REFER entirely and works with any trunk that supports outbound calls. Below is a concise TypeScript example showing the flow: create a transfer room, dial the transferee via CreateSIPParticipant, then move the caller into the transfer room. What I'm responding to: alternative to SIP REFER + TypeScript examples. TypeScript example:
Copy code
import { 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 docs
h
Do I need to create a transfer room and move the caller into it? Can't I simply add a transferee to the current room of the caller?
t
You can add the transferee directly to the caller's current room — you do not strictly have to create a new transfer room and move the caller. Use
CreateSIPParticipant
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:
Copy code
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.
h
Whichever way is fine but I want to ensure two things: • The agent will not be involved once the transfer is initiated • When either the transferee or the caller hangs up, the other side must also automatically hang up as well
t
You're aiming for two guarantees: • Agent is not involved after transfer starts. • If either caller or transferee hangs up, the other is also disconnected. Two approaches that satisfy those requirements: 1) If your SIP trunk supports SIP REFER (recommended for cold transfer) • Use LiveKit's TransferSIPParticipant API to perform the cold transfer. After REFER completes the agent is out of the media path and the SIP provider connects caller ↔️ transferee directly, so the agent can leave immediately. The SIP provider will tear both legs when either side hangs up. • This automatically meets both requirements (no agent involvement; mutual hangup handled by provider). 2) If SIP REFER is not available (outbound + room bridging) • Dial the transferee into the same room as the caller (cold-in-room) or into a separate transfer room and then move the caller in (warm transfer). To ensure agent is not involved and to enforce mutual hangup, implement these two server-side steps: ◦ Create the transferee as a SIP participant in the caller's room using
CreateSIPParticipant
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):
Copy code
// 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 docs
h
The second way
t
Great — below is a focused, production-ready approach in TypeScript for the room-bridging (cold-in-room) method that ensures: • The agent can leave immediately after initiating the transfer. • If either caller or transferee hangs up, the other side is automatically disconnected. High-level flow 1. Agent initiates transfer: backend dials transferee into the caller's room via
createSIPParticipant
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
Copy code
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?
h
I don't want to use webhook
t
You can avoid webhooks. Two practical alternatives will enforce mutual hangup without webhooks — pick which fits your architecture and I’ll provide code: Options: • Polling participant state: your backend polls LiveKit (periodically) for room participants or participant status; when it detects one side gone, it calls the Room Service API to remove the peer. • Server-side event subscription (persistent WS/gRPC): run a backend process that subscribes to room events/participant updates directly (no public webhook). On disconnect events, remove the mapped peer immediately. Which do you prefer? • "Polling" — I’ll provide a resilient TypeScript example with backoff, TTL mappings, and race handling. • "Event subscription" — I’ll provide a TypeScript example using LiveKit's server-side event stream (or SDK event listener) to react to disconnects in real time. Also confirm: • Do you want the transferee dialed into the same room (cold-in-room)? • Do you need persistent storage for mappings (Redis/Postgres) or is in-memory acceptable?