llm-bench

"""Claude reference runner: one agentic attempt driven by headless `claude -p` (the subscription,
not the API) instead of the HTTP tool loop. Same tools, same results: agent_loop() here takes and
returns what tools.agent_loop does, so run_item, the gates and the rows are unchanged.

The instrument's toolset is served to Claude over MCP (claude_mcp.py relays each call back to a
bridge in this process, which runs it on the attempt's Workspace through tools.run_tool, with the
same truncation). Claude gets no built-in tools (--tools ""), no MCP server but ours
(--strict-mcp-config), no settings, skills or slash commands, and runs from an empty temp dir
outside any repo, so no CLAUDE.md or project memory. What it still sees beyond a local lane's
prompt: Claude Code's one-line SDK preamble, its environment block (temp cwd, darwin, date) and
the account e-mail reminder (captured 2026-10-12, CLI 2.1.296). Claude Code sets the sampler; the
lane records model and effort.

The system prompt (the task plan, ports and paths included) goes in through --system-prompt-file,
never argv: a model's `pkill -f cmd/server` matched claude's own command line and SIGTERMed the
session (Opus low, go_htmx, 2026-10-12).

One process per attempt, stream-json in and out: a query that ends without the stop tool is a
no-tool turn (done word / nudge / give up, as in tools.agent_loop). Per-turn tokens come from
the message_delta events (exact output + thinking tokens). The process is killed right after the
stop tool's result or when turn max_turns + 1 starts, so turn counts match the HTTP loop.

Lane keys (runner "claude-cli"): model (--model), effort (--effort, optional), http_timeout
(seconds per attempt), max_concurrency.
"""
import json
import os
import secrets
import shutil
import signal
import subprocess
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from bench.core import client, tools

RUNNER = "claude-cli"
CLAUDE = os.environ.get("CLAUDE_BIN", "claude")
MCP_SERVER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "claude_mcp.py")
SERVER = "bench"  # MCP server name: Claude sees mcp__bench__<tool>
ENDED = "ERROR: the session has ended; do not call more tools."


def is_claude(lane):
    return (lane.raw.get("runner") if lane is not None else None) == RUNNER


class Bridge:
    """The tools endpoint claude_mcp.py relays to. Calls run one at a time, in arrival order."""

    def __init__(self, ws, toolset, trunc_fmt, result_cap):
        self.ws, self.toolset = ws, toolset
        self.trunc_fmt, self.result_cap = trunc_fmt, result_cap
        self.calls, self.stopped, self.infra = [], False, None
        self.token = secrets.token_hex(16)
        self._lock = threading.Lock()
        bridge = self

        class Handler(BaseHTTPRequestHandler):
            def log_message(self, *a):
                pass

            def _send(self, code, obj):
                body = json.dumps(obj).encode()
                self.send_response(code)
                self.send_header("Content-Type", "application/json")
                self.send_header("Content-Length", str(len(body)))
                self.end_headers()
                self.wfile.write(body)

            def do_GET(self):
                if self.headers.get("X-Bench-Token") != bridge.token:
                    return self._send(403, {"error": "bad token"})
                self._send(200, bridge.tool_list())

            def do_POST(self):
                if self.headers.get("X-Bench-Token") != bridge.token:
                    return self._send(403, {"error": "bad token"})
                req = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)))
                self._send(200, {"text": bridge.call(req.get("name") or "", req.get("arguments") or {})})

        self.srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
        self.url = "http://127.0.0.1:%d" % self.srv.server_port
        threading.Thread(target=self.srv.serve_forever, daemon=True).start()

    def tool_list(self):
        return [{"name": f["function"]["name"], "description": f["function"].get("description", ""),
                 "inputSchema": f["function"].get("parameters") or {"type": "object", "properties": {}}}
                for f in self.toolset.schema]

    def call(self, name, args):
        with self._lock:
            rec = {"name": name, "args_head": json.dumps(args)[:200], "executed": False}
            if self.stopped or self.infra is not None:
                result = ENDED
            else:
                try:
                    result, stop = tools.run_tool(self.ws, self.toolset, name, args)
                    rec["executed"] = True
                    self.stopped = stop
                except tools.InfraError as e:
                    self.infra = e
                    result = "ERROR: the machine is unavailable"
            if self.trunc_fmt is not None and len(result) > self.result_cap:
                result = result[:self.result_cap] + self.trunc_fmt.format(n=len(result))
            rec.update(result_len=len(result), result_head=result[:200])
            self.calls.append(rec)
            return result

    def close(self):
        self.srv.shutdown()
        self.srv.server_close()


def command(lane, system_file, cfg, toolset):
    allowed = ["mcp__%s__%s" % (SERVER, f["function"]["name"]) for f in toolset.schema]
    cmd = [CLAUDE, "-p", "--output-format", "stream-json", "--input-format", "stream-json",
           "--verbose", "--include-partial-messages", "--model", lane.model,
           "--setting-sources", "", "--disable-slash-commands", "--no-session-persistence",
           "--tools", "", "--mcp-config", cfg, "--strict-mcp-config", "--permission-mode", "dontAsk",
           "--allowedTools", *allowed, "--system-prompt-file", system_file]
    if lane.raw.get("effort"):
        cmd += ["--effort", lane.raw["effort"]]
    return cmd


def _user(text):
    return json.dumps({"type": "user", "message": {"role": "user", "content": text}}) + "\n"


def agent_loop(ws, messages, toolset, *, max_turns, item_id=None, run_id=None, lane=None,
               done_word=True, give_up_after=None, nudge="", trunc_fmt="\n...[truncated, {n} total]",
               result_cap=tools.RESULT_CAP, log=print, tag="", **_http_only):
    """tools.agent_loop's contract on claude -p. messages = [system, user]; max_tokens and
    temperature are the HTTP loop's and do not apply."""
    turns = []
    out = {"stop_reason": "max_turns", "turns_used": 0, "turns": turns, "error": None,
           "error_dt": None, "harness_error": None, "last_resp": None, "row_extra": {}}
    system = "\n\n".join(m["content"] for m in messages if m["role"] == "system")
    user = "\n\n".join(m["content"] for m in messages if m["role"] == "user")
    bridge = Bridge(ws, toolset, trunc_fmt, result_cap)
    tmp = tempfile.mkdtemp(prefix="llm-bench-claude-")
    cfg = os.path.join(tmp, "mcp.json")
    with open(cfg, "w") as f:
        json.dump({"mcpServers": {SERVER: {"command": "/usr/bin/python3", "args": ["-I", MCP_SERVER],
                                           "env": {"BENCH_BRIDGE_URL": bridge.url,
                                                   "BENCH_BRIDGE_TOKEN": bridge.token}}}}, f)
    with open(os.path.join(tmp, "system.txt"), "w") as f:
        f.write(system)
    os.makedirs(os.path.join(tmp, "cwd"))
    env = dict(os.environ, MCP_TOOL_TIMEOUT="1800000", MCP_TIMEOUT="60000", DISABLE_AUTOUPDATER="1")
    t0 = time.time()
    proc, watchdog, killed = None, None, {"why": None}

    def kill(why):
        if killed["why"] is None:
            killed["why"] = why
        try:
            os.killpg(proc.pid, signal.SIGKILL)
        except (ProcessLookupError, PermissionError):
            pass

    try:
        with open(os.path.join(tmp, "stderr"), "w") as err:
            proc = subprocess.Popen(command(lane, os.path.join(tmp, "system.txt"), cfg, toolset), cwd=os.path.join(tmp, "cwd"), env=env,
                                    stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=err,
                                    text=True, start_new_session=True)
        watchdog = threading.Timer(lane.http_timeout, kill, ("timeout",))
        watchdog.daemon = True
        watchdog.start()
        proc.stdin.write(_user(user))
        proc.stdin.flush()
        cur, t_turn, streak, tools_since_user, n_results = None, time.time(), 0, False, 0
        for line in proc.stdout:
            try:
                ev = json.loads(line)
            except ValueError:
                continue
            typ = ev.get("type")
            if typ == "system" and ev.get("subtype") == "init":
                out["row_extra"] = {"claude_model": ev.get("model"),
                                    "claude_version": ev.get("claude_code_version")}
                if not any(s.get("name") == SERVER and s.get("status") == "connected"
                           for s in ev.get("mcp_servers") or ()):
                    raise client.CallError("conn", "MCP tool bridge not connected: %s"
                                           % ev.get("mcp_servers"))
            elif typ == "stream_event":
                e = ev.get("event") or {}
                if e.get("type") == "message_start":
                    if len(turns) == max_turns:
                        kill("max_turns")
                        break
                    cur = {"turn": len(turns) + 1, "id": e["message"].get("id"), "tools": [],
                           "tool_names": [], "text": "", "t_start": t_turn}
                    turns.append(cur)
                    out["turns_used"] = cur["turn"]
                elif e.get("type") == "message_delta" and cur is not None:
                    u = e.get("usage") or {}
                    cur.update(prompt_tokens=sum(u.get(k) or 0 for k in (
                        "input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens")),
                        completion_tokens=u.get("output_tokens") or 0,
                        reasoning_tokens=(u.get("output_tokens_details") or {}).get("thinking_tokens"),
                        finish=(e.get("delta") or {}).get("stop_reason"))
                elif e.get("type") == "message_stop" and cur is not None:
                    cur["wall_s"] = round(time.time() - cur.pop("t_start"), 2)
                    cur["cut_off"] = cur.get("finish") == "max_tokens"
                    log(f"  {tag}turn {cur['turn']:2d}: {cur['wall_s']:6.1f}s "
                        f"ptok={cur.get('prompt_tokens', 0):6d} ctok={cur.get('completion_tokens', 0):5d} "
                        f"rtok={cur.get('reasoning_tokens') or 0:5d} fr={str(cur.get('finish')):10s} "
                        f"tools=[{','.join(cur['tool_names']) or '(no tool call)'}]")
            elif typ == "assistant" and cur is not None:
                for b in (ev.get("message") or {}).get("content") or ():
                    if b.get("type") == "tool_use":
                        cur["tool_names"].append(str(b.get("name", "")).replace(f"mcp__{SERVER}__", ""))
                        tools_since_user = True
                    elif b.get("type") == "text":
                        cur["text"] += b.get("text") or ""
            elif typ == "user" and any(isinstance(b, dict) and b.get("type") == "tool_result"
                                       for b in (ev.get("message") or {}).get("content") or ()):
                t_turn = time.time()  # tool results are back: the next turn's clock starts
                if bridge.stopped or bridge.infra is not None:
                    kill("stop")
                    break
            elif typ == "result":
                n_results += 1
                if ev.get("is_error"):
                    raise client.CallError("http", str(ev.get("result") or ev.get("subtype"))[:500],
                                           code=429 if "limit" in str(ev.get("result")).lower() else 502)
                if bridge.stopped:
                    break
                text = str(ev.get("result") or "")
                if done_word and tools.said_done(text):
                    if turns:
                        turns[-1]["done"] = True
                    out["stop_reason"] = "done"
                    break
                streak = 1 if tools_since_user else streak + 1
                tools_since_user = False
                if give_up_after and streak >= give_up_after:
                    log(f"  {tag}-> giving up after {streak} no-tool turns")
                    out["stop_reason"] = "gave_up"
                    break
                if turns:
                    turns[-1]["nudged"] = True
                t_turn = time.time()
                proc.stdin.write(_user(nudge))
                proc.stdin.flush()
        if bridge.infra is not None:
            raise bridge.infra
        if bridge.stopped:
            out["stop_reason"] = "done"
            if turns:
                turns[-1]["done"] = True
        elif killed["why"] == "timeout":
            raise client.CallError("timeout", "claude -p passed http_timeout=%ss" % lane.http_timeout)
        elif killed["why"] is None and out["stop_reason"] == "max_turns" and len(turns) < max_turns:
            proc.wait(30)
            with open(os.path.join(tmp, "stderr")) as f:
                tail = f.read()[-400:]
            raise client.CallError("conn", "claude -p ended early (rc=%s, %d results): %s"
                                   % (proc.returncode, n_results, tail))
    except client.CallError as e:
        log(f"  {tag}CLAUDE ERROR {e.label()}: {str(e)[:200]}")
        out.update(stop_reason=e.label(), error=e, error_dt=time.time() - t0)
    except Exception as e:  # noqa: BLE001 — harness bug or InfraError: keep the turns logged so far
        log(f"  {tag}HARNESS ERROR in the claude loop: {e!r}")
        out.update(stop_reason="harness_error", harness_error=e)
    finally:
        if watchdog is not None:
            watchdog.cancel()
        if proc is not None:
            if proc.poll() is None:
                kill(killed["why"] or "done")
            proc.wait(30)
            for f in (proc.stdin, proc.stdout):
                try:
                    f.close()
                except OSError:
                    pass
        bridge.close()
        shutil.rmtree(tmp, ignore_errors=True)

    calls = iter(bridge.calls)
    for t in turns:
        t.pop("t_start", None)
        t.pop("id", None)
        t["tools"] = [next(calls, {"name": n, "executed": False}) for n in t.pop("tool_names")]
        t["n_tool_calls"] = len(t["tools"])
        t["content_head"] = t.pop("text")[:200]
    real = [t for t in turns if "wall_s" in t]
    rts = [t["reasoning_tokens"] for t in real if t.get("reasoning_tokens") 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.get("prompt_tokens", 0) for t in real),
        "completion_tokens": sum(t.get("completion_tokens", 0) for t in real),
        "reasoning_tokens": sum(rts) if rts else None,
        "peak_prompt_tokens": max((t.get("prompt_tokens", 0) for t in real), default=0),
        "cost_usd": None,  # subscription
        "finish_counts": finish_counts,
        "tool_calls": sum(len(t["tools"]) for t in real),
        "model_s": round(sum(t["wall_s"] for t in real), 2),
    })
    return out