#!/usr/bin/env python3 """Production Android AUTH/HELLO -> isolated existing ASGI gateway, no live services. Run with the existing gori-speech interpreter. Compiles Kotlin against deterministic Android main/transport/JSON adapters. All server identities and history are synthetic. """ import ast import argparse import asyncio import hashlib import json from pathlib import Path import shutil import subprocess import sys import tempfile ROOT=Path(__file__).resolve().parents[1] parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--gateway-source',type=Path,default=ROOT/'gateway', help='Existing canonical source or read-only snapshot; never changes/deploys the gateway') parser.add_argument('--unreviewed-index-sha',default='',help='Also replay actual no-action Liam HELLO and ready/pending offers of this unregistered pin') parser.add_argument('--reviewed-index-sha',default='',help='Existing registered exact pin to offer in actual production HELLO; does not change the registry') args=parser.parse_args() if args.unreviewed_index_sha: import re assert re.fullmatch('[0-9a-f]{64}',args.unreviewed_index_sha) if args.reviewed_index_sha: import re assert re.fullmatch('[0-9a-f]{64}',args.reviewed_index_sha) assert args.reviewed_index_sha in json.loads((args.gateway_source/'reviewed_action_packs.json').read_text()) gateway_root=args.gateway_source.resolve(strict=True) snapshot=gateway_root/'SNAPSHOT.json' if snapshot.exists(): for name,digest in json.loads(snapshot.read_bytes()).items(): path=(gateway_root/name).resolve(strict=True) assert path.is_relative_to(gateway_root) and hashlib.sha256(path.read_bytes()).hexdigest()==digest,'canonical snapshot drift' resolver=ast.parse((gateway_root/'persona_resolver.py').read_text()) registered=next(ast.literal_eval(n.value) for n in resolver.body if isinstance(n,ast.Assign) and any(isinstance(t,ast.Name) and t.id=='PERSONAS' for t in n.targets)) personas=['default','lvbu']+(['liam'] if 'liam' in registered else []) languages={p:json.loads((gateway_root/'personas'/registered[p][0]).read_bytes()).get('language','zh') for p in personas if p!='default'} assert all(value in ('zh','en','zh-en') for value in languages.values()) tree=ast.parse((ROOT/'scripts/check-reply-regressions.py').read_text()) nodes=[] for node in tree.body: if isinstance(node,ast.Assign) and any(isinstance(t,ast.Name) and t.id=='parser' for t in node.targets):break nodes.append(node) ns={'__file__':str(ROOT/'scripts/check-reply-regressions.py')} exec(compile(ast.Module(body=nodes,type_ignores=[]),'test-toolchain','exec'),ns) with tempfile.TemporaryDirectory(prefix='character-handshake-') as folder: stage=Path(folder) source=ROOT/'app/src/main/java/com/gorios/lanvoice' files=list((ROOT/'tests/character').glob('*.kt')) files+=[ROOT/'tests/session'/n for n in ('AndroidMain.kt','AndroidLog.kt','DebugUploadDouble.kt')] files+=[ROOT/'tests/protocol/JSONArrayDouble.kt'] files+=[source/n for n in ('net/DialogueClient.kt','net/DialogueProtocol.kt','diag/DiagnosticLog.kt', 'diag/StartupTrace.kt','avatar/ActionController.kt','dialogue/ReplyEmotion.kt', 'expression/FaceCueRules.kt','expression/ExpressionRules.kt','expression/PresenceRules.kt')] subprocess.run([ns['JAVA'],'-cp',ns['compiler'],'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler', '-no-stdlib','-no-reflect','-jvm-target','17','-nowarn','-classpath',ns['cp'], '-d',str(stage/'classes'),*map(str,files)],check=True) hello_file=stage/'hello.jsonl' subprocess.run([ns['JAVA'],'-Dcharacter.helloFile='+str(hello_file), '-Dcharacter.unreviewedPin='+args.unreviewed_index_sha, '-Dcharacter.reviewedPin='+args.reviewed_index_sha, '-Dcharacter.personas='+','.join(personas),'-cp', str(stage/'classes')+':'+ns['cp'],'HandshakeCheckKt'],check=True,timeout=30) hellos=[json.loads(row) for row in hello_file.read_text().splitlines()] for path in gateway_root.glob('*.py'):shutil.copyfile(path,stage/path.name) shutil.copyfile(gateway_root/'reviewed_action_packs.json',stage/'reviewed_action_packs.json') shutil.copytree(gateway_root/'personas',stage/'personas') (stage/'web').mkdir() (stage/'.runtime/personas').mkdir(parents=True) for persona in [p for p in personas if p!='default']+['yangmi_fiction']: (stage/'.runtime/personas'/ (persona+'.json')).write_text(json.dumps({'voice_id':'synthetic-'+persona})) # New interpreter: imports never reach a live gateway or its private configuration. runner=r''' import asyncio,json from pathlib import Path from unittest.mock import patch from fastapi.testclient import TestClient import gateway from action_protocol import configured_packs,negotiate,pending_pin from history import History from guest_sessions import GuestSessions state=gateway.app.state state.busy=False;state.token='synthetic-character-token-'+('x'*24) class NoInferenceModel: def new_state(self): return None def infer(self,*args): raise AssertionError('no ASR/VAD/model calls authorized by this fixture') state.model=NoInferenceModel();state.client=None;state.guests=GuestSessions() state.guest_enabled=False;state.lan_open=False;state.debug=None state.voices=[dict(id=v) for v in (gateway.DEFAULT_VOICE_ID,'synthetic-lvbu','synthetic-yangmi_fiction','synthetic-liam')] history=History(Path('synthetic.sqlite3'));asyncio.run(history.initialize());state.history=history client=TestClient(gateway.app) # no lifespan/model loading hellos=[json.loads(row) for row in Path('hello.jsonl').read_text().splitlines()] ids=[] sessions=[] original=gateway.Dialogue.send_history async def observe_session(self): sessions.append((self.persona,getattr(self,'persona_language','zh'),self.voice_id)) await original(self) gateway.Dialogue.send_history=observe_session for hello in hellos: with patch('gateway.load_active_profile',return_value={'persona':'yangmi_fiction','voice_id':'synthetic-yangmi_fiction'}) as profile: with client.websocket_connect('/ws/dialogue',headers={'Origin':'https://192.168.31.61:5011'}) as ws: ws.send_json(dict(type='auth',token=state.token));assert ws.receive_json()['type']=='auth' ws.send_json(hello) ack=ws.receive_json();assert ack['type']=='hello' persona=hello['persona'] expected_voice='synthetic-'+(persona if persona!='default' else 'yangmi_fiction') assert ack['voice_id']==expected_voice assert profile.call_count==(1 if persona=='default' else 0) assert ack['action_available']==bool(negotiate(hello,configured_packs())) assert ack['action_pending']==bool(pending_pin(hello,configured_packs())) if REVIEWED: assert ack['action_available']==('action_pack_sha256' in hello) assert ack['action_pending']==('action_pending_pack_sha256' in hello) if hello.get('action_pack_sha256')==UNREVIEWED or hello.get('action_pending_pack_sha256')==UNREVIEWED: assert not ack['action_available'] and not ack['action_pending'] assert ack['conversation_id'] not in ids;ids.append(ack['conversation_id']) assert ws.receive_json()['type']=='history' assert sessions[-1]==('yangmi_fiction' if persona=='default' else persona, LANGUAGES.get(persona,'zh'),expected_voice) if hello.get('action_pending_pack_sha256'): pin=hello['action_pending_pack_sha256'] ws.send_json(dict(type='client.capabilities.ready',action_protocol=1,action_pack_sha256=pin,action_kinds=['dance'])) ready=ws.receive_json() assert ready['type']=='client.capabilities' assert ready['action_available']==bool(pending_pin(hello,configured_packs())) assert ready['action_pack_sha256']==(pin if pending_pin(hello,configured_packs()) else '') assert all(k in ready for k in ('turn_id','seq','server_ms')) assert state.busy is False, 'disconnect did not release existing gateway busy owner' # A non-default persona stays server-locked even if a caller offers another voice/CID. for persona in sorted({x['persona'] for x in hellos}-{'default'}): hello=next(x for x in hellos if x['persona']==persona and 'action_pack_sha256' in x) with patch('gateway.load_active_profile',side_effect=AssertionError('explicit persona must ignore global profile')): with client.websocket_connect('/ws/dialogue',headers={'Origin':'https://192.168.31.61:5011'}) as ws: ws.send_json(dict(type='auth',token=state.token));ws.receive_json() ws.send_json(dict(hello,voice_id=gateway.DEFAULT_VOICE_ID,conversation_id=ids[0])) ack=ws.receive_json() assert ack['voice_id']=='synthetic-'+persona and ack['conversation_id'] not in ids ws.receive_json();ids.append(ack['conversation_id']) assert state.busy is False print('PASS: '+str(len(ids))+' canonical ASGI WS handshakes from actual Android HELLO; personas='+','.join(sorted({x["persona"] for x in hellos}))+'; server_languages='+json.dumps(LANGUAGES,sort_keys=True)+'; explicit persona ignores active_profile, server-locks voice/language, fresh CID, ready/pending exact pin, pending-to-ready ACK and disconnect busy cleanup; 0 ASR/LLM/TTS calls, synthetic-only') '''.replace('UNREVIEWED',repr(args.unreviewed_index_sha)).replace('REVIEWED',repr(args.reviewed_index_sha)).replace('LANGUAGES',repr(languages)) subprocess.run([sys.executable,'-c',runner],cwd=stage,check=True,timeout=30)