Files
CyberGril/src/cybergril/voice/livekit_wire.py
T
opencodeandmultica-agent 376653135b HEL-879 R5 real-machine window executed (2026-10-27 15:26:54-15:58:10 UTC, 31min16s, within 2h/3-call/40req/500k-token/200-TTS-segment/0-embed authorization): real chain verified on .12 (isolated 8360/8361 dual-entry + 8363 WSS bridge + dedicated worker 8082 + shared TTS 9880 recovered for the window only) -- 3 conversational calls incl. 3 continuous rounds with receipts acked (4 sharing_attempt ack_at/judged), 3 real barge-in interrupts (turn_cancel interrupted, old turn fail-closed), hangup deletes room with ~20ms residual, abrupt-drop rooms TTL-compensated clean after API restart epoch 4->5, voice/text mutual cancel via same chat lock observed (voice-cancelled-text direction); usage ledger 14/40 requests, 42717/500000 tokens, 12/200 TTS segments, 0 embeddings, 0 new spend, budget sealed (real usage preserved) + consistency snapshot archived; two real-machine fixes with evidence: livekit_wire server token now carries SDK-parity video grants (room_admin/room_create; grantless bearer rejected 401 by real server) and Twirp calls switched to JSON encoding (protobuf body unparseable), offline fakes updated, 352/352 pytest + ruff(src/tests/scripts) clean; self-signed cert reissued critical CA:FALSE SAN=IP after rustls CaUsedAsEndEntity rejection; D1 audition README corrected to 'non-custom-function entry' per user feedback (comment 01a17de1); precise ~1s interrupt stop timing and text-cancels-voice direction honestly listed as not-obtained (follow-up window); all window-only processes torn down, protected services untouched, ComfyUI stays paused
Co-authored-by: multica-agent <github@multica.ai>
2026-10-28 00:00:41 +08:00

233 lines
8.0 KiB
Python

"""LiveKit wire helpers for the voice session endpoint (HEL-877).
Reuses the already-running LiveKit SFU on .12 without adding the ``livekit``
package to the API process: access tokens are the same HS256 JWTs, and the
dispatch / room-delete calls use the same Twirp endpoints with the same
protobuf bodies that the installed SDK (livekit 1.1.20, read-only verified on
/opt/voice-agent/agent/venv) sends for /opt/voice-agent/web/server.py's
working /api/token flow. No keys ever leave the server: only the minted,
short-lived room token is returned to the browser.
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import time
from dataclasses import dataclass
from typing import Any
import httpx
TWIRP_PREFIX = "/twirp"
DISPATCH_SERVICE = "livekit.AgentDispatchService"
ROOM_SERVICE = "livekit.RoomService"
def _b64url(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
def _jwt_hs256(secret: str, claims: dict[str, Any]) -> str:
"""HS256 JWT with the exact header the installed SDK's PyJWT produces."""
header = _b64url(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
payload = _b64url(json.dumps(claims, separators=(",", ":"), ensure_ascii=False).encode())
signing_input = f"{header}.{payload}".encode("ascii")
signature = _b64url(hmac.new(secret.encode(), signing_input, hashlib.sha256).digest())
return f"{header}.{payload}.{signature}"
def _camel(name: str) -> str:
head, *rest = name.split("_")
return head + "".join(part.capitalize() for part in rest)
def mint_token(
api_key: str,
api_secret: str,
*,
identity: str,
name: str = "",
room: str = "",
room_join: bool = False,
can_publish: bool = True,
can_subscribe: bool = True,
ttl_seconds: float = 300.0,
now: float | None = None,
) -> str:
"""Participant access token; claims mirror livekit.api.AccessToken.to_jwt().
Video grants are emitted camelCase with empty values dropped, exactly like
Claims.asdict() in the installed SDK.
"""
now = time.time() if now is None else now
video = {
_camel(k): v
for k, v in {
"room_join": room_join,
"room": room,
"can_publish": can_publish,
"can_subscribe": can_subscribe,
"can_publish_data": True,
}.items()
if v is not None and v != ""
}
claims: dict[str, Any] = {"video": video, "sub": identity, "iss": api_key,
"nbf": int(now), "exp": int(now + ttl_seconds)}
if name:
claims["name"] = name
return _jwt_hs256(api_secret, claims)
def mint_server_token(api_key: str, api_secret: str, ttl_seconds: float = 60.0,
now: float | None = None, *,
video: dict[str, Any] | None = None) -> str:
"""Server-API bearer token; claims mirror Service._auth_header().
``video`` grants are required per endpoint exactly like the installed SDK
signs them (R5 real-machine finding 2026-10-27: a grantless bearer is
rejected 401 by CreateDispatch — the SDK sends VideoGrants(room_admin=True,
room=...) there and VideoGrants(room_create=True) for DeleteRoom).
"""
now = time.time() if now is None else now
video_claims: dict[str, Any] = {}
if video:
video_claims = {_camel(k): v for k, v in video.items() if v is not None and v != ""}
claims: dict[str, Any] = {"iss": api_key, "sub": "",
"nbf": int(now), "exp": int(now + ttl_seconds)}
if video_claims:
claims["video"] = video_claims
return _jwt_hs256(
api_secret,
claims,
)
def _proto_string(field_number: int, value: str) -> bytes:
payload = value.encode()
return bytes([(field_number << 3) | 2]) + _varint(len(payload)) + payload
def _varint(value: int) -> bytes:
out = bytearray()
while value > 0x7F:
out.append((value & 0x7F) | 0x80)
value >>= 7
out.append(value)
return bytes(out)
@dataclass
class DispatchResult:
room: str
dispatch_id: str
body: dict
async def create_dispatch(
http: httpx.AsyncClient,
*,
internal_url: str,
api_key: str,
api_secret: str,
agent_name: str,
room: str,
metadata: str = "",
timeout: float = 5.0,
) -> DispatchResult:
"""Twirp AgentDispatchService/CreateDispatch with an explicit agent_name.
Sent as Twirp JSON (content-type application/json): the server answers
JSON, so the dispatch id parses without a protobuf dependency (R5
real-machine finding: protobuf content-type returns a binary body the
JSON parser cannot read).
"""
payload: dict[str, Any] = {"agentName": agent_name, "room": room}
if metadata:
payload["metadata"] = metadata
response = await http.post(
f"{internal_url.rstrip('/')}{TWIRP_PREFIX}/{DISPATCH_SERVICE}/CreateDispatch",
json=payload,
headers={
# SDK parity: VideoGrants(room_admin=True, room=...)
"authorization": f"Bearer {mint_server_token(api_key, api_secret, video={'room_admin': True, 'room': room})}",
},
timeout=timeout,
)
response.raise_for_status()
parsed = json.loads(response.content or b"{}")
return DispatchResult(
room=room,
dispatch_id=str(parsed.get("id") or parsed.get("dispatchId") or ""),
body=parsed,
)
class RoomDeleteError(RuntimeError):
"""LiveKit refused a room delete with a status other than 2xx/404.
Raised (not returned) so callers cannot mistake a failed delete for a
settled one — the caller must keep the room owned for a bounded retry
(HEL-879). A 404 answer means the room is already gone and is reported
as success instead: the delete's goal (room no longer exists) holds.
"""
def __init__(self, status_code: int, room: str) -> None:
super().__init__(f"delete room {room!r} failed with HTTP {status_code}")
self.status_code = status_code
self.room = room
async def delete_room(
http: httpx.AsyncClient,
*,
internal_url: str,
api_key: str,
api_secret: str,
room: str,
timeout: float = 5.0,
) -> bool:
"""Twirp RoomService/DeleteRoom (livekit.DeleteRoomRequest field 1: room).
Deleting the room disconnects every participant, ends the dispatched agent
job and releases the browser microphone server-side.
Returns True when the room is gone: 2xx, or 404 (already deleted — the
retry after a lost response stays idempotent). Any other status raises
RoomDeleteError so ownership is retained until the delete really lands.
"""
response = await http.post(
f"{internal_url.rstrip('/')}{TWIRP_PREFIX}/{ROOM_SERVICE}/DeleteRoom",
json={"room": room},
headers={
# SDK parity: VideoGrants(room_create=True)
"authorization": f"Bearer {mint_server_token(api_key, api_secret, video={'room_create': True})}",
},
timeout=timeout,
)
# LiveKit answers DeleteRoom with an empty protobuf body; 404 = already gone.
if response.status_code // 100 == 2 or response.status_code == 404:
return True
raise RoomDeleteError(response.status_code, room)
def decode_token(token: str) -> tuple[dict[str, Any], bytes]:
"""Header/claims decode without verification (test helper, never trusting input)."""
header_b64, payload_b64, _ = token.split(".")
pad = lambda s: s + "=" * (-len(s) % 4) # noqa: E731
claims = json.loads(base64.urlsafe_b64decode(pad(payload_b64)))
signing_input = f"{header_b64}.{payload_b64}".encode("ascii")
return claims, signing_input
def verify_signature(token: str, secret: str) -> bool:
"""Constant-time HS256 check for tests proving the minted token is genuine."""
parts = token.split(".")
if len(parts) != 3:
return False
signing_input = f"{parts[0]}.{parts[1]}".encode("ascii")
expected = _b64url(hmac.new(secret.encode(), signing_input, hashlib.sha256).digest())
return hmac.compare_digest(expected, parts[2])