Files
CyberGril/src/cybergril/voice/seam.py
T
zonggongandmultica-agent 3228b1e0d7 HEL-879 remaining closure: auto-expiry cleanup ownership, exact SDK speech-turn attribution, and the versioned v2 subtitle contract for HEL-898
A. Room lifecycle (总管 review items A-1/A-2): the single cleanup owner now watches
   ACTIVE session deadlines as well as debts - a session nobody touches expires into
   the ledger and has its room really deleted with zero further requests (old code:
   _cleanup_loop only scanned debts, expired rooms were never deleted until some
   request ran _prune). Explicit end and the background sweep share ONE persisted
   attempt/age cap and abandoned state - _sessions no longer bypasses it (the
   manager measured 2 background attempts + 3 more interactive deletes = 5); an
   abandoned debt raises CleanupAbandoned -> 503 with room/attempts/reason instead
   of pretending done-404, success clears both _sessions and _debts, restart
   continues the same persisted cap, close/cancel leaves no dangling coroutine, and
   only this instance's own rooms are ever touched. New wake event makes a fresh
   debt retry immediately instead of waiting out a deadline sleep.

B. Queued speech turns bind EXACTLY (总管 interleaving note_handle(H1)->H2->
   note_stream(S1)->S2 gave H1=None, H2='turn-one'): CyberGrillLLM.chat now reads
   the SDK's own agents_speech_handle ContextVar (livekit-agents 1.8.8 sets it in
   _create_speech_task around every speech pipeline; source-verified on .12 and
   asserted at runtime) so each ChatApiLLMStream carries speech_handle/speech_id of
   the very handle whose generation created it. TurnLedger binds only on that exact
   attribution - a newer speech NEVER retires an older pending handle, say/proactive
   generations bind nobody, missing attribution fails closed (no ack, no subtitle
   turn), interrupt/failure discards only its own binding.

C. Versioned subtitle contract v2 for the visual author's wiring card (HEL-898):
   every cg.subtitle payload gains {v:2, seq} (session-monotonic), turn identity
   (speech_id, turn_id, same-source message_id for proactive rows) and explicit
   lifecycle events - turn_start/assistant_interim/assistant_final/turn_end/
   turn_cancel(reason) plus proactive_start/proactive_end/proactive_cancel that
   ride the say SpeechHandle instead of the receipt branch. Accumulators are
   isolated per speech_id (a late delta after cancel is dropped producer-side);
   seq + speech_id give the frontend two independent stale-rejection rules. Full
   executable contract: docs/voice-subtitle-contract-v2.md with recorded samples in
   docs/rework/hel879/subtitle-samples/ (scripts/gen_subtitle_samples_hel879.py).
   web/src untouched.

Verification: the .12 real-SDK check now LOADS THE ACTUAL WORKER MODULE and drives
the callbacks IT registered on a real AgentSession (no hand-copied functions) -
both-queued delayed generations bind exactly, a say sandwiched between user turns
steals nothing, unattributed generations fail closed, interrupted turns cancel
without final/receipt (11/11 ALL PASS, source-level proof of the ContextVar wiring
included; evidence docs/rework/hel879/sdk-check-hel879-remaining.log). The old r2
lifespan test flake is root-caused (clock freeze and block were two separate portal
calls; a 10ms life tick could slip between them and claim the frozen day unblocked)
and fixed atomically without raising timeouts or dropping assertions - 12/12 solo,
full suite 350/350 three times in a row on .venv311; ruff back to the single
pre-existing error; voice chain 8/8; release offline R1-R7 with zero failures;
requirement checks 4/4 (origin/main and c121c42, each with/without handoff).
Zero real LLM/embed/ASR/TTS calls, zero downloads/installs, nothing deployed or
merged, real caps stay 0.

Co-authored-by: multica-agent <github@multica.ai>
2026-10-27 05:10:52 +08:00

158 lines
7.0 KiB
Python

"""Minimal backend seams for CG-011 proactive voice and HER incremental reply
subtitles (HEL-879 rework: these are implementation gaps, not things that
"just need a voice/budget decision").
This module is deliberately free of livekit imports (same rule as
chat_api_client) so both seams are exercised offline by the product test
suite; worker.py only wires them into the AgentSession.
Subtitle payloads are VERSIONED (HEL-879 remaining closure, contract v2 —
docs/voice-subtitle-contract-v2.md): every message on the ``cg.subtitle``
topic carries ``v: 2``, a session-monotonic ``seq``, and the exact
turn identity (``speech_id`` for SDK speech turns, ``message_id`` for
proactive rows) plus explicit start/end/cancel kinds. A shared accumulator
keyed by nothing (the old one-text-field publisher) could not reject a late
increment from an interrupted turn; per-turn accumulators + ``seq`` can.
Seam A — assistant interim subtitles: the unified /api/chat SSE stream
already carries her reply deltas before CosyVoice's first audio packet. The
worker accumulates deltas PER speech_id and publishes the full text so far
with that turn's identity, so the page can render her answer while TTS warms
up and drop stale increments after an interrupt.
Seam B — proactive speech (CG-011): rows the server has ALREADY archived with
proactive=1 (the same rows the text inbox shows as reach-outs) can be spoken
once inside an open voice session via session.say(allow_interruptions=True).
No new model call, no second persona, no second receipt channel; disabled by
default (CYBERGRIL_PROACTIVE_VOICE=1 enables it in the wiring card, after the
visual author defines the entrance presentation). The proactive speech
carries its own subtitle lifecycle (start/end/cancel with the same-source
message_id), never a receipt-branch stand-in.
"""
from __future__ import annotations
from collections.abc import Callable
from typing import Any
from .chat_api_client import ChatApiClient
SUBTITLE_VERSION = 2
class SubtitleBus:
"""Versioned ``cg.subtitle`` envelope with session-monotonic sequence.
Ordering rules for consumers (contract v2): a payload is applied only if
its ``seq`` is strictly greater than the last applied ``seq`` (drop
replays/stale), and turn-scoped payloads (interim/final/end/cancel) are
applied only while their ``speech_id`` is the currently-open turn of that
role — a late increment from an interrupted turn is dropped by BOTH rules.
"""
def __init__(self, publish: Callable[[dict], None]) -> None:
self._publish = publish
self._seq = 0
def emit(self, kind: str, *, role: str, text: str = "",
speech_id: str = "", turn_id: str | None = None,
message_id: int | None = None, reason: str = "") -> dict:
self._seq += 1
payload: dict[str, Any] = {
"v": SUBTITLE_VERSION, "seq": self._seq, "kind": kind,
"role": role, "text": text,
}
if speech_id:
payload["speech_id"] = speech_id
if turn_id is not None:
payload["turn_id"] = turn_id
if message_id is not None:
payload["message_id"] = message_id
if reason:
payload["reason"] = reason
self._publish(payload)
return payload
@property
def seq(self) -> int:
return self._seq
class AssistantInterimPublisher:
"""PER-TURN accumulators turning /api/chat deltas into v2 subtitle events.
``begin`` opens a turn (turn_start), ``feed`` publishes the accumulated
full text so far (replace semantics) under that turn's speech_id,
``finish`` closes it with assistant_final + turn_end, ``cancel`` closes it
fail-closed (no final for an interrupted/failed turn). Accumulators are
keyed by speech_id: one turn's text can never surface as another turn's.
"""
def __init__(self, bus: SubtitleBus) -> None:
self._bus = bus
self._turns: dict[str, str] = {} # speech_id -> full text so far
def begin(self, speech_id: str) -> dict:
if not speech_id:
raise ValueError("interim turns require the speech_id attribution")
self._turns[speech_id] = "" # fresh accumulator for THIS turn only
return self._bus.emit("turn_start", role="assistant", speech_id=speech_id)
def feed(self, speech_id: str, delta: str) -> dict | None:
"""One SSE delta in; the payload published (or None for no-op)."""
if not delta or speech_id not in self._turns:
# Deltas after turn end/cancel (late) or without an open turn are
# dropped: the accumulator is per-turn, never shared.
return None
self._turns[speech_id] += delta
return self._bus.emit(
"assistant_interim", role="assistant",
text=self._turns[speech_id], speech_id=speech_id)
def finish(self, speech_id: str, *, turn_id: str, text: str,
message_id: int | None = None) -> list[dict]:
"""Close the turn with the archived final text (played out intact)."""
self._turns.pop(speech_id, None)
final = self._bus.emit(
"assistant_final", role="assistant", text=text,
speech_id=speech_id, turn_id=turn_id, message_id=message_id)
end = self._bus.emit(
"turn_end", role="assistant", speech_id=speech_id, turn_id=turn_id,
message_id=message_id)
return [final, end]
def cancel(self, speech_id: str, reason: str = "interrupted") -> dict | None:
"""Close the turn fail-closed: no final — this turn never became her
archived reply (barge-in, failure, generation lost)."""
if speech_id not in self._turns:
return None
self._turns.pop(speech_id, None)
return self._bus.emit(
"turn_cancel", role="assistant", speech_id=speech_id, reason=reason)
def pick_proactive(messages: list[dict[str, Any]], *, already_spoken: set[int],
limit: int = 1) -> list[dict[str, Any]]:
"""Pure selection: server-archived proactive rows this voice session may
speak — companion role, sent, proactive, non-empty, not spoken here yet,
newest first, bounded by `limit`. The page keeps its own unread state; the
worker never marks rows read (no second receipt/read channel)."""
candidates = [
m for m in messages
if m.get("proactive") is True and m.get("role") == "companion"
and m.get("status") == "sent"
and (m.get("text") or "").strip()
and m.get("id") not in already_spoken
]
candidates.sort(key=lambda m: m.get("id") or 0, reverse=True)
return candidates[:limit]
async def pending_proactive(client: ChatApiClient, *, already_spoken: set[int],
limit: int = 1,
fetch_limit: int = 20) -> list[dict[str, Any]]:
"""Fetch the newest message page from the unified API and select the
proactive rows the session may speak (see pick_proactive)."""
messages = await client.recent_messages(limit=fetch_limit)
return pick_proactive(messages, already_spoken=already_spoken, limit=limit)