Files
CyberGril/src/cybergril/voice/worker.py
T
施工员2号andmultica-agent 4a38106eef HEL-911: fix AgentHandoff/shutdown seams, attribute & fix the 3.66s pre-generation wait
- worker _on_item: filter conversation_item_added by the real 1.8.8 item
  discriminator (ChatMessage | AgentHandoff | _TypeDiscriminator); only
  assistant str-part body feeds the echo filter (HEL-910 AttributeError)
- bind_interrupt_channel unload: async (JobContext shutdown callbacks are
  awaited), idempotent, disconnect-safe; interrupt/receipt/budget paths
  untouched (HEL-910 TypeError await None)
- TURN_HANDLING: explicit turn_detection=None — 1.8.8 silently installs an
  English EOU TurnDetector whose unlikely verdicts on Chinese finals push
  endpointing to max_delay=6.0 (measured 3.667/3.654s HEL-910 call2; offline
  A/B on the real SDK: baseline 3.704s vs fixed 0.004s). Endpointing
  0.8/6.0 kept verbatim; no VAD/buffer_turn/semantic change
- scripts/gen_hel911_wait_repro.py: offline reproduction harness (real
  AgentSession + real silero VAD + HEL-910 wav and measured timings)
- tests: +3 real-SDK checks (11/11 on .12 agent venv; prior 8 regressions
  kept, unload call sites await the new protocol)
- hel910_call1.mjs reliability: segmented probe/recorder dumps to disk,
  timing-A trigger requires the server-committed voice turn row (not a
  we-sent-it proxy); node --check only, no real run
- window-record.md §9: appended factual corrections (companion 9 not 18,
  turn_start +6.099 not +4.10, assistant_final is the playout/receipt gate,
  post-window ListRooms token failure is not empty-room evidence); original
  record untouched
- docs/rework/hel911/summary.md + handoff-HEL-911.json; requirement checks
  pass vs origin/main and 407fc81

Co-authored-by: multica-agent <github@multica.ai>
2026-10-29 21:25:25 +08:00

438 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""CyberGril 专属语音 worker(HEL-877,agent_name=cybergril-voice-agent).
组装与 /opt/voice-agent/agent/agent.py 同源(10-16/10-24 两次真实通话验证的
级联链路):
麦克风 -> silero VAD(端点检测/打断) -> FunASR(流式 STT)
-> 统一 CyberGril 实例 POST /api/chat(她的人格/情绪/关系/记忆/生活分享/
调用限制全部在服务端同一业务链里;worker 不持有第二份人格或记忆,
不直连任何 LLM,不读通用助手 persona_state/voice_state)
-> CosyVoice3(流式 TTS) -> 播放
打断: VAD 判定用户开口即打断(AgentSession 默认 allow_interruptions):
生成任务被取消,ChatApiLLMStream 的 HTTP 流在 finally 立刻关闭,
服务端随即把旧轮 user 行标 cancelled——不等下一次 ASR final。
文字与语音同走 /api/chat,互相争用由服务端同一轮次门处理。
回执: 只有 SDK 真实播放完成(speech handle done、未被打断、无异常、轮次
完整带 receipt)才 POST /api/chat/received;被打断、断线、播放失败、
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,不替用户定。
HEL-906 连续通话 ASR 用量: entrypoint 按 job 构造 AsrUsageGuard 注入
FunASRSTT(房间名作为每通标识)。未布防(无 CYBERGRIL_ASR_WINDOW_ID)
即 fail-closed 拒绝一切 ASR 连接/音频(真实 cap=0);获批的一次性窗口
由窗口负责人启动时显式设置环境变量(见 voice/asr_usage.py 与
docs/rework/hel902/r5-followup-package.md §4)。触线时 guard 在发送前
拒绝并经 on_exhausted 回调 ctx.shutdown 结束本通 job;逐通/全窗计数落
asr-usage.jsonl,不随删房丢失。
运行位置: /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
import asyncio
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
from livekit.plugins.silero import VAD
from .asr_usage import build_usage_from_env
from .llm_chat_api import CyberGrillLLM
from .receipt import ReceiptSender, TurnLedger, should_ack
from .seam import AssistantInterimPublisher, SubtitleBus, pending_proactive
from .stt_funasr import FunASRSTT
from .tts_cosyvoice import CosyVoiceTTS
AGENT_NAME = os.environ.get("CYBERGRIL_AGENT_NAME", "cybergril-voice-agent")
API_BASE = os.environ.get("CYBERGRIL_API_BASE", "http://127.0.0.1:8360")
VOICE_STATE = Path(
os.environ.get(
"CYBERGRIL_VOICE_STATE", "/opt/voice-agent-cybergril/voice_state_cybergril.json"
)
)
WORKER_HEALTH_PORT = int(os.environ.get("CYBERGRIL_WORKER_HEALTH_PORT", "8082"))
# CG-011 语音主动开口(HEL-879 最小接缝):默认关闭,接线卡与视觉作者定好
# 入口呈现并经批准后才置 1。开启后只念服务端已落库 proactive=1 的行。
PROACTIVE_VOICE = os.environ.get("CYBERGRIL_PROACTIVE_VOICE", "") == "1"
PROACTIVE_PER_SESSION = 1
SUBTOPIC = "cg.subtitle"
# 占位指令:真正的人格由统一服务在 /api/chat 服务端组装。适配器忽略
# chat_ctx/instructions(latest_user_text 只取当前用户话轮),这里不放任何
# 人格内容,避免出现第二份她。
INSTRUCTIONS_PLACEHOLDER = "语音通道适配层:回复内容由统一服务生成。"
def read_default_voice() -> str:
"""CyberGril 自己的音色状态;缺文件回落 default(D1 未拍板不替用户定)。"""
try:
return json.loads(VOICE_STATE.read_text(encoding="utf-8")).get("voice", "default")
except Exception:
return "default"
def prewarm(proc: JobProcess) -> None:
proc.userdata["vad"] = VAD.load()
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(
room.local_participant.publish_data(data, topic=SUBTOPIC, reliable=False)
)
return subtitle
def make_voice_llm(api_base: str, *, ledger: TurnLedger,
interim: AssistantInterimPublisher, client=None) -> CyberGrillLLM:
"""CyberGrillLLM + 确切归属接线(worker 的唯一 LLM 组装方式).
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)
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():
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 返回)之后才考虑回执。
await handle.wait_for_playout()
# 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:
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
epoch = None
try:
epoch = await llm.client.current_epoch()
except Exception:
epoch = stream.receipt.get("epoch") if stream.receipt else None
# Contract v2 (HEL-879 timing fix): assistant_final means the archive
# really holds this turn — an incomplete stream, or one without a
# legal same-turn receipt (missing fields / stale epoch), closes with
# turn_cancel ONLY. The final is never sent first and retracted after.
if not getattr(stream, "completed", False):
interim.cancel(speech_id, "incomplete")
outcomes[speech_id] = "incomplete"
return
if should_ack(
played_to_end=True,
interrupted=handle.interrupted,
failed=failed,
receipt=stream.receipt,
current_epoch=epoch,
):
interim.finish(speech_id, turn_id=stream.turn_id, text=stream.text)
await receipts.confirm(stream.turn_id, stream.receipt)
outcomes[speech_id] = "acked"
else:
interim.cancel(speech_id, "no-receipt")
outcomes[speech_id] = "no-receipt"
@session.on("speech_created")
def _on_speech_created(ev) -> None:
if not ev.user_initiated:
return
ledger.note_handle(ev.speech_handle, ev.created_at)
ev.speech_handle.add_done_callback(
lambda handle=ev.speech_handle: asyncio.get_running_loop().create_task(
_after_playout(handle)
)
)
@session.on("conversation_item_added")
def _on_item(ev) -> None:
# SDK 1.8.8 的 ConversationItemAddedEvent.item 是
# ChatMessage | AgentHandoff | _TypeDiscriminator(events.py:416-420):
# 会话启动的 AgentHandoff 没有 role/content,直接取 ev.item.role 会抛
# AttributeError(HEL-910 两轮通话日志实录)。按 SDK 的类型判别字段
# 过滤,只认 type=="message" 的 ChatMessage,再按 role=="assistant"
# 取正文;用户消息、非消息项一律不更新 agent_recent_text。
item = ev.item
if getattr(item, "type", None) != "message":
return
if item.role != "assistant":
return
# ChatContent = str | ImageContent | AudioContent | CacheBreakpoint:
# 只有 str 部件是正文(chat_context.py:459-461),其余形状不冒充文本。
text = "".join(p for p in (item.content or []) if isinstance(p, str)).strip()
if text:
stt.agent_recent_text = text
@session.on("agent_state_changed")
def _on_state(ev) -> None:
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,不建第二套
调度引擎。"""
TURN_HANDLING = {
# 停顿稍久才判说完, 合并慢语速碎片(同通用 worker 实测参数)
"endpointing": {"min_delay": 0.8, "max_delay": 6.0},
# HEL-911:livekit-agents 1.8.8 对未显式给 turn_detection 的会话默认
# 构造英文 EOU TurnDetector(agent_session.py:576-579,自托管回落本地
# v1-mini)。它对中文终稿的"不太像说完"判定把 endpointing 延迟顶到
# max_delay=6.0,实测造成识别终稿后 ~3.66s 的额外等待(HEL-910 call2
# 两轮 3.667/3.654s;离线 A/B:默认 3.704s vs 显式 None 0.004s,
# scripts/gen_hel911_wait_repro.py)。显式禁用:轮次边界回到本会话配置
# 的 VAD endpointing 本身,语义不变(不降 VAD 阈值、不动 buffer_turn)。
"turn_detection": None,
}
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 注册,会话结束 await).
"""
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)
unloaded = False
async def unload() -> None:
# SDK 1.8.8 的 shutdown 回调一律被 await(job.py:622-643 把无参回调
# 包成 `await callback()`,ipc/job_proc_lazy_main.py:493 逐个 await):
# 同步返回 None 的旧卸载函数让 job 关停日志抛
# TypeError: object NoneType can't be used in 'await' expression
# (HEL-910 实录)。必须是协程;幂等(重复 shutdown/多次调用安全),
# 未连接/已断连的房间卸载监听不得抛出。
nonlocal unloaded
if unloaded:
return
unloaded = True
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 的字幕起止/打断事件.
字幕生命周期绑定在 say 返回的 SpeechHandle 上(proactive_start ->
proactive_end/proactive_cancel),不借用任何回执分支。
真实 SDK 的 AgentSession.say 是同步函数、返回可 await 的 SpeechHandle
(await 它=等整段播完,HEL-879 timing 修正):先取 handle、立刻发布
proactive_start 并注册该 handle 的 end/cancel,再等这一条播完——start
绝不能等声音播完后才发。await 型替身(测试桩)同样支持。
"""
result = session.say(row["text"], allow_interruptions=True)
# iscoroutine (NOT isawaitable): the real SpeechHandle itself defines
# __await__ (awaiting it = waiting out the playout) — only a coroutine
# from an await-style stand-in needs resolving to reach the handle.
handle = await result if inspect.iscoroutine(result) else result
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)
# 逐条念:等 THIS 行播完再返回(替身 handle 不可 await 时直接返回;
# 播放中的异常已由 done 回调按 cancel 收口,这里不再向上抛)。
if inspect.isawaitable(handle):
with contextlib.suppress(Exception):
await handle
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
def _shutdown_job(ctx, reason: str) -> None:
"""AsrUsageGuard 触线回调: 结束本通 job(异步 shutdown 兼容为任务)."""
print(f"[cybergril-worker] asr window stop: {reason}; ending this call", flush=True)
with contextlib.suppress(Exception):
result = ctx.shutdown()
if inspect.isawaitable(result):
asyncio.get_running_loop().create_task(result)
async def entrypoint(ctx: JobContext) -> None:
usage = build_usage_from_env(
on_exhausted=lambda reason: _shutdown_job(ctx, reason))
stt = FunASRSTT(usage=usage, call_label=getattr(ctx.room, "name", ""))
# 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=TURN_HANDLING,
)
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))
spoken_proactive: set[int] = set()
try:
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
print(f"[cybergril-worker] proactive seam skipped: {type(exc).__name__}: {exc}",
flush=True)
print(
f"[cybergril-worker] session started (api={API_BASE}, "
f"voice={read_default_voice()}, agent_name={AGENT_NAME}, "
f"asr_window=({usage.summary_line()}))",
flush=True,
)
if __name__ == "__main__":
cli.run_app(
WorkerOptions(
entrypoint_fnc=entrypoint,
prewarm_fnc=prewarm,
agent_name=AGENT_NAME,
port=WORKER_HEALTH_PORT,
)
)