Files
CyberGril/src/cybergril/voice/session.py
T
施工员2号 aba2aebeb0 HEL-877: wire the audited .12 voice base into the one CyberGril chat chain as backend-only code (no deploy, no real voice call) - new independent src/cybergril/voice module: session+router add POST /api/voice/session / DELETE end / GET honest status on the unified instance (server-side room + dedicated cybergril-voice-agent dispatch + short-TTL join token via zero-new-dependency livekit_wire HS256/Twirp matching the installed SDK's wire format verified claim-for-claim on the .12 agent venv stdin-only; keys never reach the browser; unconfigured/no-profile/TTS-down refuse honestly and capabilities.voice stays false), chat_api_client speaks the exact real.ts RealChatAdapter protocol (per-turn health epoch, bounded 409 resync, robust incremental SSE parsing across multibyte/CRLF/multi-data chunk splits, fixed turn_id idempotency, immediate HTTP-stream close on barge-in without waiting for the next ASR final), llm_chat_api is a livekit llm.LLM adapter whose only backend is POST /api/chat so persona/mood/dyad/memory/life-sharing/budget gates and the one same-turn chat_lock govern text and voice identically (phi spoken verbatim via ChatChunk, never archived, no receipt), receipt.py confirms a sharing receipt only after real SDK playback completion with every negative (interrupted/failed/mid-playout/phi/incomplete/stale-epoch) fail-closed and exactly once per turn, stt_funasr/tts_cosyvoice reuse the proven .12 adapters verbatim with provenance, worker.py assembles the dedicated worker (independent voice_state_cybergril.json so D1 stays undecided, no second persona, cg.subtitle data-channel contract for the visual lead, CG-011 proactive seam left as an explicit no-op hook, built-in health port 8082); app.py keeps a minimal registration with voice_service injection for isolated tests; deployment drafts only (config/voice.example.yaml, worker.env.example, restart_cybergril.sh.example with exact-pattern process matching, serve_dual_8360_8361.py keeping HTTP 8360 and the HTTPS voice entry on ONE process sharing state/locks, runbook-hel877-voice.md contract+startup+rollback incl. the >=6GB GPU precondition and the do-not-copy historical fuser warning) - verification: 281 pytest pass on 3.11 venv + requirements.lock after merging the chief engineer's mid-flight HEL-874 rework e978e87 in full (parallel work preserved), verify_hel877_voice_chain.py 8/8 offline full-chain incl. socket-level barge-in fail-close and text/voice mutual same-gate cancellation, real-SDK check on the .12 livekit-agents 1.8.8 venv 8/8 ALL PASS via SSH stdin with zero writes zero network, dual-port single-process smoke on loopback 18360/18361 with a throwaway self-signed cert then stopped, ruff clean on all new code, dual-target requirement checks pass vs origin/hel-870-assembly (current tip e978e87) and origin/main with handoff-HEL-877.json; zero real LLM/embed/TTS/ASR requests, no mic/camera, no downloads/installs, no service start/stop, no 4080 access, no third-account or profile writes, web/ untouched, not merged, not deployed
Co-authored-by: multica-agent <github@multica.ai>

## HEL-877 交付摘要(R5 后台施工,未部署未合并)

- 新独立模块 src/cybergril/voice/:专属 livekit worker(agent_name=cybergril-voice-agent,复用 .12 FunASR/CosyVoice/silero 底座,不 fork 不另搭平台,无第二人格/记忆,不直连 LLM);llm_chat_api 适配器与文字前端 real.ts 同协议走 POST /api/chat(epoch 409 有界重同步、SSE 分片、turn_id 幂等、打断即断流);/api/voice/session 建房+专属派发+短时限 token 全服务端(密钥不进浏览器;缺配置/无档案/TTS 停机诚实拒绝;capabilities.voice 不伪造);receipt 仅在 SDK 真实播放完成后确认(打断/失败/φ 轮/旧 epoch 全 fail-closed)。
- 部署草案:/opt/voice-agent-cybergril 目录、worker 健康端口 8082、HTTP 8360 + HTTPS 8361 同进程双入口(deploy/voice/serve_dual_8360_8361.py,共用同一状态/锁)、启动顺序含 TTS GPU≥6GB 前置与回滚;本卡未执行任何启停。契约(开关/字幕/失败/打断/挂断 + CG-011 主动开口接缝)见 docs/runbook-hel877-voice.md §3。
- 自测(零真实请求):281 pytest 全过(含语音 25 例:socket 级打断断流、SSE 边界、重放零调用、文字/语音同门互打断、回执全负例、token 房间隔离);scripts/verify_hel877_voice_chain.py 8/8;.12 agent venv(livekit-agents 1.8.8)真 SDK 检查 8/8(stdin-only 零写入零网络);双端口同进程本地冒烟通过;ruff 干净;需求检查双目标通过(含 handoff-HEL-877.json)。
- 施工中总工 HEL-874(e978e87)推上同分支,本卡已完整并入,不覆盖并行成果。未验证如实列明:端到端语音(TTS 停机/GPU 3.9GB<5.6GB)、真 LiveKit server 的 dispatch/delete、移动端实机——待接线/审核卡真机验收,未经真实验收不称 R5 完成。
2026-10-26 22:42:19 +08:00

210 lines
7.4 KiB
Python

"""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 and stateless apart from the small session
registry: chat state, persona, memory and locks stay in the single API process
that mounts this router (HTTP and the HTTPS voice entry share it).
"""
from __future__ import annotations
import asyncio
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
@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."""
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 = ""
@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
def __post_init__(self) -> None:
self._sessions: dict[str, VoiceSession] = {}
self._tts_health = _Health(checked=-1e9, ok=False)
self._tts_lock = asyncio.Lock()
# -- 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:
now = self.clock()
for session_id in [k for k, v in self._sessions.items() if v.expires_at < now]:
del self._sessions[session_id]
async def open_session(self, *, epoch: int) -> VoiceSession:
self._prune()
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
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:
self._prune()
session = self._sessions.pop(session_id, None)
if session is None:
return None
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,
)
return session
def get(self, session_id: str) -> VoiceSession | None:
self._prune()
return self._sessions.get(session_id)
async def aclose(self) -> None:
await self.http.aclose()