File size: 10,340 Bytes
49aa045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8e3338
49aa045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8e3338
49aa045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
"""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 / "generated/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()