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:
zonggong
2026-10-27 05:10:52 +08:00
co-authored by multica-agent
parent b4dadd82b3
commit 3228b1e0d7
19 changed files with 1185 additions and 268 deletions
+30 -23
View File
@@ -1,7 +1,7 @@
{
"baseline_version": "1.11",
"read_commit": "c121c42e39174e0f627f129e7f7e5700f33acf26",
"task": "HEL-879 \u53cc\u804c\u8d23\u4e00\u6b21\u4ea4\u4ed8\uff1aA) HEL-896 \u53d1\u5e03\u5de5\u5177\u56db\u9879\u6709\u9650\u6536\u53e3\uff08\u603b\u7ba1\u72ec\u7acb\u590d\u6838\u6e05\u5355\uff09\u2014\u2014\u2460\u5f52\u6863\u4e00\u81f4\u6027\u5f3a\u5236\uff1acheckpoint busy \u6216\u6e90/\u5feb\u7167\u884c\u6570\u4e0d\u4e00\u81f4\u4e00\u5f8b CLI \u975e0\u3001\u4e0d\u5f62\u6210\u53ef\u4ea4\u4ed8\u5305\uff0cverify \u62d2\u7edd rows_match=False \u65e7\u5305\u5e76\u6309\u6e90\u8def\u5f84\u6620\u5c04\u505a\u771f\u5b9e\u56de\u9000\u6f14\u7ec3\uff08\u89e3\u5305\u9694\u79bb\u76ee\u5f55\u3001\u5b9e\u5f00\u5404\u5e93\u6838\u884c\u6570\u4e0e\u54c8\u5e0c\uff09\uff0c\u81ea\u6d4b 9/9 \u5148\u590d\u73b0\u65e7\u5931\u8d25\u5f62\u72b6\u518d\u8bc1\u4fee\u590d\uff1b\u2461\u76ee\u5f55\u5185\u771f\u5b9e SQLite\uff08history_root/mem0_public_history.db \u7b49\uff09\u505c\u670d\u53e3\u5f84\u9012\u5f52\u8d70 checkpoint+\u9010\u8868\u6838\u5bf9\uff0c\u5728\u7ebf\u6a21\u5f0f\u4ec5\u663e\u5f0f\u5355\u5e93 backup API\u3001\u542b SQLite \u76ee\u5f55\u76f4\u63a5\u62d2\u7edd\uff1b\u2462\u63d0\u524d\u5c01\u8d26\u53ef\u6267\u884c\uff1aPersistentBudget.sealed()/seal() \u539f\u5b50\u5199\u5c01\u8d26\u6807\u8bb0\uff08\u771f\u5b9e\u7528\u91cf\u4fdd\u7559\u4e0d\u4f2a\u9020\u4e0d\u6e05\u96f6\uff09\uff0cacquire \u9996\u67e5\u5c01\u8d26\uff08budget_sealed:51/55\uff09\uff0c\u8de8\u91cd\u542f/backup \u5f52\u6863\u6062\u590d\u5747\u62d2\u7edd\u3001\u91cd\u590d seal \u5e42\u7b49\u3001\u65e0\u89e3\u5c01\u8def\u5f84\uff0ctools/seal_budget_hel879.py \u4e3a\u663e\u5f0f\u5173\u95ed\u547d\u4ee4\uff0cS6 \u8d1f\u4f8b\uff0851/55 \u63d0\u524d\u6536\u5c3e\u3001\u8bef\u91cd\u542f\u3001\u5f52\u6863\u6062\u590d\u3001\u65e5\u9876\u6709\u4f59\u91cf\u4ecd\u62d2\uff09\u5e76\u5165 verify_budget_split 10/10\uff1b\u2463\u5b89\u88c5\u5165\u53e3\u552f\u4e00\uff1ahel895-release-candidate.md \u00a72 \u5168 offline \u81ea\u8db3\u5b89\u88c5\u3001\u00a74 \u4e94\u6b65\u56fa\u5b9a SDK \u5165\u53e3\uff08tarball \u54c8\u5e0c\u2192\u56fa\u5b9a\u6e90\u6784\u5efa\u2192cp311 \u5907\u4ea7\u2192\u4ec5\u672c\u5730\u8f6e\u2192co-import\uff09\uff0chel874-release.md \u00a72/\u00a74 \u6807\u6ce8\u88ab\u53d6\u4ee3\uff0cmem0-stack.lock \u7684 mem0ai \u884c\u53ea\u4f5c\u7248\u672c\u8bb0\u5f55\uff0caudit \u5de5\u5177 head \u52a8\u6001\u5316+\u8bc1\u636e\u76ee\u5f55\u53ef\u91cd\u5b9a\u5411\uff0c\u65b0\u8bc1\u636e docs/rework/hel879/{sdk-audit,release-artifacts.json}\u3002B) \u7edf\u4e00\u8bed\u97f3\u5019\u9009\u9694\u79bb\u6574\u5408\uff1ahel-879-assembly \u5206\u652f = c121c42 + \u53d1\u5e03\u6536\u53e3(01ff919) + \u8bed\u97f3\u540e\u53f0 aba2aeb + \u8bed\u97f3\u524d\u7aef c61d9c9\uff08\u539f\u4f5c\u8005 web/src \u9010\u5b57\u8282\u4fdd\u7559\uff0cCSS \u54c8\u5e0c\u53d8\u5316\u4ec5\u539f\u4f5c\u8005 components.css +21 \u884c\uff09\uff0c\u8bed\u97f3\u9002\u914d\u5668\u6d4b\u8bd5\u5bf9\u9f50\u4e3b\u7ebf HEL-882 \u786c\u95f8\uff08engineering_budget\uff0c\u4e0d\u6539\u4ea7\u54c1\u95e8\uff09\uff0c\u5168\u7535\u6c60\u5728\u8be5 head \u5b9e\u8dd1\uff1apytest 324/324\uff08299 \u4e3b\u7ebf+25 \u8bed\u97f3\uff09\u3001ruff \u5e72\u51c0\u3001web typecheck 0 \u9519/lint 0 \u95191\u65e2\u6709\u8b66\u544a/vitest 88/88/build \u901a\u8fc7\u3001\u771f\u5b9e\u670d\u52a1\u6d4f\u89c8\u5668 9/9\uff08\u96f6\u6743\u9650\u8c03\u7528\u3001\u96f6\u975e\u56de\u73af\u51fa\u7ad9\uff0c\u8bc1\u636e docs/rework/hel879/browser/\uff09\u3001verify_hel877_voice_chain 8/8\u3001.12 \u771fSDK stdin \u68c0\u67e5 8/8 ALL PASS\uff08\u96f6\u5199\u5165\u96f6\u7f51\u7edc\uff09\u3001check_release_offline R1-R7\u3001\u56fa\u5b9aSDK\u56de\u5f52 16/16+12/12+6/6+7/7+12/12\u3002\u96f6\u771f\u5b9e LLM/\u5d4c\u5165/ASR/TTS\u3001\u96f6\u4e0b\u8f7d\u3001\u96f6\u9ea6\u514b\u98ce\u3001\u672a\u542f\u52a8/\u505c\u6b62\u4efb\u4f55\u670d\u52a1\u3001\u4e0d\u90e8\u7f72\u3001\u4e0d\u5408\u5e76 PR\u3001PR#11 \u4e0e hel-870-assembly \u672a\u52a8\u3001\u6743\u5a01\u8d26\u4e0e\u51bb\u7ed3\u672a\u5199\u3001\u771f\u5b9e cap \u4fdd\u6301 0",
"task": "HEL-879 双职责一次交付:A) HEL-896 发布工具四项有限收口(总管独立复核清单)——①归档一致性强制:checkpoint busy 或源/快照行数不一致一律 CLI 非0、不形成可交付包,verify 拒绝 rows_match=False 旧包并按源路径映射做真实回退演练(解包隔离目录、实开各库核行数与哈希),自测 9/9 先复现旧失败形状再证修复;②目录内真实 SQLite(history_root/mem0_public_history.db 等)停服口径递归走 checkpoint+逐表核对,在线模式仅显式单库 backup API、含 SQLite 目录直接拒绝;③提前封账可执行:PersistentBudget.sealed()/seal() 原子写封账标记(真实用量保留不伪造不清零),acquire 首查封账(budget_sealed:51/55),跨重启/backup 归档恢复均拒绝、重复 seal 幂等、无解封路径,tools/seal_budget_hel879.py 为显式关闭命令,S6 负例(51/55 提前收尾、误重启、归档恢复、日顶有余量仍拒)并入 verify_budget_split 10/10;④安装入口唯一:hel895-release-candidate.md §2 全 offline 自足安装、§4 五步固定 SDK 入口(tarball 哈希→固定源构建→cp311 备产→仅本地轮→co-import),hel874-release.md §2/§4 标注被取代,mem0-stack.lock 的 mem0ai 行只作版本记录,audit 工具 head 动态化+证据目录可重定向,新证据 docs/rework/hel879/{sdk-audit,release-artifacts.json}。B) 统一语音候选隔离整合:hel-879-assembly 分支 = c121c42 + 发布收口(01ff919) + 语音后台 aba2aeb + 语音前端 c61d9c9(原作者 web/src 逐字节保留,CSS 哈希变化仅原作者 components.css +21 行),语音适配器测试对齐主线 HEL-882 硬闸(engineering_budget,不改产品门),全电池在该 head 实跑:pytest 324/324(299 主线+25 语音)、ruff 干净、web typecheck 0 错/lint 0 错1既有警告/vitest 88/88/build 通过、真实服务浏览器 9/9(零权限调用、零非回环出站,证据 docs/rework/hel879/browser/)、verify_hel877_voice_chain 8/8、.12 真SDK stdin 检查 8/8 ALL PASS(零写入零网络)、check_release_offline R1-R7、固定SDK回归 16/16+12/12+6/6+7/7+12/12。零真实 LLM/嵌入/ASR/TTS、零下载、零麦克风、未启动/停止任何服务、不部署、不合并 PR、PR#11 与 hel-870-assembly 未动、权威账与冻结未写、真实 cap 保持 0;2026-10-27 剩余收口(总管 b4dadd8 复核三项):A) 房间自动到期与共享上限——清理所有者观察活跃会话截止时间与欠账,无人再发请求也会到期转债真实删房;显式挂断与后台共用同一持久尝试/年龄上限与状态(_sessions 不再旁路),超限 CleanupAbandoned→503+准确状态、绝不回完成 404,成功同清 sessions/debts,重启续同一上限,关闭不留协程;B) 排队话轮确切归属——CyberGrillLLM.chat 读 livekit-agents 1.8.8 自身 agents_speech_handle ContextVar(_create_speech_task 源级核实),流绑定到创建它的那个 SpeechHandle,无归属/未登记 fail-closed 不绑,新 speech 不再退役旧 pending(总管交错反例 H1/H2/S1/S2 修正),say/主动生成不吞用户轮流;C) 交前端的版本化字幕契约 v2——信封 v/seq、确切 speech_id/turn_id/message_id、turn_start/interim/final/turn_end/turn_cancel 起止与取消、迟到/乱序双规则保护、主动播报同源 message_id 自带 proactive_start/end/cancel(不借回执分支),契约 docs/voice-subtitle-contract-v2.md + 录制样例 subtitle-samples/,总工未改 web/src(接线归 HEL-898 原视觉作者);另修 test_r2 lifespan 旧测试的双 portal 调用竞态确定性(原子冻结+阻塞,不抬超时不删断言)",
"requirement_ids": [
"CG-006",
"CG-008",
@@ -34,33 +34,40 @@
"GOV-006",
"DEL-001"
],
"deliverable": "\u5206\u652f hel-879-assembly\uff08\u72ec\u7acb\u5019\u9009\uff0c\u672a\u5165 PR#11\uff09\uff1a\u53d1\u5e03\u6536\u53e3 tools/release_snapshot_hel896.py v2\uff08\u5f3a\u5236\u4e00\u81f4\u6027+\u56de\u9000\u6f14\u7ec3\uff09\u3001src/cybergril/life/model.py \u5c01\u8d26\uff08sealed/seal/acquire \u9996\u67e5\uff09\u3001tools/seal_budget_hel879.py\u3001tools/verify_budget_split_hel896.py S6\u3001tools/audit_sdk_offline_hel896.py head \u52a8\u6001\u5316\u3001deploy/hel895-release-candidate.md \u00a70/\u00a72/\u00a74/\u00a75 \u552f\u4e00\u5165\u53e3\u3001deploy/hel874-release.md \u00a72/\u00a74 \u53d6\u4ee3\u6807\u6ce8\u3001deploy/mem0-stack.lock \u6ce8\u91ca\u6536\u53e3\u3001docs/budget-package-hel895.md \u00a76.2 \u53ef\u6267\u884c\u5c01\u8d26\uff1b\u8bed\u97f3\u6574\u5408\uff1aaba2aeb \u540e\u53f0\u6a21\u5757 + c61d9c9 \u524d\u7aef\uff08\u539f\u4f5c\u8005\u89c6\u89c9\u9010\u5b57\u8282\u4fdd\u7559\uff09\u5408\u5e76\u5165\u5019\u9009\uff0c\u6d4b\u8bd5\u5bf9\u9f50\u4e3b\u7ebf\u786c\u95f8\uff1b\u8bc1\u636e docs/rework/hel879/{release-snapshot/selftest.json,sdk-audit/,release-artifacts.json,browser/,release-check/,regression-*.json}\uff1bHEL-879 \u8fd4\u4fee\uff08\u603b\u7ba1\u72ec\u7acb\u590d\u6838\u56db edges\uff0c78a5cfd \u8d77\uff09\uff1a\u2460deploy/voice/serve_dual_8360_8361.py \u5355\u5c5e\u4e3b\u751f\u547d\u5468\u671f\uff08uvicorn lifespan=off\uff0c\u4efb\u4e00\u76d1\u542c\u9000\u51fa\u5148\u505c\u53e6\u4e00\u4e2a\u518d\u5173\u5e93\uff1bapp lifespan \u91cd\u5165\u95e8\u536b fail-closed\uff09\uff1b\u2461voice/session.py \u623f\u95f4\u5f52\u5c5e\u6e05\u7406\u8d26\uff08\u5220\u9664\u6210\u529f\u624d\u51fa\u8d26\u3001\u5931\u8d25\u4fdd\u7559\u53ef\u91cd\u8bd5\u3001\u5230\u671f\u8f6c\u6e05\u7406\u8d26\u771f\u5b9e\u5220\u623f\u3001\u91cd\u542f\u6309\u6301\u4e45\u8d26\u6709\u754c\u8865\u507f\u4ec5\u672c\u5b9e\u4f8b\u623f\u95f4\u3001404=\u5df2\u5220\u5e42\u7b49\u3001\u8def\u7531\u5931\u8d25 503 \u4e0d\u5192\u5145 404\uff09\uff1b\u2462receipt.py TurnLedger \u663e\u5f0f\u7ed1\u5b9a\uff08\u65e0\u751f\u6210\u7684\u8f6e\u4e0d\u541e\u4e0b\u4e00\u8f6e\u6d41/\u56de\u6267\uff0cworker \u5148\u5224\u6253\u65ad/\u5931\u8d25\u518d\u6d88\u8d39\uff09\uff1b\u2463tools/release_snapshot_hel896.py v3\uff08\u4e09\u65b9\u8ba1\u6570\u76f4\u63a5\u76f8\u7b49\u3001rows_match \u53ea\u662f\u989d\u5916\u7ea6\u675f\u3001\u6309\u6e90\u8def\u5f84\u5b9e\u9645\u6062\u590d\u5230\u6301\u4e45\u76ee\u6807\u6811\u3001\u540c\u540d\u5e93\u65e0\u51b2\u7a81\u6620\u5c04\u3001\u91cd\u590d\u6e90\u62d2\u7edd\uff09\uff1bhatchling \u52d8\u8bef\uff08uv v6/v7 \u6709 1.32.4 \u7f13\u5b58\uff09+ \u56fa\u5b9a\u6e90\u79bb\u7ebf\u6784\u5efa mem0ai-2.2.1 \u8f6e\uff08sha256 698284b6\u2026\uff0c\u672a\u5b89\u88c5\u672a\u8054\u7f51\uff09\uff1bhel895 \u53d1\u5e03\u6587\u6863 \u00a70 \u5386\u53f2\u4e0e\u5f53\u524d\u5206\u79bb\u3001\u00a74/\u00a75 \u66f4\u65b0\u3001budget \u00a76.2.4 \u5c01\u8d26\u5e93\u4e0d\u53ef\u62ac cap \u91cd\u5f00\u52d8\u6b63\uff1brunbook \u00a73.3/\u00a73.5/\u00a73.6/\u00a74.4/\u00a74.5 \u4e0e\u524d\u7aef session.ts \u6ce8\u91ca\u52d8\u6b63\uff08\u6ce8\u91ca\u7ea7\uff0c\u65e0\u903b\u8f91/\u6837\u5f0f\u6539\u52a8\uff09\uff1bCG-011 \u4e3b\u52a8\u5f00\u53e3\u4e0e assistant_interim \u589e\u91cf\u5b57\u5e55\u6700\u5c0f\u540e\u53f0\u63a5\u7f1d\uff08src/cybergril/voice/seam.py+worker/llm_chat_api \u63a5\u7ebf\uff0c\u4e3b\u52a8\u5f00\u53e3\u9ed8\u8ba4\u5173\uff1b\u63a5\u53e3\u4e0e\u9a8c\u6536 docs/rework/hel879/voice-seam-interfaces.md\uff09\uff1b.12 \u771f SDK \u68c0\u67e5\u6269\u5c55\u4e3a 10 \u9879\uff08\u65b0\u589e worker \u5b9e\u9645\u56de\u8c03\u8def\u5f84\u4e0e interim seam\uff09\uff1b\u56de\u5f52 tests/test_voice_rework_hel879.py 17 \u4f8b",
"deliverable": "分支 hel-879-assembly(独立候选,未入 PR#11):发布收口 tools/release_snapshot_hel896.py v2(强制一致性+回退演练)、src/cybergril/life/model.py 封账(sealed/seal/acquire 首查)、tools/seal_budget_hel879.py、tools/verify_budget_split_hel896.py S6、tools/audit_sdk_offline_hel896.py head 动态化、deploy/hel895-release-candidate.md §0/§2/§4/§5 唯一入口、deploy/hel874-release.md §2/§4 取代标注、deploy/mem0-stack.lock 注释收口、docs/budget-package-hel895.md §6.2 可执行封账;语音整合:aba2aeb 后台模块 + c61d9c9 前端(原作者视觉逐字节保留)合并入候选,测试对齐主线硬闸;证据 docs/rework/hel879/{release-snapshot/selftest.json,sdk-audit/,release-artifacts.json,browser/,release-check/,regression-*.json};HEL-879 返修(总管独立复核四 edges,78a5cfd 起):①deploy/voice/serve_dual_8360_8361.py 单属主生命周期(uvicorn lifespan=off,任一监听退出先停另一个再关库;app lifespan 重入门卫 fail-closed);②voice/session.py 房间归属清理账(删除成功才出账、失败保留可重试、到期转清理账真实删房、重启按持久账有界补偿仅本实例房间、404=已删幂等、路由失败 503 不冒充 404);③receipt.py TurnLedger 显式绑定(无生成的轮不吞下一轮流/回执,worker 先判打断/失败再消费);④tools/release_snapshot_hel896.py v3(三方计数直接相等、rows_match 只是额外约束、按源路径实际恢复到持久目标树、同名库无冲突映射、重复源拒绝);hatchling 勘误(uv v6/v7 有 1.32.4 缓存)+ 固定源离线构建 mem0ai-2.2.1 轮(sha256 698284b6…,未安装未联网);hel895 发布文档 §0 历史与当前分离、§4/§5 更新、budget §6.2.4 封账库不可抬 cap 重开勘正;runbook §3.3/§3.5/§3.6/§4.4/§4.5 与前端 session.ts 注释勘正(注释级,无逻辑/样式改动);CG-011 主动开口与 assistant_interim 增量字幕最小后台接缝(src/cybergril/voice/seam.py+worker/llm_chat_api 接线,主动开口默认关;接口与验收 docs/rework/hel879/voice-seam-interfaces.md);.12 真 SDK 检查扩展为 10 项(新增 worker 实际回调路径与 interim seam);回归 tests/test_voice_rework_hel879.py 17 例;剩余收口代码:voice/session.py(_cleanup_loop 观察活跃截止时间+共享上限+CleanupAbandoned)、voice/router.py(到顶 503+cleanup 状态)、voice/receipt.py TurnLedger 精确绑定重写、voice/llm_chat_api.py current_speech_handle/on_stream_started(stream,handle)/stream.speech_id、voice/worker.py 接线集中 bind_voice_session+make_voice_llm/speak_proactive_row(实际模块可加载)、voice/seam.py SubtitleBus+按 speech_id 隔离的 AssistantInterimPublisher、scripts/gen_hel877_sdk_check.py 真实 worker 模块驱动(#9 不再手抄)、scripts/gen_subtitle_samples_hel879.py 样例生成、docs/voice-subtitle-contract-v2.md、docs/runbook-hel877-voice.md §3.3/3.5/3.6 更新、tests/test_voice_rework_hel879.py 新增 A/B/C 用例",
"acceptance": [
"\u5f52\u6863\u8d1f\u4f8b\uff1abusy checkpoint\uff08\u590d\u73b0 checkpoint=(1,9,8)\uff09\u4e0e\u884c\u6570\u4e0d\u4e00\u81f4\u5747\u5931\u8d25\u4e14\u96f6\u6b8b\u7559\u4ea7\u7269\uff1brows_match=False \u65e7\u5305 verify \u62d2\u7edd\uff1b\u505c\u670d\u53e3\u5f84\u76ee\u5f55\u5185 SQLite \u9010\u8868\u6838\u5bf9\uff08history=1\uff09\uff1b\u5728\u7ebf\u6a21\u5f0f\u542b SQLite \u76ee\u5f55\u62d2\u7edd\uff1bverify \u8f93\u51fa\u6e90\u8def\u5f84 rollback_plan",
"\u5c01\u8d26\u8d1f\u4f8b\uff1a51/55 \u63d0\u524d\u6536\u5c3e\u540e\u4efb\u4f55\u7c7b\u522b\u62d2\u7edd budget_sealed:51/55 \u4e14\u7528\u91cf\u4fdd\u6301 51\uff1b\u8bef\u91cd\u542f\u62d2\u7edd\uff1bbackup \u5f52\u6863\u6062\u590d\u62d2\u7edd\uff1b\u91cd\u590d seal \u5e42\u7b49\uff08sealed_at \u4e0d\u53d8\uff09\uff1b\u62d2\u7edd\u4e0d\u843d\u8d26",
"seal_budget_hel879.py \u7aef\u5230\u7aef\uff1a\u5c01\u8d26\u2192\u81ea\u68c0 acquire \u88ab\u62d2\u2192CLI ok=true",
"\u6574\u5408\u540e\u5168\u7535\u6c60\uff1apytest 324/324\u3001vitest 88/88\u3001typecheck/lint/build\u3001\u771f\u5b9e\u670d\u52a1\u6d4f\u89c8\u5668 9/9\uff08\u542b\u96f6\u6743\u9650/\u96f6\u975e\u56de\u73af\u51fa\u7ad9\uff09\u3001\u8bed\u97f3\u94fe 8/8\u3001.12 \u771fSDK 8/8\u3001R1-R7\u3001\u56fa\u5b9aSDK\u4e94\u5957\u56de\u5f52\u5168\u7eff",
"\u539f\u4f5c\u8005\u524d\u7aef\u9010\u5b57\u8282\u4fdd\u7559\uff1agit diff c61d9c9 HEAD -- web/src \u4e3a\u7a7a\uff1b\u540e\u53f0 voice \u6a21\u5757 diff aba2aeb \u4e3a\u7a7a",
"\u8fd4\u4feeedges\uff1a\u53cc\u7aef\u53e3\u540c\u8fdb\u7a0b\u5355\u6b21\u521d\u59cb\u5316\uff08\u53cc\u7aef\u540c epoch\u3001Store \u5355\u5b9e\u4f8b\u3001\u76d1\u542c\u5168\u90e8\u9000\u51fa\u540e\u624d\u5173\u5e93\u4e14\u53ea\u5173\u4e00\u6b21\uff09\uff1b\u5220\u623f\u5931\u8d25\u2192503 \u4fdd\u7559\u5f52\u5c5e\u3001\u91cd\u8bd5\u771f\u5b9e\u518d\u5220\uff08\u22652 \u6b21\u5c1d\u8bd5\uff09\u3001\u5230\u671f\u7aef\u5230\u7aef\u771f\u5b9e\u5220\u623f\uff08\u65e7\u7248 0 \u6b21\uff09\uff1bH1 \u65e0\u751f\u6210/H2 \u6709 S2 \u4ea4\u9519\u65f6 H1 \u5f97 None\u3001H2 \u5f97 S2\uff08.12 \u771f SpeechHandle/SpeechCreatedEvent \u5b9e\u8dd1\uff09\uff1brows_match=true+\u6e902/\u5feb\u71671 \u7684\u5305 verify \u62d2\u7edd\uff1b\u540c\u540d ledger.db \u5feb\u7167\u4e0d\u4e92\u76f8\u8986\u76d6\u4e14\u6062\u590d\u6811\u6309\u6e90\u8def\u5f84\u5404\u81ea\u843d\u4f4d",
"\u63a5\u7f1d\u9a8c\u6536\uff08\u79bb\u7ebf\uff09\uff1aassistant_interim \u7d2f\u79ef\u66ff\u6362+reset \u4e0d\u8de8\u8f6e\uff1bproactive \u53ea\u9009\u5df2\u843d\u5e93 proactive=1 sent companion \u884c\u6700\u65b0\u4e00\u6761\u4e14\u672c\u623f\u95f4\u672a\u5ff5\u8fc7\uff1b\u5747\u4e0d\u65b0\u589e\u6743\u9650/\u51fa\u7ad9"
"归档负例:busy checkpoint(复现 checkpoint=(1,9,8))与行数不一致均失败且零残留产物;rows_match=False 旧包 verify 拒绝;停服口径目录内 SQLite 逐表核对(history=1);在线模式含 SQLite 目录拒绝;verify 输出源路径 rollback_plan",
"封账负例:51/55 提前收尾后任何类别拒绝 budget_sealed:51/55 且用量保持 51;误重启拒绝;backup 归档恢复拒绝;重复 seal 幂等(sealed_at 不变);拒绝不落账",
"seal_budget_hel879.py 端到端:封账→自检 acquire 被拒→CLI ok=true",
"整合后全电池:pytest 324/324、vitest 88/88、typecheck/lint/build、真实服务浏览器 9/9(含零权限/零非回环出站)、语音链 8/8、.12 真SDK 8/8、R1-R7、固定SDK五套回归全绿",
"原作者前端逐字节保留:git diff c61d9c9 HEAD -- web/src 为空;后台 voice 模块 diff aba2aeb 为空",
"返修edges:双端口同进程单次初始化(双端同 epoch、Store 单实例、监听全部退出后才关库且只关一次);删房失败→503 保留归属、重试真实再删(≥2 次尝试)、到期端到端真实删房(旧版 0 次);H1 无生成/H2 有 S2 交错时 H1 得 None、H2 得 S2(.12 真 SpeechHandle/SpeechCreatedEvent 实跑);rows_match=true+源2/快照1 的包 verify 拒绝;同名 ledger.db 快照不互相覆盖且恢复树按源路径各自落位",
"接缝验收(离线):assistant_interim 累积替换+reset 不跨轮;proactive 只选已落库 proactive=1 sent companion 行最新一条且本房间未念过;均不新增权限/出站",
"剩余收口A:recover→open→不再来任何请求,过 TTL 后后台自己删房(旧版 0 次);上限2后台到顶后再3次 end 零新增远端删除(旧版共5次)且 503 带 abandoned/attempts/room 状态不回 404;重启加载 2/2 债后 recover 与 end 均不再发删除;成功同清 sessions/debts;清理器无悬空协程",
"剩余收口B:.12 真 SDK 检查 #9 加载实际 worker 模块、真 AgentSession 注册回调实跑——双 handle 先排队后生成各得各流(总管交错反例)、say 夹在用户轮不吞流、无归属流 fail-closed 不开字幕轮、打断 turn_cancel 无 final 无回执;installed-SDK 源码级证据:_create_speech_task 设 ContextVar、speech_created 先于任务、llm_node 在其中调 llm.chat",
"剩余收口C:字幕契约 v2 信封/起止/取消/乱序保护落码并有录制样例;每 speech_id 生命周期 turn_start→interim→final→turn_end(或 cancel)逐字段断言;proactive_start/end/cancel 带同源 message_id",
"旧 flaky 确定性:test_lifespan_cancels_owned_generation_and_joins_task 连跑 12 次通过、全套连跑 3 次 350/350(修复=原子冻结+阻塞,超时与断言原样保留)"
],
"deferred": [
"\u771f\u5b9e\u901a\u8bdd\u9a8c\u6536\uff08\u8fde\u7eed\u22653\u8f6e\u30011\u79d2\u5f00\u53e3\u6253\u65ad\u3001\u7ed3\u675f\u5373\u505c\u9ea6\u3001\u65e0\u65e7\u6b8b\u97f3\u3001\u65ad\u7f51\u6e05\u7406\u3001\u91cd\u5f00\u540c\u6863\u6848\uff09\uff1a\u771f\u5b9e\u8c03\u7528/D1\u97f3\u8272/\u53ef\u4fe1HTTPS\u8bbe\u5907\u8def\u5f84/\u9884\u7b97\u4e0a\u9650\u672a\u83b7\u6279\uff0c\u5f85\u4e3b\u5361\u4e00\u6b21\u7533\u8bf7",
"\u4f1a\u8bdd\u5230\u671f/API\u91cd\u542f\u540e LiveKit \u623f\u95f4\u4e0e worker \u771f\u5b9e\u91ca\u653e\u8bc1\u636e\uff1a_prune \u4ec5\u5220\u5185\u5b58\u767b\u8bb0\u3001end_session \u6709 delete_room\uff0c\u4f46\u300e\u91cd\u542f\u623f\u95f4\u81ea\u7136\u6d88\u4ea1\u300f\u9700\u771f\u5b9e\u73af\u5883\u9a8c\u8bc1\uff0c\u672a\u6d4b\u4e0d\u5192\u5145",
"\u589e\u91cf\u5b57\u5e55\uff08worker \u4ec5 final\uff0cinterim \u5951\u7ea6\u7f3a\u53e3\uff09\uff1aR5 \u5b57\u5e55\u5148\u884c\u4e0e\u5b8c\u6574\u4ea7\u54c1\u8981\u6c42\u4e0d\u964d\u7ea7",
"CG-011 \u8bed\u97f3\u4e3b\u52a8\u5f00\u53e3\u4ecd\u4e3a\u663e\u5f0f no-op \u63a5\u7f1d",
"R6 \u5929\u6c14/\u7d20\u6750/\u6bcf\u65e5\u4e0e\u624b\u52a8\u5b8c\u6574\u5907\u4efd\u3001R7 \u6709\u6761\u4ef6\u89c2\u5bdf\uff1a\u7ee7\u7eed\u4e3b\u5361\u627f\u63a5",
"\u56fa\u5b9a SDK \u771f\u7f3a\u4e0b\u8f7d\uff0837 \u9879+hatchling\uff09\u4e0e A/B/C \u9884\u7b97\u6388\u6743\uff1a\u5f85\u603b\u7ba1\u4e3b\u5361\u4e00\u6b21\u7533\u8bf7",
"\u4ea7\u54c1 PR#4\u3001\u65e7\u5c0f\u6837 PR#6\u3001\u65b0\u5c0f\u6837 PR#8\u3001\u53d1\u5e03 PR#11 \u5747\u672a\u5408\u5e76\u672a\u66ff\u6362\u6b63\u5f0f\u754c\u9762"
"真实通话验收(连续≥3轮、1秒开口打断、结束即停麦、无旧残音、断网清理、重开同档案):真实调用/D1音色/可信HTTPS设备路径/预算上限未获批,待主卡一次申请",
"会话到期/API重启后 LiveKit 房间与 worker 真实释放证据:_prune 仅删内存登记、end_session 有 delete_room,但『重启房间自然消亡』需真实环境验证,未测不冒充",
"R6 天气/素材/每日与手动完整备份、R7 有条件观察:继续主卡承接",
"固定 SDK 真缺下载(37 项+hatchling)与 A/B/C 预算授权:待总管主卡一次申请",
"产品 PR#4、旧小样 PR#6、新小样 PR#8、发布 PR#11 均未合并未替换正式界面",
"字幕 v2 的前端接线(web/src)归 HEL-898 原视觉作者:按 docs/voice-subtitle-contract-v2.md 实现,沿原认可槽位/动效,不改视觉;契约与提交经总管核对后启动",
"CG-011 会话中完整主动表达(现接缝=会话开启念已落库 proactive 留言≤1条,默认关)继续承接,不冒充完成"
],
"requirement_changes": [],
"verification": [
"docs/rework/hel879/release-snapshot/selftest.json\uff089/9\uff0c\u5148\u590d\u73b0\u65e7\u5931\u8d25\u5f62\u72b6\u518d\u8bc1\u4fee\u590d\uff09",
"docs/rework/hel896/budget-split/budget-split.json\uff0810/10 \u542b S6 \u63d0\u524d\u5c01\u8d26\u8d1f\u4f8b\uff0c\u672c head \u91cd\u8dd1\uff09",
"docs/rework/hel879/sdk-audit/ \u4e0e release-artifacts.json\uff08\u95ed\u5305 55/\u7f3a 41/\u53ef\u590d\u7528 3\uff0ctarball \u54c8\u5e0c\u5b9e\u6d4b=lock\uff0c\u7cbe\u786e\u63d0\u4ea4\uff09",
"docs/rework/hel879/browser/real-browser.json\uff089/9 \u771f\u5b9e\u670d\u52a1\u6d4f\u89c8\u5668\uff0c\u96f6\u6743\u9650\u8c03\u7528\u3001\u96f6\u975e\u56de\u73af\u51fa\u7ad9\uff09",
"docs/rework/hel879/release-check/hel882-release-check.json\uff08R1-R7\uff09\u4e0e regression-*.json\uff08\u56fa\u5b9aSDK 16/16\u300112/12\u30016/6\u30017/7\u300112/12\uff09",
".12 livekit-agents 1.8.8 \u771f SDK stdin \u68c0\u67e5 8/8 ALL PASS\uff08\u96f6\u5199\u5165\u96f6\u7f51\u7edc\uff0c\u8f93\u51fa\u5728\u8fd0\u884c\u65e5\u5fd7\uff09",
"\u672a\u9a8c\u8bc1\uff1a\u771f\u673a/Safari/\u771f\u5b9e\u901a\u8bdd/\u90e8\u7f72\u73af\u5883\uff1b\u5de5\u7a0b\u68c0\u67e5\u4e0d\u4ee3\u8868\u7528\u6237\u4f53\u9a8c\u9a8c\u6536"
"docs/rework/hel879/release-snapshot/selftest.json(9/9,先复现旧失败形状再证修复)",
"docs/rework/hel896/budget-split/budget-split.json(10/10 含 S6 提前封账负例,本 head 重跑)",
"docs/rework/hel879/sdk-audit/ 与 release-artifacts.json(闭包 55/缺 41/可复用 3,tarball 哈希实测=lock,精确提交)",
"docs/rework/hel879/browser/real-browser.json(9/9 真实服务浏览器,零权限调用、零非回环出站)",
"docs/rework/hel879/release-check/hel882-release-check.json(R1-R7)与 regression-*.json(固定SDK 16/16、12/12、6/6、7/7、12/12)",
".12 livekit-agents 1.8.8 真 SDK stdin 检查 8/8 ALL PASS(零写入零网络,输出在运行日志)",
"未验证:真机/Safari/真实通话/部署环境;工程检查不代表用户体验验收",
"docs/rework/hel879/sdk-check-hel879-remaining.log(.12 livekit-agents 1.8.8,实际 worker 模块驱动 11 项 ALL PASS)",
"docs/rework/hel879/subtitle-samples/*.jsonl(契约 v2 录制样例:正常轮/打断/主动播报)",
"全套 pytest 350/350 ×3(.venv311/Python 3.11.16,与既有交付同一解释器)"
]
}
@@ -0,0 +1,16 @@
/opt/voice-agent/agent/venv/lib/python3.12/site-packages/jwt/api_jwt.py:149: InsecureKeyLengthWarning: The HMAC key is 6 bytes long, which is below the minimum recommended length of 32 bytes for SHA256. See RFC 7518 Section 3.2.
return self._jws.encode(
/opt/voice-agent/agent/venv/lib/python3.12/site-packages/jwt/api_jwt.py:370: InsecureKeyLengthWarning: The HMAC key is 6 bytes long, which is below the minimum recommended length of 32 bytes for SHA256. See RFC 7518 Section 3.2.
decoded = self.decode_complete(
HEL-877/879 real-SDK check on livekit-agents 1.8.8: ALL PASS
OK CyberGrillLLM/ChatApiLLMStream subclass real livekit-agents 1.8.8 LLM/LLMStream
OK latest_user_text reads a real ChatContext (items/role/text_content)
OK fake-SSE turn through real LLMStream emits ChatChunks, final text and receipt
OK chat.error phi is spoken verbatim via ChatChunk and carries no receipt
OK mint_token claims byte-parity with livekit.api.AccessToken (video/iss/sub/keys)
OK mint_server_token matches SDK no-grant auth header claims
OK worker.py SDK surface (SpeechHandle, UserInputTranscribedEvent.is_final) present
OK barge-in task cancel closes the in-flight HTTP stream immediately
OK installed-SDK source verified: speech tasks set agents_speech_handle around the pipeline; speech_created precedes the task; llm_node calls llm.chat inside it
OK ACTUAL worker module loaded; its registered callbacks driven on a real AgentSession: both-queued delayed generations bind exactly (manager interleaving), say never steals a stream, unattributed fails closed, interrupt cancels without final/receipt
OK assistant_interim seam: real LLMStream deltas feed per-speech_id v2 payloads (replace semantics); unattributed streams feed nothing
@@ -0,0 +1,9 @@
{"v": 2, "seq": 1, "kind": "turn_start", "role": "assistant", "text": "", "speech_id": "speech_cut"}
{"v": 2, "seq": 2, "kind": "assistant_interim", "role": "assistant", "text": "我正想跟你说,今天下午", "speech_id": "speech_cut"}
{"v": 2, "seq": 3, "kind": "turn_cancel", "role": "assistant", "text": "", "speech_id": "speech_cut", "reason": "interrupted"}
{"v": 2, "seq": 4, "kind": "interim", "role": "user", "text": "等一下"}
{"v": 2, "seq": 5, "kind": "user_final", "role": "user", "text": "等一下,先听我说。"}
{"v": 2, "seq": 6, "kind": "turn_start", "role": "assistant", "text": "", "speech_id": "speech_next"}
{"v": 2, "seq": 7, "kind": "assistant_interim", "role": "assistant", "text": "好,你先说。", "speech_id": "speech_next"}
{"v": 2, "seq": 8, "kind": "assistant_final", "role": "assistant", "text": "好,你先说。", "speech_id": "speech_next", "turn_id": "0e2f-demo-next"}
{"v": 2, "seq": 9, "kind": "turn_end", "role": "assistant", "text": "", "speech_id": "speech_next", "turn_id": "0e2f-demo-next"}
@@ -0,0 +1,7 @@
{"v": 2, "seq": 1, "kind": "interim", "role": "user", "text": "你在听的"}
{"v": 2, "seq": 2, "kind": "user_final", "role": "user", "text": "你在听吗?"}
{"v": 2, "seq": 3, "kind": "turn_start", "role": "assistant", "text": "", "speech_id": "speech_normal"}
{"v": 2, "seq": 4, "kind": "assistant_interim", "role": "assistant", "text": "在听呢,", "speech_id": "speech_normal"}
{"v": 2, "seq": 5, "kind": "assistant_interim", "role": "assistant", "text": "在听呢,在听呢,你刚才说到一半的那件事我还在想。", "speech_id": "speech_normal"}
{"v": 2, "seq": 6, "kind": "assistant_final", "role": "assistant", "text": "在听呢,你刚才说到一半的那件事我还在想。", "speech_id": "speech_normal", "turn_id": "0e2f-demo-turn"}
{"v": 2, "seq": 7, "kind": "turn_end", "role": "assistant", "text": "", "speech_id": "speech_normal", "turn_id": "0e2f-demo-turn"}
@@ -0,0 +1,4 @@
{"v": 2, "seq": 1, "kind": "proactive_start", "role": "assistant", "text": "我看到一句很适合现在的话,先念给你听。", "speech_id": "speech_pro1", "message_id": 17}
{"v": 2, "seq": 2, "kind": "proactive_end", "role": "assistant", "text": "", "speech_id": "speech_pro1", "message_id": 17}
{"v": 2, "seq": 3, "kind": "proactive_start", "role": "assistant", "text": "还有一件事想告诉你——", "speech_id": "speech_pro2", "message_id": 18}
{"v": 2, "seq": 4, "kind": "proactive_cancel", "role": "assistant", "text": "", "speech_id": "speech_pro2", "message_id": 18, "reason": "interrupted"}
@@ -5,6 +5,13 @@
> 最小接缝、前端需要补的**精确接口**与**验收标准**。代码基点:分支
> `hel-879-assembly`(见交付评论精确 head);后台实现
> `src/cybergril/voice/seam.py` + `worker.py` 接线。
>
> **2026-10-27 收口更新**:字幕消息已升级为**版本化契约 v2**(信封
> `v/seq`、确切轮次 `speech_id`、显式起止/取消事件、迟到/乱序保护、主动
> 播报同源 `message_id`)。完整可执行契约与录制样例见
> `docs/voice-subtitle-contract-v2.md` 与
> `docs/rework/hel879/subtitle-samples/*.jsonl`——**接线卡(HEL-898)以
> 该契约为准**,本文 A 节的 v1 语义作为兼容背景保留。
## A. 她的增量回复字幕(assistant_interim)
+27 -13
View File
@@ -52,15 +52,17 @@
LiveKit 不通 503「通话服务暂时连不上…」。直接展示 detail 文案即可。
### 3.3 字幕
- worker 在房间数据通道 topic `cg.subtitle` 发布 JSON:
`{kind: "interim"|"user_final"|"assistant_interim"|"assistant_final"|"error",
role: "user"|"assistant", text}`。
- worker 在房间数据通道 topic `cg.subtitle` 发布**版本化 v2 信封**
(`{v:2, seq, kind, role, text, speech_id?, turn_id?, message_id?, reason?}`,
完整契约与录制样例:`docs/voice-subtitle-contract-v2.md`、
`docs/rework/hel879/subtitle-samples/*.jsonl`)。
interim 是用户 ASR 草稿(可频繁覆盖),user_final 是纠错终稿;
**assistant_interim(HEL-879 接缝)是她的回复在 TTS 首包前/播放中的增量文字
(累积替换语义,不落库,最终被 assistant_final 或 error 收尾,打断则无收尾)**;
assistant_final 是她的话(已落库),error 是 φ 原句(未落库,前端不得当作她
说过的话进入正式记录)。前端接线契约与验收:
`docs/rework/hel879/voice-seam-interfaces.md`。
**她的回复轮有显式起止:`turn_start → assistant_interim(累积替换) →
assistant_final(已落库) → turn_end`,打断/失败/无回执则 `turn_cancel`
收尾(无 final)**;`seq` 会话内单调,前端丢弃迟到/重放(打断后旧增量
被 seq 与 speech_id 双规则拒绝);error 是 φ 原句(未落库,前端不得当作
她说过的话进入正式记录)。前端接线契约与验收:
`docs/rework/hel879/voice-seam-interfaces.md` + v2 契约文档。
### 3.4 失败 / 打断 / 挂断
- 失败:听到 φ + `error` 字幕;草稿保留;用户可开口重试(新 turn)。
@@ -74,10 +76,17 @@
**删除失败时的 503 不是 404**——房间仍在服务端的清理账上,浏览器继续保留欠账
DELETE,重试会真实再删(HEL-879 返修:旧版先删登记再删远端,失败后重试直接
404、房间从此没人删)。
- **到顶后同样是 503、绝不是 404**(HEL-879 收口):显式挂断与后台清理共用同一
持久尝试/年龄上限与状态;超限的房间记 `abandoned`(原因+次数+最后错误留在
账上),任何路径不再发删除,DELETE 返回 503+`cleanup` 状态(未结清、待人工
收尾)——浏览器不得把欠账抹掉。
- 会话登记随进程,另有**持久清理账**(实例数据目录 `<db>-voice-sessions.json`,
HEL-879 返修):房间从创建起即归属本实例,删除成功才出账;到期/掉线/关闭/
重启由有界补偿清理(次数与 TTL+宽限期双上限,超限记 `abandoned` 原因留证、
不再重试),且只删本实例自己记录的房间,不碰通用 worker 或其他实例。
HEL-879 返修):房间从创建起即归属本实例,删除成功才出账;**清理所有者同时
观察活跃会话的截止时间与欠账——用户掉线后不再发任何请求,会话过 TTL 也会
由后台自己到期转债删除(HEL-879 收口:旧版只扫欠账,无人再请求时过期房间
永不删)**;到期/掉线/关闭/重启由有界补偿清理(次数与 TTL+宽限期双上限,
超限记 `abandoned` 原因留证、不再重试),且只删本实例自己记录的房间,不碰
通用 worker 或其他实例。
~~实例重启后房间自然消亡~~ **勘误**:旧版该句无证据——重启后补偿只删自己
登记过的房间、且给存活通话留到 TTL;LiveKit 房间/worker 在 API 重启后的真实
释放仍待获批环境实测,不以本句冒充。
@@ -88,8 +97,13 @@
「已落库、proactive=1、status=sent、本房间未念过」的 companion 行(最新一条),
`session.say()` 原文念出(allow_interruptions 可打断);不新起模型调用、不伪造
新经历、不新建回执通道(文字回执规则独立、已存在)、不代页面标已读;接缝
异常只跳过不伤会话。入口呈现、节奏与启用由总管/视觉总监在接线卡定
(`docs/rework/hel879/voice-seam-interfaces.md`),未经批准保持默认关闭。
异常只跳过不伤会话。
- **字幕生命周期(HEL-879 收口)**:主动播报发自己的 `proactive_start →
proactive_end|proactive_cancel` 事件(带与文字收件箱同源的 `message_id`,
挂在 say 的 SpeechHandle 上),不借用回执分支。语义边界:这是「会话开时念
已落库旧留言」,不是会话中完整 CG-011 主动表达。入口呈现、节奏与启用由
总管/视觉总监在接线卡定(`docs/rework/hel879/voice-seam-interfaces.md` +
v2 契约),未经批准保持默认关闭。
## 4. 部署草案(本卡未执行;总工执行,逐条核对授权)
+102
View File
@@ -0,0 +1,102 @@
# 语音字幕契约 v2(cg.subtitle topic,HEL-879 收口交付)
> 面向对象:原视觉作者(接线卡 HEL-898)与后台。本文是**可执行契约**:每条
> 消息的字段、乱序/迟到保护规则、每种场景的完整录制样例
> (`docs/rework/hel879/subtitle-samples/*.jsonl`,由
> `scripts/gen_subtitle_samples_hel879.py` 离线生成)。后台实现:
> `src/cybergril/voice/seam.py`(协议与累积器)+ `worker.py`(事件接线,
> `bind_voice_session` 唯一注册点)。v1 的 `kind/role/text` 三字段消息全部
> 向下兼容:v2 只做**增字段**(`v/seq/speech_id/turn_id/message_id/reason`)
> 与**增事件**(起止/取消),旧 kind 语义不变。
## 1. 信封(所有消息共用)
```json
{"v": 2, "seq": 7, "kind": "...", "role": "user|assistant", "text": "...",
"speech_id": "speech_xxx", "turn_id": "uuid?", "message_id": 9?, "reason": "..."?}
```
- `v`:契约版本,恒为 `2`。前端见 `v !== 2` 整条丢弃(fail-closed)。
- `seq`:**会话内单调递增**(一个 worker job 一个序列)。任何 `seq <=
已应用的最大 seq` 的消息直接丢弃——重放、迟到旧轮、跨回调乱序全被这一条
挡住。
- `speech_id`:SDK `SpeechHandle.id`,一次「她开口」的唯一标识(用户话轮的
回复、主动播报各是独立 speech)。后台把它作为字幕轮次键;前端以它隔离
累积状态。空 `speech_id` 的 turn 类消息不存在(后台不会发)。
- `turn_id`:服务端话轮 id(仅 `assistant_final`/`turn_end`,来自
/api/chat 回执归属);`message_id`:主动播报行的同源消息 id(仅
`proactive_*`)。
- `reason`:`turn_cancel`/`proactive_cancel` 的取消原因
(`interrupted|failed|no-generation|error_phi`)。
## 2. 事件种类与生命周期
### 用户侧(不变,仅加信封)
- `interim`:ASR 草稿(替换语义,`text` 为截至当前全句)。
- `user_final`:纠错终稿。
### 她的回复轮(新:显式起止 + 确切归属 + 乱序保护)
```
turn_start{speech_id}
→ assistant_interim{speech_id, text=累计全句} # 0..n 次,替换语义
→ assistant_final{speech_id, turn_id, text} # 已落库的完整回复
→ turn_end{speech_id, turn_id} # 轮关闭
```
- 打断/失败/无回执:**没有 final**,直接
`turn_cancel{speech_id, reason=interrupted|failed|no-generation}`。
前端必须把无 final 收尾的 interim 按「这轮没有成为她的正式回复」处理
(残影不越过新用户轮)。
- φ 失败:`error{speech_id, text=φ原句}` 后跟 `turn_cancel{reason=error_phi}`;
error 不落正式记录。
- **迟到保护(前端规则)**:turn 类消息按 `speech_id` 只允许作用于「当前
打开的轮」;收到 `turn_end/turn_cancel` 后同 `speech_id` 的后续
interim/final 丢弃(seq 规则已再挡一层)。打断后晚到的旧增量被两条规则
共同拒绝——这正是 v1 kind/role/text 做不到的。
### 主动开口(CG-011 最小接缝,默认关)
```
proactive_start{speech_id, message_id, text=原文}
→ proactive_end{speech_id, message_id} # 完整念完
| proactive_cancel{speech_id, message_id, reason=interrupted|failed}
```
- `message_id` 与文字收件箱同一行(同源可对齐);字幕生命周期挂在 say 的
SpeechHandle 上,**不借用回执分支**(无 LM 流也照发起止事件)。
- 语义边界:这是「会话开时念已落库的旧 proactive 留言」(每会话 ≤1 条,
`CYBERGRIL_PROACTIVE_VOICE=1` 才启用),**不是**会话中完整 CG-011 主动
表达——后者继续承接,不得冒充完成。未读/已读仍归页面,worker 不代标。
## 3. 前端实现要求(HEL-898,不改已认可视觉)
1. `web/src/voice/session.ts`:按 §2 生命周期维护「当前 assistant 轮」
(`speech_id` 键 + `seq` 闸);`turn_start` 开轮、interim 替换渲染、
final 原子替换、`turn_end/turn_cancel` 关轮清残影;挂断全清。
2. `assistant_interim` 与 `assistant_final` 同一气泡位(替换式过渡),
与用户 `interim` 视觉可区分;不进入正式聊天记录(只有 final 落库)。
3. `proactive_*` 复用「她的回复」位或留言卡语义由视觉作者定;
`message_id` 供未读联动,不代标已读。
4. v1 兼容期:页面可以先按 v1 消费(忽略新字段),接线卡再切 v2 生命周期。
## 4. 录制样例(验收对照)
`docs/rework/hel879/subtitle-samples/`(离线生成,零真实调用):
- `normal-turn.jsonl`:用户 interim→final→她的 turn_start→2×interim→
final→turn_end(seq 连续单调)。
- `interrupt.jsonl`:interim 后用户打断→turn_cancel(interrupted);新用户轮
正常开始——旧轮无 final。
- `proactive.jsonl`:proactive_start→proactive_end 与打断版
proactive_cancel,均带同源 message_id。
真 SDK 驱动(.12, livekit-agents 1.8.8, 假 SSE/假媒体):`scripts/
gen_hel877_sdk_check.py` 第 9 项加载真实 worker 模块、在真 AgentSession 上
触发其注册回调,覆盖「双 handle 先排队后生成」「say 夹在用户轮」「无归属
fail-closed」「打断取消」——与本文契约逐字段一致。
## 5. 后台保证(已实现并测)
- 每个 `assistant_interim`/`final` 的 `speech_id` 来自 SDK 生成上下文的
**确切归属**(`agents_speech_handle` ContextVar),不按事件先后猜;无归属
的流不开轮、不绑回执(fail-closed)。
- 累积器按 `speech_id` 隔离,轮关闭后同 id 增量在后台即被丢弃(生产端先挡
一层);`seq` 由单点 `SubtitleBus` 发号,会话内严格单调。
- 回执确认仍只发生在「真实播完 + 未打断 + 有完整回执 + epoch 一致」
(`should_ack`),字幕事件与回执互相独立:主动播报永不走回执分支。
+174 -62
View File
@@ -5,10 +5,16 @@ 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).
HEL-879 additions: the check drives the WORKER'S ACTUAL callback path with real
SpeechHandle/SpeechCreatedEvent objects — the handle-without-generation and
late-cleanup interleavings from the manager's independent review — and verifies
the assistant_interim delta seam through the real LLMStream machinery.
HEL-879 remaining closure: the check LOADS THE ACTUAL WORKER MODULE
(cybergril.voice.worker, wiring included — no hand-copied callbacks) and drives
the callbacks IT registered on a real AgentSession with real
SpeechHandle/SpeechCreatedEvent objects. Attribution is proven two ways:
(a) source-level — the installed SDK's _create_speech_task sets the private
agents_speech_handle ContextVar around every speech task and speech_created is
emitted before the task starts; (b) runtime — generations started inside that
ContextVar bind exactly, including the manager's both-queued-then-delayed
interleaving, a say speech sandwiched between user turns, an unattributed
generation (fail-closed) and an interrupted turn (cancel, no receipt).
"""
from __future__ import annotations
@@ -17,10 +23,11 @@ import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
MODULES = ["chat_api_client", "receipt", "seam", "llm_chat_api"]
MODULES = ["chat_api_client", "receipt", "seam", "llm_chat_api",
"stt_funasr", "tts_cosyvoice", "worker"]
TEMPLATE = r'''
import asyncio, base64, json, sys, types
import asyncio, base64, inspect, json, sys, types
SOURCES = json.loads(base64.b64decode("__B64__"))
@@ -179,86 +186,191 @@ async def cancel_case():
asyncio.run(cancel_case())
ok.append("barge-in task cancel closes the in-flight HTTP stream immediately")
# 9. HEL-879: the worker's ACTUAL callback path on real SpeechHandle objects —
# the manager's two interleavings (handle without generation consuming the
# next turn's stream; late cleanup) plus interrupt/failure discard order,
# driven exactly like worker.entrypoint wires them.
# 9. HEL-879 remaining closure: THE ACTUAL WORKER MODULE's registered callbacks
# on a real AgentSession — exact attribution from the SDK generation context.
from livekit.agents import AgentSession
from livekit.agents.voice import agent_activity
from livekit.agents.voice.speech_handle import SpeechHandle
from livekit.agents.voice.events import SpeechCreatedEvent
# 9a. source-level proof on the INSTALLED SDK: every speech task runs inside
# the private agents_speech_handle ContextVar, and speech_created is
# emitted BEFORE the pipeline task is created (so note_handle always
# happens-before its generation's llm.chat).
create_src = inspect.getsource(agent_activity.AgentActivity._create_speech_task)
assert "_SpeechHandleContextVar.set(speech_handle)" in create_src, create_src
gen_src = inspect.getsource(agent_activity.AgentActivity._generate_reply)
assert gen_src.index("speech_created") < gen_src.index("_pipeline_reply_task"), gen_src
say_src = inspect.getsource(agent_activity.AgentActivity.say)
assert say_src.index("speech_created") < say_src.index("_create_speech_task"), say_src
llm_call_src = inspect.getsource(
__import__("livekit.agents.voice.agent", fromlist=["Agent"]).Agent.default.llm_node)
assert "self.llm.chat(" in llm_call_src or "activity_llm.chat(" in llm_call_src
ok.append("installed-SDK source verified: speech tasks set agents_speech_handle around "
"the pipeline; speech_created precedes the task; llm_node calls llm.chat inside it")
worker_mod = sys.modules["cybergril.voice.worker"]
receipt_mod = sys.modules["cybergril.voice.receipt"]
seam_mod = sys.modules["cybergril.voice.seam"]
def receipt_echo_handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/api/health":
return httpx.Response(200, json={"epoch": 1})
if request.url.path == "/api/chat/received":
return httpx.Response(200, json={"accepted": True})
body = json.loads(request.content)
turn_id = body["turn_id"]
payload = (
'data: {"t":"chat.delta","epoch":1,"turn_id":null,"delta":"这句是"}\n\n'
'data: {"t":"chat.final","epoch":1,"turn_id":null,"utterance":{"text":"这句是她的完整回复。"},'
'"receipt":{"message_id":42,"turn_id":"' + turn_id + '","epoch":1,'
'"token":"' + "t" * 48 + '","text_hash":"' + "z" * 64 + '"}}\n\n'
).encode()
return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=payload)
confirmed: list[str] = []
subtitle_payloads: list[dict] = []
class RecordingReceipts:
async def confirm(self, turn_id, receipt):
confirmed.append(turn_id)
return True
async def worker_callback_path():
session = AgentSession() # real SDK session object
ledger = receipt_mod.TurnLedger()
done_futures = []
bus = seam_mod.SubtitleBus(subtitle_payloads.append)
interim = seam_mod.AssistantInterimPublisher(bus)
stt = types.SimpleNamespace(agent_speaking=False, agent_recent_text="")
client = llm_mod.ChatApiClient("http://x",
transport=httpx.MockTransport(receipt_echo_handler))
llm = worker_mod.make_voice_llm("http://x", ledger=ledger, interim=interim,
client=client)
# the ACTUAL worker wiring registers every callback on the real session
worker_mod.bind_voice_session(session, llm=llm, ledger=ledger, interim=interim,
bus=bus, stt=stt, receipts=RecordingReceipts())
def on_speech_created(ev): # same guard + wiring as worker._on_speech_created
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)
)
)
def speech(hid_source):
handle = SpeechHandle.create()
session.emit("speech_created", SpeechCreatedEvent(
user_initiated=True, source=hid_source, speech_handle=handle,
created_at=1.0))
return handle
async def after_playout(handle): # same order as worker._after_playout
await handle.wait_for_playout()
failed = handle.exception() is not None
if handle.interrupted or failed:
ledger.discard(handle)
done_futures.append(("discarded", handle))
return
stream = ledger.stream_for(handle)
done_futures.append((stream, handle))
async def generation_for(handle):
# EXACTLY what _create_speech_task does (source-verified in 9a): the
# pipeline task runs with the SDK's own ContextVar set to its handle.
tk = agent_activity._SpeechHandleContextVar.set(handle)
try:
stream = llm.chat(chat_ctx=ctx)
async for _ in stream:
pass
return stream
finally:
agent_activity._SpeechHandleContextVar.reset(tk)
# H1: real handle, its turn is interrupted BEFORE any LLM stream starts.
h1 = SpeechHandle.create()
ev1 = SpeechCreatedEvent(user_initiated=True, source="generate_reply",
speech_handle=h1, created_at=1.0)
on_speech_created(ev1)
# H2: the next turn does start a generation (real handle + noted stream).
h2 = SpeechHandle.create()
ev2 = SpeechCreatedEvent(user_initiated=True, source="generate_reply",
speech_handle=h2, created_at=2.0)
on_speech_created(ev2)
s2 = types.SimpleNamespace(turn_id="new", receipt={"message_id": 2})
ledger.note_stream(s2, 2.1)
# Complete both handles through the SDK's own done-future machinery:
# H1 was interrupted (public interrupt()) before any generation started;
# H2 played out cleanly (done, no error).
h1.interrupt()
# the manager's exact interleaving: BOTH speech events queued first, the
# generations only start afterwards (delayed, in queue order).
h1 = speech("generate_reply")
h2 = speech("generate_reply")
s1, s2 = await asyncio.gather(generation_for(h1), generation_for(h2))
h1._mark_done()
h2._mark_done()
await asyncio.sleep(0.05) # let the scheduled done callbacks run
outcomes = {id(handle): (stream, handle) for stream, handle in done_futures}
assert outcomes[id(h1)][0] == "discarded", "interrupted handle must discard fail-closed"
assert outcomes[id(h2)][0] is s2, "the real turn must get its OWN stream"
# The manager's exact inputs, re-checked through stream_for directly:
assert ledger.stream_for(h1) is None
await asyncio.sleep(0.1) # let the scheduled done callbacks (_after_playout) run
assert ledger.stream_for(h1) is None and ledger.stream_for(h2) is None # consumed
assert s1.speech_handle is h1 and s2.speech_handle is h2, "exact attribution"
# both completed turns acked exactly once, each with its own turn_id
assert sorted(confirmed) == sorted([s1.turn_id, s2.turn_id]), confirmed
# v2 subtitle lifecycle per speech_id, seq monotonic, interleaved correctly
kinds = [(p["kind"], p.get("speech_id")) for p in subtitle_payloads]
assert kinds[0] == ("turn_start", h1.id)
for sid in (h1.id, h2.id):
seq = [p["kind"] for p in subtitle_payloads if p.get("speech_id") == sid]
assert seq == ["turn_start", "assistant_interim", "assistant_final", "turn_end"], seq
seqs = [p["seq"] for p in subtitle_payloads]
assert seqs == sorted(seqs) and len(set(seqs)) == len(seqs)
# no payload without a speech_id ever opened a turn
assert all(p.get("speech_id") for p in subtitle_payloads
if p["kind"] in ("turn_start", "assistant_interim")), subtitle_payloads
# a say speech sandwiched between user turns never takes a user stream
before = len(confirmed)
h_user = speech("generate_reply")
h_say = speech("say") # proactive/programmatic say: user_initiated but no LLM stream
stream_user = await generation_for(h_user)
h_say._mark_done() # say finishes without any generation
h_user._mark_done()
await asyncio.sleep(0.1)
assert stream_user.speech_handle is h_user
assert confirmed.count(stream_user.turn_id) == 1 and len(confirmed) == before + 1
say_events = [p for p in subtitle_payloads if p.get("speech_id") == h_say.id]
assert say_events == [], "say without an LLM stream opens/closes no subtitle turn"
# an UNATTRIBUTED generation (no speech task context) binds nobody
h_late = speech("generate_reply")
async def unattributed():
assert agent_activity._SpeechHandleContextVar.get(None) is None
return llm.chat(chat_ctx=ctx) # proactive background generation shape
stray = await unattributed()
await generation_for(h_late)
assert stray.speech_handle is None and stray.speech_id == ""
assert ledger.stream_for(h_late).speech_handle is h_late
assert stray in ledger.unattributed
assert not [p for p in subtitle_payloads if p["kind"] == "turn_start"
and not p.get("speech_id")], "unattributed generation must not open a subtitle turn"
# interrupted turn: cancel event, no final, no receipt
before = len(confirmed)
h3 = speech("generate_reply")
await generation_for(h3)
h3.interrupt()
h3._mark_done()
await asyncio.sleep(0.1)
assert len(confirmed) == before
ev3 = [p["kind"] for p in subtitle_payloads if p.get("speech_id") == h3.id]
assert ev3 == ["turn_start", "assistant_interim", "turn_cancel"], ev3
asyncio.run(worker_callback_path())
ok.append("worker callback path on real SpeechHandle/SpeechCreatedEvent: no-generation "
"handle discards, next turn keeps its own stream (explicit binding)")
ok.append("ACTUAL worker module loaded; its registered callbacks driven on a real "
"AgentSession: both-queued delayed generations bind exactly (manager "
"interleaving), say never steals a stream, unattributed fails closed, "
"interrupt cancels without final/receipt")
# 10. HEL-879: assistant_interim seam through the REAL LLMStream machinery.
# 10. HEL-879: assistant_interim seam through the REAL LLMStream machinery,
# per-speech_id accumulators (stream-passing delta callback).
interim_payloads = []
async def interim_seam():
publisher = seam_mod.AssistantInterimPublisher(interim_payloads.append)
from livekit.agents.voice import agent_activity
bus = seam_mod.SubtitleBus(interim_payloads.append)
publisher = seam_mod.AssistantInterimPublisher(bus)
adapter = llm_mod.CyberGrillLLM("http://x", client=llm_mod.ChatApiClient(
"http://x", transport=httpx.MockTransport(handler)),
on_assistant_delta=publisher.feed)
publisher.reset()
on_assistant_delta=lambda stream, delta: publisher.feed(stream.speech_id, delta))
publisher.begin("speech_seam")
# attribute the stream exactly like the SDK would (a speech task setting
# its own handle): the deltas then feed THIS turn's accumulator
fake_handle = types.SimpleNamespace(id="speech_seam")
tk = agent_activity._SpeechHandleContextVar.set(fake_handle)
stream = adapter.chat(chat_ctx=ctx)
async for _ in stream:
pass
assert [p["text"] for p in interim_payloads] == ["真实链路上", "真实链路上的一句完整回复。"]
assert all(p["kind"] == "assistant_interim" and p["role"] == "assistant"
for p in interim_payloads)
agent_activity._SpeechHandleContextVar.reset(tk)
assert stream.speech_handle is fake_handle and stream.speech_id == "speech_seam"
interims = [p for p in interim_payloads if p["kind"] == "assistant_interim"]
assert [p["text"] for p in interims] == ["真实链路上", "真实链路上的一句完整回复。"]
assert all(p["role"] == "assistant" and p["v"] == 2 and p["speech_id"] == "speech_seam"
for p in interims)
assert interim_payloads[0]["kind"] == "turn_start" # begin opened the turn
# a stream without attribution feeds no open turn (fail-closed, no leak)
stray = adapter.chat(chat_ctx=ctx) # no ctxvar set here
async for _ in stray:
pass
assert stray.speech_handle is None and stray.speech_id == ""
assert len(interim_payloads) == 3, interim_payloads # turn_start + 2 interims only
asyncio.run(interim_seam())
ok.append("assistant_interim seam: SSE deltas through real LLMStream feed her "
"incremental subtitle payloads (replace semantics, reset works)")
ok.append("assistant_interim seam: real LLMStream deltas feed per-speech_id v2 "
"payloads (replace semantics); unattributed streams feed nothing")
print("HEL-877/879 real-SDK check on livekit-agents", end=" ")
import importlib.metadata as md
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Generate the v2 subtitle contract sample recordings (HEL-879).
Drives the REAL seam implementation (seam.SubtitleBus / AssistantInterimPublisher
/ speak_proactive_row's event shape) offline — zero livekit imports, zero model
calls — and writes the JSONL sequences the visual author wires against:
docs/rework/hel879/subtitle-samples/normal-turn.jsonl
docs/rework/hel879/subtitle-samples/interrupt.jsonl
docs/rework/hel879/subtitle-samples/proactive.jsonl
Each line is exactly one cg.subtitle payload as it would be published on the
room topic (see docs/voice-subtitle-contract-v2.md).
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from cybergril.voice.seam import ( # noqa: E402
AssistantInterimPublisher,
SubtitleBus,
)
OUT = ROOT / "docs/rework/hel879/subtitle-samples"
def record(name: str, payloads: list[dict]) -> Path:
OUT.mkdir(parents=True, exist_ok=True)
path = OUT / name
path.write_text(
"".join(json.dumps(p, ensure_ascii=False) + "\n" for p in payloads),
encoding="utf-8")
return path
def normal_turn() -> list[dict]:
payloads: list[dict] = []
bus = SubtitleBus(payloads.append)
interim = AssistantInterimPublisher(bus)
bus.emit("interim", role="user", text="你在听的")
bus.emit("user_final", role="user", text="你在听吗?")
interim.begin("speech_normal")
interim.feed("speech_normal", "在听呢,")
interim.feed("speech_normal", "在听呢,你刚才说到一半的那件事我还在想。")
interim.finish("speech_normal", turn_id="0e2f-demo-turn",
text="在听呢,你刚才说到一半的那件事我还在想。",
message_id=None)
return payloads
def interrupt_turn() -> list[dict]:
payloads: list[dict] = []
bus = SubtitleBus(payloads.append)
interim = AssistantInterimPublisher(bus)
interim.begin("speech_cut")
interim.feed("speech_cut", "我正想跟你说,今天下午")
# barge-in: the turn dies without a final; the next user turn starts clean
interim.cancel("speech_cut", "interrupted")
bus.emit("interim", role="user", text="等一下")
bus.emit("user_final", role="user", text="等一下,先听我说。")
interim.begin("speech_next")
interim.feed("speech_next", "好,你先说。")
interim.finish("speech_next", turn_id="0e2f-demo-next", text="好,你先说。")
return payloads
def proactive() -> list[dict]:
payloads: list[dict] = []
bus = SubtitleBus(payloads.append)
# spoken to the end (same-source message_id 17)
bus.emit("proactive_start", role="assistant", speech_id="speech_pro1",
text="我看到一句很适合现在的话,先念给你听。", message_id=17)
bus.emit("proactive_end", role="assistant", speech_id="speech_pro1",
message_id=17)
# interrupted variant (message_id 18)
bus.emit("proactive_start", role="assistant", speech_id="speech_pro2",
text="还有一件事想告诉你——", message_id=18)
bus.emit("proactive_cancel", role="assistant", speech_id="speech_pro2",
message_id=18, reason="interrupted")
return payloads
def main() -> int:
for name, fn in (("normal-turn.jsonl", normal_turn),
("interrupt.jsonl", interrupt_turn),
("proactive.jsonl", proactive)):
path = record(name, fn())
seqs = [json.loads(line)["seq"] for line in
path.read_text(encoding="utf-8").splitlines()]
assert seqs == sorted(seqs) and len(set(seqs)) == len(seqs), (name, seqs)
print(f"{path} ({len(seqs)} payloads, seq 1..{seqs[-1]})")
return 0
if __name__ == "__main__":
sys.exit(main())
+36 -5
View File
@@ -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
+42 -33
View File
@@ -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:
+17 -1
View File
@@ -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
View File
@@ -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]]:
+70 -17
View File
@@ -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
View File
@@ -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
+20 -3
View File
@@ -632,10 +632,27 @@ def test_lifespan_cancels_owned_generation_and_joins_task(tmp_path):
c.post("/api/companion", json=CREATE)
runtime = app.state.life
clock = fixed_clock()
runtime.clock = lambda: clock[0]
async def block_next():
async def freeze_and_block_next():
# HEL-879 determinism fix: the clock freeze and the block must be
# ONE atomic step on this loop. They used to be two portal calls,
# and a 10ms life tick could slip between them — a frozen-clock
# tick then claimed the day UNBLOCKED, the run was marked done,
# and wait_started timed out forever (full-suite flake; single-run
# passed). Also wait for any in-flight real-day generation first:
# a tick that already claimed the real day may resume past this
# point, and its later provider calls must not trip the block.
loop = asyncio.get_running_loop()
deadline = loop.time() + 5
while app.state.store.query_one(
"SELECT 1 FROM life_run WHERE status='pending'"):
if loop.time() > deadline:
raise TimeoutError("real-day run never settled")
await asyncio.sleep(0.005)
runtime.clock = lambda: clock[0]
p.block, p.entered, p.release = True, asyncio.Event(), asyncio.Event()
c.portal.call(block_next)
c.portal.call(freeze_and_block_next)
async def wait_started():
await asyncio.wait_for(p.entered.wait(), 1)
c.portal.call(wait_started)
+7 -4
View File
@@ -267,12 +267,15 @@ def test_receipt_before_playout_not_possible_by_construction():
async def test_ledger_binds_handle_to_its_stream():
ledger = TurnLedger()
handle = type("H", (), {"created_at": 1.0})()
older = type("S", (), {"created_at": 0.5, "text": "old"})()
ledger.note_stream(older, 0.5)
stray = type("S", (), {"created_at": 0.5, "text": "old"})()
# A stream without exact attribution binds to nobody (fail-closed)...
assert ledger.note_stream(stray, None, 0.5) is False
assert ledger.unattributed == [stray]
ledger.note_handle(handle, 1.0)
stream = type("S", (), {"created_at": 1.2, "text": "new"})()
ledger.note_stream(stream, 1.2)
assert ledger.stream_for(handle) is stream, "first stream at/after the handle"
# ...and a noted handle claims ONLY the stream of its own generation.
assert ledger.note_stream(stream, handle, 1.2) is True
assert ledger.stream_for(handle) is stream, "exactly its own generation's stream"
assert ledger.stream_for(handle) is None, "binding consumed exactly once"
+282 -25
View File
@@ -53,52 +53,91 @@ def _stream(turn_id: str) -> SimpleNamespace:
return SimpleNamespace(turn_id=turn_id, receipt={"message_id": hash(turn_id) % 1000})
def test_ledger_binds_each_handle_to_its_own_stream():
def _handle(hid: str = "speech_x") -> SimpleNamespace:
return SimpleNamespace(id=hid, created_at=1.0)
def test_ledger_binds_each_handle_to_exactly_its_own_generation():
ledger = TurnLedger()
h1, h2 = object(), object()
h1, h2 = _handle("speech_1"), _handle("speech_2")
s1, s2 = _stream("old"), _stream("new")
ledger.note_handle(h1, 1.0)
ledger.note_stream(s1, 1.1)
ledger.note_stream(s1, h1, 1.1)
ledger.note_handle(h2, 2.0)
ledger.note_stream(s2, 2.1)
# A late cleanup of H2 must leave H1's own stream to H1 (old code: None).
ledger.note_stream(s2, h2, 2.1)
# Each handle consumes exactly the stream of ITS generation, in any order.
assert ledger.stream_for(h2) is s2
assert ledger.stream_for(h1) is s1
def test_ledger_manager_interleaving_no_cross_turn_steal():
"""总管独立复核的精确反例:两个 speech 事件先排队、生成后到。
note_handle(H1)→note_handle(H2)→note_stream(S1)→note_stream(S2) 旧代码
把 S1 错绑给 H2(H1=None, H2=turn-one)。绑定改为只认 SDK 生成上下文的
确切 handle:S1 只属于 H1,S2 只属于 H2;没有归属的流不绑任何轮。
"""
ledger = TurnLedger()
h1, h2 = _handle("speech_h1"), _handle("speech_h2")
s1, s2 = _stream("turn-one"), _stream("turn-two")
ledger.note_handle(h1, 1.0)
ledger.note_handle(h2, 2.0) # 旧代码在这里把 H1 退役掉
assert ledger.note_stream(s1, h1, 3.0) is True # S1 归 H1,绝不给 H2
assert ledger.note_stream(s2, h2, 4.0) is True
assert ledger.stream_for(h1) is s1
assert ledger.stream_for(h2) is s2
def test_ledger_newer_speech_never_retires_older_generation():
"""新 speech 出现不能证明旧 speech 不会再开始生成(总管复核 B)。"""
ledger = TurnLedger()
h1, h2 = _handle("speech_a"), _handle("speech_b")
s1 = _stream("old-turn")
ledger.note_handle(h1, 1.0)
ledger.note_handle(h2, 2.0)
# H2 出现之后 H1 的生成才真正开始:S1 在 H1 的生成上下文里创建。
assert ledger.note_stream(s1, h1, 3.0) is True
assert ledger.stream_for(h1) is s1
def test_ledger_handle_without_generation_consumes_nothing():
ledger = TurnLedger()
no_generation, real = object(), object()
no_generation, real = _handle("speech_ng"), _handle("speech_real")
s2 = _stream("new")
ledger.note_handle(no_generation, 10.0)
ledger.note_handle(real, 11.0) # retires the older, generation-less handle
ledger.note_stream(s2, 11.1)
ledger.note_handle(real, 11.0)
# real 的生成上下文只绑 real;no_generation 永远拿不到流(fail-closed)。
assert ledger.note_stream(s2, real, 11.1) is True
assert ledger.stream_for(no_generation) is None
assert ledger.stream_for(real) is s2
def test_ledger_interrupted_handle_discards_only_its_own_binding():
ledger = TurnLedger()
h1, h2 = object(), object()
h1, h2 = _handle("speech_1"), _handle("speech_2")
s1, s2 = _stream("one"), _stream("two")
ledger.note_handle(h1, 1.0)
ledger.note_stream(s1, 1.0)
ledger.note_stream(s1, h1, 1.0)
ledger.note_handle(h2, 2.0)
ledger.note_stream(s2, 2.0)
ledger.note_stream(s2, h2, 2.0)
ledger.discard(h1) # worker fail-closed path (interrupted/failed playout)
assert ledger.stream_for(h1) is None
assert ledger.stream_for(h2) is s2
def test_ledger_stream_without_pending_handle_stays_unclaimed():
def test_ledger_stream_without_noted_handle_stays_unclaimed():
"""无确切归属即 fail-closed:未登记的 handle(主动/程序化生成)的流
不绑给任何用户轮,事后到达的 note_handle 也拿不到它。"""
ledger = TurnLedger()
stray = _stream("proactive")
ledger.note_stream(stray, 1.0) # no user turn awaited a generation
handle = object()
assert ledger.note_stream(stray, None, 1.0) is False # 无归属
assert ledger.note_stream(stray, object(), 1.0) is False # 未登记的 handle
handle = _handle("speech_late")
ledger.note_handle(handle, 2.0)
later = _stream("answer")
ledger.note_stream(later, 2.5)
assert ledger.note_stream(later, handle, 2.5) is True
assert ledger.stream_for(handle) is later
assert ledger.unattributed == [stray, stray]
# --------------------------------------------------- session ownership ledger
@@ -344,6 +383,140 @@ async def test_active_room_surives_restart_until_ttl_then_compensated(tmp_path):
await second.aclose()
# ------------------------------------- HEL-879 remaining closure: item A
@pytest.mark.asyncio
async def test_expiry_deletes_room_with_no_further_request():
"""总管复核 A-1 精确复现:recover→open→不再来任何请求,过 TTL 后远端
删除必须由清理所有者自己完成(旧代码 0 次删除、登记仍在)。"""
standin = StandinLiveKit()
now = [100.0]
service = _service(standin, clock=lambda: now[0],
session_ttl_seconds=0.01, backoff=0.005)
try:
session = await service.open_session(epoch=1)
await service.recover()
await asyncio.sleep(0.025) # cleaner exits in the old code right here
now[0] += 1.0 # past TTL — with NO further request of any kind
for _ in range(100):
if standin.deleted:
break
await asyncio.sleep(0.02)
assert standin.deleted == [session.room]
assert session.session_id not in service._sessions
assert service.cleanup_debt(session.session_id) is None
# settled: the cleaner exits by itself, no dangling coroutine
for _ in range(100):
if service._cleaner is None or service._cleaner.done():
break
await asyncio.sleep(0.02)
assert service._cleaner is None or service._cleaner.done()
finally:
await service.aclose()
assert service._cleaner is None
@pytest.mark.asyncio
async def test_cleaner_stays_alive_while_a_session_is_registered():
"""活跃登记存在期间清理所有者不得退出(A-1 的 cleaner_present 维度)。"""
standin = StandinLiveKit()
now = [100.0]
service = _service(standin, clock=lambda: now[0],
session_ttl_seconds=0.01, backoff=0.005)
try:
await service.recover()
await service.open_session(epoch=1)
await asyncio.sleep(0.1)
assert service._cleaner is not None and not service._cleaner.done()
finally:
await service.aclose()
@pytest.mark.asyncio
async def test_end_after_abandoned_cap_sends_no_further_deletes():
"""总管复核 A-2 精确复现:上限 2,后台到顶后再 3 次 end 不得再发删除
(旧代码共发 5 次,_sessions 旁路上限);也不得回 404 假装已完成。"""
standin = StandinLiveKit()
standin.delete_errors = [503] * 50 # never succeeds
now = [100.0]
service = _service(standin, clock=lambda: now[0], backoff=0.005,
cleanup_max_attempts=2)
try:
session = await service.open_session(epoch=1)
with pytest.raises(livekit_wire.RoomDeleteError):
await service.end_session(session.session_id) # attempt 1
for _ in range(100):
debt = service.cleanup_debt(session.session_id)
if debt is not None and debt.abandoned:
break
await asyncio.sleep(0.02)
debt = service.cleanup_debt(session.session_id)
assert debt is not None and debt.abandoned == "attempts-exhausted"
total_errors = len(standin.delete_errors) + 2 # errors consumed = deletes sent
calls_at_abandon = total_errors - len(standin.delete_errors)
assert calls_at_abandon == 2
for _ in range(3):
from cybergril.voice.session import CleanupAbandoned
with pytest.raises(CleanupAbandoned):
await service.end_session(session.session_id)
# 3 more end requests: ZERO additional remote deletes (old code: +3).
assert total_errors - len(standin.delete_errors) == calls_at_abandon
# The failure state stays accurate and visible, never a done-404.
debt = service.cleanup_debt(session.session_id)
assert debt.abandoned == "attempts-exhausted" and debt.attempts == 2
finally:
await service.aclose()
@pytest.mark.asyncio
async def test_restart_continues_the_same_attempt_cap(tmp_path):
"""重启续同一上限:已到 2/2 的持久债,新进程不再发删除,end 也拒绝。"""
from cybergril.voice.session import CleanupAbandoned
standin = StandinLiveKit()
state = tmp_path / "voice-sessions.json"
state.write_text(json.dumps({
"version": 1,
"sessions": [],
"debts": [{"session": {"session_id": "sid-restart", "room": "cg-voice-restart",
"identity": "user-x", "created_at": 100.0,
"expires_at": 1100.0, "epoch": 1, "dispatch_id": "AD_9"},
"attempts": 2, "first_debt_at": 100.0, "last_error": "RuntimeError: x",
"abandoned": "attempts-exhausted", "eligible_at": 0.0}],
}), encoding="utf-8")
service = _service(standin, clock=lambda: 1000.0, state_path=state,
cleanup_max_attempts=2)
try:
await service.recover()
await asyncio.sleep(0.1)
assert standin.deleted == [], "abandoned debt is never re-deleted"
with pytest.raises(CleanupAbandoned):
await service.end_session("sid-restart")
assert standin.deleted == []
finally:
await service.aclose()
@pytest.mark.asyncio
async def test_success_clears_both_sessions_and_debts():
standin = StandinLiveKit()
standin.delete_errors = [503] # first delete fails, retry lands
service = _service(standin)
try:
session = await service.open_session(epoch=1)
with pytest.raises(livekit_wire.RoomDeleteError):
await service.end_session(session.session_id)
assert service.cleanup_debt(session.session_id) is not None
assert session.session_id not in service._sessions # debt is the owner now
ended = await service.end_session(session.session_id)
assert ended.room == session.room
assert service.cleanup_debt(session.session_id) is None
assert session.session_id not in service._sessions
assert await service.end_session(session.session_id) is None # honest 404
finally:
await service.aclose()
# ------------------------------------------------------ router-level semantics
def _voice_app(standin: StandinLiveKit, tts_ok=True):
@@ -387,19 +560,103 @@ def test_router_delete_failure_is_503_and_keeps_room_owned():
assert again.status_code == 404
def test_router_abandoned_cleanup_is_503_with_state_never_404():
"""到顶后的 end:503 + 准确状态(attempts/原因),绝不是 404 假完成。"""
from fastapi.testclient import TestClient
standin = StandinLiveKit()
standin.delete_errors = [503] * 50
provider = R2LLM()
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
def handler(request: httpx.Request) -> httpx.Response:
if request.url.host == "tts.test":
return httpx.Response(200)
return standin._handle(request)
service = _service(standin, backoff=3600.0, cleanup_max_attempts=2)
service.http = httpx.AsyncClient(transport=httpx.MockTransport(handler))
app = create_app(db_path=":memory:", router=router,
life_config=LifeConfig(enabled=False), semantic_mode="stub",
voice_service=service)
with TestClient(app) as client:
client.post("/api/companion", json={
"name": "语音到顶", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友"})
opened = client.post("/api/voice/session")
session_id = opened.json()["session_id"]
assert client.delete(f"/api/voice/session/{session_id}").status_code == 503
# background sweep to the cap (backoff 3600 keeps it at exactly one
# more attempt here), then explicit end must refuse without deleting
for _ in range(100):
debt = service.cleanup_debt(session_id)
if debt is not None and debt.abandoned:
break
import asyncio as _a
client.portal.call(_a.sleep, 0.02)
debt = service.cleanup_debt(session_id)
assert debt is not None and debt.abandoned == "attempts-exhausted"
refused = client.delete(f"/api/voice/session/{session_id}")
assert refused.status_code == 503
detail = refused.json()["detail"]
assert detail["cleanup"]["abandoned"] == "attempts-exhausted"
assert detail["cleanup"]["attempts"] == 2
assert detail["cleanup"]["room"] == opened.json()["room"]
# still owned, still unsettled — never collapses into 404
assert service.cleanup_debt(session_id) is not None
# ------------------------------------------------- CG-011 seam (HEL-879)
def test_assistant_interim_publisher_accumulates_and_resets():
def test_assistant_interim_publisher_is_per_turn_and_fail_closed():
from cybergril.voice.seam import SubtitleBus
published: list[dict] = []
publisher = AssistantInterimPublisher(published.append)
assert publisher.feed("") is None
assert publisher.feed("她在") is not None
publisher.feed("打字中")
assert published[-1] == {"kind": "assistant_interim", "role": "assistant",
"text": "她在打字中"}
publisher.reset()
publisher.feed("新的一轮")
assert published[-1]["text"] == "新的一轮", "no inheritance across turns"
bus = SubtitleBus(published.append)
publisher = AssistantInterimPublisher(bus)
publisher.begin("speech_1")
assert publisher.feed("speech_1", "") is None
assert publisher.feed("speech_1", "她在") is not None
publisher.feed("speech_1", "打字中")
interim = published[-1]
assert interim == {"v": 2, "seq": 3, "kind": "assistant_interim",
"role": "assistant", "speech_id": "speech_1",
"text": "她在打字中"}
# A delta after the turn closed (late/stale) is dropped, not accumulated.
publisher.finish("speech_1", turn_id="turn-1", text="她在打字中。")
assert publisher.feed("speech_1", "迟到") is None
# Another turn NEVER inherits the previous turn's text.
publisher.begin("speech_2")
publisher.feed("speech_2", "新的一轮")
assert published[-1]["text"] == "新的一轮"
assert published[-1]["speech_id"] == "speech_2"
# Cancel closes fail-closed: no final for this turn.
cancel = publisher.cancel("speech_2", "interrupted")
assert cancel["kind"] == "turn_cancel" and cancel["speech_id"] == "speech_2"
assert publisher.cancel("speech_2", "interrupted") is None # already closed
# Late interim from the cancelled turn cannot re-open it.
assert publisher.feed("speech_2", "残影") is None
kinds = [p["kind"] for p in published]
assert kinds == ["turn_start", "assistant_interim", "assistant_interim",
"assistant_final", "turn_end", "turn_start",
"assistant_interim", "turn_cancel"]
def test_subtitle_bus_seq_is_monotonic_and_enveloped():
from cybergril.voice.seam import SubtitleBus
published: list[dict] = []
bus = SubtitleBus(published.append)
a = bus.emit("interim", role="user", text="你在说什么")
b = bus.emit("user_final", role="user", text="你在说什么呀")
c = bus.emit("proactive_start", role="assistant", text="主动留言",
speech_id="speech_p", message_id=9)
assert [a["seq"], b["seq"], c["seq"]] == [1, 2, 3]
assert all(p["v"] == 2 for p in (a, b, c))
assert c["message_id"] == 9 and c["speech_id"] == "speech_p"
assert "turn_id" not in c and "reason" not in c
d = bus.emit("proactive_cancel", role="assistant", speech_id="speech_p",
message_id=9, reason="interrupted")
assert d["reason"] == "interrupted"
def test_proactive_selection_is_archived_newest_bounded():