Recreate-AAA / bench_builder /lite_runtime.py
CharlieDreemur's picture
RecreateAAA 0.1.0 from Recreate-AAA/Recreate-AAA@7da1a3d
966b234 verified
Raw History Blame Contribute Delete
10 kB
"""Inspect the trusted host dependencies used by the WebGame Lite runtime.
Nothing here executes an untrusted agent. The native Agent harness is launched
through the separate exact-root Windows sandbox implementation.
"""
from __future__ import annotations
import json
import os
import re
import shutil
import stat
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Literal, Sequence
_CAPABILITY_SCHEMA = "program-bench.lite-runtime-capabilities.v1"
_PYTHON_VERSION = re.compile(r"Python\s+([0-9]+(?:\.[0-9]+){1,2})")
_NODE_VERSION = re.compile(r"v?([0-9]+(?:\.[0-9]+){1,2})")
class LiteRuntimeError(ValueError):
"""Raised when lightweight runtime inputs violate the public-only contract."""
@dataclass(frozen=True)
class LiteRuntimeCapabilityReport:
"""Frontend-safe capability summary; executable paths are intentionally absent."""
project_venv_ready: bool
node_ready: bool
playwright_ready: bool
chromium_ready: bool
python_version: str | None
node_version: str | None
playwright_version: str | None
node_source: Literal["project", "system", "missing"]
diagnostics: tuple[str, ...]
@property
def static_web_ready(self) -> bool:
return (
self.project_venv_ready
and self.playwright_ready
and self.chromium_ready
)
@property
def node_web_ready(self) -> bool:
return self.static_web_ready and self.node_ready
def to_dict(self) -> dict[str, Any]:
return {
"schema": _CAPABILITY_SCHEMA,
"project_venv_ready": self.project_venv_ready,
"node_ready": self.node_ready,
"playwright_ready": self.playwright_ready,
"chromium_ready": self.chromium_ready,
"static_web_ready": self.static_web_ready,
"node_web_ready": self.node_web_ready,
"python_version": self.python_version,
"node_version": self.node_version,
"playwright_version": self.playwright_version,
"node_source": self.node_source,
"diagnostics": list(self.diagnostics),
}
def _is_link_or_reparse(path: Path) -> bool:
try:
metadata = path.stat(follow_symlinks=False)
except OSError as exc:
raise LiteRuntimeError("Cannot inspect a lightweight runtime input.") from exc
reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)
return path.is_symlink() or bool(
reparse_flag and getattr(metadata, "st_file_attributes", 0) & reparse_flag
)
def _inside(path: Path, root: Path) -> bool:
return path == root or path.is_relative_to(root)
def _safe_regular_file(path: Path) -> bool:
try:
return path.is_file() and not _is_link_or_reparse(path)
except LiteRuntimeError:
return False
def _has_link_in_chain(path: Path) -> bool:
"""Detect a link/reparse point in an existing lexical path or its parents."""
current = path.absolute()
while True:
if current.exists() and _is_link_or_reparse(current):
return True
parent = current.parent
if parent == current:
return False
current = parent
def _probe_environment() -> dict[str, str]:
"""Minimal environment for trusted capability probes, excluding credentials."""
allowed = (
"COMSPEC",
"HOME",
"LOCALAPPDATA",
"PATH",
"PATHEXT",
"SYSTEMROOT",
"TEMP",
"TMP",
"USERPROFILE",
"WINDIR",
)
return {name: os.environ[name] for name in allowed if name in os.environ}
def _probe(
runner: Callable[..., Any],
argv: Sequence[str],
) -> Any:
return runner(
tuple(argv),
capture_output=True,
text=True,
timeout=10,
check=False,
shell=False,
env=_probe_environment(),
)
def _version_from_probe(
runner: Callable[..., Any],
argv: Sequence[str],
pattern: re.Pattern[str],
) -> str | None:
try:
result = _probe(runner, argv)
except (OSError, subprocess.SubprocessError):
return None
if getattr(result, "returncode", 1) != 0:
return None
output = f"{getattr(result, 'stdout', '')}\n{getattr(result, 'stderr', '')}"
match = pattern.search(output.strip())
return match.group(1) if match else None
def _default_venv_python(project_root: Path) -> Path:
windows = project_root / ".venv" / "Scripts" / "python.exe"
return windows if windows.exists() else project_root / ".venv" / "bin" / "python"
def _default_node(project_root: Path) -> tuple[Path | None, Literal["project", "system", "missing"]]:
candidates = (
project_root / ".node" / "node.exe",
project_root / ".node" / "bin" / "node",
project_root / "node_modules" / ".bin" / "node.exe",
project_root / "node_modules" / ".bin" / "node",
)
for candidate in candidates:
if _safe_regular_file(candidate):
return candidate, "project"
discovered = shutil.which("node")
if discovered:
return Path(discovered), "system"
return None, "missing"
def inspect_lite_runtime(
project_root: Path,
*,
python_executable: Path | None = None,
node_executable: Path | None = None,
runner: Callable[..., Any] = subprocess.run,
) -> LiteRuntimeCapabilityReport:
"""Inspect lightweight WebGame dependencies without launching a browser.
Python and Playwright must come from ``project_root/.venv``. Node may be a
project-local toolchain or a system executable; the report exposes only its
provenance category and version, never executable paths.
"""
root = Path(project_root).resolve()
venv_root = (root / ".venv").resolve()
python = Path(python_executable) if python_executable else _default_venv_python(root)
try:
resolved_python = python.resolve(strict=True)
except OSError:
resolved_python = python.resolve()
python_path_valid = (
(
_inside(resolved_python, venv_root)
and _safe_regular_file(python)
and not _has_link_in_chain(python)
)
if os.name == "nt"
else (
python.is_file()
and (venv_root / "pyvenv.cfg").is_file()
and _inside(python.absolute(), venv_root)
)
)
if not python_path_valid:
return LiteRuntimeCapabilityReport(
project_venv_ready=False,
node_ready=False,
playwright_ready=False,
chromium_ready=False,
python_version=None,
node_version=None,
playwright_version=None,
node_source="missing",
diagnostics=("Project-owned Python venv is unavailable.",),
)
diagnostics: list[str] = []
probe_python = python if os.name != "nt" else resolved_python
python_version = _version_from_probe(
runner, (str(probe_python), "--version"), _PYTHON_VERSION
)
project_venv_ready = python_version is not None
if not project_venv_ready:
diagnostics.append("Project-owned Python venv could not be verified.")
if node_executable is None:
node, node_source = _default_node(root)
else:
node = Path(node_executable)
try:
resolved_node = node.resolve(strict=True)
except OSError:
resolved_node = node.resolve()
node_source = "project" if _inside(resolved_node, root) else "system"
node_version: str | None = None
if node is not None and _safe_regular_file(node):
resolved_node = node.resolve()
node_version = _version_from_probe(
runner, (str(resolved_node), "--version"), _NODE_VERSION
)
node_ready = node_version is not None
if not node_ready:
node_source = "missing"
diagnostics.append("Node.js capability is unavailable.")
playwright_ready = False
chromium_ready = False
playwright_version: str | None = None
if project_venv_ready:
script = (
"import importlib.metadata,json\n"
"from pathlib import Path\n"
"from playwright.sync_api import sync_playwright\n"
"with sync_playwright() as p:\n"
" print(json.dumps({'playwright_version': "
"importlib.metadata.version('playwright'), "
"'chromium_installed': Path(p.chromium.executable_path).is_file()}))\n"
)
try:
result = _probe(runner, (str(probe_python), "-c", script))
lines = [line for line in str(getattr(result, "stdout", "")).splitlines() if line]
payload = json.loads(lines[-1]) if getattr(result, "returncode", 1) == 0 and lines else {}
if not isinstance(payload, dict):
payload = {}
raw_version = payload.get("playwright_version")
if isinstance(raw_version, str) and re.fullmatch(r"[0-9]+(?:\.[0-9]+){1,3}", raw_version):
playwright_version = raw_version
playwright_ready = True
chromium_ready = payload.get("chromium_installed") is True
except (ImportError, IndexError, json.JSONDecodeError, OSError, subprocess.SubprocessError):
pass
if not playwright_ready:
diagnostics.append("Project venv Playwright is unavailable.")
elif not chromium_ready:
diagnostics.append("Playwright Chromium is not installed.")
return LiteRuntimeCapabilityReport(
project_venv_ready=project_venv_ready,
node_ready=node_ready,
playwright_ready=playwright_ready,
chromium_ready=chromium_ready,
python_version=python_version,
node_version=node_version,
playwright_version=playwright_version,
node_source=node_source,
diagnostics=tuple(diagnostics),
)
__all__ = ["LiteRuntimeCapabilityReport", "LiteRuntimeError", "inspect_lite_runtime"]