Files
baji-vc/scripts/collect-voice-evidence.py
T

210 lines
10 KiB
Python

#!/usr/bin/env python3
"""Run in this workspace's ordinary shell. Read-only remote inspection, no credentials/log bodies saved."""
import io
import json
import os
import re
import ssl
import subprocess
import sys
import tarfile
import urllib.error
import urllib.request
from pathlib import Path
REMOTE_ROOT = Path('/home/gorios-spark-2/lan-voice')
HOST = 'gorios-spark-2@192.168.31.61'
SERVICE = re.compile(r'lan.?voice|gateway|stt|tts|qwen|vllm|asr|cosy', re.I)
def command(args, cwd=None):
try:
result = subprocess.run(args, cwd=cwd, capture_output=True, timeout=20)
return result.returncode, result.stdout.decode(errors='replace'), result.stderr.decode(errors='replace')
except (OSError, subprocess.TimeoutExpired) as error:
return -1, '', type(error).__name__
def log_metadata(entry):
if not isinstance(entry, dict):
entry = {'message': str(entry)}
msg = str(entry.get('msg', entry.get('message', entry.get('MESSAGE', ''))))
# Do not print arbitrary messages, recognitions, prompts, completions or exception bodies.
prefixes = ('onEvent', 'acceptTurn', 'ABORT', 'LISTEN', 'AudioRecord', 'startCapture',
'capture start', 'connection', 'finish', 'ws', 'auth', 'hello', 'health',
'state=', 'downlink', 'voice button', 'microphone', 'activity', 'session',
'foreground', 'app_launch', 'send_report')
event = next((p for p in prefixes if msg.startswith(p)), 'redacted')
for phase in ('capture.end', 'llm.finished', 'tts.start', 'tts.stop', 'playback.drained',
'ws open', 'hello received', 'hello sent', 'auth ok', 'ws closed', 'ws failure',
'initialization ok', 'startRecording ok'):
if phase in msg:
event = phase
break
result = {'event': event}
for key in ('ts', 'timestamp_ms', '__REALTIME_TIMESTAMP'):
if str(entry.get(key, '')).isdigit():
result[key] = int(entry[key])
tag = entry.get('tag')
if tag in ('connect', 'ws', 'auth', 'audio', 'error'):
result['tag'] = tag
numeric = r'turn_id|turn|oldTurn|currentTurn|nextTurn|blockedTurn|nextBlocked|id|seq|epoch|retired|retiredNow|frames|bytes|samples|duration_ms|elapsed_ms|latency_ms|rtf|status|code'
for match in re.finditer(r'\b(' + numeric + r')=(-?\d+(?:\.\d+)?|null)\b', msg):
result[match[1]] = match[2]
for key in ('kind', 'state', 'phase', 'reason', 'active', 'capturing', 'hasTurn',
'accepted', 'listenReset', 'released', 'permission', 'changingConfig'):
match = re.search(r'\b' + key + r'=([A-Za-z_][A-Za-z_0-9:.-]{0,70}|true|false|null)\b', msg)
if match:
# Only structural identifiers; no arbitrary quoted/free-text values.
result[key] = match[1]
statuses = re.findall(r'\b(?:CONNECTED|DISCONNECTED|CONNECTING|BUSY)\b', msg)
if statuses:
result['connection_states'] = statuses
code = re.search(r'\b(?:closed:|HTTP)\s*(\d{3,4})\b', msg)
if code:
result['http_or_close_code'] = int(code[1])
result['exception_types'] = sorted(set(re.findall(r'\b[A-Z][A-Za-z]*(?:Exception|Error)\b', msg)))
return result
def items(value, keys):
if isinstance(value, list):
return value
if isinstance(value, dict):
for key in keys:
if isinstance(value.get(key), list):
return value[key]
return [value] if isinstance(value, dict) else []
def remote_evidence():
ctx = ssl.create_default_context(cafile=str(REMOTE_ROOT / '.runtime/gateway-cert.pem'))
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), urllib.request.HTTPSHandler(context=ctx))
result = {}
for endpoint in ('health', 'debug/report', 'debug/log'):
try:
with opener.open('https://192.168.31.61:5011/' + endpoint, timeout=5) as response:
data = response.read(2_000_001)
if len(data) > 2_000_000:
raise ValueError('response exceeds bounded inspection size')
data = json.loads(data)
if endpoint == 'debug/report':
reports = []
for wrapped in items(data, ('reports', 'items', 'entries')):
if not isinstance(wrapped, dict):
continue
report = wrapped.get('report', wrapped)
if isinstance(report, dict) and report.get('logs'):
reports.append(report)
report = max(reports, key=lambda r: float(r.get('timestamp', 0)), default=None)
if report:
summary = {key: report.get(key) for key in ('timestamp', 'app_version', 'device',
'android_api', 'connection', 'voice_active', 'phase', 'aec')}
summary['logs'] = [log_metadata(e) for e in report['logs'][-500:]]
result[endpoint] = summary
else:
result[endpoint] = {'nonempty_report_found': False, 'response_keys': list(data)[:20] if isinstance(data, dict) else []}
elif endpoint == 'debug/log':
result[endpoint] = [log_metadata(e) for e in items(data, ('logs', 'items', 'entries'))[-100:]]
else:
result[endpoint] = {key: data.get(key) for key in ('status', 'version', 'ok')}
except Exception as error:
result[endpoint] = {'error_type': type(error).__name__, 'http_status': getattr(error, 'code', None)}
code, status, _ = command(['docker', 'ps', '--format', '{{.Names}}\t{{.Status}}'])
result['containers_status'] = [line for line in status.splitlines() if SERVICE.search(line)]
result['docker_exit'] = code
result['container_logs'] = {}
for line in result['containers_status']:
name = line.split('\t')[0]
_, out, err = command(['docker', 'logs', '--since', '20m', '--tail', '150', name])
result['container_logs'][name] = [log_metadata(s) for s in (out + err).splitlines()]
result['systemd'] = []
result['journal'] = {}
for user in (False, True):
prefix = ['systemctl'] + (['--user'] if user else [])
_, out, _ = command(prefix + ['list-units', '--all', '--type=service', '--no-pager', '--no-legend', '--plain'])
for line in out.splitlines():
if not SERVICE.search(line):
continue
result['systemd'].append({'user': user, 'status': line.strip()})
unit = line.strip().split()[0]
_, journal, _ = command(['journalctl'] + (['--user'] if user else []) +
['-u', unit, '--since', '-20min', '-n', '400', '--no-pager', '-o', 'json'])
result['journal'][unit] = []
for record in journal.splitlines():
try:
result['journal'][unit].append(log_metadata(json.loads(record)))
except ValueError:
pass
print(json.dumps(result, ensure_ascii=False, indent=2))
def remote_sources():
# Deployment directories may have no tracked files. Inspect live source files,
# with explicit exclusions, instead of assuming this is a populated Git checkout.
paths = []
excluded = {'models', 'data', 'assets', 'voices', 'lorebooks', 'node_modules',
'venv', '__pycache__', 'logs', 'artifacts', 'build', 'dist'}
for base, directories, files in os.walk(REMOTE_ROOT, followlinks=False):
directories[:] = [d for d in directories if not d.startswith('.') and d not in excluded
and not (Path(base) / d).is_symlink()]
for name in files:
if Path(name).suffix in ('.py', '.toml') or name == 'AGENTS.md':
paths.append((Path(base) / name).relative_to(REMOTE_ROOT))
if not paths:
raise RuntimeError('no live gateway Python sources found')
total = 0
with tarfile.open(fileobj=sys.stdout.buffer, mode='w|gz') as archive:
for relative in sorted(paths):
path = Path(relative)
if path.is_absolute() or '..' in path.parts or path.suffix not in ('.py', '.toml') and path.name != 'AGENTS.md':
continue
if any(part.startswith('.') or part in ('models', 'data', 'assets', 'voices', 'lorebooks') for part in path.parts):
continue
source = REMOTE_ROOT / path
if source.is_symlink() or not source.is_file() or source.stat().st_size > 1_000_000:
continue
total += source.stat().st_size
if total > 12_000_000:
raise RuntimeError('gateway source snapshot exceeds 12MB')
archive.add(source, arcname=relative, recursive=False)
def local():
root = Path(__file__).resolve().parents[1]
output = root / 'logs/voice-investigation'
output.mkdir(parents=True, exist_ok=True)
source = Path(__file__).read_bytes()
ssh = ['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5', HOST, 'python3', '-']
for mode in ('--remote-evidence', '--remote-sources'):
result = subprocess.run(ssh + [mode], input=source, capture_output=True, timeout=180)
if result.returncode:
# SSH diagnostics contain no report, chat or credential bodies.
print(result.stderr.decode(errors='replace')[-1000:], file=sys.stderr)
raise SystemExit(result.returncode)
if mode == '--remote-evidence':
summary = json.loads(result.stdout)
(output / 'evidence.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n')
else:
destination = output / 'backend-source'
destination.mkdir(exist_ok=True)
with tarfile.open(fileobj=io.BytesIO(result.stdout), mode='r:gz') as archive:
for member in archive:
path = Path(member.name)
if not member.isfile() or path.is_absolute() or '..' in path.parts:
raise RuntimeError('unsafe source archive entry')
target = destination / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(archive.extractfile(member).read())
print('Saved redacted evidence and gateway sources to logs/voice-investigation/ (git ignored).')
if __name__ == '__main__':
if '--remote-evidence' in sys.argv:
remote_evidence()
elif '--remote-sources' in sys.argv:
remote_sources()
else:
local()