feat: add single-call action protocol and Android stage interfaces

This commit is contained in:
zenord
2026-10-13 00:41:55 +08:00
parent dfd1372ba2
commit e91354c9e8
41 changed files with 1438 additions and 70 deletions
+124 -9
View File
@@ -20,6 +20,8 @@ import uuid
from history import History
from face_context import FaceContext
from reply_emotion import SYSTEM_FRAGMENT, parse_reply
from action_reply import ACTION_FRAGMENT, ExpressionPrefix, parse_action_reply
from action_protocol import ActionPlans, negotiate
from guest_sessions import GuestSessions, COOKIE
from tts_debug import DebugStore
from persona_resolver import resolve_persona
@@ -30,7 +32,7 @@ from protocol import WavStream, pack, unpack
from vad import Config, Silero, VadSession
ROOT = Path(__file__).resolve().parent
VERSION = '0.7.3'
VERSION = '0.8.0'
DEFAULT_VOICE_ID = '9a97272c-3919-5606-9c8f-9552ab602528'
ORIGINS = {'https://192.168.31.61:5011', 'https://localhost:5011', 'https://127.0.0.1:5011'}
@@ -39,7 +41,11 @@ ORIGINS = {'https://192.168.31.61:5011', 'https://localhost:5011', 'https://127.
async def lifespan(app):
token = os.environ.get('LAN_GATEWAY_TOKEN', '')
if len(token) < 32: raise RuntimeError('missing gateway token')
app.state.llm_structured_output = LLMProvider().structured_output
provider = LLMProvider()
app.state.llm_structured_output = provider.structured_output
app.state.llm_model = provider.model
app.state.llm_time_zone = provider.clock.zone.key
app.state.expression_prepare = provider.expression_prepare
path = ROOT / 'models/silero_vad.onnx'
if hashlib.sha256(path.read_bytes()).hexdigest() != EXPECTED_HASH: raise RuntimeError('model checksum')
app.state.model = await asyncio.to_thread(Silero, path)
@@ -138,7 +144,11 @@ async def logout(request: Request):
@app.get('/health')
async def health():
return {'status': 'ok', 'version': VERSION, 'codec': 'pcm16', 'opus': False, 'busy': app.state.busy, 'llm_structured_output': getattr(app.state, 'llm_structured_output', 'prompt'), 'stt': 'batch SenseVoice', 'tts': 'per-turn full text / single streaming generator VoxCPM2', 'voice_mode_default': 'continuous_voice', 'default_voice_id': DEFAULT_VOICE_ID}
return {'status': 'ok', 'version': VERSION, 'codec': 'pcm16', 'opus': False, 'busy': app.state.busy,
'llm_model': getattr(app.state, 'llm_model', 'unknown'),
'llm_time_zone': getattr(app.state, 'llm_time_zone', 'unknown'),
'expression_prepare': getattr(app.state, 'expression_prepare', False),
'llm_structured_output': getattr(app.state, 'llm_structured_output', 'prompt'), 'stt': 'batch SenseVoice', 'tts': 'per-turn full text / single streaming generator VoxCPM2', 'voice_mode_default': 'continuous_voice', 'default_voice_id': DEFAULT_VOICE_ID}
@app.post('/debug/log')
@@ -222,6 +232,13 @@ class Dialogue:
self.face_context = FaceContext()
self.face_messages = {}
self.pending_drained = None
self.connection_generation = secrets.token_hex(16)
self.owner = secrets.token_hex(16)
self.action_plans = ActionPlans(self.owner, self.connection_generation)
self.action_capability = None
self.action_expiry_task = None
self.action_holding = False
self.followup_pending = None
self.capture_offset = 0
self.received_samples = 0
self.vad = VadSession(model, Config(max_session_seconds=600))
@@ -243,12 +260,12 @@ class Dialogue:
self.playback_waiting = False
self.auth_check = lambda: True
async def event(self, kind, turn=None, **fields):
async def event(self, event_type, turn=None, **fields):
async with self.lock:
if turn is not None and turn != self.turn: return
if not self.auth_check(): raise ValueError('guest expired')
self.event_seq += 1
await asyncio.wait_for(self.ws.send_json({'type': kind, 'turn_id': self.turn if turn is None else turn, 'seq': self.event_seq, 'server_ms': round((time.monotonic() - self.wall) * 1000, 3), **fields}), 5)
await asyncio.wait_for(self.ws.send_json({'type': event_type, 'turn_id': self.turn if turn is None else turn, 'seq': self.event_seq, 'server_ms': round((time.monotonic() - self.wall) * 1000, 3), **fields}), 5)
async def audio(self, turn, pcm):
async with self.lock:
@@ -259,6 +276,12 @@ class Dialogue:
async def invalidate(self, reason, preserve_vad=False):
old_turn = self.turn
self.action_plans.clear()
self.action_holding = False
self.followup_pending = None
expiry = self.action_expiry_task
self.action_expiry_task = None
if expiry and expiry is not asyncio.current_task(): expiry.cancel()
self.turn += 1
if reason == 'new_turn':
self.face_context.advance_capture(old_turn, self.turn)
@@ -305,6 +328,7 @@ class Dialogue:
await self.event('listen', state='stop', mode=mode)
async def input(self, frame):
if self.action_holding: return # Drop all stale input; no capture/VAD/ASR buffering.
turn, seq, pcm = unpack(frame, 1)
if turn != self.turn: return
if not self.listening: raise ValueError('not listening')
@@ -388,9 +412,20 @@ class Dialogue:
async def drained(self):
self.pending_drained = None
self.playback_waiting = False
if self.followup_pending and self.followup_pending[0] == self.turn:
_, rid, text = self.followup_pending
self.followup_pending = None
if self.history: await self.history.spoken(self.conversation_id, rid, text)
if self.history and self.run_id:
await self.history.drained(self.run_id)
await self.send_history()
ticket = self.action_plans.drained(self.turn)
if ticket is not None:
self.action_holding = True
self.capture.clear(); self.start = None; self.vad.reset()
await self.event('action.plan', action_id=ticket.id, kind='dance', pack_sha256=ticket.pack_sha,
ttl_ms=max(0, int((ticket.expires-time.monotonic())*1000)))
return
if not self.barge:
self.capture.clear(); self.start = None; self.base = 0
self.capture_offset = self.received_samples
@@ -450,6 +485,8 @@ class Dialogue:
await self.event('error', turn, code='backend_failed', message='Backend timeout, format or synthesis failure')
await self.event('tts', turn, state='stop')
finally:
if turn == self.turn and status != 'completed':
self.action_plans.clear()
answer = self.answers.pop(turn, '')
self.contexts.pop(turn, None)
self.face_messages.pop(turn, None)
@@ -470,11 +507,13 @@ class Dialogue:
metrics.update(voice_mode=self.voice_mode, voice_id=self.voice_id, tts_request_count=0)
# Exactly one initial system: Qwen's deployed template rejects a second system.
system = '以下角色设定只约束reply字段的可朗读正文。\n' + self.persona_rules + ''.join(
'\n\n' + item['content'] for item in self.face_messages.get(turn, [])) + '\n\n' + SYSTEM_FRAGMENT
'\n\n' + item['content'] for item in self.face_messages.get(turn, [])) + '\n\n' + SYSTEM_FRAGMENT + '\n' + ACTION_FRAGMENT + '\n网关实际可用动作:' + ('dance' if self.action_capability else '无')
messages = [{'role': 'system', 'content': system}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}]
url, headers, body = self.llm_provider.request(messages, max_tokens=160)
url, headers, body = self.llm_provider.request(messages, max_tokens=160, action_plan=True)
metrics['llm_request_count'] = 1
raw_body = ''
prefix = ExpressionPrefix(turn)
prepare_enabled = self.llm_provider.expression_prepare
finish_reason = 'not_provided'
usage = {}
async with asyncio.timeout(30):
@@ -501,11 +540,23 @@ class Dialogue:
if not delta: continue
metrics.setdefault('llm_first_token_ms', round((time.perf_counter() - request_start) * 1000, 2))
raw_body += delta
candidate = prefix.feed(delta, self.turn)
if candidate is not None and prepare_enabled:
metrics['expression_prepare_ms'] = round((time.perf_counter()-request_start)*1000, 2)
await self.event('reply.emotion.prepare', turn, emotion=candidate[0], intensity=candidate[1], preload_only=True)
if len(raw_body) > 8192: raise ValueError('structured reply limit')
if turn != self.turn: return
if not raw_body.strip(): raise ValueError('empty LLM body')
parse_start = time.perf_counter()
result = parse_reply(raw_body, finish_reason=finish_reason)
plan = parse_action_reply(raw_body, finish_reason, bool(self.action_capability))
result = plan.speech
metrics['action_reason'] = plan.action_reason
metrics['expression_prepare_mode'] = 'schema_prefix_preload' if prepare_enabled else 'full_reply'
if prepare_enabled and prefix.candidate and not prefix.consistent(plan, self.turn):
await self.event('reply.emotion.prepare.cancel', turn, reason='final_invalid')
if plan.action == 'dance':
ticket = self.action_plans.create(turn, plan.after, self.action_capability)
self.action_expiry_task = asyncio.create_task(self.expire_action(ticket.id, turn))
metrics.update(reply_emotion_reason=result.reason, reply_parse_branch=result.parse_branch,
reply_emotion=result.emotion, reply_intensity=result.intensity,
llm_finish_reason=finish_reason, llm_usage=usage, llm_max_tokens=body['max_tokens'],
@@ -529,6 +580,60 @@ class Dialogue:
await enqueue(result.reply)
await queue.put(None)
async def expire_action(self, action_id, turn):
try:
ticket = self.action_plans.ticket
if ticket is None: return
await asyncio.sleep(max(0, ticket.expires-time.monotonic()))
if turn == self.turn and self.action_plans.ticket and self.action_plans.ticket.id == action_id:
await self.invalidate('action_timeout')
await self.event('action.cancel', action_id=action_id, reason='timeout')
await self.event('listen', state='resumed', mode=self.mode)
except asyncio.CancelledError:
pass
async def action_status(self, data):
status, after = self.action_plans.status(data, self.turn, self.owner, self.connection_generation)
if status in ('cancelled', 'failed'):
await self.invalidate('action_cancelled')
await self.event('listen', state='resumed', mode=self.mode)
elif status == 'completed':
await self.invalidate('action_followup')
turn = self.turn
self.run_id = str(uuid.uuid4())
await self.event('speech.start', turn, origin='after_action')
self.task = asyncio.create_task(self.speak_followup(turn, after))
async def speak_followup(self, turn, speech):
began = time.perf_counter()
rid = self.run_id
metrics = {'llm_request_count': 0, 'tts_request_count': 0, 'origin': 'after_action'}
try:
self.playback_waiting = True
await self.event('tts', turn, state='start', sample_rate=48000, codec='pcm16', frame_duration=20)
await self.event('llm', turn, text=speech.reply)
await self.event('reply.emotion', turn, emotion=speech.emotion, intensity=speech.intensity,
source=speech.source, reason=speech.reason, parse_branch=speech.parse_branch)
queue = asyncio.Queue(2)
await queue.put(speech.reply); await queue.put(None)
await self.synthesize(turn, queue, metrics, began)
if turn != self.turn: return
self.followup_pending = (turn, rid, speech.reply)
await self.event('metrics', turn, values=metrics)
await self.event('tts', turn, state='stop')
except asyncio.CancelledError:
raise
except Exception:
self.followup_pending = None
await self.event('error', turn, code='after_synthesis_failed', message='Action followup synthesis failed')
await self.event('tts', turn, state='stop')
finally:
capture = self.debug_captures.pop(turn, None)
if capture:
await asyncio.to_thread(capture.finalize, 'completed' if self.followup_pending else 'interrupted')
if turn == self.turn and not self.closed and self.pending_drained == turn:
await self.drained()
async def synthesize(self, turn, queue, metrics, began):
sentence = 0
previous_end = None
@@ -597,8 +702,13 @@ class Dialogue:
async def close(self):
self.closed = True
self.action_plans.clear()
self.followup_pending = None
self.action_holding = False
if self.action_expiry_task: self.action_expiry_task.cancel()
self.turn += 1
tasks = list(self.cancelled_tasks)
if self.action_expiry_task: tasks.append(self.action_expiry_task)
if self.task: tasks.append(self.task)
for task in tasks: task.cancel()
if tasks: await asyncio.gather(*tasks, return_exceptions=True)
@@ -642,6 +752,9 @@ async def dialogue(ws: WebSocket):
Segmenter(synthesis_mode)
session = Dialogue(ws, app.state.model, app.state.client, app.state.history, cid)
session.synthesis_mode = synthesis_mode
session.owner = owner or 'admin'
session.action_plans = ActionPlans(session.owner, session.connection_generation)
session.action_capability = negotiate(hello, json.loads(os.environ.get('LAN_ACTION_PACKS', '{}')))
if owner: session.auth_check = lambda: bool(app.state.guests.get(owner))
voice_mode = hello.get('voice_mode', 'continuous_voice')
if voice_mode not in ('continuous_voice', 'fragment'): raise ValueError('voice mode')
@@ -656,7 +769,7 @@ async def dialogue(ws: WebSocket):
session.voice_id = voice_id
session.debug_store = app.state.debug
session.debug_enabled = hello.get('tts_debug', True) is True
await session.event('hello', context_face_cue_version=1, reply_emotion_version=1, llm_structured_output=session.llm_provider.structured_output, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices)
await session.event('hello', action_protocol=1, action_available=bool(session.action_capability), context_face_cue_version=1, reply_emotion_version=1, llm_structured_output=session.llm_provider.structured_output, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices)
await session.send_history()
started = time.monotonic()
while time.monotonic() - started < 600:
@@ -704,6 +817,8 @@ async def dialogue(ws: WebSocket):
else: raise ValueError('history action')
elif data.get('type') == 'playback.drained':
await session.request_drained(data.get('turn_id'))
elif data.get('type') == 'action.status':
await session.action_status(data)
elif data.get('type') == 'ping': await session.event('pong')
else: raise ValueError('control')
except (WebSocketDisconnect, RuntimeError):