llm-bench

"""Workspace, tool implementations, gate helpers and the tool loop shared by the agentic
instruments (agentic-fix's hard tier, agentic-multitask, sleuth).

Workspace     one per attempt: its own work dir (work/<run_id>/<item_id>-<sample_idx>/), its own
              subprocess bookkeeping and environment, so attempts can run concurrently. Every
              subprocess (tool AND gate) runs in a new session and is killed as a process group
              on timeout and when the attempt ends (servers the model started in the background
              included). Each also carries LLM_BENCH_WS=<per-workspace token>, so anything that
              left its group (`setsid ./server &`) is found through /proc and killed too (Linux;
              elsewhere only the groups).
Toolset       the OpenAI `tools` schema + implementations for one task. build_toolset() makes the
              work-dir toolset with per-language run_build/run_test (GO_/RUST_/TS_TOOLSET).
agent_loop()  the multi-turn loop: call the model, execute tool calls, append results, until
              DONE / give-up / turn cap / CallError.

Hygiene rules
- Tool arguments must parse to a JSON object (a dict passed by the server is accepted); anything
  else gets an error result and is NOT executed. On a length-cut turn such a call gets
  CUT_OFF_MSG instead (the client repairs its arguments to "{}" in the next request).
- Every implementation runs inside try/except: a tool returns an error string, never kills the run.
- Paths must be non-empty, relative, and resolve (symlinks included) inside the work dir.
- Reads are binary-safe: a NUL byte in the first 8 KiB is reported, not dumped; search skips them.
- Tool subprocesses get stdin=/dev/null and write to temp files, not pipes, so a background
  child holding the stream open can't stall the call until timeout.

DONE (said_done): a no-tool turn whose answer text (inline <think> removed) contains the whole
word "done" in any case, not directly preceded by `not`, `never` or a word ending in `n't`
(optionally with one of yet/quite/fully/really/completely/all in between). "DONE", "Done.",
"`DONE`" count; "abandoned", "undone", "not done", "isn't done yet", "haven't done" don't.
"""
import json
import os
import re
import shlex
import signal
import socket
import sqlite3
import subprocess
import tempfile
import threading
import time
import urllib.parse
import urllib.request
import uuid

from bench.core import client

LLM_BENCH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
WORK_ROOT = os.environ.get("BENCH_WORK_DIR") or os.path.join(LLM_BENCH, "work")
# Set when the bench is started from an AI agent (Claude Code: CLAUDECODE). Tools change their output
# for agents (bun 1.3 drops its per-test "(pass)" lines), so graded subprocesses never see them.
AGENT_ENV = ("CLAUDECODE", "AGENT", "REPL_ID")

RESULT_CAP = 6000  # tool results longer than this are truncated before going to the model

CUT_OFF_MSG = ("ERROR: your output hit the max_tokens limit and this call was cut off; it was "
               "NOT executed. Re-issue it, splitting large files into several smaller "
               "write_file calls.")

BINARY_SNIFF = 8192


class ToolError(Exception):
    """A tool refused its input; the message goes back to the model as `ERROR: <msg>`."""


class InfraError(Exception):
    """The sandbox under a tool failed (not the model's command): the attempt is infra, ungraded."""


class Symlink(str):
    """A materialize() value: a symlink to this target instead of a file."""


class ToolResult:
    """A tool result that can also end the loop (agentic-fix's submit_fix)."""

    def __init__(self, text, stop=False):
        self.text = text
        self.stop = stop


# ============================================================ ports

_reserved = set()
_port_lock = threading.Lock()


def _listening(port):
    for host in ("127.0.0.1", "::1"):
        fam = socket.AF_INET6 if ":" in host else socket.AF_INET
        try:
            s = socket.socket(fam, socket.SOCK_STREAM)
        except OSError:
            continue
        s.settimeout(0.3)
        try:
            s.connect((host, port))
            return True
        except OSError:
            pass
        finally:
            s.close()
    return False


def port_is_free(port):
    """Nothing listens on loopback (v4 or v6) and the port can be bound on all interfaces.
    SO_REUSEADDR is set for the bind probe so TIME_WAIT leftovers don't count as busy."""
    if _listening(port):
        return False
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(("", port))
        return True
    except OSError:
        return False
    finally:
        s.close()


def free_port():
    """An OS-assigned free port, never handed out twice in this process (concurrent items)."""
    with _port_lock:
        for _ in range(50):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind(("", 0))
            p = s.getsockname()[1]
            s.close()
            if p not in _reserved and port_is_free(p):
                _reserved.add(p)
                return p
    raise RuntimeError("could not find a free port")


def release_port(port):
    with _port_lock:
        _reserved.discard(port)


def wait_port_free(port, timeout=5.0):
    end = time.time() + timeout
    while True:
        if port_is_free(port):
            return True
        if time.time() >= end:
            return False
        time.sleep(0.1)


# ============================================================ subprocesses

class RunResult:
    def __init__(self, rc, out, err, timed_out, timeout, dt):
        self.rc = rc
        self.out = out
        self.err = err
        self.timed_out = timed_out
        self.timeout = timeout
        self.dt = dt

    @property
    def ok(self):
        return self.rc == 0 and not self.timed_out

    def text(self):
        """The format the model sees."""
        if self.timed_out:
            return f"TIMEOUT after {self.timeout}s"
        return f"exit={self.rc}\n{(self.out + chr(10) + self.err).strip()}"

    def combined(self):
        return (self.out + self.err).strip()


def _killpg(pgid, sig):
    try:
        os.killpg(pgid, sig)
        return True
    except (ProcessLookupError, PermissionError):
        return False


def group_alive(pgid):
    try:
        os.killpg(pgid, 0)
        return True
    except ProcessLookupError:
        return False
    except PermissionError:
        return True


MARKER_ENV = "LLM_BENCH_WS"


def marked_pids(marker):
    """PIDs (ours, not this process) whose environment carries LLM_BENCH_WS=<marker>. Linux /proc
    only; [] elsewhere or for processes we can't read."""
    needle = f"{MARKER_ENV}={marker}".encode()
    out = []
    try:
        names = os.listdir("/proc")
    except OSError:
        return out
    for name in names:
        if not name.isdigit() or int(name) == os.getpid():
            continue
        try:
            with open(f"/proc/{name}/environ", "rb") as f:
                if needle in f.read().split(b"\0"):
                    out.append(int(name))
        except OSError:
            continue
    return out


def kill_marked(marker, grace=1.0):
    """SIGTERM every process carrying the marker, SIGKILL what's left after `grace`. Returns the
    PIDs still alive after that (should be empty)."""
    pids = marked_pids(marker)
    for sig in (signal.SIGTERM, signal.SIGKILL):
        for pid in pids:
            try:
                os.kill(pid, sig)
            except (ProcessLookupError, PermissionError):
                pass
        end = time.time() + (grace if sig == signal.SIGTERM else 2.0)
        while pids and time.time() < end:
            time.sleep(0.05)
            pids = [p for p in pids if _pid_running(p)]
        if not pids:
            break
    return pids


def _pid_running(pid):
    """Alive and not a zombie (a reparented child stays a zombie until init reaps it)."""
    try:
        with open(f"/proc/{pid}/stat", "rb") as f:
            return f.read().rsplit(b")", 1)[1].split()[0] != b"Z"
    except (OSError, IndexError):
        return False


def _read_tmp(f):
    try:
        f.flush()
        f.seek(0)
        return f.read().decode("utf-8", errors="replace")
    finally:
        f.close()


class Workspace:
    """Work dir + subprocess bookkeeping for one attempt. Use as a context manager or call
    close(); close() kills every process group started through it."""

    def __init__(self, path, env=None):
        self.dir = os.path.abspath(path)
        os.makedirs(self.dir, exist_ok=True)
        self.env_extra = dict(env or {})
        self.state = {}          # per-attempt scratch for instruments (fix: submission, reads)
        self.marker = uuid.uuid4().hex  # LLM_BENCH_WS: finds descendants that left their group
        self._groups = {}        # pgid -> Popen (leaders we started)
        self._lock = threading.Lock()
        self.ports = []
        self.cleanups = []       # callables run at close(), after the process groups die

    # ---- env / files -----------------------------------------------------------
    def env(self, extra=None):
        e = {k: v for k, v in os.environ.items() if k not in AGENT_ENV}
        for src in (self.env_extra, extra or {}):
            for k, v in src.items():
                if v is None:
                    e.pop(k, None)
                else:
                    e[k] = str(v)
        e[MARKER_ENV] = self.marker
        return e

    def materialize(self, files):
        return materialize(files, self.dir)

    def allocate_port(self):
        p = free_port()
        self.ports.append(p)
        return p

    # ---- processes ---------------------------------------------------------------
    def _prune(self):
        """Forget groups observed empty, so a recycled PGID is never signalled later.
        (A PGID can't be reused while its group has members; it can be once it is empty.)"""
        with self._lock:
            for g, p in list(self._groups.items()):
                if p.poll() is not None and not group_alive(g):
                    del self._groups[g]

    def _track(self, proc):
        self._prune()
        with self._lock:
            self._groups[proc.pid] = proc

    def live_groups(self):
        self._prune()
        with self._lock:
            return list(self._groups)

    def run(self, cmd, timeout, env=None):
        """Run `cmd` (str -> sh -c; list -> argv) in the work dir, in its own session.
        On timeout the whole process group is SIGKILLed. Background children that outlive
        the command stay tracked and die at close()."""
        out_f = tempfile.TemporaryFile()
        err_f = tempfile.TemporaryFile()
        t0 = time.time()
        try:
            proc = subprocess.Popen(cmd, shell=isinstance(cmd, str), cwd=self.dir,
                                    env=self.env(env), stdin=subprocess.DEVNULL,
                                    stdout=out_f, stderr=err_f, start_new_session=True)
        except Exception:
            out_f.close()
            err_f.close()
            raise
        self._track(proc)
        timed_out = False
        try:
            rc = proc.wait(timeout=timeout)
        except subprocess.TimeoutExpired:
            timed_out = True
            _killpg(proc.pid, signal.SIGKILL)
            rc = proc.wait()
        self._prune()
        return RunResult(None if timed_out else rc, _read_tmp(out_f), _read_tmp(err_f),
                         timed_out, timeout, time.time() - t0)

    def popen(self, argv, env=None):
        """Start a long-running process (a server under test) in its own session.
        Output goes to a temp file: read it with proc_output(proc)."""
        log = tempfile.TemporaryFile()
        proc = subprocess.Popen(argv, cwd=self.dir, env=self.env(env), stdin=subprocess.DEVNULL,
                                stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
        proc._bench_log = log
        self._track(proc)
        return proc

    @staticmethod
    def proc_output(proc, tail=2000):
        log = getattr(proc, "_bench_log", None)
        if log is None or log.closed:
            return ""
        try:
            log.flush()
            log.seek(0)
            return log.read().decode("utf-8", errors="replace")[-tail:]
        except (OSError, ValueError):
            return ""

    def stop(self, proc, grace=5.0):
        """SIGTERM the group, wait `grace`, then SIGKILL whatever is left of it."""
        _killpg(proc.pid, signal.SIGTERM)
        try:
            proc.wait(timeout=grace)
        except subprocess.TimeoutExpired:
            pass
        _killpg(proc.pid, signal.SIGKILL)
        try:
            proc.wait(timeout=5)
        except subprocess.TimeoutExpired:
            pass
        log = getattr(proc, "_bench_log", None)
        if log is not None and not log.closed:
            log.close()

    def kill_all(self, grace=1.0):
        """Kill every process group started through this workspace. Returns the pgids that
        still had live members afterwards (should be empty)."""
        self._prune()
        with self._lock:
            groups = dict(self._groups)
        live = [g for g in groups if group_alive(g)]
        for g in live:
            _killpg(g, signal.SIGTERM)
        end = time.time() + grace
        while live and time.time() < end:
            for g in live:
                p = groups[g]
                if p.poll() is None:
                    try:
                        p.wait(timeout=0.05)
                    except subprocess.TimeoutExpired:
                        pass
            live = [g for g in live if group_alive(g)]
            if live:
                time.sleep(0.05)
        for g in live:
            _killpg(g, signal.SIGKILL)
        for p in groups.values():
            if p.poll() is None:
                try:
                    p.wait(timeout=5)
                except subprocess.TimeoutExpired:
                    pass
            log = getattr(p, "_bench_log", None)
            if log is not None and not log.closed:
                log.close()
        end = time.time() + 2.0
        survivors = [g for g in groups if group_alive(g)]
        while survivors and time.time() < end:  # reparented zombies take a moment to reap
            time.sleep(0.05)
            survivors = [g for g in survivors if group_alive(g)]
        return survivors + kill_marked(self.marker, grace)

    def close(self):
        survivors = self.kill_all()
        for p in self.ports:
            release_port(p)
        for fn in self.cleanups:
            try:
                fn()
            except Exception:  # noqa: BLE001 — one failed cleanup must not skip the rest
                pass
        return survivors

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.close()


def materialize(files, dest):
    """Write {relative_path: str | bytes | Symlink} into dest (cleared first)."""
    import shutil
    shutil.rmtree(dest, ignore_errors=True)
    os.makedirs(dest, exist_ok=True)
    for path, content in files.items():
        fp = os.path.join(dest, path)
        os.makedirs(os.path.dirname(fp), exist_ok=True)
        if isinstance(content, Symlink):
            os.symlink(content, fp)
        elif isinstance(content, bytes):
            with open(fp, "wb") as f:
                f.write(content)
        else:
            with open(fp, "w", encoding="utf-8") as f:
                f.write(content)
    return dest


def prune(work_dir, names=("node_modules", "target", ".next")):
    """Delete heavy build dirs at the top of a finished work dir (keeps the source)."""
    import shutil
    for n in names:
        p = os.path.join(work_dir, n)
        if os.path.isdir(p) and not os.path.islink(p):
            shutil.rmtree(p, ignore_errors=True)


# ============================================================ test-count parsing (gates)

_GO_PASS = re.compile(r"^\s*--- PASS: ", re.M)
_CARGO_RESULT = re.compile(r"test result: \w+\. (\d+) passed")


def go_tests_passed(output):
    """Number of passing tests in `go test -v` output (subtests included)."""
    return len(_GO_PASS.findall(output or ""))


def cargo_tests_passed(output):
    """Sum of `N passed` over every `test result:` line of `cargo test` output."""
    return sum(int(n) for n in _CARGO_RESULT.findall(output or ""))


def build_test_gates(ws, toolset, test_cmd, count):
    """build: the toolset's build command exits 0; test: `test_cmd` exits 0 AND count(output)
    >= 1 (a suite with zero tests passes vacuously otherwise). -> ({build, test}, detail)"""
    t = toolset.commands["timeouts"]
    b = ws.run(toolset.commands["run_build"], t["build"])
    r = ws.run(test_cmd, t["test"])
    n = count(r.combined())
    g, d = {"build": b.ok, "test": r.ok and n >= 1}, {"tests_passed": n}
    if not b.ok:
        d["build_tail"] = b.text()[-400:]
    if not g["test"]:
        d["test_tail"] = r.text()[-400:]
    return g, d


def go_has_real_app(work_dir):
    """Not the starter stub: cmd/server/main.go serves HTTP and internal/ has >= 3 packages
    (build and test pass vacuously on `func main(){}`)."""
    main_go = os.path.join(work_dir, "cmd", "server", "main.go")
    internal = os.path.join(work_dir, "internal")
    if not os.path.isfile(main_go) or not os.path.isdir(internal):
        return False
    with open(main_go) as f:
        src = f.read()
    return (("ListenAndServe" in src or "http.Server" in src)
            and sum(os.path.isdir(os.path.join(internal, x)) for x in os.listdir(internal)) >= 3)


def _rm_db(path):
    for p in (path, path + "-wal", path + "-shm"):
        try:
            os.remove(p)
        except OSError:
            pass


def go_web_probe(ws, port, page_ok, form, table, column):
    """Build ./cmd/server and run it with NOTES_PORT/NOTES_DB; serves = GET / answers 200 with
    page_ok(html). Then POST `form` to /, GET / again and count the rows of `table` whose
    `column` = form[column] in the SQLite file.
    -> (serves, {post_fragment, later_get, db_row} or {} if the POST failed, detail)"""
    binpath, mark = os.path.join(ws.dir, "server"), form[column]
    r = ws.run(f"go build -o {shlex.quote(binpath)} ./cmd/server",
               GO_TOOLSET.commands["timeouts"]["build"])
    if not r.ok or not os.path.isfile(binpath):
        return False, {}, {"serves": "go build -o server failed: " + r.text()[-300:]}
    if port is None or not port_is_free(port):
        port = ws.allocate_port()
    d = {"port": port}
    dbpath = os.path.join(ws.dir, f"bench_{port}.db")
    _rm_db(dbpath)
    try:
        proc = ws.popen([binpath], env={"NOTES_PORT": str(port), "NOTES_DB": dbpath})
    except Exception as e:  # noqa: BLE001
        return False, {}, dict(d, serves=f"failed to start binary: {e!r}")
    try:
        for _ in range(40):
            try:
                with socket.create_connection(("127.0.0.1", port), 0.25):
                    break
            except OSError:
                time.sleep(0.25)
        else:
            return False, {}, dict(d, serves="binary did not start listening within 10s: "
                                   + ws.proc_output(proc, 300))
        url = f"http://127.0.0.1:{port}/"
        try:
            with urllib.request.urlopen(url, timeout=20) as resp:
                status, html = resp.status, resp.read().decode(errors="replace")
        except Exception as e:  # noqa: BLE001
            return False, {}, dict(d, serves=f"GET / failed: {e!r}")
        if status != 200 or not page_ok(html):
            return False, {}, dict(d, serves=f"GET / -> {status}, page check failed")
        try:
            data = urllib.parse.urlencode(form).encode()
            with urllib.request.urlopen(urllib.request.Request(url, data=data), timeout=20) as resp:
                post_body = resp.read().decode(errors="replace")
        except Exception as e:  # noqa: BLE001
            return True, {}, dict(d, persists=f"POST / failed: {e!r}")
        try:
            with urllib.request.urlopen(url, timeout=20) as resp:
                later = mark in resp.read().decode(errors="replace")
        except Exception as e:  # noqa: BLE001
            later, d["later_get_error"] = False, repr(e)[:200]
        db_row = False
        if not os.path.exists(dbpath):
            d["db_error"] = "no SQLite file at NOTES_DB"
        else:
            try:
                conn = sqlite3.connect(dbpath)
                try:
                    q = f"SELECT count(*) FROM {table} WHERE {column} = ?"
                    db_row = conn.execute(q, (mark,)).fetchone()[0] > 0
                finally:
                    conn.close()
            except Exception as e:  # noqa: BLE001
                d["db_error"] = repr(e)[:200]
        checks = {"post_fragment": mark in post_body, "later_get": later, "db_row": db_row}
        d["persists"] = " ".join(f"{k}={v}" for k, v in checks.items())
        return True, checks, d
    finally:
        ws.stop(proc)
        _rm_db(dbpath)


# ============================================================ path + file helpers

def resolve_path(ws, p):
    if not isinstance(p, str) or not p.strip():
        raise ToolError("path must be a non-empty, work-dir-relative string")
    if os.path.isabs(p) or p.startswith("~"):
        raise ToolError(f"path {p!r} is absolute; use a path relative to the work dir")
    full = os.path.normpath(os.path.join(ws.dir, p))
    root = os.path.realpath(ws.dir)
    real = os.path.realpath(full)
    if real != root and not real.startswith(root + os.sep):
        raise ToolError(f"path {p!r} is outside the work dir")
    return full


def _is_binary(data):
    return b"\x00" in data[:BINARY_SNIFF]


def _str_arg(args, key, default=None):
    v = args.get(key, default)
    if v is None:
        v = default
    if not isinstance(v, str):
        raise ToolError(f"`{key}` must be a string, got {type(v).__name__}")
    return v


def _walk(ws):
    for root, dirs, files in os.walk(ws.dir):
        dirs[:] = sorted(d for d in dirs if d not in {".git"})
        for f in sorted(files):
            full = os.path.join(root, f)
            yield full, os.path.relpath(full, ws.dir)


# ============================================================ work-dir tool impls

def _list_files(ws, args):
    return "\n".join(rel for _full, rel in _walk(ws))


def _read_file(ws, args):
    p = args.get("path", "")
    if isinstance(p, str) and not p.strip():
        return f"ERROR: no such file {p!r}. Use list_files."
    fp = resolve_path(ws, p)
    if not os.path.isfile(fp):
        return f"ERROR: no such file {p!r}. Use list_files."
    with open(fp, "rb") as f:
        data = f.read()
    if _is_binary(data):
        return f"ERROR: {p!r} is a binary file ({len(data)} bytes); not shown."
    return data.decode("utf-8", errors="replace")


def _write_file(ws, args):
    p = args.get("path", "")
    content = _str_arg(args, "content", "")
    fp = resolve_path(ws, p)
    if os.path.isdir(fp):
        raise ToolError(f"{p!r} is a directory")
    os.makedirs(os.path.dirname(fp), exist_ok=True)
    with open(fp, "w", encoding="utf-8") as f:
        f.write(content)
    return f"wrote {p} ({len(content)} bytes)"


def _edit_file(ws, args):
    p = args.get("path", "")
    old = _str_arg(args, "old_str", "")
    new = _str_arg(args, "new_str", "")
    fp = resolve_path(ws, p)
    if not os.path.isfile(fp):
        return f"ERROR: no such file {p!r}."
    with open(fp, "rb") as f:
        data = f.read()
    try:
        content = data.decode("utf-8")
    except UnicodeDecodeError:
        return f"ERROR: {p!r} is not a UTF-8 text file; use write_file to replace it."
    count = content.count(old)
    if count == 0:
        return f"ERROR: old_str not found in {p}."
    if count > 1:
        return f"ERROR: old_str appears {count} times in {p}; make it unique."
    new_content = content.replace(old, new, 1)
    with open(fp, "w", encoding="utf-8") as f:
        f.write(new_content)
    return f"edited {p} ({len(old)} -> {len(new)} chars)"


def _search(ws, args):
    pat = _str_arg(args, "pattern", "")
    try:
        rx = re.compile(pat)
    except re.error as e:
        return f"ERROR: bad regex: {e}"
    hits = []
    for full, rel in _walk(ws):
        try:
            with open(full, "rb") as fh:
                data = fh.read()
        except OSError:
            continue
        if _is_binary(data):
            continue
        for i, line in enumerate(data.decode("utf-8", errors="replace").splitlines(), 1):
            if rx.search(line):
                hits.append(f"{rel}:{i}: {line.strip()}")
    return "\n".join(hits) if hits else "(no matches)"


def _cmd_tool(cmd, timeout):
    def impl(ws, args):
        return ws.run(cmd, timeout).text()
    return impl


def _shell_tool(timeout):
    def impl(ws, args):
        cmd = _str_arg(args, "cmd", "")
        if not cmd:
            return "ERROR: empty cmd"
        return ws.run(cmd, timeout).text()
    return impl


# ============================================================ toolsets

class Toolset:
    def __init__(self, name, schema, impls, cut_off_msg=CUT_OFF_MSG, commands=None,
                 unknown_fmt="ERROR: unknown tool {name!r}"):
        self.name = name
        self.schema = schema
        self.impls = impls
        self.cut_off_msg = cut_off_msg
        self.unknown_fmt = unknown_fmt
        self.commands = dict(commands or {})

    def describe(self):
        return {"name": self.name, "commands": self.commands,
                "tools": [t["function"]["name"] for t in self.schema]}


def _env_int(name, default):
    v = os.environ.get(name)
    return int(v) if v else default


def build_toolset(name, *, build_cmd, test_cmd, build_desc, test_desc, shell_uses,
                  build_timeout, test_timeout, shell_timeout):
    """The work-dir toolset; languages differ only in run_build/run_test/run_shell."""
    build_timeout = _env_int("BUILD_TIMEOUT", build_timeout)
    test_timeout = _env_int("TEST_TIMEOUT", test_timeout)
    shell_timeout = _env_int("SHELL_TIMEOUT", shell_timeout)
    schema = [
        {"type": "function", "function": {
            "name": "list_files",
            "description": "List all file paths in the work dir (the project you are building). Returns one path per line.",
            "parameters": {"type": "object", "properties": {}},
        }},
        {"type": "function", "function": {
            "name": "read_file",
            "description": "Return the full contents of one file in the work dir.",
            "parameters": {"type": "object", "properties": {
                "path": {"type": "string", "description": "Project-relative file path"},
            }, "required": ["path"]},
        }},
        {"type": "function", "function": {
            "name": "write_file",
            "description": "Create or overwrite a file in the work dir with the given contents. Use for new files or full rewrites.",
            "parameters": {"type": "object", "properties": {
                "path": {"type": "string"},
                "content": {"type": "string", "description": "Full file contents to write"},
            }, "required": ["path", "content"]},
        }},
        {"type": "function", "function": {
            "name": "edit_file",
            "description": "Apply a patch-style edit to an existing file: replace the first occurrence of old_str with new_str. Fails if old_str is not found or appears more than once. Use this for surgical edits instead of rewriting the whole file.",
            "parameters": {"type": "object", "properties": {
                "path": {"type": "string"},
                "old_str": {"type": "string", "description": "The exact text to find (must be unique in the file)"},
                "new_str": {"type": "string", "description": "The replacement text"},
            }, "required": ["path", "old_str", "new_str"]},
        }},
        {"type": "function", "function": {
            "name": "search",
            "description": "Regex-search the whole work dir; returns matching path:line: text, one per line.",
            "parameters": {"type": "object", "properties": {
                "pattern": {"type": "string"},
            }, "required": ["pattern"]},
        }},
        {"type": "function", "function": {
            "name": "run_build",
            "description": build_desc,
            "parameters": {"type": "object", "properties": {}},
        }},
        {"type": "function", "function": {
            "name": "run_test",
            "description": test_desc,
            "parameters": {"type": "object", "properties": {}},
        }},
        {"type": "function", "function": {
            "name": "run_shell",
            "description": "Run an arbitrary shell command in the work dir (cwd = work dir). Use for " + shell_uses + ". Returns exit code + combined stdout/stderr. Timeout " + str(shell_timeout) + "s.",
            "parameters": {"type": "object", "properties": {
                "cmd": {"type": "string", "description": "The shell command to run (sh -c)"},
            }, "required": ["cmd"]},
        }},
    ]
    impls = {
        "list_files": _list_files,
        "read_file": _read_file,
        "write_file": _write_file,
        "edit_file": _edit_file,
        "search": _search,
        "run_build": _cmd_tool(build_cmd, build_timeout),
        "run_test": _cmd_tool(test_cmd, test_timeout),
        "run_shell": _shell_tool(shell_timeout),
    }
    return Toolset(name, schema, impls, commands={
        "run_build": build_cmd, "run_test": test_cmd,
        "timeouts": {"build": build_timeout, "test": test_timeout, "shell": shell_timeout}})


GO_TOOLSET = build_toolset(
    "go", build_cmd="go build ./...", test_cmd="go test ./...",
    build_desc="Run `go build ./...` in the work dir. Returns exit code + combined stdout/stderr.",
    test_desc="Run `go test ./...` in the work dir. Returns exit code + combined stdout/stderr.",
    shell_uses="`go get`, `go mod tidy`, starting the server in the background, curl, etc",
    build_timeout=180, test_timeout=180, shell_timeout=60)
RUST_TOOLSET = build_toolset(
    "rust", build_cmd="cargo build", test_cmd="cargo test",
    build_desc="Run `cargo build` in the work dir. Returns exit code + combined stdout/stderr.",
    test_desc="Run `cargo test` in the work dir. Returns exit code + combined stdout/stderr.",
    shell_uses="`cargo add`, `cargo run`, running the built binary, curl, etc",
    build_timeout=600, test_timeout=600, shell_timeout=60)
TS_TOOLSET = build_toolset(
    "ts", build_cmd="npx tsc --noEmit", test_cmd="npm test",
    build_desc="Run `npx tsc --noEmit` (the TypeScript typecheck) in the work dir. Returns exit code + combined stdout/stderr.",
    test_desc="Run `npm test` in the work dir. Returns exit code + combined stdout/stderr.",
    shell_uses="`npm install`, `npx prisma generate`, `npx prisma db push`, starting the dev server in the background, curl, etc",
    build_timeout=120, test_timeout=120, shell_timeout=300)


# ============================================================ tool-call execution

def parse_args(raw):
    """(args_dict, None) or (None, error_text). Empty/None arguments mean {}."""
    if isinstance(raw, dict):
        return raw, None
    if raw is None or (isinstance(raw, str) and not raw.strip()):
        return {}, None
    if not isinstance(raw, str):
        return None, f"arguments must be a JSON object, got {type(raw).__name__}"
    try:
        v = json.loads(raw)
    except ValueError as e:
        return None, str(e)
    if not isinstance(v, dict):
        return None, f"arguments must be a JSON object, got {type(v).__name__}"
    return v, None


def run_tool(ws, toolset, name, args):
    """Execute one call. Returns (text, stop). Never raises."""
    impl = toolset.impls.get(name)
    if impl is None:
        return toolset.unknown_fmt.format(name=name), False
    try:
        r = impl(ws, args)
    except ToolError as e:
        return f"ERROR: {e}", False
    except InfraError:
        raise  # agent_loop records it as harness_error: infra, never a grade
    except Exception as e:  # noqa: BLE001 — a tool may fail, the run may not
        return f"ERROR: {name} raised {e!r}", False
    if isinstance(r, ToolResult):
        return str(r.text), r.stop
    return str(r), False


_DONE_RE = re.compile(r"\bdone\b", re.I)
_NEG_RE = re.compile(r"(?:\bnot|\bnever|n't)\s+(?:(?:yet|quite|fully|really|completely|all)\s+)?$",
                     re.I)


def said_done(text):
    """Whole-word, un-negated "done" (see module docstring)."""
    if not text:
        return False
    for m in _DONE_RE.finditer(text):
        if not _NEG_RE.search(text[max(0, m.start() - 40):m.start()]):
            return True
    return False


def _fmt(v, width, spec="d"):
    if v is None:
        return "-".rjust(width)
    return format(v, f"{width}{spec}")


def agent_loop(ws, messages, toolset, *, max_turns, max_tokens, temperature, item_id=None,
               run_id=None, lane=None, done_word=True, give_up_after=None, nudge="",
               bad_json_fmt="ERROR: invalid JSON args ({e}); re-emit the {name} call.",
               trunc_fmt="\n...[truncated, {n} total]", result_cap=RESULT_CAP,
               log=print, tag=""):
    """Run the tool loop on `messages` (mutated in place).

    done_word      a no-tool turn whose answer says DONE ends the loop (stop_reason "done")
    give_up_after  stop after this many consecutive no-tool turns (None = never; nudge each)
    nudge          user message appended after a no-tool turn that didn't end the loop
    bad_json_fmt   tool result for a non-cut call whose arguments aren't a JSON object
    trunc_fmt      suffix for results over result_cap ({n} = full length); None = no cap

    Returns {stop_reason, turns_used, turns, error, error_dt, harness_error, cut_off_turns,
    totals...}. stop_reason: done | max_turns | gave_up | <CallError label> | harness_error.
    Nothing escapes: a CallError lands in `error`, any other exception (a harness bug) in
    `harness_error`, with the turns logged up to that point."""
    turns = []
    out = {"stop_reason": "max_turns", "turns_used": 0, "turns": turns, "error": None,
           "error_dt": None, "harness_error": None, "last_resp": None}
    no_tool_streak = 0
    try:
        for turn in range(1, max_turns + 1):
            out["turns_used"] = turn
            t_call = time.time()
            try:
                resp, dt = client.call_model(messages, tools=toolset.schema, max_tokens=max_tokens,
                                             temperature=temperature, item_id=item_id,
                                             run_id=run_id, lane=lane)
            except client.CallError as e:
                dt = time.time() - t_call
                log(f"  {tag}turn {turn:2d}: REQUEST ERROR {e.label()}: {str(e)[:200]}")
                turns.append({"turn": turn, **client.error_meta(e, dt)})
                out.update(stop_reason=e.label(), error=e, error_dt=dt)
                break
            out["last_resp"] = resp
            msg = resp["choices"][0].get("message") or {}
            fr = client.finish_reason(resp)
            tcs = [tc for tc in client.tool_calls(resp) if isinstance(tc, dict)]
            text = client.content(resp)
            cut_off = fr == "length"
            tlog = {"turn": turn, **client.meta(resp, dt), "cut_off": cut_off,
                    "content_head": text[:200], "n_tool_calls": len(tcs), "tools": []}
            turns.append(tlog)
            names = ",".join(((tc.get("function") or {}).get("name") or "?") for tc in tcs)
            log(f"  {tag}turn {turn:2d}: {dt:6.1f}s ptok={_fmt(tlog['prompt_tokens'], 6)} "
                f"ctok={_fmt(tlog['completion_tokens'], 5)} rtok={_fmt(tlog['reasoning_tokens'], 5)} "
                f"fr={str(fr):10s} tools=[{names or '(no tool call)'}]{' CUT-OFF' if cut_off else ''}")

            a_msg = dict(msg)
            a_msg["role"] = "assistant"
            a_msg["content"] = msg.get("content") or ""
            if tcs:
                a_msg["tool_calls"] = tcs
            else:
                a_msg.pop("tool_calls", None)

            if not tcs:
                if done_word and said_done(text):
                    tlog["done"] = True
                    out["stop_reason"] = "done"
                    break
                no_tool_streak += 1
                if give_up_after and no_tool_streak >= give_up_after:
                    log(f"  {tag}-> giving up after {no_tool_streak} no-tool turns")
                    tlog["gave_up"] = True
                    out["stop_reason"] = "gave_up"
                    break
                tlog["nudged"] = True
                messages.append(a_msg)
                messages.append({"role": "user", "content": nudge})
                continue

            no_tool_streak = 0
            messages.append(a_msg)
            stop = False
            for tc in tcs:
                fn = tc.get("function") or {}
                name = fn.get("name") or ""
                raw = fn.get("arguments")
                args, perr = parse_args(raw)
                executed = False
                if args is None:
                    result = toolset.cut_off_msg if cut_off else bad_json_fmt.format(e=perr, name=name)
                else:
                    result, stop = run_tool(ws, toolset, name, args)
                    executed = True
                if trunc_fmt is not None and len(result) > result_cap:
                    result = result[:result_cap] + trunc_fmt.format(n=len(result))
                messages.append({"role": "tool", "tool_call_id": tc.get("id", ""), "content": result})
                raw_s = raw if isinstance(raw, str) else json.dumps(raw)
                tlog["tools"].append({"name": name, "executed": executed,
                                      "args_head": (raw_s or "")[:200], "result_len": len(result),
                                      "result_head": result[:200]})
                if stop:
                    break
            if stop:
                tlog["done"] = True
                out["stop_reason"] = "done"
                break

    except Exception as e:  # noqa: BLE001 — harness bug: keep the turns logged so far
        log(f"  {tag}HARNESS ERROR in the loop: {e!r}")
        turns.append({"turn": out["turns_used"], **client.error_meta(e)})
        out.update(stop_reason="harness_error", harness_error=e)

    real = [t for t in turns if "error" not in t]
    rts = [t["reasoning_tokens"] for t in real if t.get("reasoning_tokens") is not None]
    costs = [t["cost_usd"] for t in real if t.get("cost_usd") is not None]
    finish_counts = {}
    for t in real:
        finish_counts[str(t.get("finish"))] = finish_counts.get(str(t.get("finish")), 0) + 1
    out.update({
        "cut_off_turns": sum(1 for t in real if t.get("cut_off")),
        "prompt_tokens": sum(t["prompt_tokens"] for t in real),
        "completion_tokens": sum(t["completion_tokens"] for t in real),
        "reasoning_tokens": sum(rts) if rts else None,
        "peak_prompt_tokens": max((t["prompt_tokens"] for t in real), default=0),
        "cost_usd": round(sum(costs), 6) if costs else None,
        "finish_counts": finish_counts,
        "tool_calls": sum(len(t["tools"]) for t in real),
        "model_s": round(sum(t.get("wall_s") or 0 for t in turns), 2),
    })
    return out