edbeeching's picture
edbeeching HF Staff
Create the evidence directory before restricted puzzle startup
e649f81 verified
Raw History Blame
10.3 kB
"""Generate standalone Harbor tasks from the pinned AgentEscapeBench scenarios."""
import argparse
import hashlib
import json
import shutil
import tempfile
from collections import Counter
from pathlib import Path
SOURCE_REVISION = "03742c79f48646e0130886e18e3e79798cf8edd7"
ROOT = Path(__file__).resolve().parents[2]
RUNTIME = Path(__file__).parent / "runtime"
BASE_IMAGE = "python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f"
def digest(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def task_id(path):
return (
"agentescape-"
+ path.parent.parent.name
+ "-"
+ path.stem.replace("_narrative", "").replace("_", "-")
)
def write(path, text):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
if path.suffix == ".sh":
path.chmod(0o755)
def generate(source, output, max_actions=500, overwrite=False):
name = task_id(source)
target = output / name
if target.exists() and not overwrite:
raise FileExistsError(f"Refusing to overwrite {target}; pass --overwrite")
scenario_hash = digest(source)
source_hash = hashlib.sha256(
Path(__file__).read_bytes()
+ b"".join(
p.read_bytes()
for p in sorted(RUNTIME.rglob("*.py"))
if "__pycache__" not in p.parts
)
+ (ROOT / "runtime-requirements.txt").read_bytes()
).hexdigest()[:12]
output.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=".generate-", dir=output) as temporary:
task = Path(temporary) / name
env = task / "environment"
write(env / "agent/cli.py", (RUNTIME / "cli.py").read_text())
agent_dockerfile = f"""FROM {BASE_IMAGE}
RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/*
COPY cli.py /usr/local/bin/escape
RUN chmod 755 /usr/local/bin/escape
WORKDIR /workspace
"""
write(env / "agent/Dockerfile", agent_dockerfile)
# Harbor requires an environment definition even though Compose selects the narrower context.
write(env / "Dockerfile", agent_dockerfile)
backend = env / "puzzle"
backend.mkdir(parents=True)
for file in ("service.py", "export.py", "worker.py", "child.py"):
shutil.copyfile(RUNTIME / file, backend / file)
shutil.copytree(
RUNTIME / "upstream",
backend / "upstream",
ignore=shutil.ignore_patterns("__pycache__"),
)
shutil.copyfile(ROOT / "runtime-requirements.txt", backend / "requirements.txt")
shutil.copyfile(source, backend / "scenario.json")
write(
backend / "Dockerfile",
f"""FROM {BASE_IMAGE}
COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt
WORKDIR /app
COPY upstream /app/upstream
COPY service.py export.py /app/
COPY scenario.json /private/scenario.json
RUN mkdir -p /evidence && chmod 0755 /evidence
ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS={max_actions}
CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"]
""",
)
write(
backend / "worker.Dockerfile",
f"""FROM {BASE_IMAGE}
RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/*
COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt
WORKDIR /app
COPY worker.py child.py /app/
COPY upstream/simulator.py /app/simulator.py
CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"]
""",
)
write(
env / "docker-compose.yaml",
f"""services:
main:
image: agentescapebench-agent:{source_hash}
build:
context: ./agent
networks: [default, puzzle]
security_opt: [no-new-privileges:true]
depends_on:
puzzle:
condition: service_healthy
puzzle:
image: agentescapebench-puzzle:{name}-{source_hash}
build:
context: ./puzzle
networks: [puzzle, execution]
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
pids_limit: 64
mem_limit: 512m
healthcheck:
test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
interval: 1s
timeout: 3s
retries: 30
depends_on:
worker:
condition: service_healthy
worker:
image: agentescapebench-worker:{source_hash}
build:
context: ./puzzle
dockerfile: worker.Dockerfile
networks: [execution]
read_only: true
tmpfs: ["/tmp:size=64m,mode=1777"]
cap_drop: [ALL]
cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE]
security_opt: [no-new-privileges:true]
pids_limit: 64
mem_limit: 384m
healthcheck:
test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"]
interval: 1s
timeout: 3s
retries: 30
networks:
puzzle:
internal: true
execution:
internal: true
""",
)
write(
task / "task.toml",
f'''schema_version = "1.4"
source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench"
[[artifacts]]
source = "/evidence/final.json"
service = "puzzle"
[[artifacts]]
source = "/evidence/trace.jsonl"
service = "puzzle"
[task]
name = "edbeeching/{name}"
version = "0.1.0"
[metadata]
difficulty = {int(source.parent.parent.name)}
source_revision = "{SOURCE_REVISION}"
scenario_sha256 = "{scenario_hash}"
protocol = "harbor-cli-action-budget-v1"
max_actions = {max_actions}
[agent]
timeout_sec = 1200
[environment]
build_timeout_sec = 900
cpus = 1
memory_mb = 1024
[verifier]
environment_mode = "separate"
timeout_sec = 60
[[verifier.collect]]
service = "puzzle"
command = "python -I /app/export.py"
timeout_sec = 15
''',
)
write(
task / "instruction.md",
f"""# Escape the room
Discover the victory string and submit it with `escape submit-answer`.
Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID.
Use these commands (JSON responses):
```sh
escape investigate NODE_ID
escape tool-call NODE_ID --arguments-json '{{"parameter": "value"}}'
escape use-item NODE_ID --arguments-json '{{"parameter": "value"}}'
escape submit-answer 'exact victory string'
escape state
```
Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text.
Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **{max_actions} puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment.
""",
)
write(
task / "solution/oracle.py",
(Path(__file__).parent / "oracle.py").read_text(),
)
shutil.copyfile(source, task / "solution/scenario.json")
write(
task / "solution/solve.sh",
"#!/bin/sh\nset -eu\npython -I /solution/oracle.py\n",
)
write(task / "tests/grade.py", (RUNTIME / "grade.py").read_text())
write(
task / "tests/expected.json",
json.dumps({"scenario_sha256": scenario_hash, "max_actions": max_actions}),
)
write(task / "tests/test.sh", "#!/bin/sh\nset -eu\npython -I /tests/grade.py\n")
write(task / "tests/Dockerfile", f"FROM {BASE_IMAGE}\nCOPY . /tests/\n")
if target.exists():
shutil.rmtree(target)
task.rename(target)
return {
"id": name,
"difficulty": int(source.parent.parent.name),
"source_file": str(source.relative_to(ROOT)),
"scenario_sha256": scenario_hash,
"max_actions": max_actions,
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output-dir", type=Path, default=ROOT / "tasks")
parser.add_argument("--task-ids", nargs="*")
parser.add_argument("--limit", type=int)
parser.add_argument("--pilot", action="store_true")
parser.add_argument("--overwrite", action="store_true")
parser.add_argument("--max-actions", type=int, default=500)
args = parser.parse_args()
if args.max_actions < 1:
parser.error("--max-actions must be positive")
sources = sorted((ROOT / "data/questions").glob("*/narrative/*.json"), key=task_id)
if args.pilot:
ordinary = next(
p
for p in sources
if p.parent.parent.name == "5" and "code_py_exec" not in p.read_text()
)
code = next(
p
for p in sources
if p.parent.parent.name == "25" and "code_py_exec" in p.read_text()
)
sources = [ordinary, code]
if args.task_ids:
wanted = set(args.task_ids)
sources = [p for p in sources if task_id(p) in wanted]
missing = wanted - {task_id(p) for p in sources}
if missing:
parser.error(f"Unknown task IDs: {sorted(missing)}")
if args.limit is not None:
sources = sources[: args.limit]
rows = [
generate(p, args.output_dir, args.max_actions, args.overwrite) for p in sources
]
write(
args.output_dir / "manifest.json",
json.dumps({"source_revision": SOURCE_REVISION, "tasks": rows}, indent=2)
+ "\n",
)
print(
json.dumps(
{
"tasks": len(rows),
"difficulty_counts": dict(Counter(row["difficulty"] for row in rows)),
"output": str(args.output_dir),
}
)
)
if __name__ == "__main__":
main()