File size: 10,400 Bytes
b199558 | 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 303 | """TerminalBench-DockerLess evaluation harness.
A Terminal-Bench trial is: build the environment, let the agent work in it, then
run a verifier that decides success. Docker normally provides the environment;
here each row carries a `dockerless.setup` script that builds the same state in a
throwaway directory, so a trial needs only bash, git and python.
$TB_ROOT/
workspace/ <- the agent's cwd (the container's /workspace)
home/ <- HOME
tmp/ <- TMPDIR
bin/ <- prepended to PATH (holds a python3 shim)
tests/ <- the verifier, uploaded read-only-ish after the agent runs
Usage
-----
python run_harness.py --solution # oracle, expect 4/4
python run_harness.py --baseline # do nothing, expect 0/4
python run_harness.py --predictions preds.jsonl # {"task_id", "agent_script"}
A task is resolved when every verifier test passes (reward 1.0), which is the
Terminal-Bench rule.
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
RESULT_RE = re.compile(
r"^(test_[A-Za-z0-9_]+\.py::[A-Za-z0-9_\[\]\-\.]+)\s+(PASSED|FAILED|ERROR|SKIPPED|XFAIL|XPASS)"
)
PYTHON_SHIM = '#!/bin/sh\nexec python "$@"\n'
_BASH_CACHE = []
def find_bash():
"""Resolve a usable POSIX shell.
On Windows ``bash`` on PATH is often the WSL launcher, which may be blocked
or simply start a different filesystem; prefer Git's own bash and prove the
candidate works before trusting it.
"""
if _BASH_CACHE:
return _BASH_CACHE[0]
candidates = []
override = os.environ.get("TBDL_BASH")
if override:
candidates.append(override)
exepath = os.environ.get("EXEPATH")
if exepath:
candidates.append(os.path.join(exepath, "bash.exe"))
git = shutil.which("git")
if git:
git_bin = Path(git).resolve().parent
candidates.append(str(git_bin.parent / "bin" / "bash.exe"))
candidates.append(str(git_bin.parent / "usr" / "bin" / "bash.exe"))
if os.name == "nt":
candidates.append(r"C:\Program Files\Git\bin\bash.exe")
candidates.append(r"C:\Program Files\Git\usr\bin\bash.exe")
candidates.append(shutil.which("bash") or "bash")
for candidate in candidates:
if not candidate or not Path(candidate).exists():
continue
try:
probe = subprocess.run(
[candidate, "-c", "echo tbdl-ok"],
capture_output=True,
text=True,
timeout=20,
)
except (OSError, subprocess.SubprocessError):
continue
if probe.returncode == 0 and "tbdl-ok" in probe.stdout:
_BASH_CACHE.append(candidate)
return candidate
_BASH_CACHE.append("bash")
return "bash"
def write_files(files, dest):
for rel, content in files.items():
path = dest / rel
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8", newline="\n") as handle:
handle.write(content)
def sandbox_env(root):
env = os.environ.copy()
env.update(
{
"TB_ROOT": str(root),
"TB_WORK": str(root / "workspace"),
"HOME": str(root / "home"),
"TMPDIR": str(root / "tmp"),
"TEMP": str(root / "tmp"),
"TMP": str(root / "tmp"),
"PATH": str(root / "bin") + os.pathsep + env.get("PATH", ""),
"PYTHONIOENCODING": "utf-8",
"PYTHONDONTWRITEBYTECODE": "1",
"GIT_CONFIG_NOSYSTEM": "1",
"GIT_AUTHOR_NAME": "tbdl",
"GIT_AUTHOR_EMAIL": "tbdl@example.invalid",
"GIT_COMMITTER_NAME": "tbdl",
"GIT_COMMITTER_EMAIL": "tbdl@example.invalid",
"GIT_AUTHOR_DATE": "2026-10-30T12:00:00+0000",
"GIT_COMMITTER_DATE": "2026-10-30T12:00:00+0000",
"TB_BASH": find_bash(),
}
)
return env
def build_sandbox(row, root):
for name in ("workspace", "home", "tmp", "bin", "tests"):
(root / name).mkdir(parents=True, exist_ok=True)
shim = root / "bin" / "python3"
shim.write_text(PYTHON_SHIM, encoding="utf-8", newline="\n")
write_files(row["dockerless"]["files"], root / "workspace")
write_files(row["tests"], root / "tests")
env = sandbox_env(root)
setup = row["dockerless"].get("setup", "")
if setup.strip():
script = root / "setup.sh"
script.write_text(setup, encoding="utf-8", newline="\n")
proc = subprocess.run(
[find_bash(), str(script)],
cwd=str(root / "workspace"),
capture_output=True,
text=True,
encoding="utf-8",
env=env,
timeout=row["dockerless"].get("setup_timeout_sec", 120),
)
if proc.returncode != 0:
raise RuntimeError(
"setup failed for %s\n%s\n%s" % (row["task_id"], proc.stdout[-3000:], proc.stderr[-3000:])
)
return env
def run_script(path, cwd, env, timeout, label):
try:
return subprocess.run(
[find_bash(), str(path)],
cwd=str(cwd),
capture_output=True,
text=True,
encoding="utf-8",
env=env,
timeout=timeout,
)
except subprocess.TimeoutExpired:
return subprocess.CompletedProcess([], 124, "", "%s timed out after %ss" % (label, timeout))
def parse_results(stdout):
results = {}
for raw in stdout.splitlines():
match = RESULT_RE.match(raw.strip())
if match:
results[match.group(1)] = match.group(2)
return results
def evaluate(row, agent_script, root, keep=False):
env = build_sandbox(row, root)
work = root / "workspace"
note = "ok"
if agent_script is not None and agent_script.strip():
agent_path = root / "agent.sh"
agent_path.write_text(agent_script, encoding="utf-8", newline="\n")
proc = run_script(
agent_path, work, env, row.get("max_agent_timeout_sec", 300), "agent"
)
if proc.returncode != 0:
note = "agent script exited %d" % proc.returncode
test_cmd = row["dockerless"]["test_cmd"]
test_script = root / "tests" / "test.sh"
if test_cmd and test_cmd.strip():
test_path = root / "run-tests.sh"
test_path.write_text(test_cmd, encoding="utf-8", newline="\n")
else:
test_path = test_script
proc = run_script(
test_path, work, env, row.get("max_test_timeout_sec", 120), "verifier"
)
results = parse_results(proc.stdout)
passed = [name for name, outcome in results.items() if outcome == "PASSED"]
failed = sorted(name for name, outcome in results.items() if outcome != "PASSED")
resolved = bool(results) and not failed
return {
"task_id": row["task_id"],
"reward": 1.0 if resolved else 0.0,
"resolved": resolved,
"tests_passed": len(passed),
"tests_total": len(results),
"failing": failed[:12],
"note": note if results else "no tests collected",
"seconds": 0.0,
}, proc
def load_rows(path):
return [json.loads(line) for line in open(path, encoding="utf-8") if line.strip()]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset", default="TerminalBench-DockerLess.jsonl")
parser.add_argument("--solution", action="store_true", help="run each task's oracle solution")
parser.add_argument("--baseline", action="store_true", help="run no agent at all")
parser.add_argument("--predictions", help="JSONL of {task_id, agent_script}")
parser.add_argument("--only", help="restrict to one task_id")
parser.add_argument("--out", help="write a JSON report here")
args = parser.parse_args()
rows = load_rows(args.dataset)
if args.only:
rows = [row for row in rows if row["task_id"] == args.only]
if not rows:
parser.error("unknown task_id: %s" % args.only)
predictions = {}
if args.predictions:
for line in open(args.predictions, encoding="utf-8"):
if line.strip():
record = json.loads(line)
predictions[record["task_id"]] = record.get("agent_script", "")
started = time.time()
results = []
print("%-24s %-7s %-8s %s" % ("task_id", "reward", "tests", "note"))
for row in rows:
if args.solution:
agent_script = row.get("solution") or row["dockerless"].get("solution", "")
elif args.baseline:
agent_script = ""
else:
agent_script = predictions.get(row["task_id"], "")
root = Path(tempfile.mkdtemp(prefix="tbdl-%s-" % row["task_id"][:12]))
begin = time.time()
try:
result, proc = evaluate(row, agent_script, root)
finally:
shutil.rmtree(root, ignore_errors=True)
result["seconds"] = round(time.time() - begin, 2)
results.append(result)
print(
"%-24s %-7.1f %d/%-6d %s"
% (
result["task_id"],
result["reward"],
result["tests_passed"],
result["tests_total"],
result["note"],
)
)
if result["failing"] and args.baseline:
for name in result["failing"]:
print(" fail %s" % name)
solved = sum(1 for result in results if result["resolved"])
elapsed = time.time() - started
summary = {
"dataset": Path(args.dataset).name,
"mode": "solution" if args.solution else ("baseline" if args.baseline else "predictions"),
"tasks": len(rows),
"resolved": solved,
"resolve_rate": round(solved / len(rows), 4) if rows else 0.0,
"seconds": round(elapsed, 2),
"results": results,
}
print(
"\nresolved %d/%d (%.1f%%) in %.1fs"
% (solved, len(rows), 100.0 * summary["resolve_rate"], elapsed)
)
if args.out:
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
Path(args.out).write_text(json.dumps(summary, indent=2), encoding="utf-8")
print("report -> %s" % args.out)
if __name__ == "__main__":
main()
|