Voice Agent Warm Transfer Testing: Verify Human Handoffs
Five checks for a voice agent warm transfer: bridge, context, hold, unanswered lines and hangups, with pass rules, SIP mechanics, platform notes and code.
Table of Contents
Picture a dental clinic line (an illustrative case, not a real call). A caller confirms her date of birth and insurance plan with the voice agent, then asks for a person about a disputed charge. The desk line is busy, and the blind transfer drops her into voicemail.
The agent’s log closes the call as forwarded, and the transcript reads clean. You have to check a voice agent warm transfer at the phone legs, because some platforms record a busy line or a voicemail pickup as a finished transfer.
You get five checks with pass rules, the Session Initiation Protocol (SIP) mechanics, how Vapi, Retell, LiveKit and Twilio report a failed transfer, a harness tested end to end on ten fixture cases, and a log record that catches the next failed human handoff.
TL;DR
- A voice agent warm transfer passes only when a confirmed person answers and hears the caller’s context first, and the agent leg leaves after the answer.
- On the phone network a cold transfer hands the call away with a SIP REFER or a newly dialed leg, while a warm transfer keeps the caller’s leg until the human is on.
- Test five things with a number you set for each: bridge success, context delivery, hold experience, unavailable destination and caller recovery.
- Vapi, Retell, LiveKit and Twilio each report a failed transfer in a different place, so log the mode, every leg time and the provider’s outcome code.
- A standard library harness, tested end to end, replays ten fixture cases and blocks a release on any stranded caller whatever the pass rate.
Warm transfer vs cold transfer on the phone network
A cold transfer sends the caller to a new number and the agent leaves at once, while a warm transfer holds the caller until a person answers and is briefed. On SIP the cold path is a REFER or a newly dialed leg, and the warm path is an attended transfer or a bridge the platform runs.
SIP REFER and the blind path
RFC 3515, the SIP REFER method has the recipient answer 202 Accepted and report the new call’s progress in NOTIFY requests. RFC 5589 on SIP call transfer (BCP 149, 2009) keeps a basic transfer’s signalling up “so the call is recoverable if the Transfer Target cannot be reached”.
Send BYE as soon as the REFER transaction completes and you get what the RFC says is sometimes known as “unattended transfer” or “blind transfer”: no leg is left to take a caller back from a busy target. Section 6.3 shows the recoverable case.
Attended transfer and the platform bridge
RFC 5589 section 7.3 attended transfer holds the transferee, calls the target to alert them, then sends REFER with an escaped Replaces header (RFC 3891). The original leg stays up while the person is briefed, so a fallback stays possible. Vapi’s transfer assistant and Retell’s warm transfer follow the same pattern, reaching the destination while the caller waits.
A Twilio Conference adds the new participant before the initiator drops off, and LiveKit WarmTransferTask dials the human into a separate room.
Text handoffs between agents are a different problem, covered in evaluating agent-to-agent handoffs.
Five checks every voice agent warm transfer must pass
Five checks decide whether a transfer to a person worked: the bridge, the context the person hears, the hold, the unavailable destination and the caller’s recovery. Each one needs a pass rule with a number, and since the platforms document timeouts rather than caller targets, you set those numbers yourself.
The harness numbers below are example values we set, not a standard, and the rest of the call belongs to end-to-end voice agent evaluation.

Bridge success
Pass rule: a person, not a machine, confirmed on the answered leg before the caller joined, and the agent leg left only after the person answered. Vapi’s guide to debugging forwarding drops shows why answered is not enough: for blind and non-assistant warm transfers on Twilio, “voicemail counts as answered”.
Confirmed-person signals: Retell’s warm transfer can wait for a real person to speak, a Vapi transfer assistant calls transferSuccessful, LiveKit’s human calls connect_to_caller, and a Twilio participant with machine detection returns AnsweredBy. The voicemail_answered case fails this check.
Context delivery
Pass rule: the caller’s identity, intent and steps already taken reach the person before the caller joins, with each field a nonempty string. Retell’s transfer call settings offer a Whisper Debrief Message the caller cannot hear, and Vapi’s traditional modes have Twilio speak a message of at most 1,000 characters or a generated summary.
LiveKit hands the human the conversation history, and Retell’s agentic transfer agent gets the original conversation but nothing said after the transfer starts. In the harness, context_missing and context_late fail here, the second because context arrived at 18.0s, after the 15.0s join.
Hold experience
Pass rule: hold from start to bridge, fallback or hangup stays under your limit (45 seconds in the harness), the caller hears hold audio, not dead air, and a long hold gets a spoken update. The hold_over_limit case fails at 69.0s.
A held Twilio Conference participant hears your holdUrl (waitUrl plays only before the conference starts). Vapi’s assistant-based transfer plays default hold audio unless transferPlan.holdAudioUrl is set, but nothing plays while Vapi waits on a transfer-destination-request. Retell defaults to a standard ringtone and LiveKit to BuiltinAudioClip.HOLD_MUSIC. Hold audio and spoken updates need a live call.
Unavailable destination
Pass rule: busy, no answer, timeout and declined each start a fallback (return to the agent, callback offer or voicemail) within 5 seconds in the harness, and a stranded caller is a critical failure. RFC 5589 section 6.3 is the basis: after a failed transfer, the transferor takes the caller off hold and resumes the session.
Vapi assistant-based warm transfer rolls a busy or unanswered destination back to its fallbackPlan, and Vapi’s debugging guide says to “Test the chosen transfer mode with a reachable operator, a busy destination, and an unanswered call before using it for production escalation”. Cases destination_busy and no_answer pass; declined fails as critical.
Caller recovery
Pass rule: if the caller hangs up during hold or a leg drops after the bridge, every surviving active leg, including the agent, is released within your cleanup window, 5 seconds in the harness. Log a drop as a drop, not a success. Both caller_hangup_during_hold and drop_after_bridge pass.
Retell adds a two-call case: if the caller hangs up while an agentic transfer agent is still speaking, its separate call can continue, with its charges, until it ends. Check both call records before you count the cleanup as a pass.
How Vapi, Retell, LiveKit and Twilio expose warm transfer
Vapi, Retell, LiveKit and Twilio all support a warm transfer, but each one builds it differently and reports a failure in a different place. Read each platform’s page for the mode you run, because the same busy line can end as a fallback, a forwarded call or an error.
The table below is not ranked and comes from each vendor’s current docs, and the mode matters more than the vendor: Vapi’s traditional warm modes cannot take the caller back, while Vapi assistant-based, Retell agentic, LiveKit and a Twilio Refer with an action URL can.
| Platform and mode | Warm leg | Busy or no answer | Where the outcome shows |
|---|---|---|---|
| Vapi traditional warm | Twilio dials; a message, summary or TwiML first | Cannot return the caller | Logs tab: connected, busy, no-answer or unconfirmed |
| Vapi assistant-based | Transfer assistant dials, caller holds | Rolls back to fallbackPlan | call.forwarding.operator-busy, if the call ends after the fallback message |
| Retell warm | Can wait for a person, whispers a debrief | Unanswered after Transfer Ring Duration | call_transfer, not proof a person answered |
| Retell agentic warm | Second agent screens, then bridges or cancels | Cancel Transfer returns the caller | transfer_bridged or transfer_cancelled, second call |
| LiveKit WarmTransferTask | Separate SIP room, hold music, history to the human | ringing_timeout raises ToolError; caller resumes | WarmTransferResult or a ToolError reason |
| Twilio Refer | Blind REFER, SIP legs only | ReferCallStatus busy, NotifySipResponseCode 486 | Action URL parameters |
| Twilio Conference | Participant added, then initiator drops | Ring timeout, default 60s | Participant status, AnsweredBy |
Vapi
Vapi warm transfer modes work on Twilio calls; on other providers Vapi transfers like a blind transfer. Because “The original assistant leaves the call, and Twilio dials the destination while the caller waits”, these modes cannot return the caller or pass the bridge check.
Assistant-based warm transfer (warm-transfer-experimental) rolls back to fallbackPlan on busy or no answer, defaults maxDurationSeconds to 120 and silenceTimeoutSeconds to 30, and does not detect voicemail automatically, so its prompt must call transferCancel. Both Vapi pages supplied these blocks verbatim.
curl --request PATCH \
--url https://api.vapi.ai/tool/TOOL_ID \
--header 'Authorization: Bearer YOUR_API_KEY' \
--header 'Content-Type: application/json' \
--data '{
"destinations": [
{
"type": "number",
"number": "+14155550100",
"description": "Transfer to an account specialist after the customer agrees",
"transferPlan": {
"mode": "warm-transfer-say-message",
"message": "A customer needs help with an account issue. Connecting the caller now."
}
}
]
}'
{
"mode": "warm-transfer-say-summary",
"summaryPlan": {
"enabled": true,
"timeoutSeconds": 5,
"messages": [
{
"role": "system",
"content": "Summarize why the caller needs help in two sentences. Return only the summary."
},
{
"role": "user",
"content": "{{transcript}}"
}
]
}
}
curl --request POST \
--url https://api.vapi.ai/tool \
--header 'Authorization: Bearer YOUR_API_KEY' \
--header 'Content-Type: application/json' \
--data '{
"type": "transferCall",
"destinations": [
{
"type": "number",
"number": "+14155550100",
"description": "Transfer to an account specialist after the customer agrees",
"transferPlan": {
"mode": "warm-transfer-experimental",
"transferAssistant": {
"firstMessage": "Hello, I have a customer who needs help with an account issue. Are you available to take the call?",
"firstMessageMode": "assistant-speaks-first",
"maxDurationSeconds": 120,
"silenceTimeoutSeconds": 30,
"model": {
"provider": "openai",
"model": "gpt-4o",
"messages": [
{
"role": "system",
"content": "Confirm that a human operator is ready. Use transferSuccessful when the operator accepts the call. Use transferCancel for voicemail, no answer, or a declined transfer. Keep the conversation focused on the transfer."
}
]
}
},
"holdAudioUrl": "https://example.com/audio/hold.mp3",
"transferCompleteAudioUrl": "https://example.com/audio/transfer-complete.mp3",
"fallbackPlan": {
"message": "I could not reach an account specialist. I can continue helping you.",
"endCallEnabled": false
}
}
}
],
"messages": [
{
"type": "request-start",
"content": "I will call an account specialist now. Please hold."
},
{
"type": "request-failed",
"content": "I could not start the transfer."
}
]
}'
Call transferCancel if the destination plays an IVR message, automated queue announcement, or hold message. Call transferSuccessful only after a live operator responds and accepts the call.
Retell
Retell’s Transfer Call has cold, warm and agentic warm modes on phone calls. Cold offers SIP INVITE or SIP REFER, and warm can wait for a real person and whisper a debrief. Transfer Ring Duration sets the unanswered point, and agentic Cancel Transfer returns the caller.
Retell’s disconnection reasons list Retell’s outcome codes in the table, and the blocks below were copied from Retell’s API reference: a cold transfer_call example (dedented) and an abridged TransferOptionWarmTransfer excerpt.
- type: transfer_call
name: transfer_to_support
description: Transfer to the support team.
transfer_destination:
type: predefined
number: '16175551212'
ignore_e164_validation: false
transfer_option:
type: cold_transfer
show_transferee_as_caller: false
TransferOptionWarmTransfer:
type: object
title: Warm Transfer
properties:
type:
type: string
enum:
- warm_transfer
show_transferee_as_caller:
type: boolean
agent_detection_timeout_ms:
type: number
minimum: 10000
maximum: 300000
description: The time to wait before considering transfer fails.
transfer_ring_duration_ms:
type: integer
minimum: 5000
maximum: 90000
on_hold_music:
type: string
enum:
- none
- relaxing_sound
- uplifting_beats
- ringtone
- custom
public_handoff_option:
type: object
oneOf:
- $ref: '#/components/schemas/WarmTransferPrompt'
- $ref: '#/components/schemas/WarmTransferStaticMessage'
description: If set, when transfer is successful, will say the handoff message to both the transferee and the agent receiving the transfer. Set to null to disable warm handoff.
private_handoff_option:
type: object
oneOf:
- $ref: '#/components/schemas/WarmTransferPrompt'
- $ref: '#/components/schemas/WarmTransferStaticMessage'
description: If set, when transfer is connected, will say the handoff message only to the agent receiving the transfer. Set to null to disable warm handoff.
ivr_option:
$ref: '#/components/schemas/WarmTransferPrompt'
type: object
opt_out_human_detection:
type: boolean
description: If set to true, will not perform human detection for the transfer. Default to false.
enable_bridge_audio_cue:
type: boolean
default: true
LiveKit
LiveKit’s WarmTransferTask dials the human over SIP into a separate room, plays hold music, passes the history and gives the human connect_to_caller, decline_transfer and voicemail_detected. On ringing_timeout it ends with a ToolError and the caller conversation resumes. Python ships it under beta.workflows, Node.js under stable workflows.
Below is LiveKit’s warm transfer example at commit f980b7ea, beside the WarmTransferTask source.
import os
from dotenv import load_dotenv
from support_agent import SUMMARY_INSTRUCTIONS, SupportAgent, start_session
from livekit.agents import AgentServer, JobContext, cli
from livekit.agents.beta.workflows import WarmTransferResult, WarmTransferTask
load_dotenv()
# ensure the following variables/env vars are set
SIP_TRUNK_ID = os.getenv("LIVEKIT_SIP_OUTBOUND_TRUNK") # "ST_abcxyz"
SUPERVISOR_PHONE_NUMBER = os.getenv("LIVEKIT_SUPERVISOR_PHONE_NUMBER") # "+12003004000"
SIP_NUMBER = os.getenv("LIVEKIT_SIP_NUMBER") # "+15005006000" - caller ID shown to supervisor
class SIPSupportAgent(SupportAgent):
async def _start_transfer(self) -> WarmTransferResult:
assert SIP_TRUNK_ID is not None
assert SUPERVISOR_PHONE_NUMBER is not None
return await WarmTransferTask(
sip_call_to=SUPERVISOR_PHONE_NUMBER,
sip_trunk_id=SIP_TRUNK_ID,
sip_number=SIP_NUMBER,
chat_ctx=self.chat_ctx,
# to reach an extension behind an IVR, pass DTMF tones to send once
# answered, e.g. dtmf="wwww1234#" (each `w` pauses ~0.5s):
# dtmf=SUPERVISOR_EXTENSION,
# give up if the supervisor doesn't pick up within 25s:
# ringing_timeout=25,
# add extra instructions for summarization
extra_instructions=SUMMARY_INSTRUCTIONS,
)
server = AgentServer()
@server.rtc_session(agent_name="sip-inbound")
async def entrypoint(ctx: JobContext) -> None:
await start_session(ctx, SIPSupportAgent())
if __name__ == "__main__":
cli.run_app(server)
Twilio
Twilio TwiML Refer is “only supported on SIP call legs” and posts ReferCallStatus, ReferSipResponseCode and NotifySipResponseCode to your action URL, so the app can resume when ReferCallStatus is not in-progress. A Conference is the warm pattern: participant ring timeout 5 to 600 seconds (default 60), plus AnsweredBy.
Both blocks are copied verbatim, the second from Twilio’s Conference TwiML page.
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Refer action="/handleRefer" method="POST">
<Sip>sip:alice@example.com</Sip>
</Refer>
</Response>
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Dial>
<Conference startConferenceOnEnter="true" endConferenceOnExit="true">
moderated-conference-room
</Conference>
</Dial>
</Response>
A fixture harness for warm transfer testing
A small state machine can check your transfer logic before any phone rings, by replaying scripted events for the caller, agent and human legs against the five pass rules. It refuses to pass a trace it cannot read, so a bad fixture never shows up as a green run.
An event counts only when the legs sit in the states it needs, so an illegal step stops the replay. The ten cases are the rows of the matrix in the next section, and all are illustrative fixture events, not recorded calls.
"""Warm transfer harness: one state machine, scripted event fixtures, pass criteria.
Standard library only. The Python version used is printed at the top of the run output.
All events below are "illustrative fixture events, not recorded calls". No phone
call, platform account or human destination is involved. The thresholds are
example values we picked, not a standard: no vendor or RFC publishes a maximum
hold time or a cleanup window.
A transfer is modelled as three legs (caller, agent, human) with a small state
each. An event is only accepted if the legs are in the states it needs. An
unknown event, a malformed event, a missing leg state, an illegal transition, a
bad timestamp, a duplicate case id or an empty case list is an ERROR, never a PASS (fail closed).
"""
import math
import sys
# Example thresholds (ours, configurable, not a standard).
MAX_HOLD_S = 45.0 # caller on hold, from hold_started to bridge, fallback or hangup
FALLBACK_WITHIN_S = 5.0 # unavailable destination: caller must hear a fallback within this
CLEANUP_S = 5.0 # a leg whose partner is gone must be released within this
CONTEXT_FIELDS = ("caller_identity", "intent", "steps_taken") # what the human must receive
FALLBACKS = ("return_to_agent", "callback_offer", "voicemail")
LEGS = ("caller", "agent", "human")
# event -> (required leg states, resulting leg states). leg_dropped and leg_released
# take a "leg" attribute and are handled in step().
RULES = {
"transfer_requested": ({"caller": {"connected"}, "agent": {"connected"}, "human": {"idle"}}, {}),
"hold_started": ({"caller": {"connected"}}, {"caller": "held"}),
"human_dial_started": ({"caller": {"held"}, "human": {"idle"}}, {"human": "dialing"}),
"human_ringing": ({"human": {"dialing"}}, {"human": "ringing"}),
"human_answered": ({"human": {"dialing", "ringing"}}, {"human": "answered"}),
"human_confirmed": ({"human": {"answered"}}, {}), # a person, not a machine, is on the answered leg
"human_busy": ({"human": {"dialing", "ringing"}}, {"human": "gone"}),
"human_no_answer": ({"human": {"dialing", "ringing"}}, {"human": "gone"}),
"human_declined": ({"human": {"ringing", "answered"}}, {"human": "gone"}),
"context_delivered": ({"human": {"answered", "bridged"}}, {}),
"caller_joined": ({"caller": {"held"}, "human": {"answered"}}, {"caller": "bridged", "human": "bridged"}),
"agent_left": ({"agent": {"connected"}}, {"agent": "gone"}),
"fallback_started": ({"caller": {"held"}, "human": {"gone"}}, {"caller": "connected"}),
"caller_hangup": ({"caller": {"connected", "held", "bridged"}}, {"caller": "gone"}),
"human_hangup": ({"human": {"answered", "bridged"}}, {"human": "gone"}),
"leg_dropped": None,
"leg_released": None,
"transfer_outcome_logged": ({}, {}),
"call_ended": ({}, {}),
}
UNAVAILABLE = {"human_busy": "busy", "human_no_answer": "no_answer", "human_declined": "declined"}
class ProtocolError(Exception):
pass
def step(legs, t, name, attrs, facts):
"""Apply one event to the leg states and record facts. Raises ProtocolError."""
if name not in RULES:
raise ProtocolError(f"unknown event {name!r}")
if name in ("leg_dropped", "leg_released"):
leg = attrs.get("leg")
if leg not in LEGS:
raise ProtocolError(f"{name} needs leg in {LEGS}, got {leg!r}")
if name == "leg_dropped" and legs[leg] != "bridged":
raise ProtocolError(f"leg_dropped on {leg} in state {legs[leg]!r}, needs 'bridged'")
if name == "leg_released" and legs[leg] == "gone":
raise ProtocolError(f"leg_released on {leg} already gone")
if name == "leg_dropped":
facts["drop"] = (leg, t)
facts["recovery_legs"] = [l for l in LEGS if l != leg and legs[l] not in ("idle", "gone")]
legs[leg] = "gone"
facts["gone_at"][leg] = t
return
need, setto = RULES[name]
for leg, ok in need.items():
if legs[leg] not in ok:
raise ProtocolError(f"{name} needs {leg} in {sorted(ok)}, found {legs[leg]!r}")
if name == "fallback_started":
kind = attrs.get("kind")
if kind not in FALLBACKS:
raise ProtocolError(f"unknown fallback kind {kind!r}")
if kind != "voicemail" and legs["agent"] != "connected":
raise ProtocolError(f"fallback {kind} needs the agent leg connected, found {legs['agent']!r}")
facts["fallback"] = (kind, t)
if name == "caller_hangup" and legs["caller"] == "held":
facts["abandoned_at"] = t
facts["recovery_legs"] = [l for l in LEGS if l != "caller" and legs[l] not in ("idle", "gone")]
if name in UNAVAILABLE:
facts["unavailable"] = (UNAVAILABLE[name], t)
if name == "transfer_requested":
facts["requested"] = t
if name == "hold_started":
facts["hold"] = t
if name == "human_dial_started":
facts["dial"] = t
if name == "human_answered":
facts["answered"] = t
if name == "human_confirmed":
facts["confirmed"] = t
if name == "context_delivered":
facts["context"] = (t, dict(attrs.get("fields") or {}))
if name == "caller_joined":
facts["joined"] = t
if name == "agent_left":
facts["agent_left"] = t
if name == "transfer_outcome_logged":
facts.setdefault("logged", []).append(attrs.get("outcome"))
if name == "call_ended":
facts["ended"] = t
for leg, state in setto.items():
legs[leg] = state
if state == "gone":
facts["gone_at"][leg] = t
def derive_outcome(f):
if "joined" in f:
return "dropped_after_bridge" if "drop" in f else "bridged"
if "fallback" in f:
return "fallback:" + f["fallback"][0]
if "unavailable" in f:
return "stranded"
if "abandoned_at" in f:
return "caller_abandoned"
raise ProtocolError("no outcome can be derived from this trace") # fail closed, no catch-all label
def criteria(f, legs):
"""Return a list of (name, status, critical, detail). status is PASS, FAIL or N/A."""
out = []
outcome = derive_outcome(f)
bridged = "joined" in f
if bridged:
bad = []
if f["answered"] > f["joined"]:
bad.append("caller joined before the human answered")
if f.get("agent_left", math.inf) < f["answered"]:
bad.append("agent left before the human answered")
if "agent_left" not in f:
bad.append("agent leg never left")
if f.get("confirmed", math.inf) > f["joined"]:
bad.append(f"answered at {f['answered']:.1f}s but no human confirmed before the caller joined at {f['joined']:.1f}s")
out.append(("bridge_success", "FAIL" if bad else "PASS", False, "; ".join(bad) or "human answered, caller joined, agent left"))
if "context" not in f:
out.append(("context_delivery", "FAIL", False, "no context message reached the human"))
else:
ct, fields = f["context"]
miss = [k for k in CONTEXT_FIELDS if not isinstance(fields.get(k), str) or not fields[k].strip()]
bad = []
if miss:
bad.append("missing fields " + ",".join(miss))
if ct < f["answered"]:
bad.append("context sent before the human answered")
if ct > f["joined"]:
bad.append(f"context at {ct:.1f}s arrived after the caller joined at {f['joined']:.1f}s")
out.append(("context_delivery", "FAIL" if bad else "PASS", False, "; ".join(bad) or f"all fields before the caller joined (t={ct:.1f}s)"))
else:
out.append(("bridge_success", "N/A", False, "no bridge in this case"))
out.append(("context_delivery", "N/A", False, "no bridge in this case"))
if "hold" in f:
ends = (f.get("joined"), f["fallback"][1] if "fallback" in f else None, f.get("abandoned_at"), f.get("ended"))
end = next(v for v in ends if v is not None) # explicit None checks: a join at t=0.0 is still a join
held = end - f["hold"]
ok = held <= MAX_HOLD_S
out.append(("hold_within_limit", "PASS" if ok else "FAIL", False, f"hold {held:.1f}s, example limit {MAX_HOLD_S:.0f}s"))
else:
out.append(("hold_within_limit", "FAIL", False, "caller was never put on hold"))
if "unavailable" in f:
why, ut = f["unavailable"]
fb = f.get("fallback")
ok = fb is not None and fb[1] - ut <= FALLBACK_WITHIN_S
detail = f"{why} at {ut:.1f}s, " + (f"fallback {fb[0]} at {fb[1]:.1f}s" if fb else "no fallback, caller stranded")
out.append(("unavailable_destination", "PASS" if ok else "FAIL", not ok, detail))
else:
out.append(("unavailable_destination", "N/A", False, "destination did not fail"))
if "abandoned_at" in f or "drop" in f:
at, what = (f["abandoned_at"], "caller hung up during hold") if "abandoned_at" in f else (f["drop"][1], f"{f['drop'][0]} leg dropped after bridge")
survivors = f["recovery_legs"]
late = [l for l in survivors if f["gone_at"].get(l, math.inf) - at > CLEANUP_S]
out.append(("caller_recovery", "FAIL" if late else "PASS", False,
f"{what} at {at:.1f}s; " + (f"{','.join(late)} leg not released within {CLEANUP_S:.0f}s" if late else f"other legs released within {CLEANUP_S:.0f}s")))
else:
out.append(("caller_recovery", "N/A", False, "caller did not hang up during hold and no drop"))
orphans = [l for l in LEGS if legs[l] != "gone"]
out.append(("no_orphan_legs", "FAIL" if orphans else "PASS", False, "legs still open at call end: " + ",".join(orphans) if orphans else "all legs closed at call end"))
logged = f.get("logged", [])
ok = logged == [outcome]
out.append(("outcome_logged", "PASS" if ok else "FAIL", False, f"derived {outcome!r}, logged {logged!r}"))
return out
def run_case(case, quiet=False):
"""Replay one fixture. Returns dict(verdict, criteria, error). Never raises."""
say = (lambda s: None) if quiet else print
try:
legs = dict(case["legs"])
if sorted(legs) != sorted(LEGS):
raise ProtocolError(f"missing leg state, have {sorted(legs)}, need {sorted(LEGS)}")
facts = {"gone_at": {}}
prev = None
events = case["events"]
if not events:
raise ProtocolError("empty event list")
for t, name, attrs in events:
if isinstance(t, bool) or not isinstance(t, (int, float)) or not math.isfinite(t) or t < 0 or (prev is not None and t < prev):
raise ProtocolError(f"bad timestamp {t!r} at event {name!r}")
if "ended" in facts:
raise ProtocolError(f"event {name!r} after call_ended")
step(legs, float(t), name, attrs, facts)
prev = t
extra = ",".join(f"{k}={v}" for k, v in attrs.items() if k != "fields")
if "fields" in attrs:
extra = (extra + "," if extra else "") + "fields=" + "+".join(sorted(attrs["fields"]))
say(f" t={t:6.1f}s {name:<24}{extra:<42}| caller={legs['caller']:<9} agent={legs['agent']:<9} human={legs['human']}")
if "ended" not in facts:
raise ProtocolError("trace does not end with call_ended")
crit = criteria(facts, legs)
verdict = "FAIL" if any(s == "FAIL" for _, s, _, _ in crit) else "PASS"
return {"verdict": verdict, "criteria": crit, "error": None, "facts": facts}
except (ProtocolError, KeyError, TypeError, AttributeError, ValueError) as e:
return {"verdict": "ERROR", "criteria": [], "error": f"{type(e).__name__}: {e}", "facts": {}}
def gate(results, min_pass_rate=0.9):
"""Release gate, fails closed. Returns (blocked, reasons)."""
if not results:
return True, ["no cases"]
reasons = []
errors = sum(r["verdict"] == "ERROR" for r in results)
critical = sum(1 for r in results for _, s, c, _ in r["criteria"] if s == "FAIL" and c)
rate = sum(r["verdict"] == "PASS" for r in results) / len(results)
if errors:
reasons.append(f"{errors} case(s) ERROR")
if critical:
reasons.append(f"{critical} critical failure(s), pass rate cannot clear these")
if rate < min_pass_rate:
reasons.append(f"pass rate {rate:.3f} below target {min_pass_rate}")
return bool(reasons), reasons
# ---- fixtures: illustrative fixture events, not recorded calls ----
LEGS0 = {"caller": "connected", "agent": "connected", "human": "idle"}
CTX = {"caller_identity": "fixture caller A", "intent": "dispute a charge", "steps_taken": "identity checked, charge found"}
def bridged(answer_t, ctx_t, join_t, ctx=CTX, hold_t=1, confirm=True):
"""Shared prefix: request, hold, dial, ring, answer, human confirmed, optional context, join, agent leaves."""
ev = [(0, "transfer_requested", {}), (hold_t, "hold_started", {}), (hold_t, "human_dial_started", {}),
(hold_t + 2, "human_ringing", {}), (answer_t, "human_answered", {})]
if confirm:
ev.append((answer_t, "human_confirmed", {}))
if ctx_t is not None:
ev.append((ctx_t, "context_delivered", {"fields": ctx}))
ev += [(join_t, "caller_joined", {}), (join_t, "agent_left", {})]
ev.sort(key=lambda e: e[0]) # stable: events at the same time keep their order
return ev
CASES = [
{"id": "success", "expect": "PASS", "legs": LEGS0,
"events": bridged(11, 12, 15) + [(180, "caller_hangup", {}), (181, "human_hangup", {}),
(181, "transfer_outcome_logged", {"outcome": "bridged"}), (181, "call_ended", {})]},
{"id": "context_missing", "expect": "FAIL", "legs": LEGS0,
"events": bridged(11, None, 15) + [(180, "caller_hangup", {}), (181, "human_hangup", {}),
(181, "transfer_outcome_logged", {"outcome": "bridged"}), (181, "call_ended", {})]},
{"id": "context_late", "expect": "FAIL", "legs": LEGS0,
"events": bridged(11, 18, 15) + [(180, "caller_hangup", {}), (181, "human_hangup", {}),
(181, "transfer_outcome_logged", {"outcome": "bridged"}), (181, "call_ended", {})]},
{"id": "hold_over_limit", "expect": "FAIL", "legs": LEGS0,
"events": bridged(66, 67, 70) + [(200, "caller_hangup", {}), (201, "human_hangup", {}),
(201, "transfer_outcome_logged", {"outcome": "bridged"}), (201, "call_ended", {})]},
{"id": "voicemail_answered", "expect": "FAIL", "legs": LEGS0,
"events": bridged(11, 12, 15, confirm=False) + [(180, "caller_hangup", {}), (181, "human_hangup", {}),
(181, "transfer_outcome_logged", {"outcome": "bridged"}), (181, "call_ended", {})]},
{"id": "destination_busy", "expect": "PASS", "legs": LEGS0,
"events": [(0, "transfer_requested", {}), (1, "hold_started", {}), (1, "human_dial_started", {}),
(3, "human_ringing", {}), (5, "human_busy", {}), (6, "fallback_started", {"kind": "return_to_agent"}),
(40, "caller_hangup", {}), (40, "leg_released", {"leg": "agent"}),
(40, "transfer_outcome_logged", {"outcome": "fallback:return_to_agent"}), (40, "call_ended", {})]},
{"id": "no_answer", "expect": "PASS", "legs": LEGS0,
"events": [(0, "transfer_requested", {}), (1, "hold_started", {}), (1, "human_dial_started", {}),
(3, "human_ringing", {}), (33, "human_no_answer", {}), (34, "fallback_started", {"kind": "callback_offer"}),
(60, "caller_hangup", {}), (60, "leg_released", {"leg": "agent"}),
(60, "transfer_outcome_logged", {"outcome": "fallback:callback_offer"}), (60, "call_ended", {})]},
{"id": "declined", "expect": "FAIL", "legs": LEGS0,
"events": [(0, "transfer_requested", {}), (1, "hold_started", {}), (1, "human_dial_started", {}),
(3, "human_ringing", {}), (12, "human_answered", {}), (14, "human_declined", {}),
(60, "caller_hangup", {}), (60, "leg_released", {"leg": "agent"}),
(60, "transfer_outcome_logged", {"outcome": "stranded"}), (60, "call_ended", {})]},
{"id": "caller_hangup_during_hold", "expect": "PASS", "legs": LEGS0,
"events": [(0, "transfer_requested", {}), (1, "hold_started", {}), (1, "human_dial_started", {}),
(3, "human_ringing", {}), (9, "caller_hangup", {}), (10, "leg_released", {"leg": "human"}),
(10, "leg_released", {"leg": "agent"}),
(10, "transfer_outcome_logged", {"outcome": "caller_abandoned"}), (10, "call_ended", {})]},
{"id": "drop_after_bridge", "expect": "PASS", "legs": LEGS0,
"events": bridged(11, 12, 15) + [(95, "leg_dropped", {"leg": "human"}), (97, "leg_released", {"leg": "caller"}),
(97, "transfer_outcome_logged", {"outcome": "dropped_after_bridge"}), (97, "call_ended", {})]},
]
def check_ids(cases):
ids = [c["id"] for c in cases]
if not ids or len(ids) != len(set(ids)):
raise ProtocolError("empty case list or duplicate case id")
def fail_closed_checks():
"""Each bad input must come back ERROR (or a blocked gate), never PASS."""
base = CASES[0]["events"]
bad = {
"unknown_event": [(0, "transfer_requested", {}), (1, "caller_teleported", {})],
"illegal_transition": [(0, "transfer_requested", {}), (1, "caller_joined", {})],
"non_finite_time": [(0, "transfer_requested", {}), (float("nan"), "hold_started", {})],
"no_call_ended": base[:-1],
"event_after_end": base + [(182, "caller_hangup", {})],
"empty_events": [],
"malformed_event": [(0, "transfer_requested")],
"no_derivable_outcome": [(0, "transfer_requested", {}), (1, "call_ended", {})],
}
for name, ev in bad.items():
r = run_case({"id": name, "legs": LEGS0, "events": ev}, quiet=True)
assert r["verdict"] == "ERROR", (name, r)
print(f" {name:<20} -> ERROR ({r['error']})")
r = run_case({"id": "missing_leg", "legs": {"caller": "connected", "agent": "connected"}, "events": base}, quiet=True)
assert r["verdict"] == "ERROR", r
print(f" {'missing_leg_state':<20} -> ERROR ({r['error']})")
assert gate([])[0], "empty case list must block"
print(f" {'empty_case_list':<20} -> gate BLOCKED {gate([])[1]}")
assert gate([{"verdict": "ERROR", "criteria": []}])[0]
try:
check_ids(CASES + [CASES[0]])
raise AssertionError("duplicate id accepted")
except ProtocolError as e:
print(f" {'duplicate_case_id':<20} -> ERROR (ProtocolError: {e})")
def check_log_record(results):
"""The illustrative record must agree with the destination_busy case it mirrors. Raises AssertionError."""
import json
import os
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "transfer_log_record.json")
with open(path) as fh:
rec = json.load(fh)
need = {"transfer_id", "legs", "mode", "destination", "t", "request_to_fallback_seconds", "outcome", "provider", "provider_code"}
assert need <= set(rec), f"record missing {sorted(need - set(rec))}"
assert rec["mode"] in ("blind", "warm"), rec["mode"]
r = results[[c["id"] for c in CASES].index("destination_busy")]
f = r["facts"]
outcome = derive_outcome(f)
assert rec["outcome"] == outcome, (rec["outcome"], outcome)
mirror = {"requested": f["requested"], "destination_failed": f["unavailable"][1],
"fallback_started": f["fallback"][1], "call_ended": f["ended"]}
for key, want in mirror.items():
assert rec["t"][key] == want, (key, rec["t"][key], want)
assert rec["request_to_fallback_seconds"] == f["fallback"][1] - f["requested"]
nulls = sorted(k for k, v in rec["t"].items() if v is None)
print(f" record outcome {rec['outcome']!r} matches the destination_busy case; mirrored times {mirror}")
print(f" null fields (a Twilio Refer action callback does not expose them): {', '.join(nulls)}")
def main():
print(f"Python {sys.version.split()[0]}, standard library only")
print("Warm transfer harness. All events are illustrative fixture events, not recorded calls.")
print(f"Example thresholds (ours, not a standard): max hold {MAX_HOLD_S:.0f}s, fallback within {FALLBACK_WITHIN_S:.0f}s, "
f"leg cleanup within {CLEANUP_S:.0f}s, context fields {', '.join(CONTEXT_FIELDS)}")
check_ids(CASES)
results, mismatches = [], []
for case in CASES:
print(f"\nCASE {case['id']} (expected {case['expect']})")
r = run_case(case)
results.append(r)
for name, status, critical, detail in r["criteria"]:
if status != "N/A":
print(f" {status:<4} {name}{' [critical]' if critical else ''}: {detail}")
if r["error"]:
print(f" ERROR {r['error']}")
print(f" VERDICT {r['verdict']}")
if r["verdict"] != case["expect"]:
mismatches.append(case["id"])
n = len(results)
p = sum(r["verdict"] == "PASS" for r in results)
f = sum(r["verdict"] == "FAIL" for r in results)
e = sum(r["verdict"] == "ERROR" for r in results)
print(f"\nSUMMARY cases={n} PASS={p} FAIL={f} ERROR={e} verdicts matching expectation={n - len(mismatches)}/{n}")
for target in (0.9, 0.5):
blocked, why = gate(results, min_pass_rate=target)
print(f"RELEASE GATE if these were live results (target pass rate {target}): {'BLOCKED' if blocked else 'OPEN'}"
+ (" because " + "; ".join(why) if why else ""))
print("\nFAIL-CLOSED CHECKS")
fail_closed_checks()
print("\nfail-closed checks: ok")
print("\nLOG RECORD CHECK (transfer_log_record.json is an illustrative record, not a recorded call)")
check_log_record(results)
print("\nlog record check: ok")
print("\nNOT RUN HERE (see snippets.md): Vapi, Retell, LiveKit and Twilio snippets. "
"not executed: needs a telephony account, phone numbers and a human destination")
return 1 if mismatches or e else 0
if __name__ == "__main__":
sys.exit(main())
python3 -I transfer_harness.py
Save it as transfer_harness.py beside transfer_log_record.json from the logging section, which the script reads by name. We tested end to end with Python 3.12.5: exit 0, every verdict as expected, and the declined case’s critical failure keeps the gate blocked even at 0.5.
CASE voicemail_answered (expected FAIL)
t= 0.0s transfer_requested | caller=connected agent=connected human=idle
t= 1.0s hold_started | caller=held agent=connected human=idle
t= 1.0s human_dial_started | caller=held agent=connected human=dialing
t= 3.0s human_ringing | caller=held agent=connected human=ringing
t= 11.0s human_answered | caller=held agent=connected human=answered
t= 12.0s context_delivered fields=caller_identity+intent+steps_taken | caller=held agent=connected human=answered
t= 15.0s caller_joined | caller=bridged agent=connected human=bridged
t= 15.0s agent_left | caller=bridged agent=gone human=bridged
t= 180.0s caller_hangup | caller=gone agent=gone human=bridged
t= 181.0s human_hangup | caller=gone agent=gone human=gone
t= 181.0s transfer_outcome_logged outcome=bridged | caller=gone agent=gone human=gone
t= 181.0s call_ended | caller=gone agent=gone human=gone
FAIL bridge_success: answered at 11.0s but no human confirmed before the caller joined at 15.0s
PASS context_delivery: all fields before the caller joined (t=12.0s)
PASS hold_within_limit: hold 14.0s, example limit 45s
PASS no_orphan_legs: all legs closed at call end
PASS outcome_logged: derived 'bridged', logged ['bridged']
VERDICT FAIL
CASE declined (expected FAIL)
t= 0.0s transfer_requested | caller=connected agent=connected human=idle
t= 1.0s hold_started | caller=held agent=connected human=idle
t= 1.0s human_dial_started | caller=held agent=connected human=dialing
t= 3.0s human_ringing | caller=held agent=connected human=ringing
t= 12.0s human_answered | caller=held agent=connected human=answered
t= 14.0s human_declined | caller=held agent=connected human=gone
t= 60.0s caller_hangup | caller=gone agent=connected human=gone
t= 60.0s leg_released leg=agent | caller=gone agent=gone human=gone
t= 60.0s transfer_outcome_logged outcome=stranded | caller=gone agent=gone human=gone
t= 60.0s call_ended | caller=gone agent=gone human=gone
FAIL hold_within_limit: hold 59.0s, example limit 45s
FAIL unavailable_destination [critical]: declined at 14.0s, no fallback, caller stranded
PASS caller_recovery: caller hung up during hold at 60.0s; other legs released within 5s
PASS no_orphan_legs: all legs closed at call end
PASS outcome_logged: derived 'stranded', logged ['stranded']
VERDICT FAIL
SUMMARY cases=10 PASS=5 FAIL=5 ERROR=0 verdicts matching expectation=10/10
RELEASE GATE if these were live results (target pass rate 0.9): BLOCKED because 1 critical failure(s), pass rate cannot clear these; pass rate 0.500 below target 0.9
RELEASE GATE if these were live results (target pass rate 0.5): BLOCKED because 1 critical failure(s), pass rate cannot clear these
The harness also fails closed. Unknown or malformed events, a missing leg state, a non-finite time, a trace with no call_ended, an empty event list, a duplicate case id and an empty case list all come back ERROR or a blocked gate.
FAIL-CLOSED CHECKS
unknown_event -> ERROR (ProtocolError: unknown event 'caller_teleported')
illegal_transition -> ERROR (ProtocolError: caller_joined needs caller in ['held'], found 'connected')
non_finite_time -> ERROR (ProtocolError: bad timestamp nan at event 'hold_started')
no_call_ended -> ERROR (ProtocolError: trace does not end with call_ended)
event_after_end -> ERROR (ProtocolError: event 'caller_hangup' after call_ended)
empty_events -> ERROR (ProtocolError: empty event list)
malformed_event -> ERROR (ValueError: not enough values to unpack (expected 3, got 2))
no_derivable_outcome -> ERROR (ProtocolError: no outcome can be derived from this trace)
missing_leg_state -> ERROR (ProtocolError: missing leg state, have ['agent', 'caller'], need ['agent', 'caller', 'human'])
empty_case_list -> gate BLOCKED ['no cases']
duplicate_case_id -> ERROR (ProtocolError: empty case list or duplicate case id)
fail-closed checks: ok
Build the voice agent warm transfer test matrix and regression plan
Put every transfer case in one matrix with its fixture, its pass rule and the live signal you expect from your platform. Re-run that matrix whenever the prompt, the transfer tool or the routing changes, because a provider move alone can turn a Vapi warm mode into a blind transfer.
| Case | Fixture events | Pass rule | Harness verdict | Live signal to compare |
|---|---|---|---|---|
| success | Confirm 11s, context 12s, join 15s | All checks | PASS | LiveKit WarmTransferResult |
| context_missing | No context event | Context before join | FAIL | No whisper or handoff message |
| context_late | Context 18s, join 15s | Context before join | FAIL | Your log timestamps |
| hold_over_limit | Answer at 66s | Hold at most 45s | FAIL | Your hold timer |
| voicemail_answered | Answered, never confirmed | Person confirmed first | FAIL | Vapi blind or traditional warm on Twilio: voicemail counts as answered; LiveKit voicemail_detected |
| destination_busy | Busy 5s, return to agent 6s | Fallback within 5s | PASS | Twilio Refer 486; Vapi call.forwarding.operator-busy (outcome detection on) |
| no_answer | No answer 33s, callback 34s | Fallback within 5s | PASS | Vapi call.forwarding.no-answer (outcome detection on); Retell transfer_cancelled |
| declined | Declined 14s, no fallback | Fallback within 5s, critical | FAIL | LiveKit “human agent declined to connect” |
| caller_hangup_during_hold | Caller gone 9s, legs freed 10s | Cleanup within 5s | PASS | Twilio ReferCallStatus canceled |
| drop_after_bridge | Human drops 95s, caller freed 97s | Cleanup within 5s | PASS | Leg end times |
Re-run on four triggers: a prompt change; a transfer tool or destination change; a routing change to numbers, hours or queues; and a telephony provider change. Keep every must-pass case even when the baseline passes them all, and block the release on any stranded caller whatever the pass rate.
Fixture replay checks your logic and fixed transcripts measure drift on past contexts, but neither shows how new callers behave, so call a reachable, a busy and an unanswered number. Retell’s Transfer Call “works on phone calls only, not web calls”, and Vapi says “Test the transfer through the same Twilio phone number and destination you will use in production”.
Run the fixtures in CI with voice agent regression testing in CI/CD.

What to log for every transfer
Log one record per transfer that ties the three legs together, names the mode, stamps every step and stores the provider’s own outcome code. Without that record, a busy desk, a voicemail pickup and a dropped bridge all look like the same finished call in your dashboard.
Store the transfer id, three leg ids, mode, destination, step times, request-to-fallback seconds, context fields, outcome and provider code. Outcomes are the six the fixtures log (bridged, fallback:return_to_agent, fallback:callback_offer, stranded, caller_abandoned, dropped_after_bridge) plus fallback:voicemail, which the code allows.
On Vapi, “No server message reports a failed phone or SIP transfer”, and an unconfirmed Transfer Completed result “doesn’t confirm the destination answered or even received the call”. With Vapi blind transfer the recording and transcript stop when the transfer starts, so record from the media path.
The sample below mirrors destination_busy as a blind Twilio Refer with its busy codes: an illustrative record, not a recorded call.
{
"_label": "illustrative record, not a recorded call; times mirror the harness case destination_busy, provider codes mirror the busy example on the Twilio Refer docs page; a null time means a Twilio Refer action callback does not expose that event",
"transfer_id": "tr_0001",
"legs": {"caller": "call_caller_0001", "agent": "call_agent_0001", "human": "call_human_0001"},
"mode": "blind",
"destination": "sip:support@example.com",
"t": {
"requested": 0.0,
"hold_start": null,
"dial": null,
"ringing": null,
"answered": null,
"destination_failed": 5.0,
"fallback_started": 6.0,
"context_delivered": null,
"caller_joined": null,
"call_ended": 40.0
},
"request_to_fallback_seconds": 6.0,
"context_fields_present": [],
"outcome": "fallback:return_to_agent",
"provider": "twilio_sip_refer",
"provider_code": {
"ReferCallStatus": "busy",
"ReferSipResponseCode": "202",
"NotifySipResponseCode": "486"
}
}
Running transfer scenarios in Future AGI Simulate
Future AGI Simulate dials your voice agent over the phone while a persona plays the caller, and a scenario graph can route that call through a Transfer call node. Each call comes back with its transcript, its recording and the evals scored on that call.
To connect your voice agent to Simulate, pick Vapi or Retell (native), Bland.ai from the provider list, or Others with any number Simulation can dial.
In scenario graphs with a Transfer call node, that node “Hands off, typically to a human, and can merge paths”, and each row pairs a persona with one case.
Each call in calls, transcripts and per-call evals shows what it cost, and a voice call reruns with Run Evals or Run test + Evals.
Tool call evaluation for Vapi agents scores the tool calls a Vapi agent made, set when the run is created. Voice simulation runs on Future AGI Cloud or an Enterprise deployment, with the open-source core at Future AGI on GitHub.
Before your next caller asks for a human
Back at the dental clinic, the busy desk line triggers a callback offer within seconds, and the person who calls back already has her name and the disputed charge. Your log shows a fallback where it used to show a forwarded call, so you see the failure the day it happens.
This week, run the ten fixture cases against your transfer configuration and fix the first failure. Before the next release, add the busy and unanswered live calls, and keep the escalation design itself in the AI voice agents for customer service playbook.
Frequently Asked Questions
How do you test a voice agent warm transfer end to end?
Warm transfer vs cold transfer: what is the difference?
What does warm transfer mean?
What are the three types of call transfer?
How does warm transfer work in Retell AI?
Speech emotion recognition gives a voice agent a model's guess about tone. Score the detector and the escalation rule apart, and pick audio you can license.
How to run IVR testing when your agent is the caller: send DTMF the far-end menu accepts, handle changed menus, timeouts and retries, and reach the right desk.
Voice agent echo makes an agent transcribe its own TTS as the caller and cut itself off. Reproduce it with a playback sweep, read the trace, fix the source.