diff --git a/python/livekit-agents/livekit/agents/_generated/_core_voice.pyi b/python/livekit-agents/livekit/agents/_generated/_core_voice.pyi index 28d147749b..3da21bc1bc 100644 --- a/python/livekit-agents/livekit/agents/_generated/_core_voice.pyi +++ b/python/livekit-agents/livekit/agents/_generated/_core_voice.pyi @@ -1013,6 +1013,11 @@ class _core_SessionOwner: """`aclose` without waiting for it.""" async def finish_recording(self) -> None: """The recording's final result remains available to the job reporter.""" + async def keep_console_recording(self, report: SessionReport) -> str | None: + """`console --record`: `report` and the call's audio are kept in + `.livekit/sessions//` under the working directory, which is returned; + `None` for any other session. Call after `finish_recording`. + """ @property def started_at(self) -> float | None: """When the session started (wall clock seconds), once its startup prepared it.""" diff --git a/python/livekit-agents/livekit/agents/job.py b/python/livekit-agents/livekit/agents/job.py index af9a9b003c..64246e1f87 100644 --- a/python/livekit-agents/livekit/agents/job.py +++ b/python/livekit-agents/livekit/agents/job.py @@ -16,13 +16,11 @@ from __future__ import annotations import asyncio import contextvars -import datetime import functools import inspect import logging import multiprocessing as mp import os -import shutil import tempfile from collections.abc import Awaitable, Callable, Coroutine from pathlib import Path @@ -201,22 +199,13 @@ class JobContext: logger.exception("failed to snapshot the session report") return - from .voice._session_bindings import ConsoleCall - - if ConsoleCall.record: - directory = Path( - ".livekit", "sessions", datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S") - ) - try: - await asyncio.to_thread( - _keep_console_recording, - self.make_session_report(), - self.session_directory, - directory, - ) - logger.info(f"session recording saved to {directory.resolve()}") - except Exception: - logger.exception("failed to save the session recording") + try: + kept = await session._native.keep_console_recording(self.make_session_report()) + except Exception: + logger.exception("failed to keep the session recording") + else: + if kept is not None: + logger.info(f"session recording saved to {Path(kept).resolve()}") async def _on_cleanup(self) -> None: await asyncio.to_thread(self._tempdir.cleanup) @@ -705,12 +694,3 @@ class JobProcess: @property def http_proxy(self) -> str | None: return self._http_proxy - - -def _keep_console_recording(report: SessionReport, session: Path, directory: Path) -> None: - """`console --record`: the report and the call's audio outlive the job's temporary directory.""" - directory.mkdir(parents=True, exist_ok=True) - (directory / "session_report.json").write_text(_core.session_report_json(report)) - audio = session / "audio.ogg" - if audio.is_file(): - shutil.copyfile(audio, directory / "audio.ogg") diff --git a/python/tests_new/smoke/test_session_regressions.py b/python/tests_new/smoke/test_session_regressions.py index ad3d477f0f..1db2b39b09 100644 --- a/python/tests_new/smoke/test_session_regressions.py +++ b/python/tests_new/smoke/test_session_regressions.py @@ -15,7 +15,7 @@ from tests_new.fakes import FakeAudioInput, FakeSTT, FakeVAD, until from .conftest import ConsolePeer RECORDING_AGENT_MODULE = """ -import asyncio, os, shutil +import asyncio from livekit.agents import Agent, AgentServer, VoiceSession, cli from tests_new.fakes import FakeTTS @@ -29,7 +29,6 @@ async def entrypoint(ctx): await session.say("hello there") await asyncio.sleep(0.5) # the call lasts half a second await session.aclose() - shutil.copy(ctx.session_directory / "audio.ogg", os.environ["RECORDING"]) ctx.shutdown() if __name__ == "__main__": @@ -70,9 +69,9 @@ async def test_a_recorded_console_call_writes_its_audio_without_a_room( agent_env: dict[str, str], tmp_path: Path, ) -> None: - """``console --record`` records the call's audio although the console has no room. - https://github.com/livekit/agents/pull/4575""" - agent, recording = agent_module(RECORDING_AGENT_MODULE), tmp_path / "audio.ogg" + """``console --record`` records the call's audio although the console has no room, and keeps + it with the report under ``.livekit/sessions/``. https://github.com/livekit/agents/pull/4575""" + agent = agent_module(RECORDING_AGENT_MODULE) console_call = await asyncio.create_subprocess_exec( sys.executable, @@ -81,11 +80,14 @@ async def test_a_recorded_console_call_writes_its_audio_without_a_room( "--record", "--connect-addr", console.addr, - env={**agent_env, "RECORDING": str(recording)}, + env=agent_env, cwd=tmp_path, ) assert await console_call.wait() == 0 + [kept] = list((tmp_path / ".livekit" / "sessions").iterdir()) + assert (kept / "session_report.json").is_file() + recording = kept / "audio.ogg" decoder = media.AudioStreamDecoder(format="audio/ogg") decoder.push(recording.read_bytes()) decoder.end_input() diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 88d3319d21..73d038f07e 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1770,6 +1770,7 @@ dependencies = [ "async-trait", "base64 0.22.1", "bytes", + "chrono", "futures-util", "libc", "livekit-protocol", diff --git a/rust/crates/lk-agents-abi/src/voice/session_owner.rs b/rust/crates/lk-agents-abi/src/voice/session_owner.rs index f79087d99e..e638840853 100644 --- a/rust/crates/lk-agents-abi/src/voice/session_owner.rs +++ b/rust/crates/lk-agents-abi/src/voice/session_owner.rs @@ -215,6 +215,14 @@ pub trait SessionOwner: Send + Sync + Sized + 'static { /// The recording's final result remains available to the job reporter. #[host(await)] async fn finish_recording(&self) -> Result<(), crate::recorder::RecordingFailure>; + /// `console --record`: `report` and the call's audio are kept in + /// `.livekit/sessions//` under the working directory, which is returned; + /// `None` for any other session. Call after `finish_recording`. + #[host(await)] + async fn keep_console_recording( + &self, + report: crate::telemetry::report::SessionReport, + ) -> Result, crate::recorder::RecordingFailure>; /// When the session started (wall clock seconds), once its startup prepared it. #[host(getter)] fn started_at(&self) -> Option; diff --git a/rust/crates/lk-agents-py/src/generated/voice.rs b/rust/crates/lk-agents-py/src/generated/voice.rs index b9bc7811f8..133cf9db53 100644 --- a/rust/crates/lk-agents-py/src/generated/voice.rs +++ b/rust/crates/lk-agents-py/src/generated/voice.rs @@ -4600,6 +4600,25 @@ impl CoreSessionOwner { }) } + /// `console --record`: `report` and the call's audio are kept in + /// `.livekit/sessions//` under the working directory, which is returned; + /// `None` for any other session. Call after `finish_recording`. + #[pyo3(signature = (report))] + fn keep_console_recording<'py>( + &self, + py: Python<'py>, + report: Bound<'_, PyAny>, + ) -> PyResult> { + crate::py_calls::check_pid()?; + let report = crate::generated::records::telemetry::session_report_from_py(report.as_any())?; + let this = ::std::sync::Arc::clone(&self.0); + crate::py_calls::future_into_py(py, async move { + let out = ::keep_console_recording(&this, report) + .await.map_err(|e: ::lk_agents_abi::recorder::RecordingFailure| <::lk_agents_abi::recorder::RecordingFailure as crate::py_errors::HostException>::to_py_err(&e))?; + Python::attach(|py| ::pyo3::IntoPyObjectExt::into_py_any(out, py)) + }) + } + /// When the session started (wall clock seconds), once its startup prepared it. #[getter] fn started_at(&self, py: Python<'_>) -> PyResult { diff --git a/rust/crates/lk-agents-runtime/Cargo.toml b/rust/crates/lk-agents-runtime/Cargo.toml index dade96827c..30f86ff38f 100644 --- a/rust/crates/lk-agents-runtime/Cargo.toml +++ b/rust/crates/lk-agents-runtime/Cargo.toml @@ -26,6 +26,7 @@ lk-agents-voice = { path = "../lk-agents-voice", default-features = false } lk-agents-worker = { path = "../lk-agents-worker" } lk-agents-media = { path = "../lk-agents-media" } serde_json = { workspace = true, features = ["preserve_order"] } +chrono = { version = "0.4", default-features = false, features = ["alloc", "clock"] } log.workspace = true thiserror.workspace = true async-trait.workspace = true diff --git a/rust/crates/lk-agents-runtime/src/voice/session/owner.rs b/rust/crates/lk-agents-runtime/src/voice/session/owner.rs index 54b732093d..53818920d3 100644 --- a/rust/crates/lk-agents-runtime/src/voice/session/owner.rs +++ b/rust/crates/lk-agents-runtime/src/voice/session/owner.rs @@ -118,6 +118,8 @@ struct Inner { started_at: OnceLock, recording_options: OnceLock, audio: OnceLock<(String, Arc)>, + /// The console's call recorded with `--record`: its recording is kept past the job. + console_recording: OnceLock, /// The report's events: which are kept, and the job allowed to read them. retention: Mutex, tasks: Arc, @@ -384,6 +386,7 @@ impl Inner { args.job = None; } let _ = self.started_at.set(lk_agents_abi::unix_secs(self.env.clock.wall())); + let _ = self.console_recording.set(args.console.is_some() && record_audio); let Some(job) = job else { return Ok(()) }; if recording.audio || record_audio { let dir = std::path::PathBuf::from(job.recording_dir()?); @@ -507,6 +510,7 @@ impl lk_agents_abi::voice::session_owner::SessionOwner for SessionOwner { started_at: OnceLock::new(), recording_options: OnceLock::new(), audio: OnceLock::new(), + console_recording: OnceLock::new(), retention: Mutex::new(Retention::process()), tasks: Arc::new(TaskSet::default()), opened, @@ -736,6 +740,36 @@ impl lk_agents_abi::voice::session_owner::SessionOwner for SessionOwner { self.0.finish_recording().await } + async fn keep_console_recording( + &self, + report: telemetry::SessionReport, + ) -> Result, RecordingFailure> { + if self.0.console_recording.get() != Some(&true) { + return Ok(None); + } + use lk_agents_abi::telemetry::report::SessionReportFunctions as _; + let json = lk_agents_net::export::session_report::ReportFiles::session_report_json(report) + .map_err(|error| RecordingFailure::Encode(error.to_string()))?; + let stamp = chrono::DateTime::::from(self.0.env.clock.wall()); + let directory = std::path::Path::new(".livekit/sessions") + .join(stamp.format("%Y-%m-%d-%H%M%S").to_string()); + let audio = self.0.audio.get().map(|(path, _)| std::path::PathBuf::from(path)); + let kept = directory.clone(); + lk_agents_net::blocking_io::blocking_io() + .run((), move || -> std::io::Result<()> { + std::fs::create_dir_all(&kept)?; + std::fs::write(kept.join("session_report.json"), json)?; + if let Some(audio) = audio.filter(|audio| audio.is_file()) { + std::fs::copy(audio, kept.join("audio.ogg"))?; + } + Ok(()) + }) + .await + .map_err(|lost| RecordingFailure::Worker(lost.to_string()))? + .map_err(|error| RecordingFailure::Io(error.to_string()))?; + Ok(Some(directory.to_string_lossy().into_owned())) + } + fn started_at(&self) -> Option { self.0.started_at.get().copied() }