"""SSH stdin payload body. sources/expected are supplied by the bounded launcher. No production history, recordings, debug reports or model output is read/persisted. Real services supply ASR/LLM/TTS; manual VAD and all media confirmations are fixtures. """ import asyncio import base64 from contextlib import suppress import hashlib import inspect import io import json import math import os from pathlib import Path import re import secrets import socket import ssl import struct import subprocess import sys import tempfile import time import urllib.request import wave import httpx LIVE=Path('/home/gorios-spark-2/lan-voice') report={'status':'failed','scope':'isolated actual WebSocket/ASR/Qwen/TTS; simulated mic/media/drain', 'paid_calls':0,'max_tokens':160,'device':'not_run','naturalness':'not_certified','semantic_rows':[], 'llm_requests':0,'tts_requests':0,'asr_requests':0,'events':[]} digest=lambda p:hashlib.sha256(p.read_bytes()).hexdigest() def live_health(): ctx=ssl.create_default_context(cafile=str(LIVE/'.runtime/gateway-cert.pem')) opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx)) with opener.open('https://192.168.31.61:5011/health',timeout=5) as response: return json.load(response) async def main(stage): import websockets import uvicorn import gateway as g from action_reply import ACTION_FRAGMENT, ExpressionPrefix, parse_action_reply from guest_sessions import GuestSessions from history import History from llm_provider import LLMProvider from protocol import pack,unpack from reply_emotion import SYSTEM_FRAGMENT from tests_fake import FakeModel provider=LLMProvider() assert (provider.base_url,provider.model,provider.structured_output,provider.clock.zone.key)==( 'http://127.0.0.1:8888/v1','qwen3.8-27b','json_schema','Asia/Shanghai') report.update(provider=provider.model,zone=provider.clock.zone.key,mode=provider.structured_output) fixture_sha=hashlib.sha256(b'isolated-public-action-calling-path-fixture-not-an-asset').hexdigest() if approved: from action_protocol import configured_packs assert configured_packs().get(approved['sha256'])==approved['durations'] fixture_sha=approved['sha256'];playback_ms=max(approved['durations'].values()) report['approved_pack_metadata']=approved else: playback_ms=1000 os.environ['LAN_ACTION_PACKS']=json.dumps({fixture_sha:{'asset_01':1000,'asset_02':1000}}) token=secrets.token_urlsafe(32) # Ephemeral fixture token, never output. history=History(stage/'fixture-history.sqlite3');await history.initialize() clocks=[] async def request_hook(request): if live_health().get('busy'): raise RuntimeError('busy_no_probe') port=request.url.port if port==8888: report['llm_requests']+=1 assert report['llm_requests']<=5 body=json.loads(request.content);systems=[m['content'] for m in body['messages'] if m['role']=='system'] assert len(systems)==1 and systems[0].count('当前服务器时间:')==1 and body['max_tokens']==160 assert '时区:Asia/Shanghai' in systems[0] reference=re.search(r'当前服务器时间:([^\n]+)',systems[0])[1] clocks.append(reference) report.setdefault('request_metadata',[]).append({'request':report['llm_requests'],'system_count':1, 'clock':reference,'zone':'Asia/Shanghai','max_tokens':160,'nested_nullable_schema': body['response_format']['json_schema']['schema']['properties']['after_action'].get('anyOf') is not None}) elif port==5002: report['tts_requests']+=1;assert report['tts_requests']<=3 elif port==5001: report['asr_requests']+=1;assert report['asr_requests']==1 else: raise ValueError('unexpected_backend') async with httpx.AsyncClient(timeout=40,trust_env=False,event_hooks={'request':[request_hook]}) as client: # New public synthetic phrase; no prior/user audio files are accessed. response=await client.post('http://192.168.31.61:5002/v1/audio/speech',json={ 'model':'openbmb/VoxCPM2','voice':g.DEFAULT_VOICE_ID,'input':'请跳一段舞,结束后自然问我一个问题。','stream':True}) response.raise_for_status() with wave.open(io.BytesIO(response.content),'rb') as audio: assert (audio.getframerate(),audio.getnchannels(),audio.getsampwidth())==(48000,1,2) generated=audio.readframes(audio.getnframes());assert 0last_event_seq;last_event_seq=event['seq'];trace(event) if kind=='error': raise ValueError('isolated_gateway_backend_error') if kind=='capture.end': pre_turn=turn if kind=='llm': assert event['text'].strip() and not event['text'].lstrip().startswith(('{','[','```')) bodies[turn]=event['text'] if kind=='reply.emotion': assert turn in bodies and turn not in emotions and turn not in pcm_stats assert event['source']=='model';emotions[turn]=(event['emotion'],event['intensity']) if turn==pre_turn: assert event['finish_reason']=='stop' if kind=='metrics': metrics[turn]=event['values'] if kind=='tts' and event.get('state')=='sentence_start': assert event['text']==bodies[turn] sentence_counts[turn]=sentence_counts.get(turn,0)+1 if kind=='tts' and event.get('state')=='stop': assert turn in pcm_stats and pcm_stats[turn]['peak']>327 if turn==after_turn: rows=await history.rows(event_conversation) assert len(rows)==2 report['after_history_before_drain']=False;after_text=bodies[turn] await ws.send(json.dumps({'type':'playback.drained','turn_id':turn})) trace({'type':'fixture.playback.drained.sent','turn_id':turn}) if kind=='history': event_conversation=event['conversation_id'];history_counts.append(len(event['messages'])) if kind=='action.plan': assert plan is None and after_turn is None and report['tts_requests']==2 assert len(emotions)==1 and len(pcm_stats)==1 plan=event # This is a simulated media acknowledgement, not physical AudioRecord/video evidence. status={'type':'action.status','turn_id':pre_turn,'action_id':plan['action_id'], 'status':'started','asset_id':'asset_01','mic_stopped':True} await ws.send(json.dumps(status));started_at=time.monotonic() trace({'type':'fixture.mic_stop_and_music_started','turn_id':pre_turn}) # Delayed pre-recorded PCM during ACTION must be dropped before capture/ASR. await ws.send(pack(1,pre_turn,999,bytes(640))) complete={**status,'status':'completed','video_ended':True,'audio_stopped':True,'idle_restored':True} await ws.send(json.dumps(complete)) # Deliberate premature event. await ws.send(json.dumps({'type':'ping'})) if kind=='pong' and plan is not None and after_turn is None: assert report['tts_requests']==2 and len(emotions)==1 await asyncio.sleep(max(0,(playback_ms/1000+.05)-(time.monotonic()-started_at))) await ws.send(json.dumps(complete));await ws.send(json.dumps(complete)) trace({'type':'fixture.audio_video_end_returnA_completed_twice','turn_id':pre_turn}) if kind=='speech.start': assert plan is not None and event['origin']=='after_action' and turn>pre_turn and after_turn is None after_turn=turn assert len(emotions)==1 # Future after expression was not sent with the plan. if kind=='listen' and event.get('state')=='resumed' and turn==after_turn: rows=await history.rows(event_conversation) assert len(rows)==3 and rows[-1]['text']==bodies[after_turn] and rows[-1]['playback']=='confirmed' assert metrics[pre_turn]['llm_request_count']==1 and metrics[after_turn]['llm_request_count']==0 assert metrics[pre_turn]['tts_request_count']==metrics[after_turn]['tts_request_count']==1 assert sentence_counts=={pre_turn:1,after_turn:1} and report['asr_requests']==1 assert report['llm_requests']==1 and report['tts_requests']==3 await ws.send(json.dumps(complete));await ws.send(json.dumps({'type':'ping'})) break while True: event=json.loads(await asyncio.wait_for(ws.recv(),5));trace(event) assert event['type']!='speech.start' if event['type']=='pong':break assert report['tts_requests']==3 for row in pcm_stats.values(): row['rms']=round(math.sqrt(row.pop('square')/(row['bytes']//2)),2) report['chain']={'status':'passed','pre_turn':pre_turn,'after_turn':after_turn, 'llm_requests':1,'pre_tts_generators':1,'after_tts_generators':1,'input_public_tts_requests':1, 'pcm':pcm_stats,'sentence_counts':sentence_counts,'after_emotion_only_in_after_turn':True, 'after_history_only_after_drain':True,'duplicate_completion_no_repeat':True, 'premature_completion_no_after':True,'action_pcm_no_second_asr':True, 'prepare_ms':metrics[pre_turn].get('expression_prepare_ms'), 'full_reply_ms':metrics[pre_turn]['llm_first_body_ms'],'finish_reason':metrics[pre_turn]['llm_finish_reason'], 'simulated_media_duration_ms':playback_ms,'mic_audio_record':'not_run','music_video_playback':'not_run'} finally: server.should_exit=True with suppress(Exception): await asyncio.wait_for(task,5) if not task.done(): task.cancel();await asyncio.gather(task,return_exceptions=True) sock.close() # Exactly four additional requests: variation, negation, quotation, legacy unavailable. cases=[('dance_variation','请跳一小段舞,结束后自然问问我今天的安排。',True,'dance'), ('negation','不要跳舞,只说你好。',True,'none'), ('quotation','解释“请跳舞”这三个字的含义,不执行这句话。',True,'none'), ('legacy_unavailable','请跳一段舞。',False,'none')] for name,text,available,wanted in cases: system=SYSTEM_FRAGMENT+'\n'+ACTION_FRAGMENT+'\n网关实际可用动作:'+('dance' if available else '无') url,headers,body=provider.request([{'role':'system','content':system},{'role':'user','content':text}],max_tokens=160,action_plan=True) prefix=ExpressionPrefix(1);raw='';finish='not_provided';done=False;prepare=None;began=time.monotonic() async with client.stream('POST',url,headers=headers,json=body) as response: response.raise_for_status() async for line in response.aiter_lines(): if not line.startswith('data:'):continue payload=line[5:].strip() if payload=='[DONE]':done=True;break data=json.loads(payload) for choice in data.get('choices',[]): value=choice.get('finish_reason') if value is not None: finish=value if value in ('stop','length','content_filter','tool_calls','function_call') else 'unknown' delta=choice.get('delta',{}).get('content') or '';raw+=delta;assert len(raw)<=8192 if prefix.feed(delta,1) is not None:prepare=round((time.monotonic()-began)*1000,2) parsed=parse_action_reply(raw,finish,available) row={'case':name,'finish_reason':finish,'sse_done':done,'source':parsed.speech.source, 'action':parsed.action,'after_valid':parsed.after is not None,'prepare_ms':prepare, 'complete_ms':round((time.monotonic()-began)*1000,2),'header_final_consistent':prefix.consistent(parsed,1), 'expected_action_matched':parsed.action==wanted,'reply_chars':len(parsed.speech.reply)} if parsed.after: row['after_differs_from_chain']=parsed.after.reply!=after_text report['semantic_rows'].append(row) assert done and finish=='stop' and parsed.speech.source=='model' and parsed.action==wanted if wanted=='dance': assert parsed.after is not None assert report['llm_requests']==5 and report['tts_requests']==3 and report['asr_requests']==1 assert len(set(clocks))>=2 report['clock_refreshed_each_request']=True try: health=live_health() assert health.get('status')=='ok' and not health.get('busy'), 'busy_no_probe' report['live_health_before']={k:health.get(k) for k in ('version','busy','llm_model','llm_time_zone','llm_structured_output')} actual={name:digest(LIVE/name) for name in expected} assert actual==expected, 'live_source_drift_no_probe' pid=subprocess.check_output(['systemctl','--user','show','lan-voice-gateway.service','-p','MainPID','--value'],text=True).strip() private=LIVE/'.runtime' private_hashes={str(p):digest(p) for p in private.glob('*.env')} unit=subprocess.check_output(['systemctl','--user','cat','lan-voice-gateway.service']) env=dict(item.split('=',1) for item in Path('/proc/'+pid+'/environ').read_bytes().decode().split('\0') if '=' in item) # Private provider settings stay in this process; no env file/service is written. os.environ.update({k:v for k,v in env.items() if k.startswith('LAN_LLM_')}) with tempfile.TemporaryDirectory(prefix='action-public-calling-path-') as folder: stage=Path(folder) for name,content in sources.items(): (stage/name).write_bytes(base64.b64decode(content)) (stage/'web').mkdir() sys.path.insert(0,folder) asyncio.run(main(stage)) assert {name:digest(LIVE/name) for name in expected}==actual assert all(digest(Path(p))==value for p,value in private_hashes.items()) assert subprocess.check_output(['systemctl','--user','cat','lan-voice-gateway.service'])==unit assert subprocess.check_output(['systemctl','--user','show','lan-voice-gateway.service','-p','MainPID','--value'],text=True).strip()==pid report['live_source_env_unit_pid_unchanged']=True report['status']='passed' except Exception as error: report['error_type']=type(error).__name__ if isinstance(error,(AssertionError,RuntimeError)) and str(error) in ('busy_no_probe','live_source_drift_no_probe'): report['reason']=str(error) if isinstance(error,httpx.HTTPStatusError):report['http_status']=error.response.status_code print(json.dumps(report,ensure_ascii=False)) raise SystemExit(report['status']!='passed')