microscopic-dress-75199
12/09/2025, 6:30 PMtall-airline-16756
12/09/2025, 6:30 PMtall-airline-16756
12/09/2025, 6:30 PMmicroscopic-dress-75199
12/09/2025, 6:30 PMtall-airline-16756
12/09/2025, 6:31 PM{
"room_name": "call-12345",
"audio_only": false,
"file_outputs": [
{
"filepath": "/out/recordings/call-12345.mp4"
}
]
}
2) Start via cURL against your Egress service:
curl -X POST http://YOUR_EGRESS_HOST:7880/twirp/livekit.Egress/StartRoomCompositeEgress \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN_WITH_roomRecord" \
-d '@request.json'
• Replace YOUR_EGRESS_HOST, YOUR_ACCESS_TOKEN_WITH_roomRecord.
• Save the JSON above as request.json.
3) Ensure your self-hosted Egress can write the file:
• Run Egress with a host volume mount so /out/recordings maps to a local path:
docker run --rm \
-e EGRESS_CONFIG_FILE=/configs/config.yaml \
-v /path/to/configs:/configs \
-v /path/to/recordings:/out/recordings \
livekit/egress
• Confirm /path/to/recordings has write permissions and sufficient disk space.
4) Stopping the recording:
• Use the egress ID returned when you started the job:
curl -X POST http://YOUR_EGRESS_HOST:7880/twirp/livekit.Egress/StopEgress \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN_WITH_roomRecord" \
-d '{"egress_id":"EG_XXXXXXXXXXXX"}'
Notes and options:
• To record audio-only set "audio_only": true.
• The Egress service will join the room and record SIP participants as part of the room composite.
• Ensure the access token includes the roomRecord permission.
• Check Egress logs for status and errors if the file does not appear.
Would you like the same example for audio-only, an S3 output instead of local file, or a sample config.yaml for your Egress service?
Sources: Egress API | LiveKit docs | Egress output types | LiveKit docs | Self-hosting the Egress Service | LiveKit docsmicroscopic-dress-75199
12/09/2025, 6:32 PM"""Helper utilities for LiveKit Egress recording.
This module provides functions for:
- Constructing egress file paths with phone normalization
- Starting room composite egress recordings (audio-only for telephony)
- Stopping egress recordings gracefully
"""
import logging
from datetime import datetime
from typing import Optional
from livekit import api
from livekit.protocol import egress
from ..state.session_state import ReceptionistState
from .fuzzy_matcher import normalize_phone
logger = logging.getLogger("egress_helper")
def construct_egress_filepath(caller_id: str, room_name: str) -> str:
"""Construct file path for egress recording.
File structure: calls/{normalized_phone}/{YYYY-MM-DD}/{room_name}.mp4
Args:
caller_id: Phone number from SIP (will be normalized)
room_name: LiveKit room name (unique identifier)
Returns:
Relative file path for recording
Examples:
>>> construct_egress_filepath("+1-416-555-1234", "RM_abc123")
"calls/4165551234/2025-12-09/RM_abc123.mp4"
>>> construct_egress_filepath("unknown", "RM_xyz789")
"calls/unknown/2025-12-09/RM_xyz789.mp4"
"""
# Normalize phone (e.g., "+1-416-555-1234" -> "4165551234")
normalized = normalize_phone(caller_id)
if not normalized:
normalized = "unknown"
# Canadian date format: YYYY-MM-DD
date_str = datetime.now().strftime("%Y-%m-%d")
# Result: calls/4165551234/2025-12-09/RM_abc123def456.mp4
return f"calls/{normalized}/{date_str}/{room_name}.mp4"
async def start_room_recording(
lkapi: api.LiveKitAPI,
room_name: str,
caller_id: str,
userdata: ReceptionistState,
) -> Optional[str]:
"""Start audio-only room composite egress recording.
Steps:
1. Construct file path using normalized phone and date
2. Create RoomCompositeEgressRequest with EncodedFileOutput
3. Call api.egress.start_room_composite_egress()
4. Update userdata with egress_id, status, and file_path
5. Return egress_id or None on error
Args:
lkapi: LiveKitAPI instance from JobContext
room_name: LiveKit room name
caller_id: Phone number from SIP
userdata: ReceptionistState to update with egress info
Returns:
egress_id string if successful, None if failed
Note:
Recording failures are logged but do NOT raise exceptions
to avoid breaking the call. Recording is best-effort.
"""
try:
# Step 1: Construct file path
filepath = construct_egress_filepath(caller_id, room_name)
logger.info(f"Starting egress recording: {filepath}")
# Step 2: Create RoomCompositeEgressRequest
request = api.RoomCompositeEgressRequest(
room_name=room_name,
layout="speaker",
preset=api.EncodingOptionsPreset.H264_720P_30,
file_outputs=[
api.EncodedFileOutput(
file_type=egress.EncodedFileType.MP4,
filepath=filepath,
)
],
)
# Step 3: Call egress API
egress_info = await lkapi.egress.start_room_composite_egress(request)
# Step 4: Update userdata
userdata.egress_id = egress_info.egress_id
userdata.egress_status = "recording"
userdata.egress_file_path = filepath
userdata.egress_started_at = datetime.now()
logger.info(
f"✓ Egress recording started successfully | "
f"egress_id={egress_info.egress_id} | "
f"file={filepath}"
)
# Step 5: Return egress_id
return egress_info.egress_id
except Exception as e:
logger.error(f"Failed to start egress recording: {e}", exc_info=True)
userdata.egress_status = "failed"
return None
async def stop_room_recording(
lkapi: api.LiveKitAPI,
egress_id: str,
userdata: ReceptionistState,
) -> bool:
"""Stop active egress recording.
Steps:
1. Call api.egress.stop_egress(StopEgressRequest(egress_id=egress_id))
2. Update userdata status to "completed" or "failed"
3. Log final file path
4. Return success status
Args:
lkapi: LiveKitAPI instance from JobContext
egress_id: Egress session ID from start_room_recording
userdata: ReceptionistState to update with completion status
Returns:
True if successfully stopped, False otherwise
Note:
Errors are logged but do NOT raise exceptions to avoid
blocking call termination.
"""
try:
# Step 1: Stop egress
logger.info(f"Stopping egress recording: {egress_id}")
request = api.StopEgressRequest(egress_id=egress_id)
egress_info = await lkapi.egress.stop_egress(request)
# Step 2: Update userdata status
# EgressStatus enum values: https://docs.livekit.io/home/egress/api/#egressstatus
if egress_info.status == api.EgressStatus.EGRESS_COMPLETE:
userdata.egress_status = "completed"
logger.info(
f"✓ Egress recording completed | "
f"egress_id={egress_id} | "
f"file={userdata.egress_file_path}"
)
return True
else:
userdata.egress_status = "failed"
logger.warning(
f"Egress stopped but status is not COMPLETE: {egress_info.status}"
)
return False
except Exception as e:
logger.error(f"Failed to stop egress recording: {e}", exc_info=True)
userdata.egress_status = "failed"
return Falsetall-airline-16756
12/09/2025, 6:32 PMstart_room_recording(...) when the SIP call/room is established (pass a LiveKitAPI instance, room name, caller_id, and your ReceptionistState).
• Call stop_room_recording(...) when the call ends (use the returned egress_id stored on your state).
• Ensure the LiveKitAPI (lkapi) you pass is initialized and authenticated with an API token that includes the roomRecord permission.
Configuration and deployment checks (required)
• Egress service must be self-hosted with a writable mount for /out/recordings (or whatever path you map). Your filepath (e.g., calls/…/room.mp4) will be relative to the container path you mount.
• Ensure the egress process has permission to write into the mounted directory and there’s enough disk space.
• Ensure your egress service can connect to the LiveKit server (ws URL, API key/secret in config.yaml).
Small code suggestion
• Your filepath is relative; the Egress service will write relative to its container filesystem. If you want clarity, consider prefixing with /out/recordings/ in construct_egress_filepath (or keep as-is if you intentionally want a relative path and map that path on the container).
Example: return f"/out/recordings/calls/{normalized}/{date_str}/{room_name}.mp4"
Optional things I can help with
• Example of initializing livekit.api.LiveKitAPI and generating a token with roomRecord.
• Example config.yaml and docker run command for Egress with volume mounts.
• Convert your helper to audio-only explicitly (set audio_only=True in the RoomComposite request) — I can patch that snippet if you'd like.
Which of the optional items would you like next?microscopic-dress-75199
12/09/2025, 6:34 PM@server.rtc_session(
agent_name=os.getenv("AGENT_NAME", "telephony-voice-assistant"),
)
async def entrypoint(ctx: JobContext):
"""Main entrypoint function for the Realtime Agent (v1.0 pattern with AgentServer)."""
# Logging setup
ctx.log_context_fields = {
"room_name": ctx.room.name,
}
# Parse job metadata for instruction customization
metadata = None
try:
if ctx.job.metadata:
metadata = json.loads(ctx.job.metadata)
# Handle double-encoded JSON (metadata is a JSON string)
if isinstance(metadata, str):
metadata = json.loads(metadata)
logger.info(f"Job metadata loaded: {metadata}")
else:
logger.info("No metadata provided to job")
except json.JSONDecodeError:
logger.error(f"Invalid JSON in job metadata: {ctx.job.metadata}")
return
# Load system defaults and merge with frontend overrides
# Priority: settings.json (system defaults) → metadata.agent_config (frontend overrides)
agent_config = AgentConfig.load_defaults()
agent_config = agent_config.merge_with_metadata(metadata)
logger.info("✓ Final agent configuration applied")
logger.debug(f"Config: {agent_config.to_dict()}")
# Connect to Neon database BEFORE ctx.connect() (async network call)
neon_client = ctx.proc.userdata.get("neon_client")
if neon_client and not neon_client.pool:
try:
await neon_client.connect()
logger.info("✓ Connected to Neon database")
except Exception as e:
logger.error(f"Failed to connect to Neon: {e}", exc_info=True)
neon_client = None
elif not neon_client:
logger.debug(
"NeonClient not initialized in prewarm, tool failure tracking disabled"
)
# Connect to room FIRST (required to access remote_participants)
await ctx.connect()
# Extract caller_id from SIP participant (uses helper function)
caller_id, sip_participant_identity, sip_participant_sid = extract_caller_info(
ctx.room, agent_config
)
# Create ReceptionistState
userdata = ReceptionistState()
userdata.notion_schemas = ctx.proc.userdata.get("notion_schemas", {})
userdata.caller_id = caller_id
userdata.all_clients = ctx.proc.userdata.get("all_clients", [])
# Store customer SIP participant info for warm transfer track subscription control
# userdata.customer_sip_identity = sip_participant_identity
# userdata.customer_sip_sid = sip_participant_sid
# Perform phone lookup early in session (if caller_id available and client database configured)
client_database_id = os.getenv("CLIENT_DATABASE_ID", "")
notion_token = os.getenv("NOTION_TOKEN", "")
# Assign NeonClient from prewarm (may be None if not configured)
userdata.neon_client = neon_client
notion_client = NotionAPIClient(api_token=notion_token)
# Note: Egress recording will start automatically when first audio track is published
# See event_registration.py:on_track_subscribed for the egress start logic
# Perform fuzzy phone lookup (uses helper function)
# FIX: Use reference to all_clients instead of copying into userdata (memory optimization)
all_clients_ref = ctx.proc.userdata.get("all_clients", [])
logger.info(f"✓ Prewarmed client list available: {len(all_clients_ref)} clients")
lookup_result = perform_phone_lookup(caller_id, userdata.all_clients, min_overlap=8)
# Apply lookup results to userdata
if lookup_result["type"] == "single":
userdata.client_match = lookup_result["match"]
userdata.caller_company = lookup_result["company"]
userdata.phone_lookup_complete = True
elif lookup_result["type"] == "multiple":
userdata.multiple_matches = lookup_result["matches"]
userdata.caller_company = lookup_result["company"]
userdata.phone_lookup_complete = True
elif lookup_result["type"] == "none":
userdata.no_match_found = True
userdata.phone_lookup_complete = True
elif lookup_result["type"] == "error":
userdata.notion_error = lookup_result.get("error", "Unknown error")
# Initialize background audio player for on-demand sounds
userdata.background_audio = BackgroundAudioPlayer()
# Create session components (LLM, STT, TTS, turn detector) using helper
components = create_session_components(agent_config)
silero_vad = ctx.proc.userdata["vad"]
# Log agent mode
mode = "realtime" if agent_config.llm.use_realtime else "pipeline"
logger.info(f"Agent mode: {mode} ({agent_config.llm.provider})")
if agent_config.llm.use_realtime:
logger.info(
f"Realtime config: {agent_config.llm.model}, temp={agent_config.llm.temperature}, text-only"
)
logger.info(f"Realtime TTS: {agent_config.tts.provider}")
# Create AgentSession with conditional parameters (uses helper)
session: AgentSession = create_agent_session(
agent_config, components, userdata, silero_vad
)
# Setup Langfuse tracing
setup_session_tracing(ctx.room.name, userdata, mode=mode)
# Get Notion database ID for call logs
calls_database_id = os.getenv("CALLS_DATA_DATABASE_ID", "")
client_database_id = os.getenv("CLIENT_DATABASE_ID", "")
# Render agent instructions (supports metadata overrides for testing)
company_config = "cloudmetrics" # Can be overridden via metadata if needed
if metadata and "company_config" in metadata:
company_config = metadata["company_config"]
logger.info(f"Using company_config from metadata: {company_config}")
# Extract client database field names from schema
client_database_fields = "First Name, Last Name, Email, Phone, Company name"
client_schema = ctx.proc.userdata.get("notion_schemas", {}).get("client_database")
if client_schema and "properties" in client_schema:
client_database_fields = ", ".join(client_schema["properties"].keys())
logger.info(f"Client database fields extracted: {client_database_fields}")
instructions = render_agent_instructions(
caller_id=caller_id,
company_config=company_config,
call_logs_database_id=calls_database_id,
client_database_id=client_database_id,
agent_config=agent_config,
client_database_fields=client_database_fields,
userdata=userdata,
)
# Store final configuration metadata for RPC access
final_config_metadata = {
"instructions": instructions,
"configuration": {
"llm": {
"provider": agent_config.llm.provider,
"model": agent_config.llm.model,
"temperature": agent_config.llm.temperature,
"use_realtime": agent_config.llm.use_realtime,
},
"tts": {
"provider": agent_config.tts.provider,
},
"prompt": {
"name": agent_config.prompt_name,
"label": agent_config.prompt_label,
},
"caller_id": caller_id,
"mode": "realtime" if agent_config.llm.use_realtime else "pipeline",
},
}
# Add min_interruption_words only for pipeline mode
if not agent_config.llm.use_realtime:
final_config_metadata["configuration"]["min_interruption_words"] = (
agent_config.agent_session.min_interruption_words
)
# Add optional TTS fields only if they're configured
if agent_config.tts.model:
final_config_metadata["configuration"]["tts"]["model"] = agent_config.tts.model
if agent_config.tts.voice_id:
final_config_metadata["configuration"]["tts"]["voice_id"] = (
agent_config.tts.voice_id
)
# Get supervisor contact for warm transfer
# Priority: agent_config override → environment variable
supervisor_phone = agent_config.supervisor_number or os.getenv(
"SUPERVISOR_PHONE_NUMBER", ""
)
transfer_manager = None
if supervisor_phone:
# Create TransferManager for warm transfer functionality
transfer_manager = TransferManager(
ctx=ctx,
customer_session=session,
customer_room=ctx.room,
supervisor_contact=supervisor_phone,
lkapi=ctx.api,
)
source = "agent_config" if agent_config.supervisor_number else "environment"
logger.info(
f"TransferManager initialized with supervisor: {supervisor_phone} (source: {source})"
)
else:
logger.warning(
"Supervisor number not configured - warm transfer will be unavailable. "
"Set via agent_config.general.supervisor_number or SUPERVISOR_PHONE_NUMBER env var"
)
# Create Realtime agent with rendered instructions and tool overrides
agent = CloudMetricsRealtimeAgent(
instructions=instructions,
caller_id=caller_id,
call_logs_database_id=calls_database_id,
client_database_id=client_database_id,
prewarmed_schemas=ctx.proc.userdata.get("notion_schemas"),
tool_description_overrides=agent_config.tool_overrides,
transfer_manager=transfer_manager,
notion_client=notion_client,
)
# Extract tool details for RPC and API responses
tool_details = extract_tool_details(agent.tools)
final_config_metadata["tools"] = tool_details
# Register all event handlers (uses helper functions - LiveKit inline pattern)
register_session_handlers(session, agent)
register_room_handlers(ctx, agent)
register_shutdown_callback(ctx, agent, userdata) # Pass userdata for egress cleanup
register_rpc_handler(ctx, final_config_metadata)
# Configure room input options
room_input_options = RoomInputOptions(
participant_kinds=[
rtc.ParticipantKind.PARTICIPANT_KIND_SIP,
rtc.ParticipantKind.PARTICIPANT_KIND_STANDARD,
rtc.ParticipantKind.PARTICIPANT_KIND_AGENT,
]
)
# Start the session
await session.start(
agent=agent,
room=ctx.room,
room_input_options=room_input_options,
)
# Start background audio player for on-demand sounds
await userdata.background_audio.start(room=ctx.room, agent_session=session)tall-airline-16756
12/09/2025, 6:34 PMuserdata and have the LiveKit API available (after await ctx.connect() and after caller_id is extracted). That ensures the room exists and caller info is available.
2) Stop recording in your shutdown/cleanup path — you already call `register_shutdown_callback(ctx, agent, userdata)`; add the stop logic there so egress is stopped when the session ends or on error.
Minimal integration example (showing where to call your helpers):
• After extraction and userdata initialization, add:
# start recording
egress_id = await start_room_recording(lkapi=ctx.api, room_name=ctx.room.name, caller_id=caller_id, userdata=userdata)
# store egress_id already done inside helper via userdata
• In your shutdown callback (inside the function you register with register_shutdown_callback), call:
if userdata.egress_id:
await stop_room_recording(lkapi=ctx.api, egress_id=userdata.egress_id, userdata=userdata)
Notes and best practices:
• Ensure ctx.api (LiveKitAPI) is initialized and has roomRecord permission — you already pass ctx.api into TransferManager elsewhere, so reuse ctx.api.
• Start after await ctx.connect() so the egress can join the room immediately.
• Stop in the shutdown callback so it runs on normal hangup and on unexpected termination.
• Consider starting recording only after the first audio track publishes (if you prefer to avoid empty recordings). You mentioned you have logic in on_track_subscribed — you can alternatively call start_room_recording there instead of the entrypoint.
• If you want, I can produce a concrete patched snippet with the shutdown callback implementation showing where to import and call the helpers. Which would you prefer: start immediately after connect, or start on first subscribed audio track?microscopic-dress-75199
12/09/2025, 6:36 PMtall-airline-16756
12/09/2025, 6:36 PMStopEgress in your shutdown callback (your current helper), or 3) start on first audio track and stop automatically when the participant leaves. Sources: Composite and web recordings | LiveKit docs | Recording participants | LiveKit docs | Auto egress | LiveKit docs | Egress API | LiveKit docsmicroscopic-dress-75199
12/09/2025, 6:37 PMtall-airline-16756
12/09/2025, 6:37 PMawait ctx.connect() and after extracting caller_id.
2. When the human participant leaves, delete the room — egress stops automatically.
Insert after your userdata creation (near where you currently log prewarm data):
# start recording (audio-only) and save relative path
await start_room_recording(lkapi=ctx.api, room_name=ctx.room.name, caller_id=caller_id, userdata=userdata)
Implement room deletion on hangup inside your shutdown callback (registered via register_shutdown_callback). Example shutdown callback:
async def shutdown_callback(ctx: JobContext, agent, userdata: ReceptionistState):
# Optional: stop egress manually if you want, but not required for auto-stop
try:
# delete the room so RoomComposite egress stops automatically
await ctx.api.delete_room(ctx.room.name)
except Exception:
logger.exception("Failed to delete room on shutdown")
# continue existing cleanup (TTS, DB writes, etc.)
Notes:
• Deleting the room causes RoomComposite egress to stop when all participants leave.
• This avoids extra audio at the end if agent or egress participants linger.
B — Start recording and stop egress manually (explicit StopEgress)
1. Start egress same as above.
2. Stop in your registered shutdown callback using your helper.
Start (same place as A):
await start_room_recording(lkapi=ctx.api, room_name=ctx.room.name, caller_id=caller_id, userdata=userdata)
Shutdown callback snippet to stop explicitly:
async def shutdown_callback(ctx: JobContext, agent, userdata: ReceptionistState):
# stop egress explicitly if it was started
egress_id = getattr(userdata, "egress_id", None)
if egress_id:
try:
await stop_room_recording(lkapi=ctx.api, egress_id=egress_id, userdata=userdata)
except Exception:
logger.exception("Failed to stop egress in shutdown")
# Optionally also delete the room if desired:
try:
await ctx.api.delete_room(ctx.room.name)
except Exception:
logger.debug("Room delete skipped or failed")
Which to use?
• Use A (delete room / automatic stop) for simpler lifecycle and to avoid stray audio.
• Use B (manual stop) when you need deterministic control (stop at a precise event before room deletion).
If you want, I can produce a patched entrypoint showing exactly where to insert the start call and a full shutdown callback implementation that includes both stop + delete. Which patch would you like?microscopic-dress-75199
12/09/2025, 6:45 PMtall-airline-16756
12/09/2025, 6:45 PMEND_RECORDING quickly and the egress aborted with error "Start signal not received". This means Egress never observed the expected media from the room before the recorder closed (the "source" closed), so it aborted the job.
Common causes and fixes
• Egress started before any tracks were actually published. Fix: start egress after the SIP participant or at least one audio track is present, or use participant-based egress.
• The room was deleted or all participants left immediately after egress started. Fix: ensure the human participant stays in room until recording begins, or delete room only after egress completes.
• Egress container lacks access to the correct room endpoint or network and couldn't join properly — less likely here since validation passed.
• If you use a relative filepath, ensure the Egress container's writable mount is correct; otherwise file writing can fail (but your logs show the abort reason is the source).
Minimal actionable options
• Start egress on first audio track published (recommended).
• Or keep egress start where you have it, but ensure the SIP participant is already in the room and publishing.
• Also use automatic stop by deleting the room when the human leaves (preferred to avoid lingering audio), or call StopEgress manually in shutdown.
Drop-in examples
1) Start on first audio track (best to avoid "Start signal not received")
• In your existing event handler on_track_subscribed (you mentioned you already have logic there), call your helper when you detect the first remote audio track for the SIP participant:
# inside on_track_subscribed event handler
if track.kind == "audio" and is_sip_participant(participant):
if not userdata.egress_id:
await start_room_recording(lkapi=ctx.api, room_name=ctx.room.name, caller_id=userdata.caller_id, userdata=userdata)
2) Entrypoint start + shutdown delete-room (automatic stop)
• After await ctx.connect() and after you build userdata, add:
# start recording (but ensure participant is present/publishing)
await start_room_recording(lkapi=ctx.api, room_name=ctx.room.name, caller_id=caller_id, userdata=userdata)
• Shutdown callback to delete room (causes RoomComposite to stop automatically):
async def shutdown_callback(ctx: JobContext, agent, userdata: ReceptionistState):
# try stopping egress explicitly if started (optional)
egress_id = getattr(userdata, "egress_id", None)
if egress_id:
try:
await stop_room_recording(lkapi=ctx.api, egress_id=egress_id, userdata=userdata)
except Exception:
logger.exception("Failed to stop egress; continuing with room delete")
# delete the room so egress stops if still running
try:
await ctx.api.delete_room(ctx.room.name)
except Exception:
logger.debug("Room delete failed or already removed")
# other cleanup...
3) If you need deterministic control: manual StopEgress
• Start same as above.
• In shutdown callback call await stop_room_recording(...) before deleting the room.
Quick checklist to avoid the "Start signal not received" error
• Start egress only after SIP participant publishes audio (use on_track_subscribed).
• Double-check your Egress container mount maps so /out/recordings is writable (if you changed to absolute path).
• Ensure the room isn't deleted or emptied immediately after egress start.
• Watch egress logs for further details; if you still see START signal issues, start egress later (on first audio track) or use participant egress.
Which example do you want me to paste into your entrypoint file: (A) start on first audio track (I can show exact handler placement), or (B) start after connect + full shutdown callback with stop+delete?microscopic-dress-75199
12/09/2025, 6:48 PMtall-airline-16756
12/09/2025, 6:48 PM# inside on_track_subscribed(event) or similar
if track.kind == "audio" and is_sip_participant(participant):
# start once per session
if not userdata.egress_id:
await start_room_recording(lkapi=ctx.api, room_name=ctx.room.name, caller_id=userdata.caller_id, userdata=userdata)
This ensures Egress sees the audio source immediately and avoids the "Start signal not received" abort.
Option B — Start in entrypoint but ensure participant is present, then delete room on shutdown
• Start after ctx.connect() and after caller_id extraction:
# after await ctx.connect() and userdata setup
await start_room_recording(lkapi=ctx.api, room_name=ctx.room.name, caller_id=caller_id, userdata=userdata)
• Shutdown callback: delete room so RoomComposite stops automatically (and optionally StopEgress first):
async def shutdown_callback(ctx: JobContext, agent, userdata: ReceptionistState):
egress_id = getattr(userdata, "egress_id", None)
if egress_id:
try:
await stop_room_recording(lkapi=ctx.api, egress_id=egress_id, userdata=userdata)
except Exception:
logger.exception("stop egress failed; continuing")
try:
await ctx.api.delete_room(ctx.room.name)
except Exception:
logger.debug("room delete failed or already removed")
# other cleanup...
Quick checklist to resolve the abort:
• Start egress after an audio track is published (Option A) or ensure SIP participant is already publishing before start.
• Don’t delete the room immediately after starting egress — let it run until participant leaves or you call StopEgress.
• Confirm Egress container can join the room (network) and has writable mount for the file path.
• Watch egress logs — if you still see END_RECORDING immediately, move start later (on-track) or use participant egress.
If you want, I can:
• Patch your entrypoint with the exact on_track_subscribed placement, or
• Provide a complete shutdown callback file to register with register_shutdown_callback.
Which would you like?