"""The Five Desks OpenEnv environment.""" import secrets from typing import Any, Optional from uuid import uuid4 from openenv.core.env_server.interfaces import Environment from openenv.core.env_server.types import State from .calc import CalcError, evaluate, format_number from .grading import answer_template, grade from .models import DeskAction, DeskObservation from .tasks import TASK_IDS, Instance, build MAX_OUTPUT_CHARS = 6000 TOOLS_HELP = ( 'Tools (reply with one JSON object per turn): {"tool": "list"}; {"tool": "read", "path": ""}; ' '{"tool": "calc", "expr": ""} (numbers, + - * / // % **, parentheses, ' "sqrt ln log10 log2 exp abs round min max pow(a,b,m) floor ceil gcd lcm comb); " '{"tool": "submit", "answer": {...}}.' ) class FiveDesksEnvironment(Environment): SUPPORTS_CONCURRENT_SESSIONS = True def __init__(self): self._state = State(episode_id=str(uuid4()), step_count=0) self._instance: Instance | None = None self._steps_left = 0 self._done = True def reset( self, seed: Optional[int] = None, episode_id: Optional[str] = None, task_id: Optional[str] = None, **kwargs: Any, ) -> DeskObservation: task_id = task_id or TASK_IDS[0] # Unseeded resets draw a fresh instance, so parallel rollouts see different data. seed = seed if seed is not None else secrets.randbits(48) self._instance = build(task_id, seed) self._state = State(episode_id=episode_id or str(uuid4()), step_count=0) self._steps_left = self._instance.max_steps self._done = False inst = self._instance text = ( f"{inst.desk.upper()} DESK. {inst.question}\n" f"Files: {', '.join(inst.files)}.\n" f"Submit exactly: {{\"tool\": \"submit\", \"answer\": {answer_template(inst.parts)}}}\n" f"{TOOLS_HELP} You have {inst.max_steps} actions; submit ends the episode." ) return DeskObservation(output=text, steps_left=self._steps_left, done=False, reward=0.0) def step(self, action: DeskAction, timeout_s: Optional[float] = None, **kwargs: Any) -> DeskObservation: # type: ignore[override] if self._instance is None or self._done: return DeskObservation(output="Episode is over. Call reset.", steps_left=0, done=True, reward=0.0) self._state.step_count += 1 self._steps_left -= 1 inst = self._instance if action.tool == "submit": reward, scores = grade(inst.parts, action.answer) self._done = True correct = sum(1 for s in scores if s == 1.0) return DeskObservation( output=f"Submitted. {correct} of {len(scores)} answer parts correct.", steps_left=self._steps_left, done=True, reward=round(reward, 4), ) if action.tool == "list": output = "\n".join(f"{name} ({len(body.splitlines())} lines)" for name, body in inst.files.items()) elif action.tool == "read": name = action.path.strip().lstrip("./") body = inst.files.get(name) if body is None: output = f"No file named {action.path!r}. Files: {', '.join(inst.files)}." else: output = body if len(body) <= MAX_OUTPUT_CHARS else body[:MAX_OUTPUT_CHARS] + "\n[truncated]" else: # calc try: output = f"= {format_number(evaluate(action.expr))}" except CalcError as exc: output = f"calc error: {exc}" if self._steps_left <= 0: self._done = True return DeskObservation(output=output + "\nOut of actions without a submission. Reward 0.", steps_left=0, done=True, reward=0.0) return DeskObservation(output=output, steps_left=self._steps_left, done=False, reward=0.0) @property def state(self) -> State: return self._state