Skip to content
22 changes: 22 additions & 0 deletions livekit-agents/livekit/agents/cli/_legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,28 @@ def _on_agent_state_changed(event: AgentStateChangedEvent) -> None:
self._io_transcription_sync.text_output,
)

def reattach_io(self, *, session: AgentSession) -> bool:
"""Reinstall the acquired console streams on a session retry.

A failed start restores the caller's I/O but keeps the console
acquisition, because the console owns the streams for the process.
This puts them back without acquiring a second time.
"""
with self._lock:
if not (self._io_acquired and self._io_session is session):
return False
audio_input = self._io_audio_input
transcription_sync = self._io_transcription_sync

self._update_sess_io(
session,
self.console_mode,
audio_input,
transcription_sync.audio_output,
transcription_sync.text_output,
)
return True

@property
def enabled(self) -> bool:
return self._enabled
Expand Down
17 changes: 17 additions & 0 deletions livekit-agents/livekit/agents/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,23 @@ def acquire_io(self, *, loop: asyncio.AbstractEventLoop, session: AgentSession)
self._io_transcription_sync.text_output,
)

def reattach_io(self, *, session: AgentSession) -> bool:
"""Reinstall the acquired console streams on a session retry."""
with self._lock:
if not (self._io_acquired and self._io_session is session):
return False
audio_input = self._io_audio_input
transcription_sync = self._io_transcription_sync

self._update_sess_io(
session,
self.console_mode,
audio_input,
transcription_sync.audio_output,
transcription_sync.text_output,
)
return True

@property
def enabled(self) -> bool:
return self._enabled
Expand Down
350 changes: 272 additions & 78 deletions livekit-agents/livekit/agents/voice/agent_session.py

Large diffs are not rendered by default.

14 changes: 14 additions & 0 deletions livekit-agents/livekit/agents/voice/recorder_io/recorder_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,10 @@ def __init__(

self._in_record: RecorderAudioInput | None = None
self._out_record: RecorderAudioOutput | None = None
# the streams the wrappers replace, restored if the session is closed
# before an activity exists to detach them
self._wrapped_input: io.AudioInput | None = None
self._wrapped_output: io.AudioOutput | None = None

self._q: queue.Queue[_Captured | _Flush | _EndRun | None] = queue.Queue()
self._session = agent_session
Expand Down Expand Up @@ -234,6 +238,14 @@ async def start(self, *, output_path: str | Path) -> None:
thread.start()

async def aclose(self) -> None:
# unwrap the session streams this recorder replaced. a start() that failed
# before publishing an activity has no activity to detach them, and the
# closed wrappers must not look like the caller's I/O on a retry
if self._in_record is not None and self._session.input.audio is self._in_record:
self._session.input.audio = self._wrapped_input
if self._out_record is not None and self._session.output.audio is self._out_record:
self._session.output.audio = self._wrapped_output

async with self._lock:
if not self._started:
return
Expand All @@ -256,6 +268,7 @@ def on_frame(started_at: float, frame: rtc.AudioFrame) -> None:
self._input_settled = started_at + frame.duration
self._put(_Captured(channel=0, started_at=started_at, frame=frame))

self._wrapped_input = audio_input
self._in_record = RecorderAudioInput(
recording_io=self, source=audio_input, on_frame=on_frame
)
Expand All @@ -266,6 +279,7 @@ def record_output(self, audio_output: io.AudioOutput) -> RecorderAudioOutput:
def on_played(started_at: float, frame: rtc.AudioFrame) -> None:
self._put(_Captured(channel=1, started_at=started_at, frame=frame))

self._wrapped_output = audio_output
self._out_record = RecorderAudioOutput(
recording_io=self, audio_output=audio_output, on_played=on_played
)
Expand Down
21 changes: 19 additions & 2 deletions livekit-agents/livekit/agents/voice/remote_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
)
from ..llm.chat_context import Instructions
from ..log import logger
from ..utils.aio.channel import ChanEmpty
from ..version import __version__
from ..voice.amd import AMDCategory, AMDPredictionEvent
from .events import (
Expand Down Expand Up @@ -417,6 +418,14 @@ def unregister_session(self) -> None:
self._session.off("close", self._on_close)
self._session = None

def discard_pending_events(self) -> None:
"""Drop events buffered for the current session without closing the host."""
while True:
try:
self._event_ch.recv_nowait()
except ChanEmpty:
return

async def start(self) -> None:
if self._started:
return
Expand All @@ -428,12 +437,20 @@ async def start(self) -> None:
self._recv_task = asyncio.create_task(self._recv_loop())

async def aclose(self) -> None:
if not self._started:
return
started = self._started
self._started = False

self.unregister_session()

if not started:
# start() never ran, so there are no tasks to drain, but the callbacks
# and the transport/channel built in __init__ still need releasing: a
# session start() that failed after register_session() leaves this as
# the only teardown
self._event_ch.close()
await self._transport.close()
return

if self._recv_task:
await utils.aio.cancel_and_wait(self._recv_task)
self._recv_task = None
Expand Down
28 changes: 28 additions & 0 deletions livekit-agents/livekit/agents/voice/room_io/room_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,14 @@ def __init__(
self._text_input_cb: TextInputCallback | None = None
self._chat_handler_registered = False

# the session I/O this RoomIO attached, detached again in aclose()
self._attached_input_audio: AudioInput | None = None
self._attached_input_video: VideoInput | None = None
self._attached_output_audio: AudioOutput | None = None
self._attached_output_transcription: TextOutput | None = None
# an output the transcription synchronizer replaced, restored on close
self._previous_output_audio: AudioOutput | None = None

def register_text_input(self, text_input_cb: TextInputCallback) -> None:
self._text_input_cb = text_input_cb

Expand Down Expand Up @@ -195,15 +203,22 @@ async def start(self, *, trace_context: otel_context.Context | None = None) -> N

# -- attach to the agent session --
if self.audio_input:
self._attached_input_audio = self.audio_input
self._agent_session.input.audio = self.audio_input

if self.video_input:
self._attached_input_video = self.video_input
self._agent_session.input.video = self.video_input

if self.audio_output:
# the transcription synchronizer may wrap a caller output (an avatar,
# for example); remember it so a failed start can restore it
self._previous_output_audio = self._agent_session.output.audio
self._attached_output_audio = self.audio_output
self._agent_session.output.audio = self.audio_output

if self.transcription_output:
self._attached_output_transcription = self.transcription_output
self._agent_session.output.transcription = self.transcription_output

self._agent_session.on("agent_state_changed", self._on_agent_state_changed)
Expand All @@ -223,6 +238,19 @@ async def aclose(self) -> None:
self._agent_session.off("user_input_transcribed", self._on_user_input_transcribed)
self._agent_session.off("close", self._on_agent_session_close)

# release the session I/O this RoomIO attached. activity teardown clears it
# normally, but a start() that failed before publishing an activity has no
# activity to clear it, and the closed streams must not look like the
# caller's I/O on a retry
if self._agent_session.input.audio is self._attached_input_audio:
self._agent_session.input.audio = None
if self._agent_session.input.video is self._attached_input_video:
self._agent_session.input.video = None
if self._agent_session.output.audio is self._attached_output_audio:
self._agent_session.output.audio = self._previous_output_audio
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
if self._agent_session.output.transcription is self._attached_output_transcription:
self._agent_session.output.transcription = None

if self._chat_handler_registered:
self._chat_handler_registered = False
try:
Expand Down
Loading
Loading