"""Science Desk environment: a TB2-shaped server for procedural science artifact tasks. Forked from Terminal Desk v2 (dnakhla, Apache-2.0). reset(task_id=...) builds that task id's fixed instance under /app (TERMINAL_DESK_APP in tests): every reset of one id is the same problem, so the arena's group of rollouts compares answers to one question. Client seeds are ignored; in-process callers (tests, calibration) may pass a seed with allow_seed=True to build other instances. The step contract mirrors the upstream OpenEnv tbench2_env wrapper the arena operator uses for its own tasks: exec runs a command, write_file writes a file, evaluate runs the hidden checks and ends the episode with reward 1 or 0, close ends it without a reward, session actions fail softly, and the instruction is repeated in every observation. Commands and writes run as nobody. """ import os import random import shutil from uuid import uuid4 from openenv.core.env_server.interfaces import Environment from ..core import shell from ..core.grading import verify from ..families import FAMILIES, instance_seed, parse_task_id from ..families.base import Built from ..models import Tbench2Action, Tbench2Observation, Tbench2State APP = os.environ.get("TERMINAL_DESK_APP", "/app") MAX_CALLS = 32 # the operator's tool_calls_total; the arena's budgets end episodes first SESSION_ACTIONS = ("write", "view", "wait", "kill") class TerminalDeskEnvironment(Environment): SUPPORTS_CONCURRENT_SESSIONS = False def __init__(self, allow_seed: bool = False): super().__init__() self._allow_seed = allow_seed self._ep: dict | None = None self._state = Tbench2State(episode_id=None, step_count=0) def reset(self, seed=None, episode_id=None, task_id=None, **kwargs) -> Tbench2Observation: if not isinstance(task_id, str): raise ValueError("reset needs task_id, for example task_id='sci_flood-L1'") family_id, level, _ = parse_task_id(task_id) rng = random.Random(seed if (seed is not None and self._allow_seed) else instance_seed(task_id)) built = FAMILIES[family_id].build(level, rng) self._cleanup() os.makedirs(APP, exist_ok=True) for name in os.listdir(APP): path = os.path.join(APP, name) if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path) else: os.unlink(path) for name, content in built.files.items(): target = os.path.join(APP, name) os.makedirs(os.path.dirname(target), exist_ok=True) mode = "wb" if isinstance(content, bytes) else "w" with open(target, mode, **({} if mode == "wb" else {"encoding": "utf-8", "newline": ""})) as fh: fh.write(content) os.chmod(APP, 0o755) shell.give_to_nobody(APP) self._ep = {"task_id": task_id, "built": built, "calls": 0, "done": False} self._state = Tbench2State( episode_id=episode_id or str(uuid4()), step_count=0, task_id=task_id, task_path=APP, terminal_ready=True, ) return self._obs("reset", "", reward=0.0, done=False, session_id=None) def step(self, action: Tbench2Action, timeout_s=None, **kwargs) -> Tbench2Observation: ep = self._ep if ep is None: raise RuntimeError("call reset(task_id=...) first") if ep["done"]: return self._obs(action.action_type, "The episode is over.", reward=None, done=True, success=False, error="episode is over") ep["calls"] += 1 self._state.step_count = ep["calls"] self._state.last_action_type = action.action_type self._state.last_command = action.command kind = action.action_type if kind in ("evaluate", "close") or ep["calls"] > MAX_CALLS: if kind == "close": self._cleanup() ep["done"] = True return self._obs("close", "Closed TB2 environment.", reward=None, done=True) return self._evaluate(kind) output, success, error, session_id = "", True, "", action.session_id or "tb2-session" try: if kind == "exec": _, output = shell.run_command(action.command, APP) elif kind == "write_file": if not action.file_path: raise ValueError("file_path is required for action_type='write_file'") code, text = shell.write_file(action.file_path, action.content, APP) if code != 0: raise OSError(text.strip() or f"could not write {action.file_path}") output = f"Wrote content to {action.file_path}" elif kind in SESSION_ACTIONS: if not action.session_id: raise ValueError(f"session_id is required for action_type='{kind}'") raise ValueError("streaming sessions are not available here; use a blocking exec") else: raise ValueError(f"Unsupported action_type: {kind}") except Exception as exc: success, error = False, str(exc) self._state.last_output = output self._state.session_id = session_id return self._obs(kind, output, reward=None, done=False, success=success, error=error, session_id=session_id) def _evaluate(self, kind: str) -> Tbench2Observation: ep = self._ep built: Built = ep["built"] ep["done"] = True shell.kill_nobody() reward, results, tail = verify(APP, built) self._cleanup() return self._obs( kind, tail, reward=reward, done=True, info={"tests_passed": reward == 1.0, "harness": "tests/test.sh", "results": results, "task_id": ep["task_id"], "calls": ep["calls"]}, ) def _obs(self, action_type: str, output: str, reward, done: bool, success: bool = True, error: str = "", session_id=None, info: dict | None = None) -> Tbench2Observation: ep = self._ep or {} built = ep.get("built") return Tbench2Observation( instruction=built.instruction if built else "", output=output, success=success, error=error, task_id=ep.get("task_id", ""), task_path=APP, session_id=session_id, action_type=action_type, info=info or {}, reward=reward, done=done, ) def _cleanup(self) -> None: shell.kill_nobody() def close(self) -> None: self._cleanup() @property def state(self) -> Tbench2State: return self._state