Download release/engine/modules/common-a8f8f1910144.py from AI45Research/ManipulationArena: direct link, hf CLI and curl.
- Browser
- Download file 5.89 kB
-
https://huggingface.co/datasets/AI45Research/ManipulationArena/resolve/main/release/engine/modules/common-a8f8f1910144.py
- Command line
-
hf download hf://datasets/AI45Research/ManipulationArena/release/engine/modules/common-a8f8f1910144.py
-
curl -L -o common-a8f8f1910144.py https://huggingface.co/datasets/AI45Research/ManipulationArena/resolve/main/release/engine/modules/common-a8f8f1910144.py
5.89 kB
| """Shared primitives for the one-pass initial-plan red/blue runner.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| from typing import Any, Iterable | |
| SCRIPT_DIR = Path(__file__).resolve().parent | |
| ATTACK_ENV = SCRIPT_DIR.parents[2] | |
| PROJECT_DIR = ATTACK_ENV.parent | |
| OUTPUT_ROOT = ATTACK_ENV / "outputs" / "result_v3_1105" | |
| # Output is organized by task first. Each task owns exactly two experiment | |
| # directories: one for initial plans and one for all execution iterations. | |
| PLANS_ROOT = OUTPUT_ROOT | |
| RESULTS_ROOT = OUTPUT_ROOT | |
| INITIAL_PLAN_DIR = "initial_attack_plan" | |
| ATTACK_ITERATIONS_DIR = "attack_iterations" | |
| GYM_DIR = PROJECT_DIR / "benign-task-env" / "toolathlon_gym" | |
| SURFACES = frozenset({ | |
| "USER_INSTRUCTION", "TOOL_SPEC", "SKILL_SPEC", "PLUGIN_MANIFEST", | |
| "INTERMEDIATE_ARTIFACT", "VISIBLE_WORKSPACE_FILE", "MEMORY", | |
| }) | |
| TASKS_AND_DUPLICATES = ATTACK_ENV / "scripts" / "attack_v3" / "TASKS_AND_DUPLICATES.md" | |
| _PERMISSION_TASK_IDS: frozenset[str] | None = None | |
| def permission_task_ids() -> frozenset[str]: | |
| """Return the authoritative 84-task permission-version set.""" | |
| global _PERMISSION_TASK_IDS | |
| if _PERMISSION_TASK_IDS is not None: | |
| return _PERMISSION_TASK_IDS | |
| if not TASKS_AND_DUPLICATES.is_file(): | |
| fail(f"Missing task-suite manifest: {TASKS_AND_DUPLICATES}") | |
| inside = False | |
| found: set[str] = set() | |
| row = re.compile(r"^\|\s*\d+\s*\|\s*`([^`]+)`\s*\|") | |
| for line in TASKS_AND_DUPLICATES.read_text(encoding="utf-8").splitlines(): | |
| if line.startswith("## 84 个权限任务"): | |
| inside = True | |
| continue | |
| if inside and line.startswith("## 其余 419 个任务"): | |
| break | |
| if inside: | |
| match = row.match(line) | |
| if match: | |
| found.add(match.group(1)) | |
| if len(found) != 84: | |
| fail(f"Expected 84 permission tasks, found {len(found)}") | |
| _PERMISSION_TASK_IDS = frozenset(found) | |
| return _PERMISSION_TASK_IDS | |
| def task_suite(task_id: str) -> str: | |
| """Map a task ID to the suite shipped in the new sandbox image.""" | |
| if task_id.startswith(("appworld-", "gaia2-", "medagent-original-", "healthagent-text25-", "tau-banking-")): | |
| return "solvable30" | |
| return "permission84" if task_id in permission_task_ids() else "finalpool" | |
| def task_suite_root(task_id: str, tasks_root: Path | None = None) -> Path: | |
| """Resolve a host task directory without silently mixing suites.""" | |
| suite = task_suite(task_id) | |
| if tasks_root is None: | |
| tasks_root = GYM_DIR / "tasks" / suite | |
| candidate = tasks_root / task_id if tasks_root.name == suite else tasks_root.parent / suite / task_id | |
| if not candidate.is_dir(): | |
| fail(f"Task {task_id} belongs to suite {suite}, but its directory is unavailable: {candidate}") | |
| return candidate | |
| class InitialAttackError(RuntimeError): | |
| pass | |
| def fail(message: str) -> None: | |
| raise InitialAttackError(message) | |
| from manipulationarena.primitives import atomic_json | |
| from manipulationarena.primitives import atomic_bytes | |
| def read_json(path: Path) -> Any: | |
| try: | |
| return json.loads(path.read_text(encoding="utf-8")) | |
| except (OSError, json.JSONDecodeError) as exc: | |
| fail(f"Invalid JSON {path}: {exc}") | |
| from manipulationarena.primitives import sha256_file | |
| from manipulationarena.primitives import sha256_json | |
| from manipulationarena.primitives import utc_stamp | |
| def validate_name(value: str, label: str) -> str: | |
| if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", value): | |
| fail(f"Invalid {label}: {value!r}") | |
| return value | |
| def load_env_file(path: Path, required: Iterable[str], optional: Iterable[str] = ()) -> dict[str, str]: | |
| if not path.is_file(): | |
| fail(f"Configuration file not found: {path}") | |
| values: dict[str, str] = {} | |
| assignment = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(['\"]?)(.*?)\2\s*$") | |
| for number, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): | |
| line = raw.strip() | |
| if not line or line.startswith("#"): | |
| continue | |
| match = assignment.match(line) | |
| if not match: | |
| fail(f"Unsupported configuration syntax at {path}:{number}") | |
| values[match.group(1)] = match.group(3) | |
| wanted = list(required) + list(optional) | |
| merged = {key: os.environ.get(key, "").strip() or values.get(key, "").strip() for key in wanted} | |
| missing = [key for key in required if not merged.get(key)] | |
| if missing: | |
| fail("Missing required configuration: " + ", ".join(missing)) | |
| return {key: value for key, value in merged.items() if value} | |
| def ordered_api_keys(profiles_raw: str, current_key: str, current_url: str, current_model: str) -> list[str]: | |
| if not profiles_raw.strip(): | |
| return [current_key] | |
| try: | |
| profiles = json.loads(profiles_raw) | |
| except json.JSONDecodeError as exc: | |
| fail(f"API profiles JSON is invalid: {exc}") | |
| if not isinstance(profiles, list): | |
| fail("API profiles must be a JSON array") | |
| keys: list[str] = [] | |
| for profile in profiles: | |
| if not isinstance(profile, dict): | |
| fail("Each API profile must be an object") | |
| if (str(profile.get("url", "")).rstrip("/") == current_url.rstrip("/") | |
| and profile.get("model") == current_model): | |
| for key in profile.get("keys", []): | |
| if isinstance(key, str) and key.strip() and key.strip() not in keys: | |
| keys.append(key.strip()) | |
| if not keys: | |
| fail("No API keys match the selected URL and model") | |
| return [current_key] + [key for key in keys if key != current_key] | |
| # Shared task sources are resolved by the public execution adapter. | |
| GYM_DIR = Path(os.environ.get("MANIPULATIONARENA_GYM", str(GYM_DIR))).resolve() | |