#!/usr/bin/env python3 """Install or inspect the assistant's pinned, project-local runtime without model calls.""" import argparse import hashlib import json import os from pathlib import Path import platform import re import shutil import subprocess ROOT = Path(__file__).resolve().parents[1] PYTHON_VERSION = '3.11.15' def locked_packages(lock): packages = {} for line in lock.read_text().splitlines(): match = re.match(r'^([A-Za-z0-9_.-]+)==([^\s;\\]+)', line) if match: packages[match[1].lower().replace('_', '-')] = match[2] if packages.get('nao-core') != '0.3.26' or not packages.get('duckdb'): raise RuntimeError('The assistant dependency lock is incomplete.') return packages def inspect_runtime(root=ROOT): target = root / '.runtime/nao-trial/venv' python = target / 'bin/python' if not python.is_file(): raise RuntimeError('Assistant runtime is missing. Run python3 scripts/setup_nao_runtime.py.') expected = locked_packages(root / 'requirements-nao.lock') probe = '''import importlib.metadata as m,json,sys import duckdb,yaml,fastapi print(json.dumps({'python':'.'.join(map(str,sys.version_info[:3])), 'packages':{d.metadata['Name'].lower().replace('_','-'):d.version for d in m.distributions()}}))''' result = subprocess.run([str(python), '-c', probe], capture_output=True, text=True, timeout=30) if result.returncode: raise RuntimeError('Assistant runtime imports failed; the existing environment was preserved.') state = json.loads(result.stdout) if state['python'] != PYTHON_VERSION: raise RuntimeError('Assistant Python version differs from the accepted runtime; stop assistant work before replacing it.') mismatches = [name for name, version in expected.items() if state['packages'].get(name) != version] if mismatches: raise RuntimeError('Assistant dependencies differ from the lock: ' + ', '.join(mismatches) + '. The existing environment was preserved; replace it only after stopping assistant work.') package = target / 'lib/python3.11/site-packages/nao_core' binary = package / 'bin/nao-chat-server' if not binary.is_file() or not os.access(binary, os.X_OK) or not (package / 'bin/fastapi/main.py').is_file(): raise RuntimeError('Assistant packaged servers are missing or not executable.') smoke = subprocess.run([str(binary), '--help'], capture_output=True, timeout=20) if smoke.returncode: raise RuntimeError('Assistant native server could not run on this host.') return {'python': state['python'], 'naoCore': expected['nao-core'], 'lockedPackages': len(expected), 'lockSha256': hashlib.sha256((root / 'requirements-nao.lock').read_bytes()).hexdigest(), 'importsVerified': True, 'nativeServerVerified': True, 'modelContacted': False} def install(root=ROOT): if platform.system() != 'Darwin' or platform.machine() != 'arm64' or int(platform.mac_ver()[0].split('.')[0]) < 15: raise RuntimeError('This assistant runtime lock targets macOS 15+ on Apple Silicon.') target = root / '.runtime/nao-trial/venv' if target.exists(): result = inspect_runtime(root) print('Assistant runtime already matches the lock; existing sessions were preserved.') return result uv = shutil.which('uv') if not uv: raise RuntimeError('Install uv using https://docs.astral.sh/uv/getting-started/installation/ and run this command again.') lock = root / 'requirements-nao.lock' locked_packages(lock) target.parent.mkdir(parents=True, exist_ok=True) subprocess.run([uv, 'venv', '--python', PYTHON_VERSION, str(target)], check=True) # Only a newly created environment is synchronized. Never change a running user's environment. subprocess.run([uv, 'pip', 'sync', '--python', str(target / 'bin/python'), '--require-hashes', '--only-binary', ':all:', str(lock)], check=True) subprocess.run([uv, 'pip', 'check', '--python', str(target / 'bin/python')], check=True) result = inspect_runtime(root) print('Assistant runtime installed and checked; no model credentials or business data were used.') return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--check', action='store_true', help='Inspect existing dependencies without installing anything') args = parser.parse_args() result = inspect_runtime() if args.check else install() print(json.dumps(result, ensure_ascii=False)) if __name__ == '__main__': main()