#!/usr/bin/env python3 from __future__ import annotations import argparse import json import os import shutil import subprocess import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] DEFAULT_EVALS = ROOT / "data" / "opencode_tool_calling_eval.jsonl" DEFAULT_CONFIG = ROOT / "configs" / "opencode-qwen35.json" WORK_ROOT = ROOT / "tmp" / "opencode-eval" def iter_jsonl(path: Path): with path.open() as f: for line in f: if line.strip(): yield json.loads(line) def seed_workspace(case: dict, workdir: Path) -> None: if workdir.exists(): shutil.rmtree(workdir) workdir.mkdir(parents=True) for rel, text in case["files"].items(): path = workdir / rel path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text) def apply_expected_outputs(case: dict, workdir: Path) -> None: for rel, text in (case.get("verify") or {}).items(): path = workdir / rel path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text) for rel, needles in (case.get("verify_contains") or {}).items(): path = workdir / rel path.parent.mkdir(parents=True, exist_ok=True) path.write_text("\n".join(needles) + "\n") for rel in case.get("verify_missing") or []: path = workdir / rel if path.exists(): path.unlink() def verify_case(case: dict, workdir: Path) -> list[str]: errors: list[str] = [] for rel, expected in (case.get("verify") or {}).items(): path = workdir / rel if not path.exists(): errors.append(f"{rel} is missing") elif path.read_text() != expected: errors.append(f"{rel} did not match expected content") for rel, needles in (case.get("verify_contains") or {}).items(): path = workdir / rel if not path.exists(): errors.append(f"{rel} is missing") continue text = path.read_text().lower() for needle in needles: if needle.lower() not in text: errors.append(f"{rel} does not contain {needle!r}") for rel in case.get("verify_missing") or []: if (workdir / rel).exists(): errors.append(f"{rel} still exists") command = case.get("verify_command") if command: proc = subprocess.run(command, cwd=workdir, text=True, capture_output=True, timeout=120) if proc.returncode != 0: errors.append(f"verify_command failed: {proc.stdout}{proc.stderr}") return errors def parse_tool_mentions(text: str, expected_tools: list[str]) -> list[str]: found: list[str] = [] lower = text.lower() for name in expected_tools: if name.lower() in lower: found.append(name) return found def self_check_case(case: dict) -> dict: workdir = WORK_ROOT / f"self-check-{case['id']}" seed_workspace(case, workdir) apply_expected_outputs(case, workdir) errors = verify_case(case, workdir) return {"id": case["id"], "passed": not errors, "verify_errors": errors} def run_case(case: dict, args: argparse.Namespace) -> dict: workdir = WORK_ROOT / case["id"] seed_workspace(case, workdir) config_content = args.config.read_text() command = [ "bunx", "opencode-ai@latest", "run", "--model", args.model, "--format", "json", "--dir", str(workdir), ] if args.dangerously_skip_permissions: command.append("--dangerously-skip-permissions") command.append(case["prompt"]) env = os.environ.copy() env["OPENCODE_CONFIG_CONTENT"] = config_content env.setdefault("OPENAI_API_KEY", "omlx") start = time.time() proc = subprocess.run(command, cwd=workdir, text=True, capture_output=True, timeout=args.timeout, env=env) verify_errors = verify_case(case, workdir) if proc.returncode == 0 else ["opencode exited nonzero"] combined = f"{proc.stdout}\n{proc.stderr}" return { "id": case["id"], "returncode": proc.returncode, "seconds": round(time.time() - start, 3), "passed": proc.returncode == 0 and not verify_errors, "verify_errors": verify_errors, "expected_tools": case.get("expected_tools") or [], "observed_tool_mentions": parse_tool_mentions(combined, case.get("expected_tools") or []), "stdout_tail": proc.stdout[-4000:], "stderr_tail": proc.stderr[-4000:], } def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--evals", type=Path, default=DEFAULT_EVALS) parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG) parser.add_argument("--model", default="qwen35/qwen35") parser.add_argument("--timeout", type=int, default=300) parser.add_argument("--limit", type=int) parser.add_argument("--self-check", action="store_true", help="Verify eval seed/check logic without invoking opencode.") parser.add_argument("--dangerously-skip-permissions", action="store_true", help="Pass opencode's non-interactive permission bypass flag for disposable eval workspaces.") args = parser.parse_args() WORK_ROOT.mkdir(parents=True, exist_ok=True) cases = list(iter_jsonl(args.evals)) if args.limit is not None: cases = cases[: args.limit] results = [] for case in cases: if args.self_check: result = self_check_case(case) else: print(f"running {case['id']}") try: result = run_case(case, args) except subprocess.TimeoutExpired as exc: result = { "id": case["id"], "returncode": None, "seconds": args.timeout, "passed": False, "verify_errors": ["opencode timed out"], "expected_tools": case.get("expected_tools") or [], "observed_tool_mentions": [], "stdout_tail": (exc.stdout or "")[-4000:], "stderr_tail": (exc.stderr or "")[-4000:], } print(json.dumps(result, indent=2)) results.append(result) out = ROOT / "tmp" / "opencode-eval-results.json" out.write_text(json.dumps(results, indent=2) + "\n") failed = [row for row in results if not row["passed"]] print(f"passed {len(results) - len(failed)}/{len(results)}") return 1 if failed else 0 if __name__ == "__main__": raise SystemExit(main())