HEL-908 R1/R2 rework (HEL-909 review): whole-turn reasoning gate + cg.interrupt data channel
R1 — reasoning separation truly closed. The streaming hold leaked wholesale
on real token arrival (review A1: 'private reasoning '*20 beyond the 128-char
bound, no sentence ender; review A2: a Chinese sentence ender released the
hold) AND the adapter consumed the stray closer, so the app-level turn split
could never recover — the previous 'persistence and receipt always clean'
claim was false and is retracted. Per the engineering ruling the adapter now
has two explicit endpoint modes (GOV-006, no heuristics, no new engine):
buffer_turn (TurnReasoningGate) emits NOTHING during generation, splits the
whole turn at stream end and only then delivers the clean visible text; it
is set explicitly for all tiers in config/models.yaml (first visible text
waits for the full generation; cancelled/timed-out turns emit nothing and
end exactly as before — recorded and test-pinned, low latency NOT claimed).
stream (default, backward compatible) keeps explicit-tag/field semantics and
passes stray closers through unmodified so the turn-level split keeps its
signal. Both review strings and the recorded id=12 stream replay clean at
every chunk size through the real adapter and the real app into chat.delta,
the archive and the receipt; normal zh/en preserved byte-for-byte; unclosed
explicit thinking still fails honestly.
R2 — an authoritative interrupt when the LLM already finalized and TTS is
still playing (review evidence C: zero interrupts, old audio played out).
The page's existing hush() entry (ChatPanel untouched) now also publishes
{"v":1} on the room's own reliable data channel topic cg.interrupt
(fire-and-forget: a dropped publish never blocks or breaks the text send);
the worker subscribes data_received, validates topic/sender/payload and
calls session.interrupt(force=True) — the SDK's own programmatic interrupt,
force confirmed against the installed 1.8.8 source (non-force raises
RuntimeError on allow_interruptions=False speech). Failures log loudly; the
listener is unloaded via add_shutdown_callback; the server-cancel path in
llm_chat_api also interrupts with force and logs failures.
Verification (offline, zero real requests): real-SDK harness 8/8 including a
real SpeechHandle with a genuinely pending playout wait released by the
cg.interrupt message after a clean chat.final (evidence-C shape) plus the
full validation matrix; .venv311 full suite 480 passed / 8 skipped (2
test_r3 failures pre-exist at 5625de6); web npm ci from the existing lock,
typecheck 0 errors, lint 0 errors + 1 pre-existing warning, vitest 148/148,
build ok; ruff clean; check_requirements vs origin/main and b8ec832 with the
corrected handoff.
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -43,6 +43,7 @@ import contextlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from livekit.agents import Agent, AgentSession, JobContext, JobProcess, WorkerOptions, cli
|
||||
@@ -213,6 +214,67 @@ def bind_voice_session(session: AgentSession, *, llm: CyberGrillLLM,
|
||||
stt.agent_speaking = getattr(ev, "new_state", "") == "speaking"
|
||||
|
||||
|
||||
INTERRUPT_TOPIC = "cg.interrupt"
|
||||
"""R2(HEL-909):网页发文字时经房间数据通道发出的本通打断消息 topic。
|
||||
web/src/voice 的 hush() 在本地静音反馈之外 publish 它(reliable);worker 在
|
||||
本房间订阅。只复用 LiveKit 自己的数据通道与 session.interrupt,不建第二套
|
||||
调度引擎。"""
|
||||
|
||||
|
||||
def bind_interrupt_channel(room, session) -> Callable[[], None]:
|
||||
"""订阅本房间的 cg.interrupt 打断消息,走 SDK 自己的 programmatic 打断.
|
||||
|
||||
绑定与校验(HEL-909 R2 裁定):
|
||||
- 本通绑定是通道固有的:数据消息只到达本房间的订阅者,旧通的消息物理
|
||||
上到不了新通的 worker;
|
||||
- topic 必须精确等于 cg.interrupt(cg.subtitle 等一律忽略);
|
||||
- 发送者必须是远端参与者(用户网页);worker 自己/服务端来源不处理;
|
||||
- 载荷必须是 {"v": 1},其他形状丢弃;
|
||||
- session.interrupt(force=True):程序性用户打断按 SDK 文档越过
|
||||
allow_interruptions=False 的排队语音(真实句柄在非 force 下会抛
|
||||
RuntimeError,HEL-909 evidence B2);失败一律大声留痕,不静默假装
|
||||
成功。session.interrupt 未启动时抛 RuntimeError 同样留痕返回。
|
||||
|
||||
返回卸载函数(JobContext.add_shutdown_callback 注册,会话结束卸载)。
|
||||
"""
|
||||
def on_data(msg) -> None:
|
||||
if getattr(msg, "topic", None) != INTERRUPT_TOPIC:
|
||||
return
|
||||
participant = getattr(msg, "participant", None)
|
||||
if participant is None or getattr(participant, "is_local", False):
|
||||
return
|
||||
try:
|
||||
payload = json.loads(bytes(msg.data).decode("utf-8"))
|
||||
except Exception:
|
||||
return
|
||||
if not isinstance(payload, dict) or payload.get("v") != 1:
|
||||
return
|
||||
try:
|
||||
fut = session.interrupt(force=True)
|
||||
except Exception as exc:
|
||||
print(f"[cybergril-worker] interrupt message failed: "
|
||||
f"{type(exc).__name__}: {exc}", flush=True)
|
||||
return
|
||||
if inspect.isawaitable(fut):
|
||||
|
||||
async def _drain(f) -> None:
|
||||
try:
|
||||
await f
|
||||
except Exception as exc:
|
||||
print(f"[cybergril-worker] interrupt completion failed: "
|
||||
f"{type(exc).__name__}: {exc}", flush=True)
|
||||
|
||||
asyncio.get_running_loop().create_task(_drain(fut))
|
||||
|
||||
room.on("data_received", on_data)
|
||||
|
||||
def unload() -> None:
|
||||
with contextlib.suppress(Exception):
|
||||
room.off("data_received", on_data)
|
||||
|
||||
return unload
|
||||
|
||||
|
||||
async def speak_proactive_row(session: AgentSession, bus: SubtitleBus, row: dict) -> None:
|
||||
"""念一条已落库 proactive 行,并给同源 message_id 的字幕起止/打断事件.
|
||||
|
||||
@@ -312,6 +374,10 @@ async def entrypoint(ctx: JobContext) -> None:
|
||||
)
|
||||
bind_voice_session(session, llm=llm, ledger=ledger, interim=interim,
|
||||
bus=bus, stt=stt, receipts=receipts)
|
||||
# R2:本通文字打断通道(cg.interrupt)——LLM 已 final、TTS 仍在播时,
|
||||
# 服务端已无活动轮可取消,这里是唯一权威打断路径;会话结束卸载。
|
||||
ctx.add_shutdown_callback(
|
||||
bind_interrupt_channel(ctx.room, session))
|
||||
|
||||
await ctx.connect()
|
||||
await session.start(room=ctx.room, agent=Agent(instructions=INSTRUCTIONS_PLACEHOLDER))
|
||||
|
||||
Reference in New Issue
Block a user