"""Minimal voice-session protocol mounted on the unified API (HEL-877). POST /api/voice/session open a room, dispatch the dedicated worker, return a short-lived join token (keys stay server-side); honest refusal when voice is not configured, no companion exists yet or TTS is down. DELETE /api/voice/session/{id} end: delete the LiveKit room, which disconnects browser and worker, ends the agent job and releases the microphone. A delete that cannot land keeps the room in a bounded, persisted cleanup ledger (503, retried); it never collapses into a 404 while the room is still owned. GET /api/voice/status honest switch state for the frontend (configured / tts reachable / agent name). capabilities.voice in /api/health stays false: R5 is not real-accepted yet and this endpoint never claims end-to-end voice availability. """ from __future__ import annotations from fastapi import APIRouter, HTTPException, Request from .session import CleanupAbandoned, VoiceSessionService REFUSAL_NOT_CONFIGURED = "语音还没有在这台服务上配置,不能假装能通话。" REFUSAL_NO_COMPANION = "还没有创建真实伴侣,语音也不会开始。" REFUSAL_TTS_DOWN = "她的声音服务这会儿不在,稍后再试试。" REFUSAL_LIVEKIT_DOWN = "通话服务暂时连不上,稍后再试试。" REFUSAL_CLEANUP_ABANDONED = ( "这次通话的房间还没有删净,清理重试已达上限;已登记待人工收尾,请保留挂断状态。" ) def build_voice_router(service: VoiceSessionService | None) -> APIRouter: router = APIRouter(prefix="/api/voice", tags=["voice"]) @router.get("/status") async def status() -> dict: if service is None: return {"configured": False, "tts_ok": False, "agent_name": None, "voice": False} tts_ok = await service.tts_available() return { "configured": True, "tts_ok": tts_ok, "agent_name": service.config.agent_name, "voice": False, # honest until real-device R5 acceptance **service.config.sanitized(), } @router.post("/session", status_code=201) async def open_session(request: Request) -> dict: if service is None: raise HTTPException(503, REFUSAL_NOT_CONFIGURED) state = request.app.state if not state.store.query_one("SELECT id FROM companion"): raise HTTPException(409, REFUSAL_NO_COMPANION) if not await service.tts_available(): raise HTTPException(503, REFUSAL_TTS_DOWN) try: session = await service.open_session(epoch=state.epoch) except Exception: raise HTTPException(503, REFUSAL_LIVEKIT_DOWN) from None return { "url": service.config.livekit_url, "token": service.token_for(session), "room": session.room, "session_id": session.session_id, "agent_name": service.config.agent_name, "epoch": session.epoch, "expires_at": int(session.expires_at * 1000), } @router.delete("/session/{session_id}") async def end_session(session_id: str) -> dict: if service is None: raise HTTPException(503, REFUSAL_NOT_CONFIGURED) try: session = await service.end_session(session_id) except CleanupAbandoned as exc: # Bounded cleanup crossed its persisted cap (this process or an # earlier one): the room is STILL owned and unsettled — never a # done-404, and no further delete is issued from any path. The # state stays persisted for the operator. raise HTTPException( 503, {"message": REFUSAL_CLEANUP_ABANDONED, "cleanup": {"room": exc.debt.session.room, "abandoned": exc.debt.abandoned, "attempts": exc.debt.attempts, "last_error": exc.debt.last_error}}, ) from None except Exception: # The remote delete did not land: the room stays owned in the # bounded cleanup ledger and will be retried; the caller must NOT # treat this as done (a 404 would erase the browser's owed DELETE). raise HTTPException(503, "这次通话还没有完全挂断,会自动重试清理;请稍后再试。") from None if session is None: raise HTTPException(404, "这次通话已经不在了。") return {"ended": True, "room": session.room} return router