analyst-workbench / source /workbench /environment.py
ajinkyamulay's picture
v8: per-episode tool surface, AW-9 and AW-10 results
2bf987b verified
Raw History Blame Contribute Delete
10 kB
"""Analyst Workbench: a per-episode file workspace, a few tools, and one scored submission."""
import json
import os
import secrets
import shutil
import tempfile
import uuid
from openenv.core.env_server.interfaces import Environment
from openenv.core.env_server.types import State
from .models import MAX_STEPS, WorkbenchAction, WorkbenchObservation
from .sandbox import give_to_sandbox, new_uid, run_python
from .tasks import TASK_IDS, build_task, is_valid
OUTPUT_LIMIT = 3000
GREP_CODE = r"""
import json, re
try:
regex = re.compile(%s)
except re.error as exc:
print(json.dumps({"error": str(exc)})); raise SystemExit
hits, total = [], 0
for rel in %s:
with open(rel, encoding="utf-8", errors="replace") as f:
for n, line in enumerate(f, 1):
if regex.search(line[:2000]):
total += 1
if len(hits) < 40:
hits.append(f"{rel}:{n}: {line.rstrip()[:200]}")
print(json.dumps({"hits": hits, "total": total}))
"""
TOOLS_HELP = (
"Tools: ls; read(path, start, lines); grep(pattern, path optional); python(code: runs in "
"this folder, print what you need); write(path, content: replaces the file); edit(path, old, "
"new: replaces one exact snippet); submit(answer: "
"ends the episode). "
f"You have {MAX_STEPS} actions."
)
def clip(text: str, limit: int = OUTPUT_LIMIT) -> str:
if len(text) <= limit:
return text
head = limit * 2 // 3
return text[:head] + f"\n...[{len(text) - limit} chars cut]...\n" + text[-(limit - head):]
class WorkbenchEnvironment(Environment):
SUPPORTS_CONCURRENT_SESSIONS = True
def __init__(self):
super().__init__()
self._state = State(episode_id="", step_count=0)
self._task = None
self._workdir = None
self._done = False
self._last = None
@property
def state(self):
return self._state
def reset(self, seed=None, episode_id=None, task_id=None, **kwargs):
self.close()
task_id = task_id or TASK_IDS[0]
if not is_valid(task_id):
raise ValueError(f"Unknown task_id: {task_id}")
# Unseeded resets draw a fresh instance, so parallel GRPO rollouts differ.
self._seed = seed if seed is not None else secrets.randbits(63)
self._task = build_task(task_id, self._seed)
self._workdir = tempfile.mkdtemp(prefix="wb-")
for name, content in self._task.files.items():
path = os.path.join(self._workdir, name)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
f.write(content)
self._uid = new_uid()
give_to_sandbox(self._workdir, self._uid)
self._state = State(episode_id=episode_id or str(uuid.uuid4()), step_count=0)
self._done = False
self._last = WorkbenchObservation(
output=f"{self._task.instruction}\n\nFiles:\n{self._listing()}\n{TOOLS_HELP}",
reward=0.0,
remaining_steps=MAX_STEPS,
)
return self._last
def _files(self):
found = []
for root, _, files in os.walk(self._workdir):
for name in files:
full = os.path.join(root, name)
if os.path.islink(full): # never read through links as root
continue
found.append((os.path.relpath(full, self._workdir), full))
return sorted(found)
def _listing(self):
rows = []
for rel, full in self._files()[:60]:
try:
with open(full, "rb") as f:
lines = f.read().count(b"\n")
rows.append(f" {rel} ({lines} lines, {os.path.getsize(full)} bytes)")
except OSError:
continue
return "\n".join(rows) or " (empty)"
def _resolve(self, path):
full = os.path.realpath(os.path.join(self._workdir, path.strip().lstrip("/")))
root = os.path.realpath(self._workdir)
if not full.startswith(root + os.sep) or not os.path.isfile(full):
raise ValueError(f"No such file: {path!r}. List the workspace to see files.")
return full
def _workspace_files(self):
out = {}
for rel, full in self._files():
try:
with open(full, encoding="utf-8") as f:
out[rel] = f.read()
except (OSError, UnicodeDecodeError):
continue
return out
def _write(self, action):
if len(action.content) > 300_000:
raise ValueError("content is longer than 300,000 characters.")
root = os.path.realpath(self._workdir)
full = os.path.realpath(os.path.join(self._workdir, action.path.strip().lstrip("/")))
if not full.startswith(root + os.sep) or not action.path.strip():
raise ValueError(f"Cannot write {action.path!r}: path must be inside the workspace.")
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, "w") as f:
f.write(action.content)
give_to_sandbox(self._workdir, self._uid)
lines = action.content.count("\n")
return f"Wrote {action.path} ({lines} lines, {len(action.content)} bytes)."
def _edit(self, action):
full = self._resolve(action.path)
with open(full, encoding="utf-8") as f:
text = f.read()
if not action.old:
raise ValueError("Provide the exact text to replace in old.")
count = text.count(action.old)
if count != 1:
raise ValueError(f"old occurs {count} times in {action.path}; it must occur exactly once.")
with open(full, "w") as f:
f.write(text.replace(action.old, action.new, 1))
give_to_sandbox(self._workdir, self._uid)
return f"Edited {action.path}: replaced {len(action.old)} chars with {len(action.new)} chars."
def _read(self, action):
full = self._resolve(action.path)
with open(full, encoding="utf-8", errors="replace") as f:
all_lines = f.read().splitlines()
start = min(max(1, action.start), max(1, len(all_lines)))
chunk = all_lines[start - 1:start - 1 + min(max(1, action.lines), 80)]
body = "\n".join(f"{start + i:>5}| {line[:300]}" for i, line in enumerate(chunk))
end = start + len(chunk) - 1
return clip(f"{action.path} lines {start}-{end} of {len(all_lines)}\n{body}")
def _grep(self, action):
# The agent's regex runs in the sandbox with a timeout: a catastrophic pattern cannot
# stall the server.
targets = [action.path] if action.path else [rel for rel, _ in self._files()]
if action.path:
self._resolve(action.path)
code = GREP_CODE % (json.dumps(action.pattern), json.dumps(targets))
text, timed_out = run_python(code, self._workdir, self._uid, timeout=10.0)
if timed_out:
raise ValueError("grep timed out; simplify the pattern.")
try:
result = json.loads(text.strip().splitlines()[-1])
except (json.JSONDecodeError, IndexError):
raise ValueError("grep failed.")
if "error" in result:
raise ValueError(f"Bad regex: {result['error']}")
hits, total = result["hits"], result["total"]
more = f"\n({total - len(hits)} more matches not shown)" if total > len(hits) else ""
return clip(f"{total} matches\n" + "\n".join(hits) + more)
def step(self, action: WorkbenchAction, timeout_s=None, **kwargs):
if self._task is None:
raise RuntimeError("Reset before stepping.")
if self._done:
return self._last
self._state.step_count += 1
remaining = MAX_STEPS - self._state.step_count
reward, done = 0.0, False
try:
if action.tool == "submit":
if len(action.answer) > 20_000:
raise ValueError("Answer is longer than 20,000 characters.")
if self._task.meta.get("grades_workspace"):
score = self._task.grade(self._workspace_files())
else:
score = self._task.grade(action.answer)
reward = max(0.0, min(1.0, float(score)))
done = True
output = f"Submitted. Score: {reward:.2f}"
elif action.tool == "ls":
output = self._listing()
elif action.tool == "read":
output = self._read(action)
elif action.tool == "grep":
output = self._grep(action)
elif action.tool == "write":
output = self._write(action)
elif action.tool == "edit":
output = self._edit(action)
else:
if not action.code.strip():
raise ValueError("Provide Python source.")
if len(action.code) > 20_000:
raise ValueError("Code is longer than 20,000 characters.")
text, timed_out = run_python(action.code, self._workdir, self._uid)
output = clip(text) or "(no output; use print)"
if timed_out:
output += "\n[killed: time limit]"
except Exception as exc: # tool errors are observations, not crashes
output = f"Error: {str(exc)[:300]}"
if action.tool == "submit": # a submission always ends the episode
done, reward = True, 0.0
if not done and remaining <= 0:
done = True
output += "\nAction budget exhausted without a submission. Score: 0.00"
self._done = done
self._last = WorkbenchObservation(output=output, reward=reward, done=done,
remaining_steps=max(0, remaining))
return self._last
def close(self):
if self._workdir:
shutil.rmtree(self._workdir, ignore_errors=True)
self._workdir = None
self._task = None