"""Install and inspect the project's pinned DSH runtime without model credentials. Install: python scripts/setup_dsh_runtime.py --node /path/to/node24 Inspect: python scripts/setup_dsh_runtime.py --check The executable is copied into the project; runtime use never needs an output trial. """ from __future__ import annotations import argparse import hashlib import json import os from pathlib import Path import platform import shutil import subprocess import sys ROOT = Path(__file__).resolve().parents[1] RUNTIME = ROOT / 'runtime/dsh' VERSION = '0.2.2-rc.1' COMMIT = 'fcc0ad462172522aaf5c93a7b2e01f6b9f0b0159' def runtime_node(): """Return the explicitly installed project executable, never an ambient Node 22.""" return RUNTIME / 'bin' / ('node.exe' if os.name == 'nt' else 'node') def inspect_runtime(): """Read local identities and dependency availability without starting a model.""" errors = [] node = runtime_node() if not node.is_file() or not os.access(node, os.X_OK): errors.append('项目内 Node 24.9+ 未安装;运行 scripts/setup_dsh_runtime.py --node 。') else: try: output = subprocess.run([str(node), '--version'], capture_output=True, text=True, timeout=10, check=True).stdout.strip() numbers = tuple(int(x) for x in output.lstrip('v').split('.')[:3]) if numbers < (24, 9, 0): errors.append('DSH 要求 Node 24.9+。') except Exception: errors.append('项目内 Node 无法启动。') for package in ('dsh', 'dsh-sdk-minimal', 'dsh-sdk-jsonrpc-server', 'dsh-llm-pi-ai', 'dsh-mcp-client'): path = RUNTIME / 'node_modules/@deepseek-ai' / package / 'package.json' try: if json.loads(path.read_text())['version'] != VERSION: errors.append('DSH 依赖版本不匹配:' + package) except (OSError, ValueError, KeyError): errors.append('DSH 依赖未安装:' + package) vendor = RUNTIME / 'vendor/python-sdk' try: lock = json.loads((vendor / 'source-lock.json').read_text()) if lock['commit'] != COMMIT: raise ValueError('commit') for name, expected in lock['sdkFiles'].items(): if hashlib.sha256((vendor / 'deepseek_harness' / name).read_bytes()).hexdigest() != expected: raise ValueError('hash') except (OSError, ValueError, KeyError): errors.append('锁定 Python SDK 校验失败。') try: import pydantic if tuple(int(x) for x in pydantic.__version__.split('.')[:2]) < (2, 12) or int(pydantic.__version__.split('.')[0]) != 2: errors.append('DSH Python SDK 要求 pydantic>=2.12,<3。') except ImportError: errors.append('缺少 pydantic>=2.12,<3。') if sys.version_info < (3, 10): errors.append('DSH Python SDK 要求 Python 3.10+。') if platform.system() != 'Darwin' or not Path('/usr/bin/sandbox-exec').is_file(): errors.append('当前仅支持已实现的 macOS sandbox-exec 隔离;Linux/Windows须先提供并验证等效隔离。') if not (RUNTIME / 'stream-bridge.mjs').is_file(): errors.append('缺少受控流桥。') return {'ready': not errors, 'errors': errors, 'version': VERSION, 'sdkCommit': COMMIT, 'platform': platform.system(), 'node': str(node), 'runtime': str(RUNTIME)} def check_runtime(*, launch=False): """Inspect; optionally initialize the real SDK, MCP and stream plugin without inference.""" result = inspect_runtime() if launch and result['ready']: try: from dsh_agent_runtime import startup_smoke result['startup'] = startup_smoke() if not result['startup'].get('ready'): result['ready'] = False result['errors'].append('DSH 插件启动未通过。') except Exception as error: result['ready'] = False result['errors'].append('DSH 插件启动失败:' + type(error).__name__) return result def install(node_path=None, *, offline=False): selected = Path(node_path or (runtime_node() if runtime_node().is_file() else shutil.which('node')) or '').expanduser().resolve() version = subprocess.run([str(selected), '--version'], check=True, capture_output=True, text=True).stdout.strip() if tuple(int(x) for x in version.lstrip('v').split('.')[:3]) < (24, 9, 0): raise ValueError('请通过 --node 指定 Node 24.9+;不会下载或替换全局 Node。') runtime_node().parent.mkdir(parents=True, exist_ok=True) if selected != runtime_node(): shutil.copy2(selected, runtime_node()) runtime_node().chmod(0o755) npm = shutil.which('npm') if npm is None: raise FileNotFoundError('npm unavailable') env = os.environ.copy() env['PATH'] = str(runtime_node().parent) + os.pathsep + env.get('PATH', '') # The quality profile never enables PTY/terminal/plugin installation. Its # exercised closure needs no dependency lifecycle scripts. command = [npm, 'ci', '--ignore-scripts', '--no-audit', '--no-fund'] if offline: command.append('--offline') subprocess.run(command, cwd=RUNTIME, env=env, check=True) return check_runtime(launch=True) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--node') parser.add_argument('--check', action='store_true') parser.add_argument('--offline', action='store_true') args = parser.parse_args() result = check_runtime(launch=True) if args.check else install(args.node, offline=args.offline) print(json.dumps(result, ensure_ascii=False, indent=2)) return 0 if result['ready'] else 1 if __name__ == '__main__': raise SystemExit(main())