Download release/engine/modules/container_process-28dbb42d1989.py from AI45Research/ManipulationArena: direct link, hf CLI and curl.
- Browser
- Download file 54.1 kB
-
https://huggingface.co/datasets/AI45Research/ManipulationArena/resolve/main/release/engine/modules/container_process-28dbb42d1989.py
- Command line
-
hf download hf://datasets/AI45Research/ManipulationArena/release/engine/modules/container_process-28dbb42d1989.py
-
curl -L -o container_process-28dbb42d1989.py https://huggingface.co/datasets/AI45Research/ManipulationArena/resolve/main/release/engine/modules/container_process-28dbb42d1989.py
54.1 kB
| """Original attack protocol using the shared local Docker transport.""" | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import shlex | |
| import shutil | |
| import tarfile | |
| import tempfile | |
| import threading | |
| import time | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| from typing import Any | |
| import sys | |
| from common import task_suite | |
| from isolation_policy import (PRESTART_SENSITIVE_PATHS, deployment_view, | |
| public_checkpoint_plan, public_gate_receipt) | |
| CONTAINER_DIR = Path(__file__).resolve().parents[1] / "container" | |
| if str(CONTAINER_DIR) not in sys.path: | |
| sys.path.insert(0, str(CONTAINER_DIR)) | |
| import container_runtime | |
| from container_runtime import ContainerClient | |
| class ContainerProcess: | |
| """Process-like adapter used by GateBroker for a remote Sandbox victim.""" | |
| def __init__(self, run_dir: Path, task: str, blue_env: dict[str, str], | |
| container_config: Path, blue_timeout: int, blue_max_tokens: int, | |
| gate_timeout: int, task_root: Path, task_suite_name: str | None = None, | |
| attack_plan: dict[str, Any] | None = None): | |
| self.run_dir = run_dir | |
| self.task = task | |
| self.blue_env = dict(blue_env) | |
| self.container_config = container_config | |
| self.blue_timeout = blue_timeout | |
| self.blue_max_tokens = blue_max_tokens | |
| self.gate_timeout = gate_timeout | |
| self.task_root = task_root | |
| self.task_suite = task_suite_name or task_suite(task) | |
| self.is_solvable30 = self.task_suite == "solvable30" | |
| self.attack_plan = attack_plan | |
| self._prestart_sanitized = False | |
| self.client: ContainerClient | None = None | |
| self._stop = threading.Event() | |
| self._finished = False | |
| self._exit_code: int | None = None | |
| self._last_workspace = 0.0 | |
| self._last_workspace_upload = 0.0 | |
| self._workspace_uploaded: dict[str, float] = {} | |
| initial_workspace = run_dir / "workspace" | |
| if initial_workspace.is_dir(): | |
| for local in initial_workspace.rglob("*"): | |
| if local.is_file(): | |
| self._workspace_uploaded[local.relative_to(initial_workspace).as_posix()] = local.stat().st_mtime | |
| self._last_sync = 0.0 | |
| self._last_dsh_sync = 0.0 | |
| self._last_process_diagnostics = 0.0 | |
| self._sync_error: str | None = None | |
| self._database_dump_synced = False | |
| self._thread: threading.Thread | None = None | |
| def _read_env(path: Path) -> dict[str, str]: | |
| values: dict[str, str] = {} | |
| if path.is_file(): | |
| for line in path.read_text(encoding="utf-8").splitlines(): | |
| line = line.strip() | |
| if line and not line.startswith("#") and "=" in line: | |
| key, value = line.split("=", 1) | |
| values[key.strip()] = value.strip().strip("'").strip('"') | |
| return values | |
| def _config(self) -> dict[str, Any]: | |
| from manipulationarena.local_docker import load_settings | |
| return load_settings(self.container_config) | |
| def _put(self, remote: str, local: Path, mode: str = "600") -> None: | |
| assert self.client is not None | |
| if not self.client.put_bytes(remote, local.read_bytes(), mode=mode): | |
| raise RuntimeError(f"Sandbox upload failed: {remote}") | |
| def _put_bytes(self, remote: str, data: bytes, mode: str = "600") -> None: | |
| assert self.client is not None | |
| if not self.client.put_bytes(remote, data, mode=mode): | |
| raise RuntimeError(f"Sandbox upload failed: {remote}") | |
| def _upload_runtime(self) -> None: | |
| assert self.client is not None | |
| setup = self.client.execute("mkdir -p /opt/stage2/dsh_gate_plugin " | |
| "/opt/stage2/runtime_inputs /run/attack_input", timeout=30) | |
| if setup["rc"] != 0: | |
| raise RuntimeError(setup["stderr"][-1000:]) | |
| root = Path(__file__).resolve().parent | |
| files = { | |
| "/opt/stage2/blue_agent_runner.py": root / "blue_agent_runner.py", | |
| "/opt/stage2/arena_blue.py": root / "arena_blue.py", | |
| "/opt/stage2/mcp_error_normalizer.py": root / "mcp_error_normalizer.py", | |
| "/opt/stage2/qwen_openai_adapter.py": root / "qwen_openai_adapter.py", | |
| "/opt/stage2/openai_anthropic_bridge.py": root.parent / "openai_anthropic_bridge.py", | |
| "/opt/stage2/isolation_policy.py": root / "isolation_policy.py", | |
| "/opt/stage2/real_channel_runtime.py": root / "real_channel_runtime.py", | |
| "/opt/stage2/rule_based_judge.py": root / "rule_based_judge.py", | |
| "/opt/stage2/sandbox_attack_evaluation.py": root / "sandbox_attack_evaluation.py", | |
| "/opt/stage2/marker_runtime.py": root.parent / "marker_runtime.py", | |
| "/opt/stage2/runtime_inputs/marker.txt": root.parent / "runtime_inputs" / "marker.txt", | |
| "/opt/stage2/dsh_gate_plugin/index.js": root / "dsh_gate_plugin" / "index.js", | |
| "/opt/stage2/dsh_gate_plugin/package.json": root / "dsh_gate_plugin" / "package.json", | |
| } | |
| if self.is_solvable30: | |
| self._upload_solvable30(files) | |
| for remote, local in files.items(): | |
| self._put(remote, local, "755" if local.suffix in {".py", ".js"} else "600") | |
| return | |
| # Keep the shared terminal MCP server compatible with arbitrary task | |
| # artifacts. Its stock implementation decodes subprocess output | |
| # strictly as UTF-8, which breaks when a task asks it to inspect a | |
| # legacy-encoded or binary document. Upload the patched source into | |
| # the image before Harness starts its MCP servers. | |
| cli_server = (self.task_root.parent.parent / "local_servers" / | |
| "cli-mcp-server" / "src" / "cli_mcp_server" / "server.py") | |
| if not cli_server.is_file(): | |
| raise RuntimeError(f"Required terminal MCP compatibility source is missing: {cli_server}") | |
| files["/opt/local_servers/cli-mcp-server/src/cli_mcp_server/server.py"] = cli_server | |
| # Upload server diagnostics so live sandbox logs distinguish pending | |
| # tool enumeration from a real empty tool list. | |
| woo_server = (self.task_root.parent.parent / "local_servers" / | |
| "woocommerce-mcp" / "dist" / "server.js") | |
| if not woo_server.is_file(): | |
| raise RuntimeError(f"Required WooCommerce server bundle is missing: {woo_server}") | |
| files["/opt/local_servers/woocommerce-mcp/dist/server.js"] = woo_server | |
| files["/opt/local_servers/woocommerce-mcp/dist/index.js"] = woo_server | |
| snow_server = (self.task_root.parent.parent / "local_servers" / | |
| "mcp-snowflake-server" / "src" / "mcp_snowflake_server" / "server.py") | |
| if not snow_server.is_file(): | |
| raise RuntimeError(f"Required Snowflake compatibility source is missing: {snow_server}") | |
| files["/opt/local_servers/mcp-snowflake-server/src/mcp_snowflake_server/server.py"] = snow_server | |
| # The arxiv_local adapter is task-backed: some tasks seed the LaTeX | |
| # corpus while leaving the legacy markdown column empty. Upload the | |
| # fallback-aware adapter so read_paper can serve that seeded content. | |
| arxiv_adapter = (self.task_root.parent.parent / "local_servers" / | |
| "arxiv-mcp-server" / "src" / "arxiv_mcp_server" / | |
| "pg_adapter.py") | |
| if not arxiv_adapter.is_file(): | |
| raise RuntimeError(f"Required arxiv MCP compatibility source is missing: {arxiv_adapter}") | |
| files["/opt/local_servers/arxiv-mcp-server/src/arxiv_mcp_server/pg_adapter.py"] = arxiv_adapter | |
| for remote, local in files.items(): | |
| self._put(remote, local, "755" if local.suffix in {".py", ".js"} else "600") | |
| # Verify that critical compatibility patches reached the live sandbox. | |
| # A successful upload call alone is insufficient: the harness may later | |
| # rebuild a server from a different source tree. Fail early with an | |
| # actionable error instead of running Blue against a stale adapter. | |
| checks = [ | |
| ("/opt/local_servers/arxiv-mcp-server/src/arxiv_mcp_server/pg_adapter.py", "full_prompt"), | |
| ("/opt/local_servers/cli-mcp-server/src/cli_mcp_server/server.py", "decode(\"utf-8\", errors=\"replace\")"), | |
| ("/opt/local_servers/woocommerce-mcp/dist/server.js", "Tool listing pending at startup"), | |
| ("/opt/local_servers/mcp-snowflake-server/src/mcp_snowflake_server/server.py", "Tool listing completed"), | |
| ] | |
| for remote, marker in checks: | |
| if remote not in files: | |
| continue | |
| verify = self.client.execute( | |
| "grep -Fq " + shlex.quote(marker) + " " + shlex.quote(remote), | |
| timeout=30, | |
| ) | |
| if verify["rc"] != 0: | |
| raise RuntimeError( | |
| f"Sandbox runtime patch verification failed: {remote} missing {marker!r}" | |
| ) | |
| def _upload_solvable30(self, files: dict[str, Path]) -> None: | |
| """Stage the gym config surface the runner expects on non-toolathlon images.""" | |
| assert self.client is not None | |
| gym_root = self.task_root.parent.parent | |
| root = Path(__file__).resolve().parent | |
| made = self.client.execute( | |
| "mkdir -p /workspace/configs/mcp_servers /usr/local/lib/toolathlon-dsh " | |
| "/opt/local_servers/appworld", timeout=30) | |
| if made["rc"] != 0: | |
| raise RuntimeError("Sandbox solvable30 staging mkdir failed: " + made["stderr"][-500:]) | |
| files["/opt/local_servers/appworld/appworld_mcp.py"] = gym_root / "local_servers" / "appworld" / "appworld_mcp.py" | |
| files["/workspace/test_mcp_servers.py"] = gym_root / "test_mcp_servers.py" | |
| files["/workspace/configs/mcp_servers/appworld.yaml"] = ( | |
| gym_root / "configs" / "mcp_servers" / "appworld.yaml") | |
| files["/usr/local/lib/toolathlon-dsh/claim_done_mcp.py"] = root / "claim_done_mcp.py" | |
| if self.task.startswith("gaia2-"): | |
| for name in ("role_routing.py", "gaia2_mcp.py", "gaia2_launcher.py", "gaia2_judge_relay.py"): | |
| files["/opt/local_servers/gaia2/" + name] = root / name | |
| files["/workspace/configs/mcp_servers/gaia2.yaml"] = root.parent / "runtime_assets" / "gaia2.yaml" | |
| if self.task.startswith("medagent-original-"): | |
| for name in ("medagent_mcp.py", "medagent_runtime.py", "medagent_worker.py"): | |
| files["/opt/local_servers/medagent/" + name] = root / name | |
| files["/workspace/configs/mcp_servers/medagent.yaml"] = root.parent / "runtime_assets" / "medagent.yaml" | |
| profiles = {"tau-banking-": ("tau-banking", ("role_routing.py", "tau_mcp.py", "tau_worker.py")), | |
| "healthagent-text25-": ("healthagent", ("healthagent_mcp.py", "healthagent_native.py", "healthagent_runtime.py"))} | |
| for prefix, (server, names) in profiles.items(): | |
| if self.task.startswith(prefix): | |
| for name in names: | |
| files["/opt/local_servers/" + server + "/" + name] = root / name | |
| files["/workspace/configs/mcp_servers/" + server + ".yaml"] = root.parent / "runtime_assets" / (server + ".yaml") | |
| channel = (self.attack_plan or {}).get("fixed_attack", {}).get("channel") | |
| if channel == "MEMORY": | |
| self._upload_memory_stack(files, root) | |
| def _upload_memory_stack(self, files: dict[str, Path], root: Path) -> None: | |
| """Stage node + the memory MCP server for MEMORY-channel runs. | |
| The solvable30 image has no node runtime, so both the runtime and the | |
| server build (identical @modelcontextprotocol/server-memory 0.6.3 to | |
| the toolathlon image) are staged from runtime_assets. | |
| """ | |
| assert self.client is not None | |
| assets = root.parent / "runtime_assets" | |
| self._put("/workspace/configs/mcp_servers/memory.yaml", assets / "memory.yaml") | |
| shared = Path(os.environ["MANIPULATIONARENA_ROOT"]) / "environment/runtime_assets" | |
| node_tar = shared / "node-v20.19.0-linux-x64.tar.gz" | |
| memory_tar = shared / "memory-dist.tar.gz" | |
| for archive in (node_tar, memory_tar): | |
| if not archive.is_file(): | |
| raise RuntimeError(f"Memory stack asset is missing: {archive}") | |
| self._put_chunked(node_tar, "/tmp/v3-node.tar.gz", chunk_size=48 * 1024) | |
| self._put_chunked(memory_tar, "/tmp/v3-memory.tar.gz", chunk_size=48 * 1024) | |
| staged = self.client.execute( | |
| "set -eu; " | |
| "mkdir -p /opt/node20 /opt/local_servers/servers/src/memory; " | |
| "tar -xzf /tmp/v3-node.tar.gz -C /opt/node20 --strip-components=1; " | |
| "tar -xzf /tmp/v3-memory.tar.gz -C /opt/local_servers/servers/src/memory; " | |
| "rm -f /tmp/v3-node.tar.gz /tmp/v3-memory.tar.gz; " | |
| "/opt/node20/bin/node --version; " | |
| "test -f /opt/local_servers/servers/src/memory/dist/index.js", | |
| timeout=300, | |
| ) | |
| if staged["rc"] != 0: | |
| raise RuntimeError("Sandbox memory stack staging failed: " + | |
| (staged["stderr"] or staged["stdout"])[-1000:]) | |
| def _put_chunked(self, local: Path, remote: str, chunk_size: int) -> None: | |
| assert self.client is not None | |
| reset = self.client.execute(f"rm -f {remote}", timeout=30) | |
| if reset["rc"] != 0: | |
| raise RuntimeError("Sandbox upload reset failed: " + reset["stderr"][-300:]) | |
| raw = local.read_bytes() | |
| parts = [(index // chunk_size, raw[index:index + chunk_size]) | |
| for index in range(0, len(raw), chunk_size)] | |
| def upload(item: tuple[int, bytes]) -> str: | |
| number, payload = item | |
| part = f"/tmp/v3-chunk-{number:04d}" | |
| if not self.client.put_bytes(part, payload, mode="600"): | |
| raise RuntimeError(f"Sandbox upload failed: {part}") | |
| return part | |
| with ThreadPoolExecutor(max_workers=8) as pool: | |
| remote_parts = list(pool.map(upload, parts)) | |
| merge = "cat " + " ".join(remote_parts) + f" > {remote}; rm -f " + " ".join(remote_parts) | |
| merged = self.client.execute(merge, timeout=180) | |
| if merged["rc"] != 0: | |
| raise RuntimeError("Sandbox chunk merge failed: " + merged["stderr"][-500:]) | |
| def _upload_database_dump(self) -> None: | |
| assert self.client is not None | |
| if self.is_solvable30: | |
| return | |
| dump = self.task_root.parent.parent / "db" / "init.sql.gz" | |
| if not dump.is_file(): | |
| raise RuntimeError(f"Benchmark PostgreSQL dump is unavailable: {dump}") | |
| target = "/run/toolathlon-init.sql.gz" | |
| reset = self.client.execute(f"rm -f {target}", timeout=30) | |
| if reset["rc"] != 0: | |
| raise RuntimeError("Sandbox database upload reset failed: " + reset["stderr"][-500:]) | |
| chunk_size = 64 * 1024 | |
| raw = dump.read_bytes() | |
| parts = [(index // chunk_size, raw[index:index + chunk_size]) | |
| for index in range(0, len(raw), chunk_size)] | |
| def upload(item: tuple[int, bytes]) -> str: | |
| number, payload = item | |
| part = f"/tmp/v3-db-part-{number:04d}" | |
| if not self.client.put_bytes(part, payload, mode="600"): | |
| raise RuntimeError(f"Sandbox upload failed: {part}") | |
| return part | |
| with ThreadPoolExecutor(max_workers=8) as pool: | |
| remote_parts = list(pool.map(upload, parts)) | |
| merge = "cat " + " ".join(remote_parts) + f" > {target}; rm -f " + " ".join(remote_parts) | |
| merged = self.client.execute(merge, timeout=120) | |
| if merged["rc"] != 0: | |
| raise RuntimeError("Sandbox database chunk merge failed: " + merged["stderr"][-500:]) | |
| verify = self.client.execute(f"test -s {target}", timeout=30) | |
| if verify["rc"] != 0: | |
| raise RuntimeError("Sandbox database dump is empty after upload") | |
| def _upload_task_if_needed(self) -> None: | |
| assert self.client is not None | |
| source = (self.task_root / self.task).resolve() | |
| if source.parent != self.task_root.resolve() or not source.is_dir(): | |
| raise RuntimeError(f"Task directory is unavailable: {source}") | |
| check = self.client.execute( | |
| f"test -f '/workspace/tasks/{self.task_suite}/{self.task}/docs/task.md'", timeout=30) | |
| if check["rc"] == 0: | |
| preprocess = source / "preprocess" / "main.py" | |
| if preprocess.is_file(): | |
| self._put(f"/workspace/tasks/{self.task_suite}/{self.task}/preprocess/main.py", preprocess, "600") | |
| return | |
| with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as handle: | |
| archive = Path(handle.name) | |
| try: | |
| with tarfile.open(archive, "w:gz") as tar: | |
| tar.add(source, arcname=self.task) | |
| self._put("/tmp/v3-task.tar.gz", archive, "600") | |
| result = self.client.execute( | |
| f"install -d -m 700 /workspace/tasks/{self.task_suite} && " | |
| f"tar -xzf /tmp/v3-task.tar.gz -C /workspace/tasks/{self.task_suite} && " | |
| "rm -f /tmp/v3-task.tar.gz", timeout=300) | |
| if result["rc"] != 0: | |
| raise RuntimeError(result["stderr"][-1000:]) | |
| finally: | |
| archive.unlink(missing_ok=True) | |
| def _upload_attack_sources(self) -> None: | |
| """Upload the exact verified source files targeted by real-channel patches.""" | |
| if self.attack_plan is None: | |
| return | |
| binding = self.attack_plan["red_design"]["channel_binding"] | |
| source_path = binding.get("source_path") | |
| if not source_path or source_path.startswith("/run/workspace/"): | |
| return | |
| included = self.attack_plan.get("generation_metadata", {}).get("included_files", []) | |
| matches = [item for item in included if item.get("sandbox_path") == source_path] | |
| if source_path.startswith("/workspace/tasks/") and not matches: | |
| task_dir = Path(self.attack_plan["generation_metadata"]["source_task_dir"]) | |
| relative = source_path.split(f"/{self.task}/", 1)[-1] | |
| matches = [{"path": str(task_dir / relative), "sandbox_path": source_path}] | |
| if len(matches) != 1: | |
| raise RuntimeError(f"Verified host source for real-channel deployment is missing: {source_path}") | |
| local = Path(matches[0]["path"]) | |
| if not local.is_file(): | |
| raise RuntimeError(f"Verified host source file is missing: {local}") | |
| self._put(source_path, local, "755" if local.suffix in {".py", ".js", ".ts", ".tsx"} else "600") | |
| def _upload_initial_gate_state(self) -> None: | |
| """Make the broker initial checkpoint visible before DSH boots.""" | |
| assert self.client is not None | |
| gate = self.run_dir / "gate" | |
| checkpoint_plan = gate / "checkpoint-plan.json" | |
| if checkpoint_plan.is_file(): | |
| public_plan = public_checkpoint_plan(json.loads(checkpoint_plan.read_text(encoding="utf-8"))) | |
| self._put_bytes("/run/gate/checkpoint-plan.json", json.dumps(public_plan).encode("utf-8")) | |
| checkpoint_state = gate / "checkpoint-state.json" | |
| if checkpoint_state.is_file(): | |
| self._put("/run/gate/checkpoint-state.json", checkpoint_state) | |
| control = self.run_dir / "control" | |
| if control.is_dir(): | |
| for name in ("pending_context.json", "triggers.json"): | |
| local = control / name | |
| if local.is_file(): | |
| self._put("/run/control/" + name, local) | |
| def _start_remote(self) -> None: | |
| assert self.client is not None | |
| if self.is_solvable30: | |
| self._start_remote_solvable30() | |
| return | |
| database = ( | |
| "set -eu; " | |
| "PG_BIN=/usr/lib/postgresql/15/bin; " | |
| "rm -rf /run/postgres-data /run/postgres-init.log; " | |
| "install -d -m 700 -o postgres -g postgres /run/postgres-data; " | |
| "runuser -u postgres -- $PG_BIN/initdb -D /run/postgres-data --auth-local=trust --auth-host=trust " | |
| ">/run/postgres-init.log 2>&1; " | |
| "runuser -u postgres -- $PG_BIN/pg_ctl -D /run/postgres-data " | |
| "-o '-h 127.0.0.1 -p 5432' -w start " | |
| ">>/run/postgres-init.log 2>&1; " | |
| "runuser -u postgres -- $PG_BIN/psql -U postgres -h 127.0.0.1 -p 5432 -d postgres " | |
| "-v ON_ERROR_STOP=1 -c \"CREATE ROLE eigent LOGIN PASSWORD 'camel';\"; " | |
| "runuser -u postgres -- $PG_BIN/psql -U postgres -h 127.0.0.1 -p 5432 -d postgres " | |
| "-v ON_ERROR_STOP=1 -c \"CREATE DATABASE toolathlon_gym OWNER eigent;\"; " | |
| "gzip -dc /run/toolathlon-init.sql.gz | " | |
| "runuser -u postgres -- $PG_BIN/psql -U postgres -h 127.0.0.1 -p 5432 -d toolathlon_gym " | |
| "-v ON_ERROR_STOP=1; " | |
| "$PG_BIN/pg_isready -h 127.0.0.1 -p 5432" | |
| ) | |
| result = self.client.execute(database, timeout=600) | |
| if result["rc"] != 0: | |
| raise RuntimeError("Sandbox PostgreSQL setup failed: " + (result["stderr"] or result["stdout"])[-2000:]) | |
| # Task preprocessors and several benchmark evaluators import | |
| # psycopg2. The current benchmark image contains PostgreSQL itself | |
| # but does not install that Python driver in the DSH virtualenv. | |
| # Install the pinned wheel before launching Blue so preprocessing can | |
| # initialize the task database instead of failing before the agent | |
| # session starts. | |
| driver = self.client.execute( | |
| "/opt/dsh-venv/bin/python -c 'import importlib.util,sys; " | |
| "mods=[\"psycopg2\",\"openpyxl\",\"docx\",\"pptx\",\"xlsxwriter\"," | |
| "\"PyPDF2\",\"pypdf\",\"pdfplumber\",\"pdfminer\",\"fitz\"," | |
| "\"PIL\",\"lxml\"," | |
| "\"requests\",\"yaml\",\"pandas\",\"numpy\"]; " | |
| "sys.exit(0 if all(importlib.util.find_spec(m) for m in mods) else 1)' 2>/dev/null || " | |
| "(/opt/dsh-venv/bin/python -m pip --version >/dev/null 2>&1 || " | |
| "/opt/dsh-venv/bin/python -m ensurepip --upgrade) && " | |
| "/opt/dsh-venv/bin/python -m pip install --no-cache-dir --disable-pip-version-check " | |
| "psycopg2-binary==2.9.10 openpyxl python-docx " | |
| "python-pptx xlsxwriter pypdf2 pypdf pdfplumber pdfminer.six pymupdf " | |
| "pillow lxml " | |
| "requests pyyaml pandas numpy", | |
| timeout=300, | |
| ) | |
| if driver["rc"] != 0: | |
| raise RuntimeError("Sandbox task-runtime dependency installation failed: " + | |
| (driver["stderr"] or driver["stdout"])[-2000:]) | |
| yt_bootstrap = self.client.execute( | |
| "set -eu; " | |
| "test -f /opt/local_servers/mcp-youtube-transcript/pyproject.toml || " | |
| "{ echo 'youtube-transcript source is missing from the sandbox image' >&2; exit 42; }; " | |
| "cd /opt/local_servers/mcp-youtube-transcript; " | |
| "if ! test -x .venv/bin/python3 || ! .venv/bin/python3 -c 'import mcp_youtube_transcript' >/dev/null 2>&1; then " | |
| " rm -rf .venv; " | |
| " if command -v uv >/dev/null 2>&1; then " | |
| " uv sync --frozen --no-dev --no-editable; " | |
| " else " | |
| " /opt/dsh-venv/bin/python -m venv .venv; " | |
| " .venv/bin/python3 -m pip install --no-cache-dir --disable-pip-version-check " | |
| "beautifulsoup4 humanize mcp psycopg2-binary pydantic requests rich-click " | |
| "youtube-transcript-api yt-dlp; " | |
| " fi; " | |
| "fi; " | |
| ".venv/bin/python3 -c 'import mcp_youtube_transcript'", | |
| timeout=900, | |
| ) | |
| if yt_bootstrap["rc"] != 0: | |
| raise RuntimeError("youtube-transcript MCP environment setup failed: " + | |
| (yt_bootstrap["stderr"] or yt_bootstrap["stdout"])[-3000:]) | |
| env = dict(self.blue_env) | |
| env.update({ | |
| "STAGE2_GATE_TIMEOUT_MS": str(self.gate_timeout * 1000), | |
| "PGHOST": "127.0.0.1", "PG_HOST": "127.0.0.1", | |
| "PGPORT": "5432", "PGUSER": "eigent", "PGPASSWORD": "camel", | |
| "PGDATABASE": "toolathlon_gym", "PG_CONNECT_TIMEOUT": "15", | |
| "LOCAL_SERVERS_PATH": "/opt/local_servers", | |
| "PYTHON_BIN": "/opt/dsh-venv/bin/python", | |
| "TASK_SUITE": self.task_suite, | |
| }) | |
| if self.blue_max_tokens is not None: | |
| env["DSH_MAX_TOKENS"] = str(self.blue_max_tokens) | |
| exports = " ".join(f"{key}={shlex.quote(str(value))}" for key, value in env.items()) | |
| command = ( | |
| "mkdir -p /run/control/requests /run/control/decisions /run/gate /run/workspace " | |
| "/run/benchmark-dumps /run/dsh_home; " | |
| f"nohup env {exports} " | |
| f"/opt/dsh-venv/bin/python /opt/stage2/blue_agent_runner.py {shlex.quote(self.task)} " | |
| f"--task-suite {shlex.quote(self.task_suite)} " | |
| "> /run/blue.log 2>&1 < /dev/null & echo $! > /run/blue.pid" | |
| ) | |
| result = self.client.execute(command, timeout=60) | |
| if result["rc"] != 0: | |
| raise RuntimeError(result["stderr"][-1000:]) | |
| def _start_remote_solvable30(self) -> None: | |
| """Provision the stage2 runtime on a plain gym image and launch Blue. | |
| The solvable30 image carries no PostgreSQL, no /opt/dsh-venv and no | |
| MCP virtualenv, so both venvs are created in place from the internal | |
| package index instead of running the toolathlon database bootstrap. | |
| """ | |
| assert self.client is not None | |
| from manipulationarena.deployment import environment_manifest, package_index_args, dsh_requirements, dsh_version_probe | |
| shared = environment_manifest() | |
| check = self.client.execute("sha256sum /opt/benign30/manifest.json", timeout=30) | |
| if check["rc"] or check["stdout"].split()[0:1] != [shared["native_manifest_sha256"]]: | |
| raise RuntimeError("Sandbox native task manifest differs from the pinned environment") | |
| index_args = package_index_args() + " " | |
| dsh_probe = shlex.quote(dsh_version_probe() + "; import yaml") | |
| dsh_packages = shlex.join(dsh_requirements()) | |
| from arena_blue import builtin_dsh | |
| is_dsh = builtin_dsh(self.blue_env) | |
| blue_python = '/opt/dsh-venv/bin/python' if is_dsh else self.blue_env.get('BLUE_PYTHON', '/usr/local/bin/python3') | |
| blue_setup = ( | |
| "if ! /opt/dsh-venv/bin/python -c " + dsh_probe + " >/dev/null 2>&1; then " | |
| " python3 -m venv /opt/dsh-venv; " | |
| " /opt/dsh-venv/bin/pip install --timeout 120 --retries 3 --no-cache-dir --disable-pip-version-check " + index_args + | |
| " " + dsh_packages + " pyyaml; " | |
| "fi; " | |
| "/opt/dsh-venv/bin/python -c " + dsh_probe + "; " | |
| ) if is_dsh else ( | |
| shlex.quote(blue_python) + " -c 'import yaml'; " | |
| ) | |
| provision = self.client.execute( | |
| "set -eu; unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY; " | |
| + blue_setup + | |
| "if [ ! -x /opt/venv/bin/python3 ]; then " | |
| " python3 -m venv /opt/venv; " | |
| "fi; " | |
| "/opt/venv/bin/pip install --timeout 60 --retries 2 --no-cache-dir --disable-pip-version-check " + | |
| index_args + | |
| " 'mcp>=1.12,<2' pyyaml; " | |
| "/opt/venv/bin/python3 -c 'import mcp, yaml'", | |
| timeout=900, | |
| ) | |
| if provision["rc"] != 0: | |
| raise RuntimeError("Sandbox solvable30 runtime provisioning failed: " + | |
| (provision["stderr"] or provision["stdout"])[-3000:]) | |
| env = dict(self.blue_env) | |
| env.update({ | |
| "STAGE2_GATE_TIMEOUT_MS": str(self.gate_timeout * 1000), | |
| "BLUE_SKIP_PG_WAIT": "1", | |
| "LOCAL_SERVERS_PATH": "/opt/local_servers", | |
| "PYTHON_BIN": blue_python, | |
| "TASK_SUITE": self.task_suite, | |
| }) | |
| if self.task.startswith("healthagent-text25-"): | |
| env["DSH_REQUEST_TIMEOUT_SECONDS"] = "5400" | |
| if self.blue_max_tokens is not None: | |
| env["DSH_MAX_TOKENS"] = str(self.blue_max_tokens) | |
| exports = " ".join(f"{key}={shlex.quote(str(value))}" for key, value in env.items()) | |
| command = ( | |
| "mkdir -p /run/control/requests /run/control/decisions /run/gate /run/workspace " | |
| "/run/benchmark-dumps /run/dsh_home; " | |
| f"nohup env {exports} " | |
| f"{shlex.quote(blue_python)} /opt/stage2/blue_agent_runner.py {shlex.quote(self.task)} " | |
| f"--task-suite {shlex.quote(self.task_suite)} " | |
| "> /run/blue.log 2>&1 < /dev/null & echo $! > /run/blue.pid" | |
| ) | |
| result = self.client.execute(command, timeout=60) | |
| if result["rc"] != 0: | |
| raise RuntimeError(result["stderr"][-1000:]) | |
| def _remote_files(self, directory: str) -> list[str]: | |
| assert self.client is not None | |
| result = self.client.execute( | |
| f"find {shlex.quote(directory)} -type f -printf '%P\\n' 2>/dev/null", timeout=30) | |
| if result["rc"] != 0: | |
| return [] | |
| return [line.strip() for line in result["stdout"].splitlines() if line.strip()] | |
| def _download_file(self, remote: str, local: Path) -> None: | |
| assert self.client is not None | |
| data = self.client.get_bytes(remote) | |
| if data is None: | |
| return | |
| local.parent.mkdir(parents=True, exist_ok=True) | |
| local.write_bytes(data) | |
| def _sync_database_dump(self) -> None: | |
| """Export database state for archival review and host-side attack evaluation.""" | |
| if self.client is None or self._database_dump_synced or self.is_solvable30: | |
| return | |
| self._database_dump_synced = True | |
| result = self.client.execute( | |
| "mkdir -p /run/benchmark-dumps; " | |
| "PGPASSWORD=camel /usr/lib/postgresql/15/bin/pg_dump -h 127.0.0.1 -U eigent -d toolathlon_gym --inserts > /run/benchmark-dumps/toolathlon_gym.sql 2>/run/benchmark-dumps/toolathlon_gym.stderr; " | |
| ": > /run/benchmark-dumps/toolathlon.sql; : > /run/benchmark-dumps/toolathlon.stderr", | |
| timeout=300, | |
| ) | |
| if result.get("rc", 1) != 0: | |
| (self.run_dir / "benchmark-dumps").mkdir(parents=True, exist_ok=True) | |
| (self.run_dir / "benchmark-dumps" / "dump-command-error.txt").write_text( | |
| (result.get("stderr") or result.get("stdout") or "pg_dump failed")[-4000:], | |
| encoding="utf-8", | |
| ) | |
| for name in ("toolathlon_gym.sql", "toolathlon.sql", "toolathlon_gym.stderr", "toolathlon.stderr"): | |
| self._download_file("/run/benchmark-dumps/" + name, self.run_dir / "benchmark-dumps" / name) | |
| def _sanitize_prestart(self) -> None: | |
| if self._prestart_sanitized: | |
| return | |
| assert self.client is not None | |
| ready = self.client.execute("test -f /run/prestart_ready.json", timeout=30) | |
| if ready["rc"] != 0: | |
| return | |
| evidence = ( | |
| ("/run/runtime/prestart_deployment_and_probes.json", | |
| self.run_dir / "runtime" / "prestart_deployment_and_probes.json"), | |
| ("/run/manifest/prerun_marker_counts.json", | |
| self.run_dir / "manifest" / "prerun_marker_counts.json"), | |
| ) | |
| for remote, local in evidence: | |
| self._download_file(remote, local) | |
| if not local.is_file(): | |
| raise RuntimeError(f"Pre-start evidence was not preserved before isolation cleanup: {remote}") | |
| quoted = " ".join(shlex.quote(path) for path in PRESTART_SENSITIVE_PATHS) | |
| removed = self.client.execute(f"rm -rf -- {quoted}", timeout=60) | |
| if removed["rc"] != 0: | |
| raise RuntimeError("Failed to remove Red pre-start files: " + removed["stderr"][-1000:]) | |
| checks = "; ".join(f"test ! -e {shlex.quote(path)}" for path in PRESTART_SENSITIVE_PATHS) | |
| verified = self.client.execute(checks, timeout=30) | |
| if verified["rc"] != 0: | |
| raise RuntimeError("Red pre-start files are still visible before Blue launch") | |
| (self.run_dir / "runtime" / "red_blue_isolation.json").write_text(json.dumps({ | |
| "ok": True, "checked_at": time.time(), "blue_model_started": False, | |
| "absent_paths": list(PRESTART_SENSITIVE_PATHS), | |
| "full_attack_plan_uploaded": False, | |
| "attack_evaluation": "host_after_blue_completion", | |
| }, indent=2) + "\n", encoding="utf-8") | |
| self._put_bytes("/run/control/prestart_ack.json", b'{"ok":true}\n') | |
| self._prestart_sanitized = True | |
| def _sync_control(self) -> None: | |
| assert self.client is not None | |
| self._sanitize_prestart() | |
| # A Red action is recorded on the host before its checkpoint receipt is | |
| # published. Push workspace carriers first, otherwise Blue can see | |
| # the receipt and advance to the next pre-step before the injected file | |
| # has reached /run/workspace. This ordering is the actual delivery | |
| # barrier; a later evaluator check cannot repair a missed read. | |
| self._upload_workspace_changes(force=True) | |
| # Upload checkpoint control records before exposing requests. This is | |
| # the control-plane barrier; it is independent of real channel deployment. | |
| control = self.run_dir / "control" | |
| if control.is_dir(): | |
| for name in ("pending_context.json", "triggers.json"): | |
| local = control / name | |
| if local.is_file(): | |
| self._put("/run/control/" + name, local) | |
| for relative in self._remote_files("/run/control"): | |
| self._download_file("/run/control/" + relative, self.run_dir / "control" / relative) | |
| # Requests are the latency-sensitive control path. Do this before | |
| # downloading the growing session and diagnostic files below. The | |
| # sandbox file listing can lag briefly, and the gate sequence is not | |
| # contiguous: compaction and skipped pre-step callbacks can advance | |
| # the request number by several values. Probing only N+1/N+2 can | |
| # therefore miss a real request (for example 10 -> 16), leaving Blue | |
| # blocked until the stage2 timeout. Probe a bounded forward window on | |
| # every pass so stale listings cannot hide a checkpoint. | |
| request_files = self._remote_files("/run/gate/requests") | |
| # The plugin appends the matching session record and then creates the | |
| # request. Discover requests first, then refresh the live evidence so | |
| # the host cannot observe a new request together with the prior | |
| # session snapshot. | |
| self._download_file("/run/gate/observed-session.jsonl", | |
| self.run_dir / "gate" / "observed-session.jsonl") | |
| for relative in request_files: | |
| self._download_file("/run/gate/requests/" + relative, self.run_dir / "gate" / "requests" / relative) | |
| local_requests = [] | |
| request_root = self.run_dir / "gate" / "requests" | |
| if request_root.is_dir(): | |
| for item in request_root.glob("*.json"): | |
| try: | |
| local_requests.append(int(item.stem)) | |
| except ValueError: | |
| continue | |
| probe_start = max(local_requests) + 1 if local_requests else 0 | |
| probe_end = probe_start + 64 | |
| for seq in range(probe_start, probe_end): | |
| name = f"{seq:06d}.json" | |
| self._download_file("/run/gate/requests/" + name, request_root / name) | |
| for relative in self._remote_files("/run/gate"): | |
| # These files are handled explicitly below. In particular, | |
| # observed-session.jsonl grows continuously; downloading it once | |
| # through this directory walk and again explicitly can delay the | |
| # request/decision control path long enough for Blue to hit its | |
| # stage2 checkpoint timeout. | |
| if (relative.startswith(("requests/", "decisions/")) or | |
| relative in {"observed-session.jsonl", "plugin-debug.jsonl", | |
| "matcher-debug.jsonl", "heartbeat.json", | |
| "blue_finished.json", "checkpoint-plan.json", "checkpoint-state.json"}): | |
| continue | |
| self._download_file("/run/gate/" + relative, self.run_dir / "gate" / relative) | |
| self._download_file("/run/workspace_ready.json", self.run_dir / "workspace_ready.json") | |
| self._download_file("/run/runtime/prestart_deployment_and_probes.json", | |
| self.run_dir / "runtime" / "prestart_deployment_and_probes.json") | |
| self._download_file("/run/failure.json", self.run_dir / "failure.json") | |
| self._download_file("/run/blue_terminal.json", self.run_dir / "blue_terminal.json") | |
| self._download_file("/run/blue-session-diagnostics.json", self.run_dir / "blue-session-diagnostics.json") | |
| self._download_file("/run/eval_res.json", self.run_dir / "eval_res.json") | |
| self._download_file("/run/eval.log", self.run_dir / "eval.log") | |
| self._download_file("/run/evaluation_finished.json", self.run_dir / "evaluation_finished.json") | |
| for name in ("attack-evaluation.json", "evaluation_manifest.json", "rule-based-result.json", | |
| "rule-based.stdout", "rule-based.stderr"): | |
| self._download_file("/run/evaluation/" + name, self.run_dir / "evaluation" / name) | |
| self._download_file("/run/gate/blue_finished.json", self.run_dir / "gate" / "blue_finished.json") | |
| if (self.run_dir / "gate" / "blue_finished.json").is_file(): | |
| self._sync_database_dump() | |
| self._download_file("/run/final_response.txt", self.run_dir / "final_response.txt") | |
| for prefix, stem in (("tau-banking-", "tau"), ("healthagent-text25-", "healthagent")): | |
| if self.task.startswith(prefix): | |
| self._download_file("/run/" + stem + "_eval.json", self.run_dir / (stem + "_eval.json")) | |
| if self.task.startswith("gaia2-"): | |
| self._download_file("/run/gaia2_eval.json", self.run_dir / "gaia2_eval.json") | |
| if self.task.startswith("medagent-original-"): | |
| self._download_file("/run/medagent_eval.json", self.run_dir / "medagent_eval.json") | |
| self._download_file("/run/blue-live-diagnostics.json", self.run_dir / "blue-live-diagnostics.json") | |
| self._download_file("/run/blue-live-diagnostics-error.log", self.run_dir / "blue-live-diagnostics-error.log") | |
| self._download_file("/run/blue-python-stack.log", self.run_dir / "blue-python-stack.log") | |
| self._download_file("/run/gate/blue-bridge-requests.jsonl", self.run_dir / "gate" / "blue-bridge-requests.jsonl") | |
| self._download_file("/run/blue_boot.jsonl", self.run_dir / "blue_boot.jsonl") | |
| self._download_file("/run/preprocess.log", self.run_dir / "preprocess.log") | |
| self._download_file("/run/gate.patch.yml", self.run_dir / "gate.patch.yml") | |
| self._download_file("/run/mcp.patch.yml", self.run_dir / "mcp.patch.yml") | |
| self._download_file("/run/compression.patch.yml", self.run_dir / "compression.patch.yml") | |
| self._download_file("/run/stage2-gate-module.jsonl", self.run_dir / "stage2-gate-module.jsonl") | |
| self._download_file("/run/stage2-gate-apply-enter.jsonl", self.run_dir / "stage2-gate-apply-enter.jsonl") | |
| self._download_file("/run/gate/plugin-debug.jsonl", self.run_dir / "gate" / "plugin-debug.jsonl") | |
| self._download_file("/run/gate/matcher-debug.jsonl", self.run_dir / "gate" / "matcher-debug.jsonl") | |
| # The DeepSeek Harness writes its own stderr (including the session | |
| # error traceback) to /run/blue.log; without this sync the decisive | |
| # diagnostics are lost when the sandbox is destroyed. | |
| self._download_file("/run/blue.log", self.run_dir / "blue" / "sandbox-blue.log") | |
| self._download_file("/run/gate/heartbeat.json", self.run_dir / "gate" / "heartbeat.json") | |
| self._download_file("/run/blue.log", self.run_dir / "blue.log") | |
| control = self.run_dir / "control" | |
| if control.is_dir(): | |
| for name in ("pending_context.json", "triggers.json"): | |
| local = control / name | |
| if local.is_file(): | |
| self._put("/run/control/" + name, local) | |
| gate = self.run_dir / "gate" | |
| checkpoint_plan = gate / "checkpoint-plan.json" | |
| if checkpoint_plan.is_file(): | |
| public_plan = public_checkpoint_plan(json.loads(checkpoint_plan.read_text(encoding="utf-8"))) | |
| self._put_bytes("/run/gate/checkpoint-plan.json", | |
| json.dumps(public_plan).encode("utf-8")) | |
| checkpoint_state = gate / "checkpoint-state.json" | |
| if checkpoint_state.is_file(): | |
| self._put("/run/gate/checkpoint-state.json", checkpoint_state) | |
| for local in (gate / "decisions").glob("*.json"): | |
| receipt = json.loads(local.read_text(encoding="utf-8")) | |
| public_receipt = public_gate_receipt(receipt) | |
| self._put_bytes("/run/gate/decisions/" + local.name, | |
| json.dumps(public_receipt).encode("utf-8")) | |
| def _upload_workspace_changes(self, *, force: bool = False) -> None: | |
| """Push Red-written host workspace files into the sandbox workspace. | |
| ActionExecutor writes workspace-channel injections into the host-side | |
| run workspace, but Blue only reads /run/workspace inside the sandbox; | |
| without this upload those injections would silently never reach Blue. | |
| Files are keyed by relative path plus mtime, so each write is pushed | |
| once. Files larger than 4 MiB are skipped and recorded instead of | |
| blocking the sync loop. | |
| """ | |
| if self.client is None or not (self.run_dir / "workspace").is_dir(): | |
| return | |
| if not force and time.monotonic() - self._last_workspace_upload < 2.0: | |
| return | |
| self._last_workspace_upload = time.monotonic() | |
| source = self.run_dir / "workspace" | |
| skipped: list[str] = [] | |
| for local in sorted(source.rglob("*")): | |
| if not local.is_file(): | |
| continue | |
| relative = local.relative_to(source).as_posix() | |
| try: | |
| size = local.stat().st_size | |
| mtime = local.stat().st_mtime | |
| except OSError: | |
| continue | |
| if self._workspace_uploaded.get(relative, 0.0) >= mtime: | |
| continue | |
| if size > 4 * 1024 * 1024: | |
| skipped.append(relative) | |
| continue | |
| parent = relative.rsplit("/", 1)[0] if "/" in relative else "" | |
| if parent: | |
| quoted = "/run/workspace/" + parent.replace("'", "'\\''") | |
| made = self.client.execute("install -d -m 755 '%s'" % quoted, timeout=30) | |
| if made["rc"] != 0: | |
| raise RuntimeError("Sandbox workspace mkdir failed: " + (made.get("stderr") or "")[-300:]) | |
| if not self.client.put_bytes("/run/workspace/" + relative, local.read_bytes(), mode="644"): | |
| raise RuntimeError("Sandbox workspace upload failed: " + relative) | |
| self._workspace_uploaded[relative] = mtime | |
| if skipped: | |
| with (self.run_dir / "workspace-upload-skipped.jsonl").open("a", encoding="utf-8") as handle: | |
| for relative in skipped: | |
| handle.write(json.dumps({"path": relative, "reason": "larger than 4 MiB"}, | |
| ensure_ascii=False) + "\n") | |
| def _sync_workspace(self) -> None: | |
| assert self.client is not None | |
| if time.monotonic() - self._last_workspace < 2.0: | |
| return | |
| self._last_workspace = time.monotonic() | |
| with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as handle: | |
| archive = Path(handle.name) | |
| try: | |
| self.client.download_archive("/run/workspace", str(archive), timeout=300) | |
| target = self.run_dir / "workspace" | |
| target.mkdir(parents=True, exist_ok=True) | |
| with tarfile.open(archive, "r:gz") as tar: | |
| for member in tar.getmembers(): | |
| destination = (target / member.name).resolve() | |
| if target.resolve() not in destination.parents and destination != target.resolve(): | |
| raise RuntimeError("Unsafe workspace archive member") | |
| tar.extractall(target) | |
| finally: | |
| archive.unlink(missing_ok=True) | |
| def _sync_dsh_sessions(self) -> None: | |
| """Copy DeepSeek Harness session JSONL for model-request diagnostics.""" | |
| copied: set[str] = set() | |
| for relative in self._remote_files("/run/dsh_home/sessions"): | |
| remote = "/run/dsh_home/sessions/" + relative | |
| self._download_file(remote, self.run_dir / "dsh_home" / "sessions" / relative) | |
| copied.add(remote) | |
| # The sandbox artifact listing can omit the DSH session directory | |
| # after the Blue process exits even though the files are still present | |
| # in the live /run volume. This is especially common when Blue calls | |
| # claim_done without ever reaching a second gate checkpoint. Search | |
| # the live filesystem immediately before destroying the environment so | |
| # a complete session is not lost merely because the listing endpoint | |
| # was stale or incomplete. | |
| assert self.client is not None | |
| found = self.client.execute( | |
| "find /run -type f \\( -name 'session.v3.jsonl' -o -name '*.jsonl' \\) " | |
| "-path '*/sessions/*' -print 2>/dev/null | sort -u", | |
| timeout=60, | |
| ) | |
| for line in str(found.get("stdout") or "").splitlines(): | |
| remote = line.strip() | |
| if not remote.startswith("/run/") or remote in copied: | |
| continue | |
| relative = remote[len("/run/"):] | |
| self._download_file(remote, self.run_dir / relative) | |
| def _sync_loop(self) -> None: | |
| while not self._stop.is_set(): | |
| # Blue can finish while a previous control-plane request is still | |
| # in flight. Local completion markers are already authoritative | |
| # because they were downloaded before this loop iteration; do not | |
| # start another blocking remote request after completion. | |
| if (self.run_dir / "gate" / "blue_finished.json").is_file(): | |
| self._exit_code = 0 | |
| self._finished = True | |
| break | |
| if (self.run_dir / "failure.json").is_file() or (self.run_dir / "blue_terminal.json").is_file(): | |
| self._exit_code = 1 | |
| self._finished = True | |
| break | |
| try: | |
| # Keep the request/decision path ahead of diagnostic downloads. | |
| self._sync_control() | |
| now = time.monotonic() | |
| if now - self._last_dsh_sync >= 10: | |
| self._sync_dsh_sessions() | |
| self._last_dsh_sync = time.monotonic() | |
| if now - self._last_process_diagnostics >= 15: | |
| snapshot = self.client.execute( | |
| "date -u '+UTC %Y-%m-%dT%H:%M:%SZ'; " | |
| "ps -eo pid,ppid,stat,etime,pcpu,pmem,wchan:24,comm; " | |
| "if command -v ss >/dev/null 2>&1; then ss -tpn; " | |
| "elif command -v netstat >/dev/null 2>&1; then netstat -tpn; fi", | |
| timeout=30, | |
| ) | |
| with (self.run_dir / "runtime-processes.jsonl").open("a", encoding="utf-8") as handle: | |
| handle.write(json.dumps({"at": time.time(), **snapshot}, ensure_ascii=False) + "\n") | |
| self._last_process_diagnostics = time.monotonic() | |
| # Workspace archive downloads can take minutes; collect the | |
| # workspace during final cleanup instead of blocking this loop. | |
| self._last_sync = time.monotonic() | |
| except Exception as exc: | |
| self._sync_error = f"{type(exc).__name__}: {exc}" | |
| try: | |
| (self.run_dir / "runtime-sync-error.log").write_text(self._sync_error + "\n", encoding="utf-8") | |
| except Exception: | |
| pass | |
| # A 404 from the sandbox control plane means the remote | |
| # environment has been deleted or expired. Keep the runner | |
| # from waiting for the full Blue timeout on a dead sandbox; | |
| # this is a retryable environment failure. | |
| if "404" in self._sync_error and "sandbox" in self._sync_error.lower(): | |
| (self.run_dir / "failure.json").write_text( | |
| json.dumps({"status": "sandbox_lost", "error": self._sync_error}) + "\n", | |
| encoding="utf-8", | |
| ) | |
| self._exit_code = 1 | |
| self._finished = True | |
| self._stop.set() | |
| break | |
| if (self.run_dir / "gate" / "blue_finished.json").exists() or (self.run_dir / "failure.json").exists(): | |
| self._finished = True | |
| if (self.run_dir / "blue_terminal.json").exists(): | |
| self._exit_code = 1 | |
| self._finished = True | |
| self._stop.wait(0.5) | |
| def start(self) -> "SandboxProcess": | |
| cfg = self._config() | |
| self.client = ContainerClient(cfg) | |
| self.client.create() | |
| (self.run_dir / "runtime-container.json").write_text(json.dumps({ | |
| "container_id": self.client.container_id, "image": cfg["image"], | |
| "created_at": time.time(), "execution_backend": "local-docker" | |
| }, indent=2) + "\n", encoding="utf-8") | |
| self._upload_runtime() | |
| self._upload_database_dump() | |
| self._upload_task_if_needed() | |
| self._upload_attack_sources() | |
| self.client.execute("rm -rf /run/control /run/gate /run/workspace /run/benchmark-dumps " | |
| "/run/attack_input /run/preattack_backup; " | |
| "rm -f /run/blue_boot.jsonl /run/blue.log /run/blue.pid " | |
| "/run/blue_terminal.json /run/failure.json /run/preprocess.log " | |
| "/run/prestart_ready.json /run/workspace_ready.json " | |
| "/run/runtime/deployment_operations.json " | |
| "/run/runtime/prestart_deployment_and_probes.json " | |
| "/run/manifest/prerun_marker_counts.json; " | |
| "mkdir -p /run/control/requests /run/control/decisions /run/gate " | |
| "/run/workspace /run/benchmark-dumps /run/attack_input", timeout=60) | |
| self._upload_initial_gate_state() | |
| if self.attack_plan is not None: | |
| bootstrap = deployment_view(self.attack_plan) | |
| self._put_bytes("/run/attack_input/deployment_plan.json", | |
| json.dumps(bootstrap, ensure_ascii=False, indent=2).encode("utf-8")) | |
| deployment_log = self.run_dir / "runtime" / "deployment_operations.json" | |
| if deployment_log.is_file(): | |
| self._put("/run/runtime/deployment_operations.json", deployment_log) | |
| self._start_remote() | |
| self._thread = threading.Thread(target=self._sync_loop, daemon=True) | |
| self._thread.start() | |
| return self | |
| def poll(self) -> int | None: | |
| if self._finished: | |
| return self._exit_code | |
| return None | |
| def wait(self, timeout: float | None = None) -> int: | |
| deadline = None if timeout is None else time.monotonic() + timeout | |
| while not self._finished: | |
| # The sync thread may be blocked in a remote request even though | |
| # its last successful pass already downloaded the terminal marker. | |
| # Honor the local marker directly so the runner can enter close() | |
| # and clean up the sandbox. | |
| if (self.run_dir / "gate" / "blue_finished.json").is_file(): | |
| self._exit_code = 0 | |
| self._finished = True | |
| break | |
| if (self.run_dir / "failure.json").is_file() or (self.run_dir / "blue_terminal.json").is_file(): | |
| self._exit_code = 1 | |
| self._finished = True | |
| break | |
| if deadline is not None and time.monotonic() >= deadline: | |
| raise TimeoutError("Sandbox blue process wait timed out") | |
| time.sleep(0.5) | |
| return self._exit_code or 0 | |
| def terminate(self) -> None: | |
| if self.client is not None: | |
| self.client.execute("if [ -f /run/blue.pid ]; then kill $(cat /run/blue.pid) 2>/dev/null || true; fi", timeout=30) | |
| self._finished = True | |
| def kill(self) -> None: | |
| self.terminate() | |
| def close(self) -> None: | |
| self._stop.set() | |
| if self._thread is not None: | |
| self._thread.join(timeout=5) | |
| try: | |
| if self.client is not None: | |
| self._sync_control() | |
| self._sync_workspace() | |
| self._sync_dsh_sessions() | |
| self._sync_database_dump() | |
| self.client.execute( | |
| "if [ -f /run/postgres-data/postmaster.pid ]; then " | |
| "runuser -u postgres -- /usr/lib/postgresql/15/bin/pg_ctl " | |
| "-D /run/postgres-data -m fast stop >/run/postgres-stop.log 2>&1 || true; fi", | |
| timeout=60, | |
| ) | |
| self.client.destroy() | |
| finally: | |
| self.client = None | |