"""Voice session lifecycle for the unified API (HEL-877, approved R5 backend). The endpoint reuses the .12 voice base (LiveKit SFU + FunASR + CosyVoice TTS + silero VAD) exactly as HEL-876 audited it: this module only creates a room dispatch for the dedicated ``cybergril-voice-agent`` worker and mints a short-lived join token server-side, so no LiveKit key ever reaches the browser. Everything here is process-local apart from the small session registry and its persisted cleanup ledger (HEL-879): chat state, persona, memory and locks stay in the single API process that mounts this router (HTTP and the HTTPS voice entry share it). Room ownership stays until the delete really lands (HEL-879 总管复核第 2 项): a failed remote delete keeps the session in a bounded cleanup ledger — retried on the next end call and by a bounded background sweep — and the ledger is persisted beside the instance database so a restarted process compensates its OWN rooms (never another instance's, never the generic worker). Retries are idempotent (404 = already gone = settled). Every debt is bounded by attempts and age, then recorded as abandoned instead of retried forever. HEL-879 remaining closure: the cleanup owner also watches the ACTIVE session deadlines — a session that nobody touches expires into the ledger and has its room deleted without any further request — and explicit end shares the very same persisted attempt cap and abandoned state with the background sweep (no _sessions bypass). A debt that crossed its cap raises CleanupAbandoned instead of answering a done-404: the room is still owned-but-unsettled and the caller must keep treating the hang-up as not finished. """ from __future__ import annotations import asyncio import contextlib import json import os import secrets import string import time from dataclasses import dataclass, field from pathlib import Path import httpx import yaml from . import livekit_wire DEFAULT_AGENT_NAME = "cybergril-voice-agent" DEFAULT_TOKEN_TTL = 300.0 DEFAULT_SESSION_TTL = 2 * 3600.0 TTS_HEALTH_CACHE_SECONDS = 30.0 CLEANUP_MAX_ATTEMPTS = 8 CLEANUP_BACKOFF_SECONDS = 0.5 CLEANUP_GRACE_SECONDS = 24 * 3600.0 STATE_VERSION = 1 @dataclass class VoiceConfig: livekit_url: str livekit_internal: str api_key: str api_secret: str agent_name: str = DEFAULT_AGENT_NAME tts_health_url: str = "http://127.0.0.1:9880/health" token_ttl_seconds: float = DEFAULT_TOKEN_TTL session_ttl_seconds: float = DEFAULT_SESSION_TTL dispatch_timeout_seconds: float = 5.0 def sanitized(self) -> dict: return { "livekit_url": self.livekit_url, "agent_name": self.agent_name, "tts_health_url": self.tts_health_url, "token_ttl_seconds": self.token_ttl_seconds, "session_ttl_seconds": self.session_ttl_seconds, } class VoiceNotConfigured(Exception): """Raised when no config file exists; the endpoint refuses honestly.""" class CleanupAbandoned(Exception): """The room is still owned but its bounded cleanup crossed the cap. Raised by ``end_session`` when the persisted debt for the room is already abandoned (attempts/age exhausted): no further remote delete is issued — neither by the caller nor by the background sweep — and the state must be reported as unsettled, never as a done-404. The debt (attempts, last error, reason) stays persisted for the operator. """ def __init__(self, debt: _CleanupDebt) -> None: self.debt = debt super().__init__( f"cleanup abandoned ({debt.abandoned}) after {debt.attempts} attempts: " f"room {debt.session.room} is still owned and unsettled" ) def load_voice_config( path: Path | str | None = None, ) -> VoiceConfig | None: """Load config/voice.yaml; env overrides keep deployment keys out of the repo. Returns None (not an exception) when nothing is configured: "voice not set up on this instance" is an honest state, not an error. """ path = Path(path or os.environ.get("CYBERGRIL_VOICE_CONFIG", "config/voice.yaml")) if not path.is_file(): return None data = yaml.safe_load(path.read_text()) or {} overrides = { "livekit_url": os.environ.get("CYBERGRIL_VOICE_LIVEKIT_URL"), "livekit_internal": os.environ.get("CYBERGRIL_VOICE_LIVEKIT_INTERNAL"), "api_key": os.environ.get("CYBERGRIL_VOICE_API_KEY"), "api_secret": os.environ.get("CYBERGRIL_VOICE_API_SECRET"), "tts_health_url": os.environ.get("CYBERGRIL_VOICE_TTS_HEALTH_URL"), } values = {**data, **{k: v for k, v in overrides.items() if v}} required = ("livekit_url", "livekit_internal", "api_key", "api_secret") missing = [k for k in required if not values.get(k)] if missing: raise VoiceNotConfigured(f"voice config missing fields: {', '.join(missing)}") return VoiceConfig( livekit_url=str(values["livekit_url"]), livekit_internal=str(values["livekit_internal"]), api_key=str(values["api_key"]), api_secret=str(values["api_secret"]), agent_name=str(values.get("agent_name") or DEFAULT_AGENT_NAME), tts_health_url=str(values.get("tts_health_url") or "http://127.0.0.1:9880/health"), token_ttl_seconds=float(values.get("token_ttl_seconds") or DEFAULT_TOKEN_TTL), session_ttl_seconds=float(values.get("session_ttl_seconds") or DEFAULT_SESSION_TTL), ) @dataclass class VoiceSession: session_id: str room: str identity: str created_at: float expires_at: float epoch: int dispatch_id: str = "" def as_state(self) -> dict: return { "session_id": self.session_id, "room": self.room, "identity": self.identity, "created_at": self.created_at, "expires_at": self.expires_at, "epoch": self.epoch, "dispatch_id": self.dispatch_id, } @classmethod def from_state(cls, data: dict) -> VoiceSession: return cls( session_id=str(data["session_id"]), room=str(data["room"]), identity=str(data.get("identity", "")), created_at=float(data.get("created_at", 0)), expires_at=float(data.get("expires_at", 0)), epoch=int(data.get("epoch", 0)), dispatch_id=str(data.get("dispatch_id", "")), ) @dataclass class _CleanupDebt: """One room this instance still owns: its remote delete has not landed.""" session: VoiceSession attempts: int = 0 first_debt_at: float = 0.0 last_error: str = "" abandoned: str = "" eligible_at: float = 0.0 # background retries wait until this clock time def as_state(self) -> dict: return {"session": self.session.as_state(), "attempts": self.attempts, "first_debt_at": self.first_debt_at, "last_error": self.last_error, "abandoned": self.abandoned, "eligible_at": self.eligible_at} @classmethod def from_state(cls, data: dict) -> _CleanupDebt: return cls( session=VoiceSession.from_state(data.get("session", {})), attempts=int(data.get("attempts", 0)), first_debt_at=float(data.get("first_debt_at", 0)), last_error=str(data.get("last_error", "")), abandoned=str(data.get("abandoned", "")), eligible_at=float(data.get("eligible_at", 0)), ) @dataclass class _Health: checked: float = 0.0 ok: bool = False @dataclass class VoiceSessionService: config: VoiceConfig http: httpx.AsyncClient = field(default_factory=httpx.AsyncClient) clock: object = time.time tts_health_cache_seconds: float = TTS_HEALTH_CACHE_SECONDS state_path: Path | str | None = None cleanup_max_attempts: int = CLEANUP_MAX_ATTEMPTS cleanup_backoff_seconds: float = CLEANUP_BACKOFF_SECONDS cleanup_grace_seconds: float = CLEANUP_GRACE_SECONDS def __post_init__(self) -> None: self._sessions: dict[str, VoiceSession] = {} self._debts: dict[str, _CleanupDebt] = {} self._tts_health = _Health(checked=-1e9, ok=False) self._tts_lock = asyncio.Lock() self._cleaner: asyncio.Task | None = None self._wake = asyncio.Event() self._load_state() # -- persisted cleanup ledger (own rooms only) --------------------------- def _load_state(self) -> None: """Restart compensation: rooms recorded by a previous process of THIS instance become cleanup debts (bounded by the persisted attempt counts and age); they are the only rooms ever touched.""" if not self.state_path: return try: data = json.loads(Path(self.state_path).read_text(encoding="utf-8")) except (OSError, ValueError): return if data.get("version") != STATE_VERSION: return now = self.clock() for entry in data.get("debts", []): try: debt = _CleanupDebt.from_state(entry) except (KeyError, TypeError, ValueError): continue if debt.session.session_id not in self._debts: self._debts[debt.session.session_id] = debt for entry in data.get("sessions", []): try: session = VoiceSession.from_state(entry) except (KeyError, TypeError, ValueError): continue # A room that was live when the process went down: the call may # legitimately survive an API restart (the room lives on the SFU), # so background compensation waits for the session's own TTL — # bounded, never leaked, and never a longer-lived claim. if session.session_id not in self._debts and session.session_id not in self._sessions: self._debts[session.session_id] = _CleanupDebt( session=session, first_debt_at=now, eligible_at=max(now, session.expires_at)) self._prune() def _persist_state(self) -> None: if not self.state_path: return payload = { "version": STATE_VERSION, "sessions": [s.as_state() for s in self._sessions.values()], "debts": [d.as_state() for d in self._debts.values()], } path = Path(self.state_path) try: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=1), encoding="utf-8") tmp.replace(path) except OSError: # Best effort: losing the ledger never breaks a request, it only # costs the restart compensation for still-owned rooms. pass # -- honest readiness --------------------------------------------------- async def tts_available(self) -> bool: """Probe the CosyVoice TTS health endpoint, cached like /api/health's LLM probe.""" now = self.clock() if now - self._tts_health.checked < self.tts_health_cache_seconds: return self._tts_health.ok async with self._tts_lock: if self.clock() - self._tts_health.checked < self.tts_health_cache_seconds: return self._tts_health.ok try: response = await self.http.get(self.config.tts_health_url, timeout=3.0) ok = response.status_code // 100 == 2 except Exception: ok = False self._tts_health = _Health(checked=self.clock(), ok=ok) return ok # -- lifecycle ---------------------------------------------------------- def _prune(self) -> None: """Expired registrations move into the cleanup ledger — never silently dropped: their room stays owned until its bounded delete lands.""" now = self.clock() expired = [k for k, v in self._sessions.items() if v.expires_at < now] for session_id in expired: session = self._sessions.pop(session_id) if session_id not in self._debts: self._debts[session_id] = _CleanupDebt(session=session, first_debt_at=now) if expired: self._persist_state() def _abandon_reason(self, debt: _CleanupDebt) -> str: if debt.abandoned: return debt.abandoned if debt.attempts >= self.cleanup_max_attempts: return "attempts-exhausted" if self.clock() - debt.session.expires_at > self.cleanup_grace_seconds: return "aged-out" return "" def _retryable_debts(self) -> list[str]: now = self.clock() return [sid for sid, debt in self._debts.items() if not self._abandon_reason(debt) and now >= debt.eligible_at] async def _delete_room_once(self, session: VoiceSession) -> None: """One remote delete attempt; 2xx/404 settle, anything else raises.""" await livekit_wire.delete_room( self.http, internal_url=self.config.livekit_internal, api_key=self.config.api_key, api_secret=self.config.api_secret, room=session.room, timeout=self.config.dispatch_timeout_seconds, ) async def _cleanup_loop(self) -> None: """The single cleanup owner for THIS instance. It watches two deadlines without needing any further request: every debt's next retry eligibility and every ACTIVE session's expiry. When there is nothing left to watch (no sessions, only settled/abandoned debts) the loop exits; the next open/recover/end re-kicks it. """ try: while True: self._prune() # expired active sessions become retryable debts pending = self._retryable_debts() if not pending: now = self.clock() deadlines = [d.eligible_at for d in self._debts.values() if not self._abandon_reason(d)] deadlines += [s.expires_at for s in self._sessions.values()] if not deadlines: break # Deferred debts (restart compensation waiting out a live # session's TTL) and not-yet-expired sessions: sleep until # the earliest deadline, bounded so the loop stays cheap — # a newly created debt wakes it immediately (_wake). delay = min(max(min(deadlines) - now, 0.05), 60.0) self._wake.clear() with contextlib.suppress(asyncio.TimeoutError): await asyncio.wait_for(self._wake.wait(), timeout=delay) continue for session_id in pending: debt = self._debts.get(session_id) if debt is None or self._abandon_reason(debt): continue try: await self._delete_room_once(debt.session) self._debts.pop(session_id, None) except Exception as exc: # bounded retry, never a crash loop debt.attempts += 1 debt.last_error = f"{type(exc).__name__}: {exc}"[:200] reason = self._abandon_reason(debt) if reason: debt.abandoned = reason self._persist_state() if not debt.abandoned and session_id in self._debts: await asyncio.sleep(self.cleanup_backoff_seconds) finally: self._cleaner = None def _kick_cleanup(self) -> None: if self._cleaner is not None and not self._cleaner.done(): self._wake.set() # wake the sleeping watcher for the new debt return try: loop = asyncio.get_running_loop() except RuntimeError: return self._cleaner = loop.create_task(self._cleanup_loop()) async def recover(self) -> None: """App-start hook: compensate rooms left over by a previous process of this instance (bounded by the persisted ledger).""" self._kick_cleanup() async def open_session(self, *, epoch: int) -> VoiceSession: self._prune() self._kick_cleanup() alphabet = string.ascii_lowercase + string.digits room = "cg-voice-" + "".join(secrets.choice(alphabet) for _ in range(10)) identity = "user-" + "".join(secrets.choice(string.ascii_lowercase) for _ in range(8)) dispatch = await livekit_wire.create_dispatch( self.http, internal_url=self.config.livekit_internal, api_key=self.config.api_key, api_secret=self.config.api_secret, agent_name=self.config.agent_name, room=room, timeout=self.config.dispatch_timeout_seconds, ) now = self.clock() session = VoiceSession( session_id=secrets.token_urlsafe(18), room=room, identity=identity, created_at=now, expires_at=now + self.config.session_ttl_seconds, epoch=epoch, dispatch_id=dispatch.dispatch_id, ) self._sessions[session.session_id] = session self._persist_state() return session def token_for(self, session: VoiceSession) -> str: return livekit_wire.mint_token( self.config.api_key, self.config.api_secret, identity=session.identity, name="用户", room=session.room, room_join=True, can_publish=True, can_subscribe=True, ttl_seconds=self.config.token_ttl_seconds, now=self.clock(), ) async def end_session(self, session_id: str) -> VoiceSession | None: """End a session by actually deleting its room (HEL-879). The registration is only removed AFTER the remote delete settles: a failed delete keeps the session in the bounded cleanup ledger, so a retry (this method again, the background sweep, or the next process via the persisted ledger) still targets the same room — it can never degrade into a 404 that silently drops the room. Explicit end and the background sweep share ONE persisted attempt budget (HEL-879 remaining closure): both count into the same debt, so a room whose cap the sweep exhausted is never re-deleted from here either — it raises CleanupAbandoned (unsettled, honest) instead of answering a done-404. Unknown ids never seen here return None → 404; ids fully settled and forgotten also do. """ self._prune() session = self._sessions.get(session_id) debt = self._debts.get(session_id) if session is None and debt is None: return None if debt is None: debt = _CleanupDebt(session=session, first_debt_at=self.clock()) elif debt.abandoned: # Cap already crossed (by this process or a previous one): no more # remote deletes from any path; the room stays owned-unsettled. raise CleanupAbandoned(debt) else: session = debt.session try: await self._delete_room_once(session) except Exception as exc: # From now on the room lives in the ledger alone: _sessions no # longer bypasses the shared cap on a later end call. self._sessions.pop(session_id, None) if session_id not in self._debts: self._debts[session_id] = debt debt.attempts += 1 debt.last_error = f"{type(exc).__name__}: {exc}"[:200] reason = self._abandon_reason(debt) if reason: debt.abandoned = reason self._persist_state() self._kick_cleanup() raise self._sessions.pop(session_id, None) self._debts.pop(session_id, None) self._persist_state() return session def get(self, session_id: str) -> VoiceSession | None: self._prune() return self._sessions.get(session_id) def cleanup_debt(self, session_id: str) -> _CleanupDebt | None: """Test/diagnostics view of the owned-but-not-deleted ledger.""" return self._debts.get(session_id) async def aclose(self) -> None: if self._cleaner is not None: self._cleaner.cancel() with contextlib.suppress(asyncio.CancelledError): await self._cleaner self._cleaner = None # Graceful shutdown: rooms still active here become debts, then one # final bounded sweep runs before the transport closes; whatever # remains stays in the persisted ledger for the next process. self._prune() for session_id in self._retryable_debts(): debt = self._debts.get(session_id) if debt is None or self._abandon_reason(debt): continue try: await self._delete_room_once(debt.session) self._debts.pop(session_id, None) except Exception as exc: debt.attempts += 1 debt.last_error = f"{type(exc).__name__}: {exc}"[:200] reason = self._abandon_reason(debt) if reason: debt.abandoned = reason self._persist_state() await self.http.aclose()