"""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()