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>
This commit is contained in:
co-authored by
multica-agent
parent
b4dadd82b3
commit
3228b1e0d7
@@ -38,6 +38,26 @@ from livekit.agents.types import (
|
||||
from .chat_api_client import ChatApiClient, ChatApiConnectionError
|
||||
|
||||
|
||||
def current_speech_handle() -> Any | None:
|
||||
"""The EXACT SpeechHandle whose pipeline task is starting this generation.
|
||||
|
||||
livekit-agents 1.8.8 wraps every speech pipeline in
|
||||
``AgentActivity._create_speech_task``, which sets the SDK-private
|
||||
``agents_speech_handle`` ContextVar around the task (verified against the
|
||||
installed source on .12: agent_activity.py L120/L970; the LLM inference
|
||||
task inherits it, so ``Agent.llm_node`` -> ``LLM.chat`` runs inside it).
|
||||
Reading it here binds each ChatApiLLMStream to the very handle that owns
|
||||
its generation — no ordering assumption at all. Anything missing (absent
|
||||
symbol, no speech task) returns None and the caller fails closed.
|
||||
"""
|
||||
try:
|
||||
from livekit.agents.voice import agent_activity
|
||||
|
||||
return agent_activity._SpeechHandleContextVar.get(None) # noqa: SLF001
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def latest_user_text(chat_ctx: ChatContext) -> str:
|
||||
"""The one message the server needs: the user's current utterance.
|
||||
|
||||
@@ -74,14 +94,20 @@ class ChatApiLLMStream(LLMStream):
|
||||
self.receipt: dict[str, Any] | None = None
|
||||
self.error_phi: str | None = None
|
||||
self.completed = False
|
||||
# Exact ownership (set by CyberGrillLLM.chat from the SDK generation
|
||||
# context): the SpeechHandle whose pipeline task created this stream,
|
||||
# and its id as the subtitle turn key. None/"" = unattributed.
|
||||
self.speech_handle: Any = None
|
||||
self.speech_id: str = ""
|
||||
|
||||
def _emit(self, content: str) -> None:
|
||||
# HEL-879 seam: raw deltas also feed HER incremental subtitles
|
||||
# (assistant_interim) — same stream, no second channel, and failures
|
||||
# in the seam callback must never break the spoken turn.
|
||||
# in the seam callback must never break the spoken turn. The stream
|
||||
# itself is passed so per-turn accumulators key by its speech_id.
|
||||
if self._llm.on_assistant_delta is not None:
|
||||
with contextlib.suppress(Exception):
|
||||
self._llm.on_assistant_delta(content)
|
||||
self._llm.on_assistant_delta(self, content)
|
||||
self._event_ch.send_nowait(
|
||||
ChatChunk(id=self.turn_id, delta=ChoiceDelta(role="assistant", content=content))
|
||||
)
|
||||
@@ -122,8 +148,8 @@ class CyberGrillLLM(LLM):
|
||||
api_base: str,
|
||||
*,
|
||||
client: ChatApiClient | None = None,
|
||||
on_stream_started: Callable[[ChatApiLLMStream], None] | None = None,
|
||||
on_assistant_delta: Callable[[str], None] | None = None,
|
||||
on_stream_started: Callable[[ChatApiLLMStream, Any], None] | None = None,
|
||||
on_assistant_delta: Callable[[ChatApiLLMStream, str], None] | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.client = client or ChatApiClient(api_base)
|
||||
@@ -157,6 +183,11 @@ class CyberGrillLLM(LLM):
|
||||
tools=tools or [],
|
||||
conn_options=conn_options,
|
||||
)
|
||||
# Exact attribution from the SDK's own generation context: the handle
|
||||
# whose pipeline task is calling chat() (fail-closed None outside a
|
||||
# speech task / on an SDK without the contextvar).
|
||||
stream.speech_handle = current_speech_handle()
|
||||
stream.speech_id = getattr(stream.speech_handle, "id", "") or ""
|
||||
if self._on_stream_started is not None:
|
||||
self._on_stream_started(stream)
|
||||
self._on_stream_started(stream, stream.speech_handle)
|
||||
return stream
|
||||
|
||||
@@ -7,18 +7,21 @@ ended in chat.error (the φ line is spoken verbatim but is not her archived
|
||||
reply), missing receipt, or a receipt from an epoch the server has since left
|
||||
(the server fail-closes those anyway — this is the client-side half).
|
||||
|
||||
Speech-handle-to-stream binding lives in TurnLedger as an EXPLICIT
|
||||
association, not a time-window guess (HEL-879 总管复核第 3 项): AgentSession
|
||||
runs one user-turn generation at a time, so the LLM stream a generation starts
|
||||
is bound to the oldest handle still awaiting its generation; a handle whose
|
||||
generation never starts (cancelled/interrupted before the LLM call) is retired
|
||||
the moment a newer speech appears — it can never consume a later turn's
|
||||
stream, and a failed/interrupted handle only ever releases its own binding.
|
||||
Speech-handle-to-stream binding lives in TurnLedger as an EXACT association
|
||||
taken from the SDK's own generation context (HEL-879 remaining closure):
|
||||
``CyberGrillLLM.chat`` reads the ``agents_speech_handle`` ContextVar the SDK
|
||||
sets around every speech pipeline task, so each ChatApiLLMStream is bound to
|
||||
the very handle whose generation created it. No ordering assumption ("a newer
|
||||
speech means the older one never starts", "oldest pending gets the stream")
|
||||
is used anywhere. When attribution is missing — the var is absent, the handle
|
||||
was never noted as a user-initiated turn, or the generation belongs to an
|
||||
agent-initiated/proactive speech — the stream binds to NOBODY and the turn
|
||||
cannot ack: fail-closed, and one turn's stream can never be consumed by
|
||||
another turn's handle.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
from typing import Any, Protocol
|
||||
|
||||
from .chat_api_client import ChatApiClient
|
||||
@@ -52,46 +55,52 @@ class _HasHandle(Protocol):
|
||||
|
||||
|
||||
class TurnLedger:
|
||||
"""Binds livekit SpeechHandles to the ChatApiLLMStream of their generation.
|
||||
"""Binds livekit SpeechHandles to the ChatApiLLMStream of THEIR generation.
|
||||
|
||||
The binding is exact, never inferred from ordering timestamps: a stream is
|
||||
bound to the oldest handle that has not yet been retired (its generation is
|
||||
the one the SDK is starting), and each stream is consumed exactly once by
|
||||
exactly its own handle.
|
||||
The binding is exact, never inferred from event order: ``note_stream``
|
||||
carries the speech handle read from the SDK's generation context, so a
|
||||
stream is bound if and only if that exact handle was noted as a
|
||||
user-initiated turn. Handles without a generation (interrupted/cancelled
|
||||
before the LLM call, ``say`` speeches without an LLM stream) simply never
|
||||
bind; streams without a noted handle (proactive/agent-initiated replies)
|
||||
bind to nobody. Each stream is consumed exactly once, by exactly its own
|
||||
handle.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._pending: deque[Any] = deque() # handles awaiting their generation
|
||||
self._bound: dict[int, Any] = {} # id(handle) -> its stream
|
||||
self._retired: set[int] = set() # ended without a generation
|
||||
self._noted: dict[int, Any] = {} # id(handle) -> handle (user turns)
|
||||
self._bound: dict[int, Any] = {} # id(handle) -> its own stream
|
||||
self.unattributed: list[Any] = [] # diagnostics: streams nobody may claim
|
||||
|
||||
def note_handle(self, handle: _HasHandle, created_at: float | None = None) -> None:
|
||||
"""A new user speech started: every older handle still awaiting its
|
||||
generation will never get one (the SDK moves on to the new turn), so it
|
||||
is retired instead of staying eligible to steal the next stream."""
|
||||
while self._pending:
|
||||
self._retired.add(id(self._pending.popleft()))
|
||||
self._pending.append(handle)
|
||||
"""A user-initiated speech started. Registration only — a later speech
|
||||
NEVER retires this one: whether its generation starts is the SDK's
|
||||
decision, not an ordering inference."""
|
||||
self._noted[id(handle)] = handle
|
||||
|
||||
def note_stream(self, stream: Any, created_at: float | None = None) -> None:
|
||||
"""The generation the SDK just started belongs to the oldest handle
|
||||
still awaiting one. A stream with no pending handle (proactive speech
|
||||
outside a user turn) is left unbound: no user turn may claim it."""
|
||||
if self._pending:
|
||||
handle = self._pending.popleft()
|
||||
def note_stream(self, stream: Any, handle: Any = None,
|
||||
created_at: float | None = None) -> bool:
|
||||
"""Bind a generation's stream to EXACTLY the handle whose pipeline
|
||||
task created it (from the SDK speech context). Returns False and
|
||||
binds nobody when the attribution is missing or the handle was never
|
||||
noted — that turn cannot ack (fail-closed)."""
|
||||
if handle is not None and id(handle) in self._noted:
|
||||
self._bound[id(handle)] = stream
|
||||
return True
|
||||
self.unattributed.append(stream)
|
||||
return False
|
||||
|
||||
def stream_for(self, handle: _HasHandle) -> Any | None:
|
||||
"""This handle's own stream, exactly once; None when its generation
|
||||
never started or it was retired/interrupted without one."""
|
||||
never started or it was interrupted/discarded without one."""
|
||||
return self._bound.pop(id(handle), None)
|
||||
|
||||
def discard(self, handle: _HasHandle) -> None:
|
||||
"""Release a handle's binding without using it (fail-closed path for
|
||||
interrupted/failed playout): the turn never acks, and the binding does
|
||||
not leak into any later turn."""
|
||||
"""Release a handle's registration and binding without using it
|
||||
(fail-closed path for interrupted/failed playout): the turn never
|
||||
acks, and nothing of it leaks into any later turn."""
|
||||
self._bound.pop(id(handle), None)
|
||||
self._retired.discard(id(handle))
|
||||
self._noted.pop(id(handle), None)
|
||||
|
||||
|
||||
class ReceiptSender:
|
||||
|
||||
@@ -23,12 +23,15 @@ from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
|
||||
from .session import VoiceSessionService
|
||||
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:
|
||||
@@ -76,6 +79,19 @@ def build_voice_router(service: VoiceSessionService | None) -> APIRouter:
|
||||
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
|
||||
|
||||
+99
-22
@@ -6,18 +6,28 @@ 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.
|
||||
|
||||
Seam A — assistant_interim subtitles: the unified /api/chat SSE stream already
|
||||
carries her reply deltas before CosyVoice's first audio packet. The worker
|
||||
publishes the accumulated text as `{"kind": "assistant_interim", ...}` on the
|
||||
`cg.subtitle` topic so the page can show her answer while TTS is still warming
|
||||
up. The existing user `interim` kind is untouched.
|
||||
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).
|
||||
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
|
||||
@@ -27,32 +37,99 @@ from typing import Any
|
||||
|
||||
from .chat_api_client import ChatApiClient
|
||||
|
||||
SUBTITLE_VERSION = 2
|
||||
|
||||
class AssistantInterimPublisher:
|
||||
"""Accumulates /api/chat deltas into `assistant_interim` subtitle payloads.
|
||||
|
||||
One instance per voice session; `reset()` on every new generation so a
|
||||
later turn never starts with the previous turn's text. Payload text is the
|
||||
FULL text so far (replace semantics, same as the user interim kind).
|
||||
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._text = ""
|
||||
self._seq = 0
|
||||
|
||||
def reset(self) -> None:
|
||||
self._text = ""
|
||||
|
||||
def feed(self, delta: str) -> dict | None:
|
||||
"""One SSE delta in; the payload to publish (or None for no-op)."""
|
||||
if not delta:
|
||||
return None
|
||||
self._text += delta
|
||||
payload = {"kind": "assistant_interim", "role": "assistant",
|
||||
"text": self._text}
|
||||
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]]:
|
||||
|
||||
@@ -17,6 +17,14 @@ persisted beside the instance database so a restarted process compensates its
|
||||
OWN rooms (never another instance's, never the generic worker). Retries are
|
||||
idempotent (404 = already gone = settled). Every debt is bounded by attempts
|
||||
and age, then recorded as abandoned instead of retried forever.
|
||||
|
||||
HEL-879 remaining closure: the cleanup owner also watches the ACTIVE session
|
||||
deadlines — a session that nobody touches expires into the ledger and has its
|
||||
room deleted without any further request — and explicit end shares the very
|
||||
same persisted attempt cap and abandoned state with the background sweep (no
|
||||
_sessions bypass). A debt that crossed its cap raises CleanupAbandoned instead
|
||||
of answering a done-404: the room is still owned-but-unsettled and the caller
|
||||
must keep treating the hang-up as not finished.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -72,6 +80,24 @@ class VoiceNotConfigured(Exception):
|
||||
"""Raised when no config file exists; the endpoint refuses honestly."""
|
||||
|
||||
|
||||
class CleanupAbandoned(Exception):
|
||||
"""The room is still owned but its bounded cleanup crossed the cap.
|
||||
|
||||
Raised by ``end_session`` when the persisted debt for the room is already
|
||||
abandoned (attempts/age exhausted): no further remote delete is issued —
|
||||
neither by the caller nor by the background sweep — and the state must be
|
||||
reported as unsettled, never as a done-404. The debt (attempts, last
|
||||
error, reason) stays persisted for the operator.
|
||||
"""
|
||||
|
||||
def __init__(self, debt: _CleanupDebt) -> None:
|
||||
self.debt = debt
|
||||
super().__init__(
|
||||
f"cleanup abandoned ({debt.abandoned}) after {debt.attempts} attempts: "
|
||||
f"room {debt.session.room} is still owned and unsettled"
|
||||
)
|
||||
|
||||
|
||||
def load_voice_config(
|
||||
path: Path | str | None = None,
|
||||
) -> VoiceConfig | None:
|
||||
@@ -186,6 +212,7 @@ class VoiceSessionService:
|
||||
self._tts_health = _Health(checked=-1e9, ok=False)
|
||||
self._tts_lock = asyncio.Lock()
|
||||
self._cleaner: asyncio.Task | None = None
|
||||
self._wake = asyncio.Event()
|
||||
self._load_state()
|
||||
|
||||
# -- persisted cleanup ledger (own rooms only) ---------------------------
|
||||
@@ -299,20 +326,32 @@ class VoiceSessionService:
|
||||
)
|
||||
|
||||
async def _cleanup_loop(self) -> None:
|
||||
"""The single cleanup owner for THIS instance.
|
||||
|
||||
It watches two deadlines without needing any further request: every
|
||||
debt's next retry eligibility and every ACTIVE session's expiry. When
|
||||
there is nothing left to watch (no sessions, only settled/abandoned
|
||||
debts) the loop exits; the next open/recover/end re-kicks it.
|
||||
"""
|
||||
try:
|
||||
while True:
|
||||
self._prune() # expired active sessions become retryable debts
|
||||
pending = self._retryable_debts()
|
||||
if not pending:
|
||||
waiting = [d for d in self._debts.values()
|
||||
if not self._abandon_reason(d)]
|
||||
if not waiting:
|
||||
now = self.clock()
|
||||
deadlines = [d.eligible_at for d in self._debts.values()
|
||||
if not self._abandon_reason(d)]
|
||||
deadlines += [s.expires_at for s in self._sessions.values()]
|
||||
if not deadlines:
|
||||
break
|
||||
# Deferred debts (restart compensation waiting out a live
|
||||
# session's TTL): re-check when the earliest becomes
|
||||
# eligible, capped so the loop stays cheap and bounded.
|
||||
now = self.clock()
|
||||
delay = min(max(d.eligible_at - now for d in waiting), 60.0)
|
||||
await asyncio.sleep(max(delay, 0.05) if delay > 0 else 0.05)
|
||||
# session's TTL) and not-yet-expired sessions: sleep until
|
||||
# the earliest deadline, bounded so the loop stays cheap —
|
||||
# a newly created debt wakes it immediately (_wake).
|
||||
delay = min(max(min(deadlines) - now, 0.05), 60.0)
|
||||
self._wake.clear()
|
||||
with contextlib.suppress(asyncio.TimeoutError):
|
||||
await asyncio.wait_for(self._wake.wait(), timeout=delay)
|
||||
continue
|
||||
for session_id in pending:
|
||||
debt = self._debts.get(session_id)
|
||||
@@ -335,6 +374,7 @@ class VoiceSessionService:
|
||||
|
||||
def _kick_cleanup(self) -> None:
|
||||
if self._cleaner is not None and not self._cleaner.done():
|
||||
self._wake.set() # wake the sleeping watcher for the new debt
|
||||
return
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
@@ -397,22 +437,35 @@ class VoiceSessionService:
|
||||
a failed delete keeps the session in the bounded cleanup ledger, so a
|
||||
retry (this method again, the background sweep, or the next process
|
||||
via the persisted ledger) still targets the same room — it can never
|
||||
degrade into a 404 that silently drops the room. Unknown ids (never
|
||||
seen here, or fully settled and forgotten) still return None → 404.
|
||||
degrade into a 404 that silently drops the room.
|
||||
|
||||
Explicit end and the background sweep share ONE persisted attempt
|
||||
budget (HEL-879 remaining closure): both count into the same debt, so
|
||||
a room whose cap the sweep exhausted is never re-deleted from here
|
||||
either — it raises CleanupAbandoned (unsettled, honest) instead of
|
||||
answering a done-404. Unknown ids never seen here return None → 404;
|
||||
ids fully settled and forgotten also do.
|
||||
"""
|
||||
self._prune()
|
||||
session = self._sessions.get(session_id)
|
||||
if session is None:
|
||||
debt = self._debts.get(session_id)
|
||||
if debt is None or debt.abandoned:
|
||||
return None
|
||||
debt = self._debts.get(session_id)
|
||||
if session is None and debt is None:
|
||||
return None
|
||||
if debt is None:
|
||||
debt = _CleanupDebt(session=session, first_debt_at=self.clock())
|
||||
elif debt.abandoned:
|
||||
# Cap already crossed (by this process or a previous one): no more
|
||||
# remote deletes from any path; the room stays owned-unsettled.
|
||||
raise CleanupAbandoned(debt)
|
||||
else:
|
||||
session = debt.session
|
||||
try:
|
||||
await self._delete_room_once(session)
|
||||
except Exception as exc:
|
||||
debt = self._debts.get(session_id)
|
||||
if debt is None:
|
||||
debt = _CleanupDebt(session=session, first_debt_at=self.clock())
|
||||
# From now on the room lives in the ledger alone: _sessions no
|
||||
# longer bypasses the shared cap on a later end call.
|
||||
self._sessions.pop(session_id, None)
|
||||
if session_id not in self._debts:
|
||||
self._debts[session_id] = debt
|
||||
debt.attempts += 1
|
||||
debt.last_error = f"{type(exc).__name__}: {exc}"[:200]
|
||||
|
||||
+135
-60
@@ -13,14 +13,19 @@
|
||||
文字与语音同走 /api/chat,互相争用由服务端同一轮次门处理。
|
||||
回执: 只有 SDK 真实播放完成(speech handle done、未被打断、无异常、轮次
|
||||
完整带 receipt)才 POST /api/chat/received;被打断、断线、播放失败、
|
||||
chat.error(φ 文案原句念出)一律不确认。
|
||||
字幕: cg.subtitle 数据消息发到房间(契约见 docs/voice-contract-hel877.md)。
|
||||
chat.error(φ 文案原句念出)一律不确认。归属是确切的:生成流通过
|
||||
SDK 自己的 agents_speech_handle 上下文绑定到它所属的 SpeechHandle,
|
||||
不按事件先后猜(HEL-879 收口)。
|
||||
字幕: cg.subtitle 数据消息发到房间,契约 v2(带 v/seq/speech_id/起止事件,
|
||||
见 docs/voice-subtitle-contract-v2.md)。
|
||||
音色: 独立 voice_state_cybergril.json;D1 未拍板前回落 default,不替用户定。
|
||||
|
||||
运行位置: /opt/voice-agent-cybergril/(独立目录,复用 .12 现有 agent venv 与
|
||||
LiveKit/FunASR/CosyVoice;专属健康端口 CYBERGRIL_WORKER_HEALTH_PORT——
|
||||
livekit-agents worker 内建 HTTP 健康检查,GET / 返回 OK/503)。
|
||||
本文件只在 agent venv(livekit-agents 1.8.8)中导入;产品 API 进程不导入它。
|
||||
事件接线集中在 bind_voice_session(离线真 SDK 检查直接驱动它注册的回调,
|
||||
scripts/gen_hel877_sdk_check.py 不再手抄复刻)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -35,7 +40,7 @@ from livekit.plugins.silero import VAD
|
||||
|
||||
from .llm_chat_api import CyberGrillLLM
|
||||
from .receipt import ReceiptSender, TurnLedger, should_ack
|
||||
from .seam import AssistantInterimPublisher, pending_proactive
|
||||
from .seam import AssistantInterimPublisher, SubtitleBus, pending_proactive
|
||||
from .stt_funasr import FunASRSTT
|
||||
from .tts_cosyvoice import CosyVoiceTTS
|
||||
|
||||
@@ -71,71 +76,52 @@ def prewarm(proc: JobProcess) -> None:
|
||||
proc.userdata["vad"] = VAD.load()
|
||||
|
||||
|
||||
async def _maybe_open_proactive(session: AgentSession, room, client=None,
|
||||
already_spoken: set[int] | None = None) -> list[int]:
|
||||
"""CG-011 主动开口最小接缝(HEL-879:真实代码路径,默认关闭).
|
||||
|
||||
仅在已开启的语音会话内、只念服务端已落库、标记 proactive=1、未在本房间
|
||||
念过的 companion 行(同一 GET /api/messages 入口,无第二人格/无新模型调用),
|
||||
`session.say(..., allow_interruptions=True)` 可被用户打断,不新建回执通道
|
||||
(文字回执规则独立且已存在)。每会话有界(PROACTIVE_PER_SESSION)。
|
||||
入口呈现与节奏由总管/视觉总监在接线卡定;批准前置 CYBERGRIL_PROACTIVE_VOICE=1。
|
||||
返回本次念出的消息 id(接线/验收用;未启用返回空)。
|
||||
"""
|
||||
if not PROACTIVE_VOICE:
|
||||
return []
|
||||
spoken: set[int] = already_spoken if already_spoken is not None else set()
|
||||
rows = await pending_proactive(client, already_spoken=spoken,
|
||||
limit=PROACTIVE_PER_SESSION)
|
||||
spoken_ids: list[int] = []
|
||||
for row in rows:
|
||||
await session.say(row["text"], allow_interruptions=True)
|
||||
spoken_ids.append(row["id"])
|
||||
return spoken_ids
|
||||
|
||||
|
||||
async def entrypoint(ctx: JobContext) -> None:
|
||||
stt = FunASRSTT()
|
||||
# agent 说话期间短文本/相似文本视为回声丢弃(同通用 worker 的实测做法)
|
||||
stt.agent_speaking = False
|
||||
stt.agent_recent_text = ""
|
||||
|
||||
def make_subtitle_publisher(room):
|
||||
"""cg.subtitle 数据通道(contract v2 信封由 SubtitleBus 统一加)。"""
|
||||
def subtitle(payload: dict) -> None:
|
||||
data = json.dumps(payload, ensure_ascii=False).encode()
|
||||
asyncio.get_running_loop().create_task(
|
||||
ctx.room.local_participant.publish_data(data, topic=SUBTOPIC, reliable=False)
|
||||
room.local_participant.publish_data(data, topic=SUBTOPIC, reliable=False)
|
||||
)
|
||||
return subtitle
|
||||
|
||||
ledger = TurnLedger()
|
||||
interim = AssistantInterimPublisher(subtitle)
|
||||
|
||||
def note_stream(stream) -> None:
|
||||
interim.reset() # a new generation must not inherit the old text
|
||||
ledger.note_stream(stream, stream.created_at)
|
||||
def make_voice_llm(api_base: str, *, ledger: TurnLedger,
|
||||
interim: AssistantInterimPublisher, client=None) -> CyberGrillLLM:
|
||||
"""CyberGrillLLM + 确切归属接线(worker 的唯一 LLM 组装方式).
|
||||
|
||||
llm = CyberGrillLLM(API_BASE, on_stream_started=note_stream,
|
||||
on_assistant_delta=interim.feed)
|
||||
receipts = ReceiptSender(llm.client)
|
||||
on_stream_started 拿到 SDK 生成上下文里的确切 SpeechHandle(适配器读
|
||||
agents_speech_handle ContextVar):字幕按该 speech_id 开轮,账本按该
|
||||
handle 精确绑定;无归属(None/未登记)一律 fail-closed,不绑任何轮。
|
||||
"""
|
||||
def on_stream_started(stream, speech_handle) -> None:
|
||||
if stream.speech_id:
|
||||
interim.begin(stream.speech_id)
|
||||
ledger.note_stream(stream, speech_handle)
|
||||
|
||||
session = AgentSession(
|
||||
stt=stt,
|
||||
llm=llm,
|
||||
tts=CosyVoiceTTS(default_voice=read_default_voice()),
|
||||
vad=ctx.proc.userdata["vad"],
|
||||
turn_handling={
|
||||
# 停顿稍久才判说完, 合并慢语速碎片(同通用 worker 实测参数)
|
||||
"endpointing": {"min_delay": 0.8, "max_delay": 6.0},
|
||||
},
|
||||
)
|
||||
def on_assistant_delta(stream, delta: str) -> None:
|
||||
interim.feed(stream.speech_id, delta)
|
||||
|
||||
return CyberGrillLLM(api_base, client=client,
|
||||
on_stream_started=on_stream_started,
|
||||
on_assistant_delta=on_assistant_delta)
|
||||
|
||||
|
||||
def bind_voice_session(session: AgentSession, *, llm: CyberGrillLLM,
|
||||
ledger: TurnLedger, interim: AssistantInterimPublisher,
|
||||
bus: SubtitleBus, stt, receipts) -> None:
|
||||
"""把 worker 的全部会话事件回调注册到真 AgentSession(唯一接线点).
|
||||
|
||||
scripts/gen_hel877_sdk_check.py 在 .12 真实 SDK 上加载本模块并直接驱动
|
||||
这里注册的回调,不手抄复刻任何函数。
|
||||
"""
|
||||
outcomes: dict[str, str] = {} # speech_id -> last outcome (diagnostics)
|
||||
|
||||
@session.on("user_input_transcribed")
|
||||
def _on_transcript(ev) -> None:
|
||||
if ev.transcript.strip():
|
||||
subtitle({
|
||||
"kind": "user_final" if ev.is_final else "interim",
|
||||
"role": "user",
|
||||
"text": ev.transcript,
|
||||
})
|
||||
bus.emit("user_final" if ev.is_final else "interim",
|
||||
role="user", text=ev.transcript)
|
||||
|
||||
async def _after_playout(handle) -> None:
|
||||
# SDK 真实播放完成(wait_for_playout 返回)之后才考虑回执。
|
||||
@@ -143,17 +129,27 @@ async def entrypoint(ctx: JobContext) -> None:
|
||||
# HEL-879:先判定失败/打断并整单放弃(fail-closed)——被放弃的绑定
|
||||
# 只属于这一轮,绝不会吞掉下一轮的回执归属。
|
||||
failed = handle.exception() is not None
|
||||
speech_id = getattr(handle, "id", "")
|
||||
if handle.interrupted or failed:
|
||||
ledger.discard(handle)
|
||||
interim.cancel(speech_id, "interrupted" if handle.interrupted else "failed")
|
||||
outcomes[speech_id] = "cancelled"
|
||||
return
|
||||
stream = ledger.stream_for(handle)
|
||||
if stream is None:
|
||||
# 无确切归属(生成从未开始/被退役/主动 say 无 LLM 流):不确认、
|
||||
# 不发 final——fail-closed。
|
||||
interim.cancel(speech_id, "no-generation")
|
||||
outcomes[speech_id] = "unattributed"
|
||||
return
|
||||
if stream.error_phi:
|
||||
subtitle({"kind": "error", "role": "assistant", "text": stream.error_phi})
|
||||
bus.emit("error", role="assistant", text=stream.error_phi,
|
||||
speech_id=speech_id)
|
||||
interim.cancel(speech_id, "error_phi")
|
||||
outcomes[speech_id] = "error_phi"
|
||||
return
|
||||
if stream.text and not handle.interrupted:
|
||||
subtitle({"kind": "assistant_final", "role": "assistant", "text": stream.text})
|
||||
if stream.text:
|
||||
interim.finish(speech_id, turn_id=stream.turn_id, text=stream.text)
|
||||
epoch = None
|
||||
try:
|
||||
epoch = await llm.client.current_epoch()
|
||||
@@ -167,6 +163,9 @@ async def entrypoint(ctx: JobContext) -> None:
|
||||
current_epoch=epoch,
|
||||
):
|
||||
await receipts.confirm(stream.turn_id, stream.receipt)
|
||||
outcomes[speech_id] = "acked"
|
||||
else:
|
||||
outcomes[speech_id] = "no-receipt"
|
||||
|
||||
@session.on("speech_created")
|
||||
def _on_speech_created(ev) -> None:
|
||||
@@ -194,11 +193,87 @@ async def entrypoint(ctx: JobContext) -> None:
|
||||
def _on_state(ev) -> None:
|
||||
stt.agent_speaking = getattr(ev, "new_state", "") == "speaking"
|
||||
|
||||
|
||||
async def speak_proactive_row(session: AgentSession, bus: SubtitleBus, row: dict) -> None:
|
||||
"""念一条已落库 proactive 行,并给同源 message_id 的字幕起止/打断事件.
|
||||
|
||||
字幕生命周期绑定在 say 返回的 SpeechHandle 上(proactive_start ->
|
||||
proactive_end/proactive_cancel),不借用任何回执分支。
|
||||
"""
|
||||
handle = await session.say(row["text"], allow_interruptions=True)
|
||||
speech_id = getattr(handle, "id", "")
|
||||
bus.emit("proactive_start", role="assistant", text=row["text"],
|
||||
speech_id=speech_id, message_id=row["id"])
|
||||
|
||||
def _on_say_done(h, sid=speech_id, mid=row["id"]) -> None:
|
||||
if h.interrupted or h.exception() is not None:
|
||||
bus.emit("proactive_cancel", role="assistant", speech_id=sid,
|
||||
message_id=mid,
|
||||
reason="interrupted" if h.interrupted else "failed")
|
||||
else:
|
||||
bus.emit("proactive_end", role="assistant", speech_id=sid, message_id=mid)
|
||||
|
||||
handle.add_done_callback(_on_say_done)
|
||||
|
||||
|
||||
async def _maybe_open_proactive(session: AgentSession, room, bus: SubtitleBus,
|
||||
client=None, already_spoken: set[int] | None = None
|
||||
) -> list[int]:
|
||||
"""CG-011 主动开口最小接缝(HEL-879:真实代码路径,默认关闭).
|
||||
|
||||
仅在已开启的语音会话内、只念服务端已落库、标记 proactive=1、未在本房间
|
||||
念过的 companion 行(同一 GET /api/messages 入口,无第二人格/无新模型调用),
|
||||
`session.say(..., allow_interruptions=True)` 可被用户打断,不新建回执通道
|
||||
(文字回执规则独立且已存在)。每会话有界(PROACTIVE_PER_SESSION)。
|
||||
这是「会话开时念已落库旧留言」的最小实现,不冒充会话中完整 CG-011 主动
|
||||
表达;入口呈现与节奏由总管/视觉总监在接线卡定;批准前置
|
||||
CYBERGRIL_PROACTIVE_VOICE=1。返回本次念出的消息 id(接线/验收用;未启用
|
||||
返回空)。
|
||||
"""
|
||||
if not PROACTIVE_VOICE:
|
||||
return []
|
||||
spoken: set[int] = already_spoken if already_spoken is not None else set()
|
||||
rows = await pending_proactive(client, already_spoken=spoken,
|
||||
limit=PROACTIVE_PER_SESSION)
|
||||
spoken_ids: list[int] = []
|
||||
for row in rows:
|
||||
await speak_proactive_row(session, bus, row)
|
||||
spoken_ids.append(row["id"])
|
||||
return spoken_ids
|
||||
|
||||
|
||||
async def entrypoint(ctx: JobContext) -> None:
|
||||
stt = FunASRSTT()
|
||||
# agent 说话期间短文本/相似文本视为回声丢弃(同通用 worker 的实测做法)
|
||||
stt.agent_speaking = False
|
||||
stt.agent_recent_text = ""
|
||||
|
||||
subtitle = make_subtitle_publisher(ctx.room)
|
||||
bus = SubtitleBus(subtitle)
|
||||
ledger = TurnLedger()
|
||||
interim = AssistantInterimPublisher(bus)
|
||||
|
||||
llm = make_voice_llm(API_BASE, ledger=ledger, interim=interim)
|
||||
receipts = ReceiptSender(llm.client)
|
||||
|
||||
session = AgentSession(
|
||||
stt=stt,
|
||||
llm=llm,
|
||||
tts=CosyVoiceTTS(default_voice=read_default_voice()),
|
||||
vad=ctx.proc.userdata["vad"],
|
||||
turn_handling={
|
||||
# 停顿稍久才判说完, 合并慢语速碎片(同通用 worker 实测参数)
|
||||
"endpointing": {"min_delay": 0.8, "max_delay": 6.0},
|
||||
},
|
||||
)
|
||||
bind_voice_session(session, llm=llm, ledger=ledger, interim=interim,
|
||||
bus=bus, stt=stt, receipts=receipts)
|
||||
|
||||
await ctx.connect()
|
||||
await session.start(room=ctx.room, agent=Agent(instructions=INSTRUCTIONS_PLACEHOLDER))
|
||||
spoken_proactive: set[int] = set()
|
||||
try:
|
||||
spoken = await _maybe_open_proactive(session, ctx.room, client=llm.client,
|
||||
spoken = await _maybe_open_proactive(session, ctx.room, bus, client=llm.client,
|
||||
already_spoken=spoken_proactive)
|
||||
spoken_proactive.update(spoken)
|
||||
except Exception as exc: # seam failure never breaks the session start
|
||||
|
||||
Reference in New Issue
Block a user