File size: 3,487 Bytes
ab59633
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Core pieces of the stand-in evaluation.

Each proxy task has its own OpenEnv-style action model (so the model meets a new schema every time, as it
would on the arena's private tasks), a reset observation, a step function and a scripted oracle solution.
Tasks are played in-process; code the model writes runs in a throwaway Docker container with no network.
"""

import json
import random
import subprocess
import tempfile
import uuid
from dataclasses import dataclass
from pathlib import Path

from openenv.core.env_server.types import Action  # noqa: F401  (re-exported for task modules)

SANDBOX_IMAGE = "python:3.12-slim"


@dataclass
class Step:
    observation: dict
    done: bool = False
    reward: float = 0.0


class ProxyTask:
    """One instance of a proxy task. Subclasses set the class attributes and implement the methods."""

    family = ""
    domain = ""
    Action = None  # an openenv Action subclass
    max_steps = 12
    finish_action: dict = {}

    def __init__(self, seed: int):
        self.seed = seed
        self.steps = 0
        self.done = False
        # generators assert their own invariants; redraw until an instance satisfies them
        for attempt in range(200):
            self.rng = random.Random(f"{self.family}:{seed}:{attempt}")
            try:
                self.setup()
                return
            except AssertionError:
                continue
        raise RuntimeError(f"could not generate {self.family} seed {seed}")

    @property
    def task_id(self):
        return f"{self.family}-{self.seed}"

    def setup(self):
        raise NotImplementedError

    def reset(self) -> dict:
        raise NotImplementedError

    def act(self, action) -> Step:
        raise NotImplementedError

    def oracle(self) -> list[dict]:
        raise NotImplementedError

    def step(self, action) -> Step:
        if self.done:
            return Step({"output": "The episode is over."}, True, 0.0)
        self.steps += 1
        result = self.act(action)
        if not result.done and self.steps >= self.max_steps:
            result = Step({**result.observation, "note": "Action budget used up."}, True, 0.0)
        self.done = result.done
        return result


def run_python(files: dict[str, str], command: list[str], timeout: int = 20) -> tuple[int, str]:
    """Run a command over the given files in a disposable, network-less container. Returns (exit code, output)."""
    with tempfile.TemporaryDirectory() as tmp:
        for name, body in files.items():
            path = Path(tmp) / name
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_text(body)
        container = f"proxy-{uuid.uuid4().hex[:12]}"
        cmd = ["docker", "run", "--rm", "--name", container, "--network", "none", "--memory", "256m", "--cpus", "1",
               "--pids-limit", "64", "-v", f"{tmp}:/work", "-w", "/work", SANDBOX_IMAGE, *command]
        try:
            proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
        except subprocess.TimeoutExpired:
            subprocess.run(["docker", "kill", container], capture_output=True)
            return 124, "timed out"
        out = (proc.stdout + proc.stderr)[-3000:]
        return proc.returncode, out


def clip(text: str, limit: int = 4000) -> str:
    return text if len(text) <= limit else text[:limit] + f"\n... [{len(text) - limit} more characters]"


def dumps(obj) -> str:
    return json.dumps(obj, indent=1)