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>
This commit is contained in:
施工员2号
2026-10-26 22:40:45 +08:00
co-authored by multica-agent
parent a324fd57b7
commit 966859002a
21 changed files with 2902 additions and 0 deletions
+201
View File
@@ -0,0 +1,201 @@
#!/usr/bin/env python3
"""Generate the HEL-877 real-SDK compatibility check for the .12 agent venv.
Embeds the repo voice-module sources in a self-contained stdin script (no files
written to .12, no network, no service touched) and runs it with
/opt/voice-agent/agent/venv/bin/python (livekit-agents 1.8.8, livekit 1.1.20).
"""
from __future__ import annotations
import base64
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
MODULES = ["chat_api_client", "receipt", "llm_chat_api"]
TEMPLATE = r'''
import asyncio, base64, json, sys, types
SOURCES = json.loads(base64.b64decode("__B64__"))
pkg = types.ModuleType("cybergril"); pkg.__path__ = []
voice = types.ModuleType("cybergril.voice"); voice.__path__ = []
sys.modules["cybergril"] = pkg
sys.modules["cybergril.voice"] = voice
for name, src in SOURCES.items():
mod = types.ModuleType(f"cybergril.voice.{name}")
mod.__package__ = "cybergril.voice"
sys.modules[f"cybergril.voice.{name}"] = mod
exec(compile(src, f"<cybergril.voice.{name}>", "exec"), mod.__dict__)
setattr(voice, name, mod)
import httpx
from livekit.agents import llm as lk_llm
from livekit.agents.llm import LLM, LLMStream, ChatChunk, ChoiceDelta
ok = []
# 1. real-SDK subclass contracts
llm_mod = sys.modules["cybergril.voice.llm_chat_api"]
assert issubclass(llm_mod.CyberGrillLLM, LLM), "CyberGrillLLM must subclass the real llm.LLM"
assert issubclass(llm_mod.ChatApiLLMStream, LLMStream)
ok.append("CyberGrillLLM/ChatApiLLMStream subclass real livekit-agents 1.8.8 LLM/LLMStream")
# 2. real ChatContext -> latest_user_text
ctx = lk_llm.ChatContext()
ctx.add_message(role="assistant", content="早些的一句")
ctx.add_message(role="user", content="真实SDK链路你好")
assert llm_mod.latest_user_text(ctx) == "真实SDK链路你好"
ok.append("latest_user_text reads a real ChatContext (items/role/text_content)")
# 3. full turn through the real LLMStream machinery with fake SSE
FINAL = "真实链路上的一句完整回复。"
sse = (
'data: {"t":"chat.delta","epoch":1,"turn_id":null,"delta":"真实链路上"}\n\n'
'data: {"t":"chat.delta","epoch":1,"turn_id":null,"delta":"的一句完整回复。"}\n\n'
'data: {"t":"chat.final","epoch":1,"turn_id":null,"utterance":{"text":"' + FINAL + '"},'
'"receipt":{"message_id":9,"turn_id":null,"epoch":1,"token":"' + "k" * 48 + '","text_hash":"' + "h" * 64 + '"}}\n\n'
).encode()
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/api/health":
return httpx.Response(200, json={"epoch": 1})
return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=sse)
receipt_ok = {}
async def round_trip():
client = llm_mod.ChatApiClient("http://x", transport=httpx.MockTransport(handler))
adapter = llm_mod.CyberGrillLLM("http://x", client=client)
stream = adapter.chat(chat_ctx=ctx)
chunks = []
async for chunk in stream:
assert isinstance(chunk, ChatChunk) and chunk.delta and chunk.delta.content
chunks.append(chunk.delta.content)
assert "".join(chunks) == FINAL, chunks
assert stream.completed and stream.receipt and stream.receipt["message_id"] == 9
receipt_ok["text"] = stream.text
receipt_ok["receipt"] = stream.receipt
asyncio.run(round_trip())
assert receipt_ok["text"] == FINAL
ok.append("fake-SSE turn through real LLMStream emits ChatChunks, final text and receipt")
# 4. phi error turn: spoken verbatim, no receipt
phi_sse = (
'data: {"t":"chat.error","epoch":1,"turn_id":null,"phi":"她这会儿没接上话,稍后再试试。你写的话还在。","retryable":true}\n\n'
).encode()
def phi_handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/api/health":
return httpx.Response(200, json={"epoch": 1})
return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=phi_sse)
async def phi_turn():
adapter = llm_mod.CyberGrillLLM("http://x",
client=llm_mod.ChatApiClient("http://x", transport=httpx.MockTransport(phi_handler)))
stream = adapter.chat(chat_ctx=ctx)
spoken = []
async for chunk in stream:
spoken.append(chunk.delta.content)
assert "".join(spoken) == "她这会儿没接上话,稍后再试试。你写的话还在。"
assert stream.error_phi and not stream.completed and stream.receipt is None
asyncio.run(phi_turn())
ok.append("chat.error phi is spoken verbatim via ChatChunk and carries no receipt")
# 5. token claims parity with the real livekit.api.AccessToken
from livekit import api
import jwt as pyjwt
wire = sys.modules["cybergril.voice.livekit_wire"]
mine = wire.mint_token("devkey", "s3cret", identity="user-ab", name="用户",
room="cg-voice-test", room_join=True, ttl_seconds=300, now=1700000000.0)
sdk_token = (api.AccessToken("devkey", "s3cret").with_identity("user-ab").with_name("用户")
.with_grants(api.VideoGrants(room_join=True, room="cg-voice-test",
can_publish=True, can_subscribe=True))
.to_jwt())
mine_claims = pyjwt.decode(mine, "s3cret", algorithms=["HS256"], options={"verify_exp": False})
sdk_claims = pyjwt.decode(sdk_token, "s3cret", algorithms=["HS256"], options={"verify_exp": False})
assert mine_claims["video"] == sdk_claims["video"], (mine_claims["video"], sdk_claims["video"])
assert mine_claims["iss"] == sdk_claims["iss"] and mine_claims["sub"] == sdk_claims["sub"]
assert set(mine_claims) == set(sdk_claims), (sorted(mine_claims), sorted(sdk_claims))
ok.append("mint_token claims byte-parity with livekit.api.AccessToken (video/iss/sub/keys)")
# 6. server token decodes as the SDK Service._auth_header shape
server_tok = wire.mint_server_token("devkey", "s3cret", ttl_seconds=60, now=1700000000.0)
sc = pyjwt.decode(server_tok, "s3cret", algorithms=["HS256"], options={"verify_exp": False})
assert sc["iss"] == "devkey" and sc["sub"] == "" and "video" not in sc
ok.append("mint_server_token matches SDK no-grant auth header claims")
# 7. SpeechHandle/worker API surface used by worker.py exists on the real SDK
from livekit.agents.voice.speech_handle import SpeechHandle
for attr in ("wait_for_playout", "interrupted", "exception", "add_done_callback"):
assert hasattr(SpeechHandle, attr), attr
from livekit.agents.voice.events import UserInputTranscribedEvent
assert "is_final" in UserInputTranscribedEvent.model_fields
ok.append("worker.py SDK surface (SpeechHandle, UserInputTranscribedEvent.is_final) present")
# 8. barge-in cancellation closes the SSE response immediately
state = {"response": None}
async def slow_body():
yield 'data: {"t":"chat.delta","epoch":1,"turn_id":null,"delta":"开头"}\n\n'.encode()
await asyncio.sleep(30)
yield 'data: {"t":"chat.final","epoch":1,"turn_id":null}\n\n'.encode()
class TrackingTransport(httpx.MockTransport):
async def handle_async_request(self, request):
response = await super().handle_async_request(request)
if request.url.path == "/api/chat":
state["response"] = response
return response
def slow_handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/api/health":
return httpx.Response(200, json={"epoch": 1})
return httpx.Response(200, headers={"content-type": "text/event-stream"},
content=slow_body())
async def cancel_case():
adapter = llm_mod.CyberGrillLLM("http://x",
client=llm_mod.ChatApiClient("http://x", transport=TrackingTransport(slow_handler)))
stream = adapter.chat(chat_ctx=ctx)
task = asyncio.create_task(stream._run())
await asyncio.sleep(0.2) # first delta consumed
assert state["response"] is not None and not state["response"].is_closed
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
assert state["response"].is_closed, "adapter must close the HTTP stream on barge-in"
asyncio.run(cancel_case())
ok.append("barge-in task cancel closes the in-flight HTTP stream immediately")
print("HEL-877 real-SDK check on livekit-agents", end=" ")
import importlib.metadata as md
print(md.version("livekit-agents") + ":", "ALL PASS")
for line in ok:
print(" OK", line)
'''
def main() -> int:
sources = {}
for name in MODULES + ["livekit_wire"]:
path = ROOT / "src/cybergril/voice" / f"{name}.py"
sources[name] = path.read_text(encoding="utf-8")
payload = base64.b64encode(json.dumps(sources).encode()).decode()
script = TEMPLATE.replace("__B64__", payload)
out = ROOT / "scripts/_hel877_sdk_check_payload.py"
out.write_text(script, encoding="utf-8")
print(out)
return 0
if __name__ == "__main__":
import json
sys.exit(main())
+235
View File
@@ -0,0 +1,235 @@
"""HEL-877 offline full-chain verification (zero model / zero embed / zero TTS /
zero ASR / zero network beyond 127.0.0.1).
Runs the REAL voice wiring end to end with fakes only:
real app (fake LLM router) + real /api/voice/session router (fake LiveKit
Twirp + fake TTS health) + real ChatApiClient over a real local socket +
real receipt gate — the same protocol the text frontend and the .12 worker
adapters speak.
Run: PYTHONPATH=src .venv311/bin/python scripts/verify_hel877_voice_chain.py
"""
from __future__ import annotations
import asyncio
import contextlib
import socket
import sys
import tempfile
import threading
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
import httpx
import uvicorn
from test_r2 import R2LLM
from cybergril.api.app import create_app
from cybergril.life.runtime import LifeConfig
from cybergril.think.router import build_router
from cybergril.think.scenes import Tier
from cybergril.voice import livekit_wire
from cybergril.voice.chat_api_client import ChatApiClient
from cybergril.voice.receipt import should_ack
from cybergril.voice.session import VoiceConfig, VoiceSessionService
CREATE = {"name": "链路检查", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友"}
class FakeLiveKit:
def __init__(self) -> None:
self.dispatches: list[dict] = []
self.deleted: list[str] = []
self.fail = False
def handler(self, request: httpx.Request) -> httpx.Response:
if self.fail:
return httpx.Response(500)
if request.url.path.endswith("CreateDispatch"):
agent, room = _dispatch_fields(request.content)
self.dispatches.append({"agent_name": agent, "room": room})
return httpx.Response(200, json={"id": f"AD_{len(self.dispatches)}", "room": room})
if request.url.path.endswith("DeleteRoom"):
self.deleted.append(_dispatch_fields(request.content)[0])
return httpx.Response(200)
return httpx.Response(404)
def _read_varint(data: bytes, i: int):
shift = value = 0
while True:
b = data[i]
value |= (b & 0x7F) << shift
i += 1
if not b & 0x80:
return value, i
shift += 7
def _dispatch_fields(data: bytes) -> tuple[str, str]:
out, i = {}, 0
while i < len(data):
tag, i = _read_varint(data, i)
if tag & 7 != 2:
break
n, i = _read_varint(data, i)
out[tag >> 3] = data[i:i + n].decode()
i += n
return out.get(1, ""), out.get(2, "")
def main() -> int:
ok: list[str] = []
livekit = FakeLiveKit()
tts_ok = {"flag": True}
provider = R2LLM()
def transport(request: httpx.Request) -> httpx.Response:
if request.url.host == "tts.test":
return httpx.Response(200) if tts_ok["flag"] else httpx.Response(503)
return livekit.handler(request)
service = VoiceSessionService(
config=VoiceConfig(
livekit_url="ws://voice.test:7880",
livekit_internal="http://livekit.test",
api_key="devkey",
api_secret="verify-secret-not-real",
tts_health_url="http://tts.test/health",
),
http=httpx.AsyncClient(transport=httpx.MockTransport(transport)),
)
router = build_router(
providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)}
)
tmp = Path(tempfile.mkdtemp(prefix="hel877-"))
app = create_app(db_path=tmp / "chain.db", router=router,
life_config=LifeConfig(enabled=True, poll_seconds=3600),
semantic_mode="stub", voice_service=service)
probe = socket.socket()
probe.bind(("127.0.0.1", 0))
port = probe.getsockname()[1]
probe.close()
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port,
log_level="error"))
threading.Thread(target=server.run, daemon=True).start()
for _ in range(100):
try:
httpx.get(f"http://127.0.0.1:{port}/api/health", timeout=1)
break
except Exception:
time.sleep(0.1)
base = f"http://127.0.0.1:{port}"
async def scenario() -> None:
# 1. honest refusals in order: no companion -> TTS down -> ok
http = httpx.AsyncClient(base_url=base)
refusal = await http.post("/api/voice/session")
assert refusal.status_code == 409, refusal.text
await http.post("/api/companion", json=CREATE)
tts_ok["flag"] = False
service._tts_health.checked = -1e9
refusal = await http.post("/api/voice/session")
assert refusal.status_code == 503 and "声音服务" in refusal.json()["detail"]
tts_ok["flag"] = True
service._tts_health.checked = -1e9
# 2. dedicated dispatch + short-TTL token, keys never leave the server
opened = (await http.post("/api/voice/session")).json()
assert livekit.dispatches[-1]["agent_name"] == "cybergril-voice-agent"
claims, _ = livekit_wire.decode_token(opened["token"])
assert livekit_wire.verify_signature(opened["token"], "verify-secret-not-real")
assert claims["video"]["roomJoin"] and claims["video"]["room"] == opened["room"]
assert claims["exp"] - claims["nbf"] <= 300
ok.append("session open: dedicated worker dispatch + genuine short-TTL room token")
# 3. two sessions never share a room
second = (await http.post("/api/voice/session")).json()
assert opened["room"] != second["room"]
ok.append("token room isolation: each session is its own room")
# 4. end: the room is deleted server-side, mic and job release with it
ended = await http.delete(f"/api/voice/session/{opened['session_id']}")
assert ended.json()["ended"] is True and livekit.deleted == [opened["room"]]
assert (await http.delete(f"/api/voice/session/{opened['session_id']}")).status_code == 404
ok.append("session end deletes the LiveKit room (disconnect + job exit path)")
# 5. the worker's chat adapter over a real socket: multi-turn + receipt
client = ChatApiClient(base)
turn1 = await client.send_turn("第一句你好")
turn2 = await client.send_turn("第二句还在")
assert turn1.completed and turn2.completed and turn1.receipt and turn2.receipt
calls = len(provider.calls)
# 6. replay: no new model call
replay = await client.send_turn("第一句你好", turn_id=turn1.turn_id)
assert replay.completed and len(provider.calls) == calls
ok.append("voice turns reuse the chat chain; replay adds zero model calls")
# 7. epoch resync after a server restart (409 + fresh epoch)
server.should_exit = True
await asyncio.sleep(0.5)
threading.Thread(target=lambda: uvicorn.Server(
uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error")).run(),
daemon=True).start()
for _ in range(100):
try:
await httpx.AsyncClient().get(f"{base}/api/health", timeout=1)
break
except Exception:
await asyncio.sleep(0.1)
turn3 = await client.send_turn("重启之后", epoch=1) # stale epoch -> resync
assert turn3.completed and turn3.epoch > 1
ok.append("epoch 409 -> one bounded resync -> turn succeeds on the fresh epoch")
# 8. barge-in cancels the in-flight stream immediately; row = cancelled
provider.mode = "slow"
got = asyncio.Event()
task = asyncio.create_task(
client.send_turn("说一半我要打断你", on_delta=lambda _: got.set())
)
await asyncio.wait_for(got.wait(), timeout=10)
task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await task
provider.mode = ""
for _ in range(50):
rows = (await http.get("/api/messages")).json()["messages"]
row = next((m for m in rows if m["text"] == "说一半我要打断你"), None)
if row and row["status"] == "cancelled":
break
await asyncio.sleep(0.2)
assert row["status"] == "cancelled"
assert not any(m["role"] == "companion" and m["turn_id"] == row["turn_id"] for m in rows)
ok.append("barge-in closes the HTTP stream at once; aborted turn fails closed")
# 9. receipt gating: only a fully played-out turn acks, exactly once
assert should_ack(played_to_end=True, interrupted=False, failed=False,
receipt=turn1.receipt, current_epoch=turn1.epoch)
assert not should_ack(played_to_end=True, interrupted=True, failed=False,
receipt=turn1.receipt, current_epoch=turn1.epoch)
accepted = await client.acknowledge(turn1.receipt)
assert accepted, "server accepts the receipt of the delivered turn"
ok.append("receipt confirmed only after SDK playback completion, once per turn")
await client.aclose()
await http.aclose()
asyncio.run(scenario())
# 10. capabilities honesty: voice stays false in health (no fake readiness)
health = httpx.get(f"{base}/api/health").json()
assert health["capabilities"]["voice"] is False
ok.append("/api/health capabilities.voice stays false (R5 not real-accepted)")
print("HEL-877 offline voice-chain check: ALL PASS")
for line in ok:
print(" ✓", line)
return 0
if __name__ == "__main__":
raise SystemExit(main())