HEL-879 rework materials: hatchling cache correction with the offline mem0ai wheel actually built from the fixed source (sha256 698284b6..., zero downloads/installs, no 3.10 mixing, recorded in release-artifacts.json), hel895 release doc §0 now separates the historical HEL-895/896 candidate from the current hel-879-assembly candidate and §4/§5 carry the v3 snapshot semantics, budget §6.2.4 amended - a sealed library is never reopened by raising total_requests (contradiction removed), runbook §3.3/3.5/3.6/4.4/4.5 corrected (bounded cleanup ledger replaces the unproven rooms-die-naturally claim; assistant_interim kind; real-but-default-off proactive seam; single-owner dual launcher), one comment-only correction in web/src/voice/session.ts removing the unproven server-auto-cleanup claim (no logic/style change; CSS and JS bundle hashes byte-stable), CG-011 + her incremental subtitles now have a real minimal backend seam (voice/seam.py + worker/llm_chat_api wiring, proactive default off) with the precise frontend interface and acceptance list in docs/rework/hel879/voice-seam-interfaces.md, real-SDK check extended to 10 items (worker callback path on real SpeechHandle/SpeechCreatedEvent; interim seam through real LLMStream) and re-run on .12 ALL PASS, handoff-HEL-879.json appended with the rework scope; regression at this head: pytest 341/341, ruff clean except 1 pre-existing error identical at 7f0a739, web typecheck 0 errors / lint 0 errors 1 pre-existing warning / vitest 88/88 / build passes (CSS index-BpZaybfD.css unchanged), voice chain 8/8, budget split 10/10, release offline R1-R7, http pagination 7/7, real-service browser 9/9 with zero non-loopback outbound, pinned-SDK 16/16+12/12+6/6+7/7+12/12, requirements checks 4/4 (origin/main and c121c42, each with/without handoff)

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
zonggong
2026-10-27 04:27:04 +08:00
co-authored by multica-agent
parent 78a5cfd8d7
commit 7c73d392b9
21 changed files with 567 additions and 94 deletions
+10
View File
@@ -66,6 +66,16 @@ class ChatApiClient:
raise ChatApiConnectionError("health response missing epoch")
return epoch
async def recent_messages(self, limit: int = 20) -> list[dict[str, Any]]:
"""Newest message page from the unified archive (HEL-879 CG-011 seam:
proactive rows are read exactly as the text inbox reads them)."""
response = await self._client.get("/api/messages", params={"limit": limit})
response.raise_for_status()
messages = response.json().get("messages")
if not isinstance(messages, list):
raise ChatApiConnectionError("messages response malformed")
return messages
async def send_turn(
self,
text: str,
+9
View File
@@ -13,6 +13,7 @@ never does. Verified against livekit-agents 1.8.8 source on
from __future__ import annotations
import contextlib
import time
from collections.abc import Callable
from typing import Any
@@ -75,6 +76,12 @@ class ChatApiLLMStream(LLMStream):
self.completed = False
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.
if self._llm.on_assistant_delta is not None:
with contextlib.suppress(Exception):
self._llm.on_assistant_delta(content)
self._event_ch.send_nowait(
ChatChunk(id=self.turn_id, delta=ChoiceDelta(role="assistant", content=content))
)
@@ -116,10 +123,12 @@ class CyberGrillLLM(LLM):
*,
client: ChatApiClient | None = None,
on_stream_started: Callable[[ChatApiLLMStream], None] | None = None,
on_assistant_delta: Callable[[str], None] | None = None,
) -> None:
super().__init__()
self.client = client or ChatApiClient(api_base)
self._on_stream_started = on_stream_started
self.on_assistant_delta = on_assistant_delta
@property
def provider(self) -> str:
+80
View File
@@ -0,0 +1,80 @@
"""Minimal backend seams for CG-011 proactive voice and HER incremental reply
subtitles (HEL-879 rework: these are implementation gaps, not things that
"just need a voice/budget decision").
This module is deliberately free of livekit imports (same rule as
chat_api_client) so both seams are exercised offline by the product test
suite; worker.py only wires them into the AgentSession.
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.
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).
"""
from __future__ import annotations
from collections.abc import Callable
from typing import Any
from .chat_api_client import ChatApiClient
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).
"""
def __init__(self, publish: Callable[[dict], None]) -> None:
self._publish = publish
self._text = ""
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}
self._publish(payload)
return payload
def pick_proactive(messages: list[dict[str, Any]], *, already_spoken: set[int],
limit: int = 1) -> list[dict[str, Any]]:
"""Pure selection: server-archived proactive rows this voice session may
speak — companion role, sent, proactive, non-empty, not spoken here yet,
newest first, bounded by `limit`. The page keeps its own unread state; the
worker never marks rows read (no second receipt/read channel)."""
candidates = [
m for m in messages
if m.get("proactive") is True and m.get("role") == "companion"
and m.get("status") == "sent"
and (m.get("text") or "").strip()
and m.get("id") not in already_spoken
]
candidates.sort(key=lambda m: m.get("id") or 0, reverse=True)
return candidates[:limit]
async def pending_proactive(client: ChatApiClient, *, already_spoken: set[int],
limit: int = 1,
fetch_limit: int = 20) -> list[dict[str, Any]]:
"""Fetch the newest message page from the unified API and select the
proactive rows the session may speak (see pick_proactive)."""
messages = await client.recent_messages(limit=fetch_limit)
return pick_proactive(messages, already_spoken=already_spoken, limit=limit)
+2 -2
View File
@@ -126,7 +126,7 @@ class VoiceSession:
}
@classmethod
def from_state(cls, data: dict) -> "VoiceSession":
def from_state(cls, data: dict) -> VoiceSession:
return cls(
session_id=str(data["session_id"]), room=str(data["room"]),
identity=str(data.get("identity", "")), created_at=float(data.get("created_at", 0)),
@@ -152,7 +152,7 @@ class _CleanupDebt:
"abandoned": self.abandoned, "eligible_at": self.eligible_at}
@classmethod
def from_state(cls, data: dict) -> "_CleanupDebt":
def from_state(cls, data: dict) -> _CleanupDebt:
return cls(
session=VoiceSession.from_state(data.get("session", {})),
attempts=int(data.get("attempts", 0)),
+43 -15
View File
@@ -35,6 +35,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 .stt_funasr import FunASRSTT
from .tts_cosyvoice import CosyVoiceTTS
@@ -46,6 +47,10 @@ VOICE_STATE = Path(
)
)
WORKER_HEALTH_PORT = int(os.environ.get("CYBERGRIL_WORKER_HEALTH_PORT", "8082"))
# CG-011 语音主动开口(HEL-879 最小接缝):默认关闭,接线卡与视觉作者定好
# 入口呈现并经批准后才置 1。开启后只念服务端已落库 proactive=1 的行。
PROACTIVE_VOICE = os.environ.get("CYBERGRIL_PROACTIVE_VOICE", "") == "1"
PROACTIVE_PER_SESSION = 1
SUBTOPIC = "cg.subtitle"
# 占位指令:真正的人格由统一服务在 /api/chat 服务端组装。适配器忽略
@@ -66,15 +71,27 @@ def prewarm(proc: JobProcess) -> None:
proc.userdata["vad"] = VAD.load()
async def _maybe_open_proactive(session: AgentSession, room) -> None:
"""CG-011 主动开口接缝(本卡不实现,留明确边界,不丢需求)。
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 行,不新起模型调用)、可被
用户打断、不新造第二条回执通道。具体呈现与节奏由总管/视觉总监在接线
卡定;在此之前保持空操作。
仅在已开启的语音会话内、只念服务端已落库、标记 proactive=1、未在本房间
念过的 companion 行(同一 GET /api/messages 入口,无第二人格/无新模型调用),
`session.say(..., allow_interruptions=True)` 可被用户打断,不新建回执通道
(文字回执规则独立且已存在)。每会话有界(PROACTIVE_PER_SESSION)。
入口呈现与节奏由总管/视觉总监在接线卡定;批准前置 CYBERGRIL_PROACTIVE_VOICE=1。
返回本次念出的消息 id(接线/验收用;未启用返回空)。
"""
return None
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:
@@ -82,12 +99,22 @@ async def entrypoint(ctx: JobContext) -> None:
# agent 说话期间短文本/相似文本视为回声丢弃(同通用 worker 的实测做法)
stt.agent_speaking = False
stt.agent_recent_text = ""
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)
)
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)
llm = CyberGrillLLM(API_BASE, on_stream_started=note_stream)
llm = CyberGrillLLM(API_BASE, on_stream_started=note_stream,
on_assistant_delta=interim.feed)
receipts = ReceiptSender(llm.client)
session = AgentSession(
@@ -101,12 +128,6 @@ async def entrypoint(ctx: JobContext) -> None:
},
)
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)
)
@session.on("user_input_transcribed")
def _on_transcript(ev) -> None:
if ev.transcript.strip():
@@ -175,7 +196,14 @@ async def entrypoint(ctx: JobContext) -> None:
await ctx.connect()
await session.start(room=ctx.room, agent=Agent(instructions=INSTRUCTIONS_PLACEHOLDER))
await _maybe_open_proactive(session, ctx.room)
spoken_proactive: set[int] = set()
try:
spoken = await _maybe_open_proactive(session, ctx.room, client=llm.client,
already_spoken=spoken_proactive)
spoken_proactive.update(spoken)
except Exception as exc: # seam failure never breaks the session start
print(f"[cybergril-worker] proactive seam skipped: {type(exc).__name__}: {exc}",
flush=True)
print(
f"[cybergril-worker] session started (api={API_BASE}, "
f"voice={read_default_voice()}, agent_name={AGENT_NAME})",