diff --git a/app/nullius/catalogue/benchmarks/mypcbench/agents.json b/app/nullius/catalogue/benchmarks/mypcbench/agents.json new file mode 100644 index 000000000..c3b2d03c6 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/agents.json @@ -0,0 +1,89 @@ +{ + "about": "The upstream's agents (run_mypcbench.py --agent_type). env points each one's model client at the unit's relay: {base_url} ends in /v1, {base} is the same without it, {key} the relay's placeholder.", + "agents": { + "claude-cuabash": { + "key": "claude-cuabash", + "label": "Claude", + "summary": "Claude's computer, bash and editor tools, over Anthropic's Messages API", + "vendors": [ + "anthropic" + ], + "models": [ + "claude-opus-4-6", + "claude-sonnet-4-6" + ], + "start": { + "driver": { + "agent": "claude_cuabash", + "script": "agent-harness/run_mypcbench.py", + "env": { + "ANTHROPIC_BASE_URL": "{base}", + "ANTHROPIC_API_KEY": "{key}" + } + } + } + }, + "openai-cuabash": { + "key": "openai-cuabash", + "label": "GPT", + "summary": "OpenAI's computer and shell tools, over the Responses API", + "vendors": [ + "openai" + ], + "models": [ + "gpt-5.6-sol", + "gpt-5.6-luna", + "gpt-5.5", + "gpt-5.4-mini" + ], + "start": { + "driver": { + "agent": "openai_cuabash", + "script": "agent-harness/run_mypcbench.py", + "env": { + "OPENAI_BASE_URL": "{base_url}", + "OPENAI_API_KEY": "{key}" + } + } + } + }, + "qwen-cuabash": { + "key": "qwen-cuabash", + "label": "Qwen", + "summary": "OSWorld's Qwen agent with bash, over Chat Completions", + "models": [ + "Qwen/Qwen3.5-35B-A3B", + "Qwen/Qwen3.5-9B" + ], + "start": { + "driver": { + "agent": "qwen_cuabash", + "script": "agent-harness/run_mypcbench.py", + "env": { + "OPENAI_BASE_URL": "{base_url}", + "OPENAI_API_KEY": "{key}" + } + } + } + }, + "qwen-cua": { + "key": "qwen-cua", + "label": "Qwen, computer only", + "summary": "The Qwen agent without bash, the paper's ablation", + "models": [ + "Qwen/Qwen3.5-35B-A3B", + "Qwen/Qwen3.5-9B" + ], + "start": { + "driver": { + "agent": "qwen_cua", + "script": "agent-harness/run_mypcbench.py", + "env": { + "OPENAI_BASE_URL": "{base_url}", + "OPENAI_API_KEY": "{key}" + } + } + } + } + } +} diff --git a/app/nullius/catalogue/benchmarks/mypcbench/benchmark.json b/app/nullius/catalogue/benchmarks/mypcbench/benchmark.json new file mode 100644 index 000000000..b5806ca74 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/benchmark.json @@ -0,0 +1,62 @@ +{ + "key": "mypcbench", + "title": "MyPCBench", + "category": "Computer use", + "domain": "Personal-assistant tasks on one person's desktop: 17 logged-in web apps, mail and files whose records refer to each other.", + "scoring": "Rubric judge", + "harness": [ + "standard" + ], + "origin": "official", + "good_to_know": [ + "A pass is every rubric met, the paper's Perfect rate; the mean reward is its rubric score.", + "Claude runs on OpenRouter; GPT needs an OpenAI key; Qwen runs on OpenRouter or your model server.", + "The judge is Gemini 3.1 Flash Lite Preview, one call per rubric with every screenshot: the run's provider must serve it, or choose another judge model.", + "Each task's VM takes 4 cores and 8 GB of memory and needs /dev/kvm. The current image is 5 GB to download; the paper baseline is 6 GB.", + "For the original published harness, rubrics and VM, select Paper release. The default uses August rubrics; legacy includes July fixes. Selecting Paper baseline VM alone changes only the image." + ], + "upstream_limitations": [ + "A judge call that fails counts its rubric as not met.", + "The VM's chat apps send chat_template_kwargs, which direct OpenAI rejects; chat contacts do not reply through that provider." + ], + "limitations": [], + "datasets": [ + { + "key": "mypcbench", + "title": "MyPCBench, final tasks", + "tasks": 184, + "official": "https://github.com/ljang0/MyPCBench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "judge_results.py: one judge call per rubric over the whole trajectory.", + "notes": "184 tasks, 1,129 rubrics. MIT." + } + ], + "citation": "@misc{jang2026mypcbenchbenchmarkpersonallyintelligent,\n title={MyPCBench: A Benchmark for Personally Intelligent Computer-Use Agents},\n author={Lawrence Keunho Jang and Andrew Keunwoo Jang and Jing Yu Koh and Ruslan Salakhutdinov},\n year={2026},\n eprint={2606.16748},\n archivePrefix={arXiv},\n primaryClass={cs.LG},\n url={https://arxiv.org/abs/2606.16748},\n}", + "citation_source": "https://arxiv.org/abs/2606.16748", + "evidence": [], + "versions": { + "paper-release": { + "good_to_know": [ + "A pass is every rubric met, the paper's Perfect rate; the mean reward is its rubric score.", + "Claude runs on OpenRouter; GPT needs an OpenAI key; Qwen runs on OpenRouter or your model server.", + "The judge is Gemini 3.1 Flash Lite Preview, one call per rubric with every screenshot: the run's provider must serve it, or choose another judge model.", + "Each task's VM takes 4 cores and 8 GB of memory and needs /dev/kvm. The current image is 5 GB to download; the paper baseline is 6 GB.", + "The June 14 release pins the original harness and 1,191 rubric items with the archived paper VM. GPT-5.6 models were added to the published results later; use GPT-5.5 or GPT-5.4 mini for the paper's GPT configuration." + ], + "limitations": [], + "datasets": { + "mypcbench": { + "tasks": 184, + "notes": "184 tasks, 1,191 rubrics. Original June 2026 release. MIT." + } + }, + "upstream_limitations": [ + "A judge call that fails counts its rubric as not met.", + "The VM's chat apps send chat_template_kwargs, which direct OpenAI rejects; chat contacts do not reply through that provider.", + "The paper does not identify its exact run commit or release its evaluation trajectories; this version preserves the original public release, not verified reproduction of its scores." + ] + } + } +} diff --git a/app/nullius/catalogue/benchmarks/mypcbench/contacts.py b/app/nullius/catalogue/benchmarks/mypcbench/contacts.py new file mode 100644 index 000000000..d0580a0ec --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/contacts.py @@ -0,0 +1,33 @@ +"""Point the VM's existing chat services at the unit's simulator relay.""" +import base64 +import json +import shlex +import sys + + +def configure(env, route): + # A systemd drop-in survives the upstream runner's API-key injection. + settings = "[Service]\n" + "".join( + "Environment=" + json.dumps(f"{key}={value}") + "\n" + for key, value in (("OPENAI_API_KEY", route["key"]), + ("LLM_BASE_URL", route["base_url"]), ("LLM_MODEL", route["model"]))) + encoded = base64.b64encode(settings.encode()).decode() + script = "set -eu\n" + for service in ("mypcbench-buzzchat", "mypcbench-workbuzz"): + folder = f"/etc/systemd/system/{service}.service.d" + script += (f"test -f /etc/systemd/system/{service}.service\n" + f"mkdir -p {folder}\n" + f"echo {encoded} | base64 -d > {folder}/nullius.conf\n") + script += "systemctl daemon-reload\nsystemctl restart mypcbench-buzzchat mypcbench-workbuzz\n" + reply = env._execute_shell("sudo bash -c " + shlex.quote(script)) + if reply.get("returncode") != 0: + raise RuntimeError("chat services did not accept the simulator route") + + +if __name__ == "__main__": + from env import MyPCBenchEnv + env = MyPCBenchEnv(container_name=sys.argv[1], backend="docker") + env._start_container() + env._wait_for_ready() + with open(sys.argv[2], encoding="utf-8") as f: + configure(env, json.load(f)) diff --git a/app/nullius/catalogue/benchmarks/mypcbench/driver.py b/app/nullius/catalogue/benchmarks/mypcbench/driver.py new file mode 100644 index 000000000..1a5b2c9d6 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/driver.py @@ -0,0 +1,484 @@ +"""MyPCBench's driver for the Nullius standard (JSON lines on stdin and stdout). + +Everything that acts and scores is MyPCBench's own code at the tested commit +($NULLIUS_UPSTREAM), run as published on one task in the unit's folder. + +units - every task of the dataset, by its id, in the file's order +setup - the task's instruction. For an agent (agent.computer/v1): + runner.py, which holds the upstream's loop with the computer port's + bridge as its agent, and the shell its own agents have (runner.py's + Shell); the prompt is the instruction, then the context the upstream + gives each of its own agents +task_given, end - an agent's unit: the window before the task closes; the + unit's runner and VM go +answer - a setup's (original, model): agent-harness/run_mypcbench.py with the + run's agent (agents.json), its client pointed at the unit's relay +score - agent-harness/judge_results.py on what the runner wrote, its judge + asked through the run's judge route. An agent's turn is ended first, + and the loop's end awaited; the null control first runs the + upstream's dummy agent + +The VM is the upstream's image at a digest, in a container of the driver's +own that the runner attaches to (MYPCBENCH_REUSE_CONTAINER, the upstream's +docs/DOCKER.md), so it is pinned, gets /dev/kvm and no other privilege, and has +one owner: a keeper process in a session of its own, which ends the runner and +removes the container once this driver lets go of it or is gone. +""" +import json +import contextlib +import ipaddress +import urllib.parse +import os +import shutil +import signal +import subprocess +import sys +import tempfile +import threading +import time +import uuid + +HERE = os.path.dirname(os.path.abspath(__file__)) +UP = os.environ.get("NULLIUS_UPSTREAM", "") +# The definition's command names these files so a host's runner snapshot carries them. +_ARGS = sys.argv[1:5] if sys.argv[1:2] != ["--keep"] else [] +AGENTS_FILE, RUNNER = _ARGS[:2] if len(_ARGS) >= 2 else [os.path.join(HERE, "agents.json"), os.path.join(HERE, "runner.py")] +CONTACTS = _ARGS[2] if len(_ARGS) >= 3 else os.path.join(HERE, "contacts.py") +IMAGES_FILE = _ARGS[3] if len(_ARGS) >= 4 else os.path.join(HERE, "images.json") +API_PORT, APP_PORTS = 5000, range(3001, 3019) # env.py's CONTROL_API_PORT and the apps' ports it publishes +RESULTS = "results" +AGENT_SECONDS = 7200 # an agent's, the upstream's --timeout +READY_SECONDS = 1500 # an agent's VM: the upstream's 900 s to boot, its apps warmed +ENDED_SECONDS = 120 # the loop's end once the turn has ended, its last action included +LIVE = {} # an agent's unit: its runner, VM, lifeline and socket folder +# not a name that starts with "gemini", which the upstream's judge would send to Google's own client: this one goes to +# its OpenAI-compatible client, and the judge route pins the model that is asked +JUDGE = "google/gemini-3.1-flash-lite-preview" +# variables of the user's that would change the upstream's agents or judge +OURS = ("MYPCBENCH_", "ANTHROPIC_", "OPENAI_", "GEMINI_", "GOOGLE_", "OSWORLD_", "PERSONA", "SANDBOX_LOGIN_EMAIL") + + +def _tasks(): + with open(os.environ["NULLIUS_DATASET"], encoding="utf-8") as f: + return {t["id"]: t for t in json.load(f)} + + +def units(dataset=None, setup=None): + return {"units": list(_tasks())} + + +def preflight(participant, model, roles, setup=None, **_): + """Capture the published clients' first requests on synthetic input, with no VM + and no network. SDK transport interception ends before any response or action.""" + import asyncio + import base64 + import io + from unittest.mock import patch + import httpx + import anthropic._base_client as anthropic_client + from PIL import Image + + class Captured(BaseException): + def __init__(self, request): + self.request = {"path": request.url.raw_path.decode(), "body": json.loads(request.content), + "headers": {k: v for k, v in request.headers.items() + if k in ("anthropic-beta", "anthropic-version")}} + + def send(client, request, **kw): + raise Captured(request) + + async def async_send(client, request, **kw): + raise Captured(request) + + requests, unchecked = [], {} + image = io.BytesIO() + Image.new("RGB", (1280, 800), "white").save(image, format="PNG") + png = image.getvalue() + effort = os.environ.get("NULLIUS_OPTION_REASONING_EFFORT", "high") + env = _env(ANTHROPIC_API_KEY="nullius-relay", ANTHROPIC_BASE_URL="http://127.0.0.1:9", + OPENAI_API_KEY="nullius-relay", OPENAI_BASE_URL="http://127.0.0.1:9/v1", + MYPCBENCH_CLAUDE_EFFORT=effort, MYPCBENCH_OPENAI_REASONING_EFFORT=effort) + with patch.dict(os.environ, env, clear=True), patch.object(sys, "path", [os.path.join(UP, "agent-harness"), *sys.path]), \ + contextlib.ExitStack() as capture, contextlib.redirect_stdout(sys.stderr): + clients = {httpx, getattr(anthropic_client, "httpx2", httpx)} + for client in clients: + capture.enter_context(patch.object(client.Client, "send", send)) + capture.enter_context(patch.object(client.AsyncClient, "send", async_send)) + for role in roles: + try: + if role == "agent" and participant == "setup": + from run_mypcbench import get_agent + name, spec = _agent() + asked = spec["models"][0] if setup == "model" else model + agent = get_agent(name, asked, (1280, 800), "password", + no_computer=name == "claude_cuabash" and os.environ.get("NULLIUS_OPTION_COMPUTER", "on") == "off") + agent.reset() + agent.predict("Reply OK without taking any action.", {"screenshot": png}) + elif role == "judge": + from utils.osworld_full_traj_judge import _make_openai_client, _judge_one_rubric_openai + async def judge(): + async with _make_openai_client() as client: + await _judge_one_rubric_openai(client, JUDGE, "Compatibility check. Reply OK.", + [{"data_url": "data:image/png;base64," + base64.b64encode(png).decode()}]) + asyncio.run(judge()) + else: + unchecked[role] = "no request capture available before the task environment starts" + continue + except Captured as captured: + requests.append(dict(captured.request, role=role)) + except Exception as e: + raise RuntimeError(f"{role} request capture failed: {type(e).__name__}: {e}") from e + else: + raise RuntimeError(f"{role} request capture returned without a model request") + return {"requests": requests, "unchecked": unchecked} + + +def setup(unit, dir, participant=None, **_): + prompt = _tasks()[unit]["instruction"] + return _serve(unit, dir, prompt) if participant == "agent" else {"prompt": prompt} + + +def _agent(): + with open(AGENTS_FILE, encoding="utf-8") as f: + specs = {e["start"]["driver"]["agent"]: dict(e["start"]["driver"], models=e["models"]) + for e in json.load(f)["agents"].values()} + name = os.environ.get("NULLIUS_OPTION_AGENT") or next(iter(specs)) + return name, specs[name] + + +def _env(**extra): + """The upstream's processes': none of the user's own settings of it, and python3 is this environment's, which + the judge's command starts by that name.""" + env = {k: v for k, v in os.environ.items() if not k.startswith(OURS)} + return dict(env, PATH=os.path.dirname(sys.executable) + os.pathsep + os.environ.get("PATH", ""), **extra) + + +def _tail(log, n=3): + try: + with open(log, encoding="utf-8", errors="replace") as f: + lines = [ln.strip() for ln in f if ln.strip()] + except OSError: + return "no log" + return " | ".join(lines[-n:])[:600] or "nothing logged" + + +# -- the unit's VM and its keeper --------------------------------------------------------------------------------- + + +def keep(name): + """Read process groups and extra containers, one a line. When the pipe closes, end the groups and remove + the containers, again a little later for one whose creation the engine had already accepted.""" + groups, containers = [], [name] + for line in sys.stdin: + if line.startswith("container "): + containers.append(line.strip().split(" ", 1)[1]) + elif line.strip(): + groups.append(int(line)) + for pgid in groups: + try: + os.killpg(pgid, signal.SIGKILL) + except OSError: + pass + for wait in (0, 3, 10): + time.sleep(wait) + for container in containers: + subprocess.run(["docker", "rm", "-f", container], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +class VM: + """The unit's container, as the upstream's env.py starts it (its ports, its variables), and its keeper.""" + + def __enter__(self): + from nullius.standard.backends import container + with open(IMAGES_FILE, encoding="utf-8") as f: + image = json.load(f)[os.environ.get("NULLIUS_OPTION_VM_IMAGE", "current")]["image"] + self.socket_door = container.use_socket_doors() + self.relay_image = container.base_image() if self.socket_door else "" + self.name = "nullius-mypcbench-" + uuid.uuid4().hex[:12] + self.keeper = subprocess.Popen([sys.executable, os.path.abspath(__file__), "--keep", self.name], + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True, text=True) + try: + ports = [a for p in (API_PORT, 5901, *APP_PORTS) for a in ("-p", f"127.0.0.1:0:{p}")] + r = subprocess.run(["docker", "run", "-d", "--name", self.name, "--device", "/dev/kvm", + "-e", "PERSONA=michael_scott", "-e", "VM_ID=michael_scott", "-e", "WORLD=scranton-office", + *ports, image], capture_output=True, text=True) + if r.returncode: + raise RuntimeError("EnvironmentSetupError: the task's VM did not start: " + r.stderr.strip()[-400:]) + except BaseException: + self.__exit__() + raise + return self + + def owns(self, pid): + self.keeper.stdin.write(f"{pid}\n") + self.keeper.stdin.flush() + + def owns_container(self, name): + self.keeper.stdin.write(f"container {name}\n") + self.keeper.stdin.flush() + + def __exit__(self, *_): + self.keeper.stdin.close() # it outlives this driver; nothing waits for it + + +def _run(argv, dir, env, log, what, vm=None): + with open(log, "a") as f: + p = subprocess.Popen(argv, cwd=dir, env=env, stdout=f, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, + start_new_session=vm is not None) + if vm: + vm.owns(p.pid) + if p.wait(): + raise RuntimeError(f"{what} exited {p.returncode}: {_tail(log)}") + + +def _task_file(unit, dir): + path = os.path.join(dir, "task.json") + with open(path, "w", encoding="utf-8") as f: + json.dump([_tasks()[unit]], f) + return path + + +def _contacts(vm, directory, simulator): + """The existing chat services, with a task-scoped relay endpoint reachable from the VM.""" + from nullius.standard.backends.container import Loopback, slug + door = Loopback(simulator["base_url"], image=vm.relay_image, job=vm.name) + if vm.socket_door: + vm.owns_container(f"nullius-{slug(vm.name)}-model") + try: + door.start() + host = door.hosts.get(door.NAME, "") + ipaddress.ip_address(host) # KVM's Docker bridge must be on this machine + url = urllib.parse.urlsplit(door.base) + route = dict(simulator, base_url=urllib.parse.urlunsplit( + (url.scheme, f"{host}:{url.port}", url.path, url.query, url.fragment))) + path = os.path.join(directory, "contacts.json") + with open(path, "w", encoding="utf-8") as f: + json.dump(route, f) + _run([sys.executable, CONTACTS, vm.name, path], directory, + _env(PYTHONPATH=os.path.join(UP, "agent-harness"), MYPCBENCH_REUSE_CONTAINER="1"), + os.path.join(directory, "contacts.log"), "configure chat contacts", vm) + return door + except BaseException: + door.stop() + raise + + +def _runner(unit, dir, agent, model, simulator=None, **client): + """The upstream's runner on the one task: its result.txt and rubric_bundle.json.""" + if os.path.isdir(os.path.join(dir, RESULTS)): # the runner skips a task that has a result + shutil.rmtree(os.path.join(dir, RESULTS)) + tasks, log = _task_file(unit, dir), os.path.join(dir, "run_mypcbench.log") + argv = [sys.executable, os.path.join(UP, "agent-harness", "run_mypcbench.py"), "--backend", "docker", + "--agent_type", agent, "--model", model, "--tasks_dir", tasks, "--result_dir", os.path.join(dir, RESULTS), + "--max_steps", os.environ.get("NULLIUS_OPTION_MAX_STEPS", "100"), + "--sleep_after", os.environ.get("NULLIUS_OPTION_PAUSE", "1.0")] + if agent == "claude_cuabash" and os.environ.get("NULLIUS_OPTION_COMPUTER", "on") == "off": + argv.append("--no-computer") + effort = os.environ.get("NULLIUS_OPTION_REASONING_EFFORT", "high") + with VM() as vm, contextlib.ExitStack() as stack: + if simulator: + door = _contacts(vm, dir, simulator) + stack.callback(door.stop) + _run(argv + ["--container_name", vm.name], dir, + _env(MYPCBENCH_REUSE_CONTAINER="1", MYPCBENCH_CLAUDE_EFFORT=effort, + MYPCBENCH_OPENAI_REASONING_EFFORT=effort, **client), log, "run_mypcbench.py", vm) + where = os.path.join(dir, RESULTS, unit) + try: + with open(os.path.join(where, "incomplete.txt"), encoding="utf-8") as f: + raise RuntimeError("the upstream's runner did not finish the task: " + f.read().strip()[:400]) + except FileNotFoundError: + pass + if not os.path.exists(os.path.join(where, "rubric_bundle.json")): + raise RuntimeError("the upstream's runner wrote no rubric_bundle.json: " + _tail(log)) + return where + + +def _steps(where): + with open(os.path.join(where, "traj.jsonl"), encoding="utf-8") as f: + return [json.loads(ln) for ln in f if ln.strip()] + + +def answer(unit, dir, setup, model, base_url, key, simulator=None, **_): + if not simulator: + raise RuntimeError("MyPCBench needs the chat contacts’ simulator route") + name, spec = _agent() + if setup == "model": + model = spec["models"][0] # the agent's own: the relay sends the model chosen + elif model not in spec["models"]: + raise RuntimeError(f"{model} is not one of the {name} agent's models ({', '.join(spec['models'])}): " + "choose one of them, or the model setup") + base = base_url[:-3] if base_url.endswith("/v1") else base_url # an Anthropic client adds /v1/messages + client = {k: v.replace("{base_url}", base_url).replace("{base}", base).replace("{key}", key) + for k, v in spec["env"].items()} + steps = _steps(_runner(unit, dir, name, model, simulator=simulator, **client)) + return {"answer": str(steps[-1].get("response") or "") if steps else "", "model": model} + + +# -- an agent's unit ------------------------------------------------------------------------------------------------ +CONTEXT = """import datetime +from agents.prompts import build_mypcbench_context +print(build_mypcbench_context(has_bash=True).format( + CLIENT_PASSWORD="{CLIENT_PASSWORD}", CURRENT_DATE=datetime.datetime.today().strftime("%A, %B %d, %Y")))""" + + +def _work(dir): + """The trial's .work/mypcbench/, beside the agent's workspace and outside it.""" + return os.path.join(os.path.dirname(os.path.abspath(dir)), ".work", "mypcbench") + + +def _serve(unit, dir, instruction): + import nullius + from nullius.standard.protocols import computer_pipe + out = _work(dir) + shutil.rmtree(out, ignore_errors=True) + os.makedirs(out) + paths = os.pathsep.join([os.path.join(UP, "agent-harness"), os.path.dirname(os.path.dirname(os.path.abspath(nullius.__file__)))]) + context = subprocess.run([sys.executable, "-c", CONTEXT], env=_env(PYTHONPATH=paths), capture_output=True, text=True, + check=True).stdout + vm = VM().__enter__() + live = LIVE[dir] = {"vm": vm, "sockets": tempfile.mkdtemp(prefix="mypcbench-"), "life": None, "p": None} + try: + r, live["life"] = os.pipe() + with open(os.path.join(out, "runner.log"), "a") as log: + live["p"] = subprocess.Popen( + [sys.executable, RUNNER, _task_file(unit, out), os.path.join(out, RESULTS), vm.name, live["sockets"], str(r), + os.environ.get("NULLIUS_OPTION_MAX_STEPS", "100"), os.environ.get("NULLIUS_OPTION_PAUSE", "1.0"), out], + cwd=out, env=_env(PYTHONPATH=paths, MYPCBENCH_REUSE_CONTAINER="1"), stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True, pass_fds=(r,)) + os.close(r) + vm.owns(live["p"].pid) + said = _word(live, "ready.json", READY_SECONDS, "its VM and its task's setup") + except BaseException: + end(unit, dir) + raise + context = context.strip().replace("{CLIENT_PASSWORD}", said["password"]) + return {"prompt": f"{instruction}\n\n{context}\n\nThe desktop's shell is the tool bash of the MCP server shell, each " + "command a step; any other shell you have runs on another machine, which has none of Michael's " + "files or apps. Give your final answer as the message of done.", + "mcp": [{"name": "computer", "server": "computer", + "args": [os.path.abspath(computer_pipe.__file__), os.path.join(live["sockets"], "s")]}, + {"name": "shell", "server": "shell", + "args": [os.path.abspath(computer_pipe.__file__), os.path.join(live["sockets"], "shell")]}], + "agent_seconds": AGENT_SECONDS, "progress": os.path.join(".work", "mypcbench", "progress.json")} + + +def _word(live, name, seconds, what): + """What the runner wrote in the socket's folder, once it has; then gone.""" + path, until = os.path.join(live["sockets"], name), time.time() + seconds + while not os.path.exists(path): + if live["p"].poll() is not None or time.time() > until: + raise RuntimeError(f"EnvironmentSetupError: the runner did not get past {what}") + time.sleep(0.2) + with open(path, encoding="utf-8") as f: + said = json.load(f) + os.unlink(path) + if not said.get("ok"): + raise RuntimeError(f"EnvironmentSetupError: {what}: {said.get('error')}") + return said + + +def task_given(unit, dir, simulator=None, **_): + if not simulator: + raise RuntimeError("MyPCBench needs the chat contacts’ simulator route") + LIVE[dir]["contacts"] = _contacts(LIVE[dir]["vm"], _work(dir), simulator) + os.write(LIVE[dir]["life"], b"task-given\n") + _word(LIVE[dir], "given.json", 30, "the window before the task") + return {} + + +def end(unit, dir, **_): + live = LIVE.pop(dir, None) + if live: + if live.get("contacts"): + live["contacts"].stop() + live["vm"].__exit__() + if live["life"] is not None: + os.close(live["life"]) + shutil.rmtree(live["sockets"], ignore_errors=True) + return {} + + +def _agent_results(unit, dir): + """The agent's turn has ended: the loop ends by itself, and packs what the judge reads.""" + live, out = LIVE[dir], _work(dir) + try: + os.write(live["life"], b"turn-end\n") + except BrokenPipeError: # the loop has ended already, as after done + pass + try: + code = live["p"].wait(ENDED_SECONDS) + except subprocess.TimeoutExpired: + raise RuntimeError("the upstream's loop did not end after the agent's turn") from None + finally: + end(unit, dir) + if code or not os.path.exists(os.path.join(out, RESULTS, unit, "rubric_bundle.json")): + raise RuntimeError("the upstream's loop did not finish the task: " + _tail(os.path.join(out, "runner.log"))) + with open(os.path.join(out, "progress.json"), encoding="utf-8") as f: + return json.load(f) + + +def score(unit, dir, setup=None, judge=None, **_): + if not judge: + raise RuntimeError("MyPCBench is scored by its judge, and this run gives it no judge route") + ended = {} + if dir in LIVE: + ended = {k: v for k, v in _agent_results(unit, dir).items() if k in ("steps", "steps_limit", "ended")} + dir = _work(dir) + where = os.path.join(dir, RESULTS, unit) + if not ended and setup not in ("original", "model"): # the null control: the upstream's dummy agent + where = _runner(unit, dir, "dummy", "dummy") + log = os.path.join(dir, "judge_results.log") + _run([sys.executable, os.path.join(UP, "agent-harness", "judge_results.py"), "--result_dir", + os.path.join(dir, RESULTS), "--force"], dir, + _env(OPENAI_BASE_URL=judge["base_url"], OPENAI_API_KEY=judge["key"], MYPCBENCH_RUBRIC_JUDGE_MODEL=JUDGE), + log, "judge_results.py") + with open(os.path.join(dir, RESULTS, "scores.json"), encoding="utf-8") as f: + row = json.load(f)["rows"][0] + if row["score"] is None: # the upstream counts it as 0: here the unit has no score + raise RuntimeError(f"the upstream's judge gave no score ({row['status']}): " + str(row.get("raw"))[-400:]) + with open(os.path.join(where, "osworld_full_traj_result.json"), encoding="utf-8") as f: + said = json.load(f) + rubrics = [{k: r[k] for k in ("criterion", "weight", "success", "reasoning")} for r in said["rubric_results"]] + return {"reward": row["score"], "passed": row["score"] >= 0.999, + "detail": {"score": row["score"], "judge": judge["model"], "rubrics": rubrics, "steps": len(_steps(where)), **ended, + # a judge call that failed is a rubric failed, as the upstream scores it + "judge_errors": sum(r["reasoning"].startswith("Error judging rubric") for r in rubrics)}} + + +HANDLERS = {"units": units, "setup": setup, "answer": answer, "score": score, "preflight": preflight, + "task_given": task_given, "end": end} + + +def _read(live): + """Nullius closed this driver's input: it exits at once, which closes the keeper's pipe.""" + for line in sys.stdin: + live.append(line) + WAKE.set() + os._exit(0) + + +WAKE = threading.Event() + + +def main(): + lines = [] + threading.Thread(target=_read, args=(lines,), daemon=True).start() + while True: + WAKE.wait() + WAKE.clear() + while lines: + try: + req = json.loads(lines.pop(0)) + out = HANDLERS[req.pop("op")](**req) + except Exception as e: + said = str(e) + out = {"error": said if said.startswith("EnvironmentSetupError: ") else f"{type(e).__name__}: {said}"} + print(json.dumps(out), flush=True) + + +if __name__ == "__main__": + if sys.argv[1:2] == ["--keep"]: + keep(sys.argv[2]) + else: + main() diff --git a/app/nullius/catalogue/benchmarks/mypcbench/images.json b/app/nullius/catalogue/benchmarks/mypcbench/images.json new file mode 100644 index 000000000..e779d1c68 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/images.json @@ -0,0 +1,10 @@ +{ + "current": { + "image": "ljang/mypcbench-qemu@sha256:1648bfe424202a84a4bed1d62cb1812e3eb8113a209cf878e6846677bb5b4f60", + "source": "https://github.com/ljang0/MyPCBench/blob/937ec49882508223c7ea3f79ead3330c6810feb1/README.md#image" + }, + "paper": { + "image": "ljang/mypcbench-qemu@sha256:86d4da6575ebf5adbfa3229389f341445245d6d7f2bee6340150858b9a8dbdcf", + "source": "https://huggingface.co/datasets/ljang0/mypcbench-qemu-baseline/blob/694c6b700b7a46a4a971eae4ea61a258f963093b/README.md" + } +} diff --git a/app/nullius/catalogue/benchmarks/mypcbench/proofs.json b/app/nullius/catalogue/benchmarks/mypcbench/proofs.json new file mode 100644 index 000000000..76220e7dd --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/proofs.json @@ -0,0 +1,53 @@ +{ + "schema": "nullius.proofs/v1", + "kind": "benchmark", + "key": "mypcbench", + "versions": { + "937ec49": { + "proven": { + "final": { + "units": { + "units": 184, + "passed": "184 ids, the same twice, unique" + }, + "nop": { + "passed": "0/2", + "value": 0.0, + "expect": { + "at_most": 0.0 + }, + "units": 2, + "options": { + "max_steps": "100", + "pause": "1.0", + "vm_provider": "docker" + }, + "judge": "gpt-5.4-mini", + "limit": 2 + } + }, + "legacy": { + "units": { + "units": 184, + "passed": "184 ids, the same twice, unique" + }, + "nop": { + "passed": "0/2", + "value": 0.0, + "expect": { + "at_most": 0.0 + }, + "units": 2, + "options": { + "max_steps": "100", + "pause": "1.0", + "vm_provider": "docker" + }, + "judge": "gpt-5.4-mini", + "limit": 2 + } + } + } + } + } +} diff --git a/app/nullius/catalogue/benchmarks/mypcbench/runner.py b/app/nullius/catalogue/benchmarks/mypcbench/runner.py new file mode 100644 index 000000000..cfd4f1003 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/runner.py @@ -0,0 +1,193 @@ +"""One unit of an agent on MyPCBench: the upstream's MyPCBenchEnv and its own run_single_example, called as they are, +with the computer port's bridge as the loop's agent (nullius.standard.protocols.computer_port, agent.computer/v1). + + runner.py TASK_JSON RESULT_DIR CONTAINER SOCKET_DIR LIFELINE_FD STEPS PAUSE OUT_DIR + +The driver starts it, with the upstream's agent-harness and Nullius on its import path, beside the unit's container +(MYPCBENCH_REUSE_CONTAINER). It serves the MCP servers computer at SOCKET_DIR/s and shell at SOCKET_DIR/shell, and says it is ready in +SOCKET_DIR/ready.json once the loop asks for the agent's first step, and that the window before the task is closed in +SOCKET_DIR/given.json. The end of the lifeline ends it; its keeper removes the container.""" +import base64 +import json +import os +import shlex +import sys +import threading +import time + +from nullius.standard.protocols import computer_port as port + +FOLDER, CHUNK = "/tmp/agent", 60000 # a command's argument is at most 128 KiB +SCREEN = (1280, 800) +# the display, as the upstream's own _execute_pyautogui names it: a prepare's code imports pyautogui +DISPLAY = ("import os\nos.environ.setdefault('DISPLAY', ':0')\n" + "os.environ.setdefault('XAUTHORITY', '/run/user/1000/gdm/Xauthority')\n") + + +class Desktop: + """The port's operations over the upstream's own controller methods.""" + + def __init__(self, env): + self.env, self.shot = env, None + + def observation(self): + return self.shot or self.capture() + + def python(self, code): + return self.env._execute_command(["python3", "-c", DISPLAY + code]) + + def upload(self, path, data): + for i in range(0, max(len(data), 1), CHUNK): + part = base64.b64encode(data[i:i + CHUNK]).decode() + reply = self.python(f"import base64\nopen({path!r}, {'ab' if i else 'wb'!r}).write(base64.b64decode({part!r}))") + if reply.get("returncode") != 0: + raise RuntimeError(f"the desktop did not write {path}: {reply}") + + def read(self, path): + at = shlex.quote(path) + reply = self.env._execute_shell(f"if [ -e {at} ]; then base64 -w0 {at}; else exit 44; fi") + if reply.get("returncode") == 44: + return None + if reply.get("returncode") != 0: + raise RuntimeError(str(reply.get("error"))) + return base64.b64decode(reply["output"]) + + def capture(self): + png = self.env._get_screenshot() + if not png: + raise RuntimeError("the desktop gave no screenshot") + return png + + def password(self): + return self.env.client_password + + +class Watched: + """The env as the loop is handed it: each step's screenshot is kept for the bridge, and Python the upstream's + one-line wrapper cannot hold (a first statement with a block) is handed to it as one exec.""" + + def __init__(self, env, desktop): + self._env, self._desktop = env, desktop + + def step(self, action, pause): + if action.strip().upper() not in ("WAIT", "DONE", "FAIL"): + try: + compile("import time; " + action, "action", "exec") + except (SyntaxError, ValueError): + action = f"exec({action!r})" + out = self._env.step(action, pause) + self._desktop.shot = out[0].get("screenshot") + return out + + def __getattr__(self, name): + return getattr(self._env, name) + + +BASH = {"name": "bash", "description": "One step: a bash command run in the desktop as its user, up to 110 seconds. " + "Returns its output, its errors and its exit code, the output cut at 10000 " + "characters. Taken once the task is given.", + "inputSchema": {"type": "object", "required": ["command"], + "properties": {"command": {"type": "string", "minLength": 1}}}} +OUT = FOLDER + "/.bash-output.json" +RUN = ("import json, subprocess\ntry:\n r = subprocess.run({command!r}, shell=True, executable='/bin/bash', " + "capture_output=True, text=True, timeout=110)\n said = [r.returncode, r.stdout, r.stderr]\n" + "except subprocess.TimeoutExpired:\n said = [-1, '', 'Command timed out after 110s']\n" + "open({out!r}, 'w').write(json.dumps(said))") + + +def said(rc, output, error): + """What the upstream's own claude_cuabash answers a bash call (its _execute_bash): the text, and whether it failed.""" + text = "\n".join([p for p in (output, error and f"stderr: {error}") if p] + ([f"(exit code {rc})"] if rc else [])) + text = text or "(no output)" + if len(text) > 10000: + text = text[:10000] + f"\n... (truncated, {len(text)} total chars)" + return text, bool(rc or error) + + +class Shell(port.Server): + """The MCP server shell: bash, the shell MyPCBench's own agents have. A command is a step of the bridge, as a turn + of the upstream's agent that only runs bash is a step of its loop: the step's action runs it, and the step reads + its output back.""" + + def handle(self, m, wire): + method = m.get("method") if isinstance(m, dict) else None + if method not in ("initialize", "tools/list") or m.get("jsonrpc") != "2.0" or "id" not in m: + return super().handle(m, wire) + result = ({"protocolVersion": (m.get("params") or {}).get("protocolVersion") or port.PROTOCOL, + "capabilities": {"tools": {}}, "serverInfo": {"name": "shell", "version": "1"}} + if method == "initialize" else {"tools": [BASH]}) + return {"jsonrpc": "2.0", "id": m["id"], "result": result} + + def call(self, rid, params, wire): + args = params.get("arguments") + command = args.get("command") if isinstance(args, dict) else None + # other arguments are let be, as Codex's max_output_tokens: the output is cut as the upstream's agent cuts it + if params.get("name") != "bash" or not isinstance(command, str) or not command.strip(): + wire.send({"jsonrpc": "2.0", "id": rid, + "error": {"code": -32602, "message": "the one tool is bash, with a command"}}) + return + + def reply(call, value, image, error): + if error is None: + got = (value.get("files") or {}).get(OUT) + text, failed = said(*json.loads(base64.b64decode(got))) if isinstance(got, str) else ( + f"the command's output could not be read: {got}", True) + else: + text, failed = str(error), True + self.record({"tool": "bash", "start": call.start, "end": time.time(), "isError": failed}) + wire.send({"jsonrpc": "2.0", "id": rid, + "result": {"content": [{"type": "text", "text": text}], "isError": failed}}) + wire.answered() + + wire.opened() + call = port.Call("step", {"actions": [RUN.format(command=command, out=OUT)], "files": [OUT], + "response": "bash: " + command}, reply) + try: + port.checked(call, self.bridge.screen, self.bridge.folder) + except Exception as e: + call.answer(error=f"the command could not be taken: {e}") + return + self.bridge.submit(call) + + +class Turn: + """What the lifeline reaches.""" + + def __init__(self, bridge, given): + self.end_turn, self.bridge, self.given = bridge.end_turn, bridge, given + + def close_window(self): + self.bridge.close_window() + port.ready(self.given, ok=True) + + +def main(task, results, container, sockets, life, steps, pause, out): + with open(task, encoding="utf-8") as f: + task = json.load(f)[0] + ready = os.path.join(sockets, "ready.json") + try: + from env import MyPCBenchEnv + from run_mypcbench import run_single_example + env = MyPCBenchEnv(container_name=container, backend="docker") + desktop = Desktop(env) + bridge = port.Bridge(desktop, int(steps), float(pause), SCREEN, FOLDER, window=True, + on_first=lambda: port.ready(ready, ok=True, password=env.client_password), + progress=os.path.join(out, "progress.json"), + prepared=os.path.join(out, "computer-prepare.jsonl")) + computer = port.Server(bridge, os.path.join(sockets, "s"), os.path.join(out, "computer-calls.jsonl")) + shell = Shell(bridge, os.path.join(sockets, "shell"), os.path.join(out, "computer-calls.jsonl")) + threading.Thread(target=port.lifeline, args=(int(life), Turn(bridge, os.path.join(sockets, "given.json"))), + daemon=True).start() + where = os.path.join(results, task["id"]) + os.makedirs(where, exist_ok=True) + run_single_example(bridge, Watched(env, desktop), task, int(steps), where, float(pause), 7200) + bridge.finish() + computer.close(flush_seconds=2) + shell.close(flush_seconds=2) + except Exception as e: + port.ready(ready, ok=False, error=f"{type(e).__name__}: {e}") + raise + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/app/nullius/catalogue/benchmarks/mypcbench/standard.json b/app/nullius/catalogue/benchmarks/mypcbench/standard.json new file mode 100644 index 000000000..2b2dbe3ea --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/standard.json @@ -0,0 +1,324 @@ +{ + "schema": "nullius.benchmark/v1", + "key": "mypcbench", + "label": "MyPCBench", + "summary": "Tasks on one person's desktop, in a VM of its own: 17 web apps, mail and files that hold his life. One of MyPCBench's own agents acts, or an agent through the computer port; its judge grades the trajectory rubric by rubric.", + "family": "agent", + "needs": [ + "agent.computer/v1" + ], + "upstream": { + "repository": "https://github.com/ljang0/MyPCBench", + "branch": "main", + "tested": "937ec49882508223c7ea3f79ead3330c6810feb1", + "tested_date": "2026-11-25", + "license": "MIT" + }, + "driver": { + "command": [ + "{install}/.venv/bin/python", + "{here}/driver.py", + "{here}/agents.json", + "{here}/runner.py", + "{here}/contacts.py", + "{here}/images.json" + ], + "install": { + "python": "3.12", + "pip": [ + "anthropic==1.0.0", + "openai==3.3.1", + "httpx==0.28.1", + "requests==2.34.2", + "pillow==12.3.0" + ] + }, + "preflight": true, + "participant": true, + "unit_end": true, + "task_given": true + }, + "mcp_servers": { + "computer": { + "command": [ + "{install}/.venv/bin/python" + ], + "summary": "The computer port's pipe, joined to the socket where the unit's runner serves the desktop." + }, + "shell": { + "command": [ + "{install}/.venv/bin/python" + ], + "summary": "The shell MyPCBench's own agents have: bash in the desktop, each command a step, through the same pipe." + } + }, + "limits": { + "setup_seconds": 1800, + "score_seconds": 3600, + "scored_cuts": [ + "time", + "calls", + "end" + ] + }, + "datasets": [ + { + "id": "final", + "label": "All tasks", + "summary": "all_tasks_with_grading.json, the runner's default: rubrics aligned in August 2026.", + "path": "tasks/final/all_tasks_with_grading.json", + "sha256": "3b6ecf7ab91d7f572a320aca0f6dd11ee01fbd47b1ccfe141bd6a88bf53cf54c", + "units": 184 + }, + { + "id": "legacy", + "label": "Legacy rubrics", + "summary": "mypcbench_legacy.json: the same tasks with the rubrics before August 2026.", + "path": "tasks/final/mypcbench_legacy.json", + "sha256": "e36d9c08b8c7b6c84304c84578b64b968da0809fdda51f76795623919fc7a384", + "units": 184 + } + ], + "units": { + "noun": "task", + "nouns": "tasks" + }, + "score": { + "kind": "pass", + "says": "MyPCBench's own judge (judge_results.py) on the whole trajectory, one call per rubric: the reward is the weighted share of rubrics met, a pass is every rubric met (the paper's Perfect rate)", + "judge": { + "model": "google/gemini-3.1-flash-lite-preview", + "says": "the paper's judge, Gemini 3.1 Flash Lite Preview, once per rubric" + } + }, + "setups": { + "original": { + "summary": "One of MyPCBench's own agents as published (run_mypcbench.py), with its own prompts, tools and 100 steps, asking a model it is published with.", + "models": [ + "claude-opus-4-6", + "claude-sonnet-4-6", + "gpt-5.6-sol", + "gpt-5.6-luna", + "gpt-5.5", + "gpt-5.4-mini", + "Qwen/Qwen3.5-35B-A3B", + "Qwen/Qwen3.5-9B" + ], + "default": "claude-opus-4-6", + "served_as": { + "claude-opus-4-6": "anthropic/claude-opus-4.6", + "claude-sonnet-4-6": "anthropic/claude-sonnet-4.6", + "gpt-5.6-sol": "openai/gpt-5.6-sol", + "gpt-5.6-luna": "openai/gpt-5.6-luna", + "gpt-5.5": "openai/gpt-5.5", + "gpt-5.4-mini": "openai/gpt-5.4-mini", + "Qwen/Qwen3.5-35B-A3B": "qwen/qwen3.5-35b-a3b", + "Qwen/Qwen3.5-9B": "qwen/qwen3.5-9b" + }, + "providers": { + "openrouter": "", + "openai": "", + "custom": "" + }, + "turn_seconds": 10800, + "comparable": false + }, + "model": { + "summary": "The same agent with any model in its own model's place; the relay sends the model chosen.", + "runs_as": "claude-opus-4-6" + } + }, + "options": { + "vm_image": { + "label": "VM image", + "step": "dataset", + "summary": "The desktop image each task starts from.", + "values": [ + "current", + "paper" + ], + "names": { + "current": "Current VM", + "paper": "Paper baseline VM" + }, + "default": "current", + "setups": [ + "original", + "model", + "yours" + ], + "about": { + "current": "Upstream v0.1, pinned for repeatable runs.", + "paper": "Upstream's archived v0.0 image (eval-round0). Task and rubric selection is independent." + } + }, + "agent": { + "label": "Agent", + "summary": "Which of MyPCBench's own agents runs.", + "setups": [ + "original", + "model" + ] + }, + "max_steps": { + "label": "Steps per task", + "summary": "The agent's step limit.", + "setups": [ + "original", + "model", + "yours" + ], + "default": "100", + "pattern": "[1-9][0-9]{0,3}", + "limit": true + }, + "pause": { + "label": "Pause after each action (seconds)", + "summary": "Seconds to wait after each action before the next screenshot.", + "setups": [ + "original", + "model", + "yours" + ], + "default": "1.0", + "pattern": "[0-9]{1,2}(\\.[0-9]{1,2})?" + }, + "reasoning_effort": { + "label": "Reasoning effort", + "summary": "The effort asked of the model.", + "values": [ + "low", + "medium", + "high", + "max" + ], + "default": "high", + "setups": [ + "original", + "model" + ], + "when": { + "agent": [ + "claude_cuabash", + "openai_cuabash" + ] + } + }, + "computer": { + "label": "Computer tool", + "summary": "off: bash and the editor alone.", + "values": [ + "on", + "off" + ], + "default": "on", + "setups": [ + "original", + "model" + ], + "when": { + "agent": [ + "claude_cuabash" + ] + } + }, + "vm_provider": { + "label": "VM provider", + "step": "where", + "summary": "Where each task's VM runs.", + "values": [ + "docker" + ], + "default": "docker", + "setups": [ + "original", + "model", + "yours" + ], + "about": { + "docker": "the upstream's image, QEMU in a container" + }, + "needs": { + "docker": { + "host": [ + "docker" + ], + "vm": { + "memory_gb": 8 + } + } + } + } + }, + "host": { + "docker": { + "label": "Docker", + "summary": "Docker without sudo, and /dev/kvm.", + "check": [ + "docker" + ] + } + }, + "controls": { + "nop": { + "source": "nullius", + "from": "The upstream's dummy agent, which ends the task at once; its judge grades the untouched desktop.", + "expect": { + "at_most": 0.0 + } + } + }, + "simulator": { + "model": "gpt-5.4-mini", + "says": "The desktop\u2019s chat contacts in BuzzChat and WorkBuzz, using the upstream apps\u2019 reply code and default model." + }, + "default": "937ec49", + "versions": { + "937ec49": { + "upstream": { + "label": "Current" + } + }, + "paper-release": { + "upstream": { + "branch": "main", + "tested": "14533b53d1f6966c77e3e826771237e95d7c4cd4", + "tested_date": "2026-12-01", + "origin": "official", + "label": "Paper release" + }, + "datasets": [ + { + "id": "final", + "label": "Paper-release tasks", + "summary": "The original June 2026 release: 184 tasks and 1,191 rubric items.", + "path": "tasks/final/all_tasks_with_grading.json", + "sha256": "a6d69af246a64dfac99b0396fae1127f8cee6f99e8819d21a21400e1e82ea02a", + "units": 184 + } + ], + "options": { + "vm_image": { + "label": "VM image", + "step": "dataset", + "summary": "The desktop image each task starts from.", + "values": [ + "paper" + ], + "names": { + "paper": "Paper baseline VM" + }, + "default": "paper", + "setups": [ + "original", + "model", + "yours" + ], + "about": { + "paper": "Upstream's archived v0.0 image (eval-round0), paired with the original published harness and rubrics." + } + } + } + } + } +} diff --git a/app/nullius/catalogue/benchmarks/mypcbench/upstream-settings.json b/app/nullius/catalogue/benchmarks/mypcbench/upstream-settings.json new file mode 100644 index 000000000..dccaff3c4 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/upstream-settings.json @@ -0,0 +1,506 @@ +[ + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--agent_type", + "values": "dummy, claude_cuabash, openai_cuabash, qwen_cuabash, qwen_cua", + "default": "claude_cuabash", + "nullius": "option:agent" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--agent_type dummy", + "values": "dummy", + "default": "-", + "nullius": "fixed:the null control - its own check, no model" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--interface", + "values": "gui", + "default": "unset", + "nullius": "fixed:unset - picks the agent from the model's name; the Agent option does" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--no-computer", + "values": "on, off", + "default": "off", + "nullius": "option:computer" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--action_space", + "values": "pyautogui, computer_13", + "default": "pyautogui", + "nullius": "fixed:pyautogui - its default; no effect upstream" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--observation_type", + "values": "screenshot, a11y_tree, screenshot_a11y_tree", + "default": "screenshot", + "nullius": "fixed:screenshot - its default; no effect upstream" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--model", + "values": "a model", + "default": "claude-opus-4-6", + "nullius": "setup:original" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--model (another)", + "values": "any", + "default": "claude-opus-4-6", + "nullius": "setup:model" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--backend", + "values": "docker, qemu", + "default": "qemu", + "nullius": "fixed:docker - QEMU and its firmware come in the image; the same VM" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--qcow2_path", + "values": "a VM image", + "default": "the managed cache", + "nullius": "not offered - the qemu backend's" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--docker_image / --pull always", + "values": "an image", + "default": "ljang/mypcbench-qemu:latest", + "nullius": "option:vm_image" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--container_name", + "values": "a name", + "default": "mypcbench-agent", + "nullius": "fixed:one per unit - the container the runner attaches to" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "docker run --privileged", + "values": "on", + "default": "on", + "nullius": "fixed:off - /dev/kvm alone boots the VM" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--persona", + "values": "a value", + "default": "michael_scott", + "nullius": "fixed:michael_scott - its default, the image's own" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--world", + "values": "a value", + "default": "scranton-office", + "nullius": "fixed:scranton-office - its default, the image's own" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--screen_width", + "values": "a value", + "default": "1280", + "nullius": "fixed:1280 - its default, the image's own" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--screen_height", + "values": "a value", + "default": "800", + "nullius": "fixed:800 - its default, the image's own" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--client_password", + "values": "a value", + "default": "password", + "nullius": "fixed:password - its default, the image's own" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--tasks_dir tasks/final", + "values": "the graded tasks", + "default": "required", + "nullius": "dataset:final" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--tasks_dir tasks/final/mypcbench_legacy.json", + "values": "the earlier rubrics", + "default": "-", + "nullius": "dataset:legacy" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--tasks_dir tasks/final/", + "values": "one app's tasks", + "default": "-", + "nullius": "not offered - subsets of the same tasks; a list of units runs one" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--tasks_dir tasks/smoke_one", + "values": "one task", + "default": "-", + "nullius": "not offered - the upstream's own smoke test" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--max_steps", + "values": "a number", + "default": "100", + "nullius": "option:max_steps" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--sleep_after", + "values": "seconds", + "default": "1.0", + "nullius": "option:pause" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--soft-reset", + "values": "on, off", + "default": "off", + "nullius": "fixed:off - its default; each task has a fresh VM" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--result_dir", + "values": "a folder", + "default": "./results", + "nullius": "fixed:the unit's folder - its results stay with the trial" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "--timeout", + "values": "seconds", + "default": "7200", + "nullius": "fixed:7200 - its default" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "MYPCBENCH_REUSE_CONTAINER, MYPCBENCH_HOST_API_PORT, MYPCBENCH_HOST_VNC_PORT", + "values": "on, off; ports", + "default": "off", + "nullius": "fixed:on, ports discovered - the runner attaches to the unit's container" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "MYPCBENCH_VM_READY_TIMEOUT", + "values": "seconds", + "default": "900", + "nullius": "fixed:900 - its default" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "MYPCBENCH_REQUIRE_APPS", + "values": "0, 1", + "default": "1", + "nullius": "fixed:1 - its default: a dead app is an error" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "MYPCBENCH_MAX_IMAGE_AGE_HOURS", + "values": "hours", + "default": "36", + "nullius": "fixed:36 - its default; it only warns" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "MYPCBENCH_SKIP_PULL, MYPCBENCH_SKIP_QCOW2_REFRESH, MYPCBENCH_QCOW2, MYPCBENCH_OVMF_*, MYPCBENCH_QEMU_EXTRACTED, MYPCBENCH_VM_HOST, MYPCBENCH_HOST_APP_PORT_*, MYPCBENCH_HOST_SSH_PORT", + "values": "host settings", + "default": "unset", + "nullius": "fixed:unset - its own VM start is not used" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "OPENAI_API_KEY in the VM", + "values": "a key", + "default": "the environment's", + "nullius": "fixed:the simulator relay placeholder - no provider key in the VM" + }, + { + "entry": "agent-harness/run_mypcbench.py", + "setting": "PERSONA, SANDBOX_LOGIN_EMAIL, PERSONAS_DIR", + "values": "a persona", + "default": "michael_scott", + "nullius": "fixed:michael_scott - the one persona published" + }, + { + "entry": "agent-harness/agents/claude_cuabash.py", + "setting": "MYPCBENCH_CLAUDE_EFFORT", + "values": "low, medium, high, max", + "default": "high", + "nullius": "option:reasoning_effort" + }, + { + "entry": "agent-harness/agents/claude_cuabash.py", + "setting": "ANTHROPIC_API_KEY, ANTHROPIC_BASE_URL", + "values": "a key, an endpoint", + "default": "the environment's", + "nullius": "fixed:the unit's relay - it holds the key" + }, + { + "entry": "agent-harness/agents/claude_cuabash.py", + "setting": "ANTHROPIC_API_KEY_BACKUP", + "values": "a key", + "default": "unset", + "nullius": "fixed:unset - the relay holds the one key" + }, + { + "entry": "agent-harness/agents/openai_cuabash.py", + "setting": "MYPCBENCH_OPENAI_REASONING_EFFORT", + "values": "low, medium, high, ...", + "default": "high", + "nullius": "option:reasoning_effort" + }, + { + "entry": "agent-harness/agents/openai_cuabash.py", + "setting": "MYPCBENCH_OPENAI_MAX_OUTPUT_TOKENS", + "values": "a number, 0 for none", + "default": "1500", + "nullius": "fixed:1500 - its default" + }, + { + "entry": "agent-harness/agents/openai_cuabash.py", + "setting": "OPENAI_API_KEY, OPENAI_BASE_URL", + "values": "a key, an endpoint", + "default": "the environment's", + "nullius": "fixed:the unit's relay - it holds the key" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "OPENAI_API_KEY, OPENAI_BASE_URL", + "values": "a key, an endpoint", + "default": "a local vLLM", + "nullius": "fixed:the unit's relay - it holds the key" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_MAX_TOKENS", + "values": "a value", + "default": "32768", + "nullius": "fixed:32768 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_HISTORY_N", + "values": "a value", + "default": "100", + "nullius": "fixed:100 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_IMAGE_MAX", + "values": "a value", + "default": "20", + "nullius": "fixed:20 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_FOLD_SIZE", + "values": "a value", + "default": "10", + "nullius": "fixed:10 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_TEMPERATURE", + "values": "a value", + "default": "0.0", + "nullius": "fixed:0.0 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_TOP_P", + "values": "a value", + "default": "0.9", + "nullius": "fixed:0.9 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_PRESENCE_PENALTY", + "values": "a value", + "default": "1.5", + "nullius": "fixed:1.5 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_TOP_K", + "values": "a value", + "default": "20", + "nullius": "fixed:20 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_MIN_P", + "values": "a value", + "default": "0.0", + "nullius": "fixed:0.0 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_REPETITION_PENALTY", + "values": "a value", + "default": "1.0", + "nullius": "fixed:1.0 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_ENABLE_THINKING", + "values": "a value", + "default": "1", + "nullius": "fixed:1 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_MAX_PIXELS", + "values": "a value", + "default": "unset", + "nullius": "fixed:unset - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_MIN_PIXELS", + "values": "a value", + "default": "unset", + "nullius": "fixed:unset - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_PRESERVE_REASONING", + "values": "a value", + "default": "unset", + "nullius": "fixed:unset - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_OSWORLD_ENABLE_BASH", + "values": "a value", + "default": "0", + "nullius": "fixed:0 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "MYPCBENCH_QWEN_OSWORLD_INJECT_CONTEXT", + "values": "a value", + "default": "1", + "nullius": "fixed:1 - its default" + }, + { + "entry": "agent-harness/agents/qwen_cua.py", + "setting": "OSWORLD_ROOT, OSWORLD_HTTP_CONNECT_TIMEOUT, OSWORLD_HTTP_READ_TIMEOUT, OSWORLD_OPENAI_TIMEOUT", + "values": "a path; seconds", + "default": "~/OSWorld; 10, 120", + "nullius": "fixed:its defaults - the vendored agent is the one that runs" + }, + { + "entry": "agent-harness/judge_results.py", + "setting": "--result_dir", + "values": "a folder", + "default": "required", + "nullius": "fixed:the unit's results - one task's" + }, + { + "entry": "agent-harness/judge_results.py", + "setting": "--force", + "values": "on, off", + "default": "off", + "nullius": "fixed:on - a unit scored again is judged again" + }, + { + "entry": "agent-harness/judge_results.py", + "setting": "--judge_command / MYPCBENCH_RUBRIC_JUDGE_COMMAND", + "values": "a command", + "default": "unset", + "nullius": "fixed:unset - the paper's judge" + }, + { + "entry": "agent-harness/judge_results.py", + "setting": "--timeout", + "values": "seconds", + "default": "300", + "nullius": "fixed:300 - its default" + }, + { + "entry": "agent-harness/judge_results.py", + "setting": "MYPCBENCH_RUBRIC_JUDGE_MODEL", + "values": "a model", + "default": "gemini-3.1-flash-lite-preview", + "nullius": "fixed:google/gemini-3.1-flash-lite-preview - the same model by a name sent to its OpenAI-compatible client; the run's judge model replaces it" + }, + { + "entry": "agent-harness/judge_results.py", + "setting": "MYPCBENCH_JUDGE_FLAVOR", + "values": "full trajectory, per_step", + "default": "full trajectory", + "nullius": "fixed:full trajectory - its default, the paper's" + }, + { + "entry": "agent-harness/judge_results.py", + "setting": "MYPCBENCH_OSWORLD_JUDGE_MAX_IMAGES", + "values": "a number, 0 for all", + "default": "200", + "nullius": "fixed:200 - its default" + }, + { + "entry": "agent-harness/judge_results.py", + "setting": "MYPCBENCH_OSWORLD_JUDGE_CONCURRENCY", + "values": "a number", + "default": "4", + "nullius": "fixed:4 - its default" + }, + { + "entry": "agent-harness/judge_results.py", + "setting": "GEMINI_API_KEY, GOOGLE_API_KEY, ANTHROPIC_API_KEY, OPENAI_API_KEY", + "values": "a key", + "default": "the environment's", + "nullius": "fixed:the judge route - the relay holds the key" + }, + { + "entry": "agent-harness/judge_results.py", + "setting": "MYPCBENCH_RUBRIC_JUDGE_MOCK_SCORE, MYPCBENCH_RUBRIC_JUDGE_MOCK_RESULT", + "values": "a score", + "default": "unset", + "nullius": "not offered - a test's fixed score" + }, + { + "entry": "agent-harness/judge_results.py", + "setting": "MYPCBENCH_RUBRIC_JUDGE_TIMEOUT, MYPCBENCH_RUBRIC_JUDGE_MAX_TOKENS, MYPCBENCH_JUDGE_CONCURRENCY, MYPCBENCH_JUDGE_STEP_SAMPLE, MYPCBENCH_JUDGE_MAX_STEPS, OPENAI_PROXY_URL", + "values": "the per-step judge's", + "default": "120, 256, 4, 1, 0, unset", + "nullius": "not offered - the per_step judge's alone" + }, + { + "entry": "agent-harness/run_parallel_tasks.py", + "setting": "--num-vms, --vllm-base-urls, --timeout-per-vm, --port-base, its other flags", + "values": "batches", + "default": "2 VMs; 3600", + "nullius": "not offered - runs run_mypcbench.py side by side; Nullius runs units side by side" + }, + { + "entry": "VM chat apps (BuzzChat, WorkBuzz)", + "setting": "LLM_BASE_URL", + "values": "OpenAI-compatible endpoint", + "default": "https://api.openai.com/v1", + "nullius": "fixed:the unit’s simulator relay - calls recorded with the task" + }, + { + "entry": "VM chat apps (BuzzChat, WorkBuzz)", + "setting": "LLM_MODEL", + "values": "model ID", + "default": "gpt-5.4-mini", + "nullius": "fixed:the simulator model - gpt-5.4-mini unless --simulator-model overrides it" + } +] diff --git a/app/nullius/progress.py b/app/nullius/progress.py index 0f940157f..e2c33dafd 100644 --- a/app/nullius/progress.py +++ b/app/nullius/progress.py @@ -47,7 +47,7 @@ # What the page calls each stage. One not here is shown by its own name. LABELS = {"connect": "Connect", "uv": "uv", "tasks": "Send the tasks", "app": "Send app/", "harbor": "Harbor", - "models": "Check models", "requirements": "Check requirements", "image": "Base image", "environment": "Environment", "upstream": "Benchmark source", "dataset": "Dataset", + "models": "Check models", "compatibility": "Check compatibility", "requirements": "Check requirements", "image": "Base image", "environment": "Environment", "upstream": "Benchmark source", "dataset": "Dataset", "driver": "Driver environment", "install": "Install", "runtime": "Agent runtime", "units": "Units"} _WORD = re.compile(r'([A-Za-z_][A-Za-z0-9_]*)=("(?:[^"\\]|\\.)*"|\S*)') diff --git a/app/nullius/runs/live.py b/app/nullius/runs/live.py index 791120afc..7a4878a9b 100644 --- a/app/nullius/runs/live.py +++ b/app/nullius/runs/live.py @@ -81,7 +81,7 @@ "cancelled", "timeout", "budget") ERROR_OUTCOMES = {"agent_error", "infra_error", "timeout", "budget"} COUNTERS = ("step", "n_input_tokens", "n_cache_tokens", "n_output_tokens", "cost_usd") -PROGRESS = ("step_limit", "calls", "calls_limit") +PROGRESS = ("step_limit", "calls", "calls_limit", "failed_requests") TOKEN_FIELDS = ("n_input_tokens", "n_cache_tokens", "n_output_tokens") RATE_WINDOW_SEC = 30.0 @@ -150,7 +150,7 @@ def parse_line(line: str) -> Event: raise FeedError(f"unknown phase {data.get('phase')!r}") if raw["event"] == "trial.end" and data.get("outcome") not in OUTCOMES: raise FeedError(f"unknown outcome {data.get('outcome')!r}") - for key in ("activity", "line"): + for key in ("activity", "line", "request_error"): if isinstance(data.get(key), str): data[key] = redact(data[key])[:ACTIVITY_MAX] if key == "activity" else redact(data[key]) return Event(parse_ts(raw["ts"]), raw["seq"], str(raw["job"]), trial, raw["event"], data) @@ -212,6 +212,8 @@ class TrialState: step_limit: int | None = None calls: int | None = None calls_limit: int | None = None + failed_requests: int | None = None + request_error: str | None = None n_input_tokens: int | None = None n_cache_tokens: int | None = None n_output_tokens: int | None = None @@ -260,6 +262,7 @@ def snapshot(self, now: datetime) -> dict: "elapsed_sec": elapsed, "timeout_sec": self.timeout_sec, "phases_done": list(self.phases_done), "step": self.step, + **({"request_error": self.request_error} if self.request_error else {}), **({k: getattr(self, k) for k in PROGRESS} if any(getattr(self, k) is not None for k in PROGRESS) else {}), "n_input_tokens": self.n_input_tokens, "n_cache_tokens": self.n_cache_tokens, "n_output_tokens": self.n_output_tokens, @@ -628,6 +631,7 @@ def trial_of(e: Event) -> TrialState: t.cost_before = (t.cost_before or 0.0) + t.cost_usd for key in (*COUNTERS, *PROGRESS): setattr(t, key, None) + t.request_error = None t._series = [] if t.phase and t.phase not in t.phases_done and t.phase != d["phase"]: t.phases_done.append(t.phase) @@ -643,6 +647,8 @@ def trial_of(e: Event) -> TrialState: for key in PROGRESS: if d.get(key) is not None: setattr(t, key, _num(d[key], int)) + if d.get("request_error") is not None: + t.request_error = str(d["request_error"])[:ACTIVITY_MAX] if d.get("activity") is not None: t.activity = d["activity"] reported = {k: _num(d[k], int) for k in TOKEN_FIELDS if d.get(k) is not None} diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index b8a18c272..b0cc4c479 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -34,7 +34,7 @@ # The shape this module produces. A workspace caches parsed Jobs keyed on it, # so bump it when a Trial or Job field is added, renamed or means something # new — otherwise a cache written by the old parse is read back as current. -SCHEMA = "29" +SCHEMA = "30" # What a rate-limit record in `agent/gateway.log` looks like. The agent's SDK # retries a 429 below the harness, so a limit the run survived leaves nothing in result.json — diff --git a/app/nullius/standard/calls/preflight.py b/app/nullius/standard/calls/preflight.py new file mode 100644 index 000000000..2622fff8b --- /dev/null +++ b/app/nullius/standard/calls/preflight.py @@ -0,0 +1,103 @@ +"""Check captured upstream requests through a run's relay before starting tasks. + +Drivers may expose synthetic requests from their published clients. Unexposed +roles stay unchecked. Only successful checks are cached, for one hour, under +the exact request, source pins, options, credentials and provider route. +""" +import hashlib +import http.client +import json +import os +import time +import urllib.error +import urllib.request + +from nullius import ondisk, paths +from . import relay + +TTL = 3600 +ROUTES = {"/v1/messages", "/v1/chat/completions", "/v1/responses"} + + +class Rejected(ValueError): + """The selected route did not accept the upstream's synthetic request.""" + + +def response_matches(path, body, streamed): + """A response in the requested API, including its streamed form.""" + try: + parts = [json.loads(line[5:].strip()) for line in body.decode().splitlines() + if line.startswith("data:") and line[5:].strip() not in ("", "[DONE]")] if streamed else [json.loads(body)] + except (ValueError, UnicodeError): + return False + parts = [p for p in parts if isinstance(p, dict)] + path = path.split("?", 1)[0] + if path.endswith("/messages"): + return any(p.get("type") == ("message_stop" if streamed else "message") for p in parts) + if path.endswith("/responses"): + return any(p.get("type") in ("response.completed", "response.incomplete", "response.done") for p in parts) if streamed \ + else any(isinstance(p.get("output"), list) and p.get("status") != "failed" for p in parts) + return any(isinstance(p.get("choices"), list) and p["choices"] for p in parts) + + +def check(requests, models, *, base, key, key_header, folder, identity, serving=None, + reasoning=None, prices=None, ledger=None, timeout=60): + """Return each role's checked/cached status. Calls are recorded and budgeted; + missing roles are reported by the caller, never inferred compatible.""" + if not isinstance(requests, list): + raise Rejected("preflight requests must be a list") + cache = os.path.join(paths.cache_dir(), "standard", "preflight") + os.makedirs(cache, exist_ok=True) + results = {} + r = None + try: + for spec in requests: + if not isinstance(spec, dict) or spec.get("role") not in models or str(spec.get("path")).split("?", 1)[0] not in ROUTES \ + or not isinstance(spec.get("body"), dict) or not isinstance(spec["body"].get("model"), str) \ + or not isinstance(spec.get("headers", {}), dict): + raise Rejected("preflight request must name a selected role, an API path and its JSON body") + role = spec["role"] + model = models[role] + headers = {k.lower(): v for k, v in (spec.get("headers") or {}).items() + if k.lower() in ("anthropic-beta", "anthropic-version")} + fingerprint = json.dumps([identity, base, hashlib.sha256(key.encode()).hexdigest(), key_header, + serving, reasoning, model, spec["path"], spec["body"], headers], sort_keys=True) + path = os.path.join(cache, hashlib.sha256(fingerprint.encode()).hexdigest() + ".json") + try: + with open(path) as f: + checked = json.load(f) + valid = isinstance(checked, (int, float)) and 0 <= time.time() - checked < TTL + except (OSError, ValueError): + valid = False + if valid: + results[role] = "cached" + continue + if r is None: + r = relay.Relay(base, key, folder, key_header=key_header, serving=serving, + reasoning=reasoning, prices=prices, ledger=ledger, unit_caps=False, + timeout=timeout).start() + url = r.url("preflight-" + role, model=model).removesuffix("/v1") + spec["path"] + body = json.dumps(spec["body"]).encode() + request = urllib.request.Request(url, data=body, headers={"Content-Type": "application/json", **headers}) + try: + with urllib.request.urlopen(request, timeout=timeout + 5) as response: + body = response.read() + matches = response_matches(spec["path"], body, "text/event-stream" in response.headers.get("Content-Type", "")) + except (OSError, urllib.error.URLError, http.client.HTTPException) as e: + status = e.code if isinstance(e, urllib.error.HTTPError) else "unreachable" + advice = {401: "check the provider credentials", 403: "check the provider permissions", + 402: "check provider credit and the run's spending cap", 429: "retry after the provider's rate limit clears"}.get(status) + advice = advice or ("retry when the endpoint is reachable" if status == "unreachable" or status >= 500 + else "check the provider route and API/tool support") + if isinstance(e, urllib.error.HTTPError): + e.close() + raise Rejected(f"{role} ({model}): compatibility check failed (HTTP {status}); {advice}") from None + calls = r.calls("preflight-" + role) + if not matches or not calls or calls[-1].get("status") != 200 or (calls[-1].get("reply") or {}).get("end") == "failed": + raise Rejected(f"{role} ({model}): compatibility check returned no successful model response") + ondisk.write_whole(path, json.dumps(time.time()), mode=0o600) + results[role] = "checked" + finally: + if r is not None: + r.stop() + return results diff --git a/app/nullius/standard/calls/relay.py b/app/nullius/standard/calls/relay.py index cca8e9a75..4cb18b993 100644 --- a/app/nullius/standard/calls/relay.py +++ b/app/nullius/standard/calls/relay.py @@ -71,7 +71,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Callable, Dict, List, Optional -from nullius import prices as price_list +from nullius import ondisk, prices as price_list from nullius.redact import redact from nullius.standard.calls import exchanges as exchange_store, ledger as ledgers @@ -97,6 +97,7 @@ ANTHROPIC_VERSION = "2023-06-01" CONTEXT_ERROR = "ContextWindowExceededError" STOP = "stop" +FATAL = "fatal.json" OVERFLOW = "context window" COMPLETION = re.compile(r"^/(?:chat/completions|completions|messages|responses)$") _WHOLE = ((b"\x89PNG\r\n\x1a\n", b"IEND\xaeB`\x82", "image/png"), (b"\xff\xd8\xff", b"\xff\xd9", "image/jpeg"), @@ -1046,6 +1047,8 @@ def record(body): rec["error_code"] = code if wait is not None: rec["retry_after"] = wait # the provider's word on when to call again (pace) + if rec.get("model") and permanent(dict(rec, error=body[:100000].decode("utf-8", "replace"))): + rec["permanent"] = True # validation details can be nested in provider metadata sent = _images(req) if status in (400, 413, 422) else [] if sent: rec["images"] = sent @@ -1071,6 +1074,12 @@ def record(body): if not side and not self.models.get(tag) and overflowed(rec): with open(os.path.join(self.dir, STOP), "a") as f: f.write(OVERFLOW + "\n") + if rec.get("model") and permanent(rec) and not os.path.exists(os.path.join(self.dir, FATAL)): + # The runner reads this also when the relay lives in a container. + # Keep provider text in the call record, never in the public stop reason. + kind = failure([rec], words=False)[0] + why = f"{tag}: the model endpoint rejected a required request (HTTP {status}, {kind}); check the model, credentials and API/tool support" + ondisk.write_whole(os.path.join(self.dir, FATAL), json.dumps([kind, why])) if number is not None: # the exchange whole, after its record: it never raises self.exchanges.write(tag, number, t0, rest, req if dumped else None, raw, {k: v for k, v in sent_headers.items() if not _CREDENTIAL.search(k)}, status, streamed, body) @@ -1253,6 +1262,34 @@ def asked(record_dir: str) -> Optional[str]: CALLS_ERROR = "UnitCallCapError" +def permanent(call: dict) -> bool: + """Failures retrying cannot repair. Ordinary 400s can be corrected by an agent; + only explicit model/tool compatibility refusals stop the run. Rate limits, + context overflow, malformed conversations and server failures remain retryable.""" + if call.get("refused") or _free(str(call.get("path") or "")): + return False + if call.get("permanent") is True: + return True + status, said = call.get("status"), str(call.get("error") or "") + if status in (401, 403, 402) or (status == 429 and call.get("error_code") == "insufficient_quota"): + return True + if status == 404 and "model" in said.lower(): + return True + return status in (400, 422) and bool(_NO_MODEL.search(said) or re.search( + r"unknown server-tool shorthand|(?:unsupported|not supported|does not support)[^\n]{0,100}(?:computer.use|tool.type|tool_choice)|" + r"(?:computer.use|tool.type|tool_choice)[^\n]{0,100}(?:unsupported|not supported|does not support)", said, re.I)) + + +def fatal(record_dir: str) -> Optional[tuple]: + """The relay's permanent refusal, if fully written.""" + try: + with open(os.path.join(record_dir, FATAL)) as f: + value = json.load(f) + return tuple(value) if isinstance(value, list) and len(value) == 2 and all(isinstance(v, str) for v in value) else None + except (OSError, ValueError): + return None + + def failure(calls: List[dict], words: bool = True, agent: bool = False) -> Optional[tuple]: """When a unit's model calls ended failing, the exception a trial carries for it - named so ``nullius.runs.classify`` sorts it as the diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index bdff8ea59..0bc1343b9 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -283,9 +283,11 @@ def fix_parts(fix: str) -> Tuple[str, str, str, str]: def version_label(d: dict) -> str: - """A version as a reader names it: its release tag, else its branch and short commit - (``main (044bc33)``), else its key.""" + """A version's display label, else its tag, branch and commit, or key.""" up = d.get("upstream") or {} + if isinstance(up.get("label"), str) and up["label"].strip(): + commit = f" ({str(up['tested'])[:7]})" if up.get("tested") else "" + return up["label"] + commit if up.get("tag"): return str(up["tag"]) if up.get("branch") and up.get("tested"): @@ -873,6 +875,8 @@ def _upstream(u) -> List[str]: if not isinstance(u, dict): return ["upstream: an object"] bad = [] + if "label" in u and (not isinstance(u["label"], str) or not u["label"].strip()): + bad.append("upstream.label: a non-empty display label") if "repository" in u: if not _HTTPS.match(str(u["repository"])): bad.append("upstream.repository: an https address") @@ -1249,10 +1253,15 @@ def comparable(orig: dict, model: str) -> bool: return model in c if isinstance(c, list) else bool(c) +def setup_model(orig: dict, model: str, provider: str) -> str: + """An original model's served name; direct OpenAI takes no OpenRouter maker prefix.""" + name = (orig.get("providers") or {}).get(provider, "") + (orig.get("served_as") or {}).get(model, model) + return name.removeprefix("openai/") if provider == "openai" else name + + def upstream_name(orig: dict, model: str, provider: str) -> str: """``model`` by the name the original's upstream knows, when given as ``provider`` lists it.""" - pre = (orig.get("providers") or {}).get(provider, "") - names = {pre + (orig.get("served_as") or {}).get(m, m): m for m in orig.get("models") or []} + names = {setup_model(orig, m, provider): m for m in orig.get("models") or []} return model if model in (orig.get("models") or []) else names.get(model, model) @@ -1458,8 +1467,7 @@ def setup(bench: dict, which: str, model: str = "", provider: str = "", agent: s return None, (f"the paper's models are not served by {provider}: the original runs on " + " or ".join(orig["providers"])) asked = model - prefix = orig["providers"].get(provider, "") if provider else "" - served = lambda m: prefix + (orig.get("served_as") or {}).get(m, m) + served = lambda m: setup_model(orig, m, provider) sent = served(model) # the other models its code asks, each sent as the provider serves it; one the answerer is served as is its own side = [f"{m}={served(m)}" for m in orig.get("side_models") or [] if served(m) != sent] @@ -1467,6 +1475,13 @@ def setup(bench: dict, which: str, model: str = "", provider: str = "", agent: s if not model: return None, f"the model setup needs a model: the one to put in {orig['default']}'s place" asked, sent = (mine["models"][0] if mine else x["runs_as"]), model # its own agent asks its own first model + # the vendor a name proves: a first-party provider's, or OpenRouter's prefix; a server of your own proves none + vendor = provider if provider in ("openai", "anthropic") else model.split("/", 1)[0] if provider == "openrouter" else "" + if mine and mine.get("vendors") and vendor and vendor not in mine["vendors"]: + from nullius.providers import PRESETS + name = lambda v: (PRESETS.get(v) or {}).get("name", v) + return None, (f"{mine['label']} sends tools only {' or '.join(map(name, mine['vendors']))} models know: " + f"{model}{' on ' + name(provider) if provider in ('openai', 'anthropic') else ''} is not one") units = orig.get("units") or bench.get("units") or {"noun": "unit", "nouns": "units"} return {**({"agent": mine["key"]} if mine else {}), "model": {"side_models": side}, "key": which, "label": f"{bench['label']} {setup_label(bench, which).lower()}", "summary": x["summary"], "asked": asked, "sent": sent, "units": units, "comparable": which == "original" and comparable(x, model), @@ -1505,6 +1520,9 @@ def _driver_agent(d: dict) -> List[str]: if not isinstance(ms, list) or not ms or len(set(map(str, ms))) != len(ms) \ or not all(isinstance(m, str) and _MODEL_NAME.match(m) for m in ms): bad.append("models: the models it is published with, each once, as its code names them") + vs = d.get("vendors", []) + if not isinstance(vs, list) or not all(isinstance(v, str) and _OPTION_VALUE.match(v) for v in vs): + bad.append("vendors: the model vendors whose built-in tools it sends, as a provider names them (anthropic)") return bad @@ -1686,6 +1704,8 @@ def problems(d: dict, kind: str) -> List[str]: bad += _install(dict(driver_install(d), install=drv["install"]), "driver.install") elif any("{install}" in w for w in drv.get("command") or [] if isinstance(w, str)): bad.append("driver.command: {install} names driver.install, which is not set") + if "preflight" in drv and not isinstance(drv["preflight"], bool): + bad.append("driver.preflight: true or false - whether the driver captures synthetic upstream requests") if "participant" in drv and not isinstance(drv["participant"], bool): bad.append("driver.participant: true or false - whether setup is told the participant's kind") if "unit_end" in drv and not isinstance(drv["unit_end"], bool): @@ -1797,8 +1817,10 @@ def problems(d: dict, kind: str) -> List[str]: if sim is not None: if not isinstance(sim, dict) or not _MODEL_NAME.match(str(sim.get("model", ""))) or not sim.get("says"): bad.append("simulator: {model: the official simulated user's model, as the provider names it; says: whom it plays}") - elif "agent.conversation/v1" not in (needs if isinstance(needs, list) else []): - bad.append("simulator: only a benchmark that needs agent.conversation/v1 has a user to simulate") + elif not {"agent.conversation/v1", "agent.computer/v1"}.intersection(needs if isinstance(needs, list) else []): + bad.append("simulator: only a benchmark that needs agent.conversation/v1 or agent.computer/v1 has a user to simulate") + elif "agent.conversation/v1" not in needs and not (d.get("driver") or {}).get("task_given"): + bad.append("simulator: a desktop benchmark needs driver.task_given to receive its route") bad += _served_as("simulator", sim) bad += _controls(d.get("controls")) bad += _leaderboard(d) diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 89875646b..9ab3a9520 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -204,8 +204,8 @@ def _bench_page(b: dict) -> dict: "reference_agent": x.get("reference_agent", ""), "turn_seconds": x.get("turn_seconds"), "gone": x.get("comparable") == [], "comparable": k == "original" and b["setups"]["original"].get("comparable", True) not in (False, []), "units": (b["setups"]["original"].get("units") or b.get("units") or {}), **({"models": definitions.paper_models(x), "default": x["default"], "providers": list(x["providers"]), - "sent": {p: {m: pre + (x.get("served_as") or {}).get(m, m) for m in definitions.paper_models(x)} - for p, pre in x["providers"].items()}} + "sent": {p: {m: definitions.setup_model(x, m, p) for m in definitions.paper_models(x)} + for p in x["providers"]}} if "models" in x else {"any": True, "providers": list(x["providers"])})} for k, x in (b.get("setups") or {}).items() if k == "original"], # its own options (a search, a mode): each value with its line and what it needs; and the host requirements @@ -767,7 +767,7 @@ def add(step, message, shown=False, field=None, unset=False): if not _MODEL.match(model) and (needs_model or model): add("model", "Choose a model or enter its ID.", unset=not model) if model_choice == "paper" and model in orig.get("models", []) and provider_ in orig.get("providers", {}): - model = orig["providers"][provider_] + (orig.get("served_as") or {}).get(model, model) + model = definitions.setup_model(orig, model, provider_) # each unit tried K times (the upstream's --num-trials: pass^k); the user simulator's and the judge's models repeat = _int(recipe.get("repeat") or lb.get("repeat") or 1, 1, 32) if repeat is None: diff --git a/app/nullius/standard/protocols/cancellation.py b/app/nullius/standard/protocols/cancellation.py index e664334a8..17be64bf7 100644 --- a/app/nullius/standard/protocols/cancellation.py +++ b/app/nullius/standard/protocols/cancellation.py @@ -4,6 +4,16 @@ from concurrent.futures import CancelledError +class Either: + """A protocol wait ends on user cancellation or a permanent provider refusal.""" + + def __init__(self, *events): + self.events = events + + def is_set(self): + return any(e.is_set() for e in self.events) + + def reply(messages, timeout, stopped=None, cut=None): """The next message within ``timeout`` seconds; ``queue.Empty`` past them, and as soon as ``cut`` is set: the wait then ends as if its time had run out.""" diff --git a/app/nullius/standard/protocols/computer_port.py b/app/nullius/standard/protocols/computer_port.py index bed853941..2a20f53e3 100644 --- a/app/nullius/standard/protocols/computer_port.py +++ b/app/nullius/standard/protocols/computer_port.py @@ -925,8 +925,14 @@ def _write(self): break with self.lock: self.out_bytes -= len(data) + self.ready.notify_all() self.close() + def flush(self, seconds): + """Wait at most seconds for queued answers, including a write in progress.""" + with self.ready: + self.ready.wait_for(lambda: self.closed or not self.out_bytes, timeout=max(0, seconds)) + def opened(self): with self.lock: self.open_calls += 1 @@ -980,7 +986,7 @@ def _state(self, bridge, path, log): self.log_lock, self.lock = threading.Lock(), threading.Lock() self.closing, self.wires = False, set() - def close(self): + def close(self, flush_seconds=0): with self.lock: self.closing = True wires = list(self.wires) @@ -988,7 +994,10 @@ def close(self): self.listener.shutdown(socket.SHUT_RDWR) with contextlib.suppress(OSError): self.listener.close() + until = time.monotonic() + flush_seconds for wire in wires: + if flush_seconds: + wire.flush(until - time.monotonic()) wire.close() with contextlib.suppress(OSError): os.unlink(self.path) diff --git a/app/nullius/standard/runner/rerun.py b/app/nullius/standard/runner/rerun.py index dcf069d1b..2a876ea40 100644 --- a/app/nullius/standard/runner/rerun.py +++ b/app/nullius/standard/runner/rerun.py @@ -729,7 +729,9 @@ def write(ended: List[dict], budget: Optional[dict]) -> None: mode=stat.S_IMODE(kept.st_mode) if kept and stat.S_ISREG(kept.st_mode) else None) ended, budget, u0 = r.run_units(work, write, first) - if r.halted: + if r.permanent_failure: + r.say("stopped: " + r.permanent_failure[1]) + elif r.halted: r.say(r.halt_said(len(work) - len(ended))) p.emit("units", "done", seconds=round(time.time() - u0, 1)) p.emit("done", n=len(ended), seconds=round(time.time() - t0, 1)) @@ -747,7 +749,7 @@ def write(ended: List[dict], budget: Optional[dict]) -> None: r.say(f"ran again: {len(record['replaced'])} of {len(picked) - len(fresh)} replaced" + "".join(f"; {x['trial']}: {'no result' if x['trial'] in killed else _word(x['was'])} -> {_word(x['now'])}" for x in record["replaced"])) - return dict(record, job=job_dir, **({"halted": True} if r.halted else {})) + return dict(record, job=job_dir, **({"halted": True} if r.halted or r.permanent_failure else {})) def _word(result: dict) -> str: diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index 4e4a408e9..fb9612307 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -518,7 +518,8 @@ class Ticker: read stays; a record line not yet ended is read once it is. A unit's last counts are queued as it stops being watched (:meth:`drop`). Its end waits at most one tick for them.""" - def __init__(self, feed, every: Optional[float] = None): + def __init__(self, feed, every: Optional[float] = None, on_failure=None, failure_records=()): + self.on_failure, self.failure_records = on_failure, failure_records self.feed, self.every = feed, TICK_SECONDS if every is None else every self.units: Dict[str, dict] = {} # by trial name: what is read of it, and what was last sent self.pending: List[tuple] = [] @@ -567,6 +568,10 @@ def drop(self, name: str) -> None: done.wait(self.every) def tick(self) -> None: + for folder in self.failure_records: + failed = relay.fatal(folder) + if failed and self.on_failure is not None: + self.on_failure(failed) with self.lock: units = list(self.units.items()) pending, self.pending = self.pending, [] @@ -581,8 +586,10 @@ def tick(self) -> None: def _read(self, name: str, u: dict) -> None: self._steps(u) self._calls(u) + self._failures(u) n, steps = u["counts"], u["steps"] or (None, None) values = {"step": steps[0], "step_limit": steps[1], + **({"failed_requests": u["failed_requests"], "request_error": u["request_error"]} if u.get("failed_requests") else {}), **({"calls": n["calls"], "calls_limit": u["calls_limit"], "n_input_tokens": n["input"], "n_cache_tokens": n["cached"], "n_output_tokens": n["output"], "cost_usd": n["cost"]} if n else {})} if all(v is None for v in values.values()) or values == u["sent"]: @@ -593,6 +600,43 @@ def _read(self, name: str, u: dict) -> None: return u["sent"] = values + def _failures(self, u: dict) -> None: + """Every route of this unit, including its judge and simulated user.""" + if u["record"] is None: + return + folder = os.path.dirname(u["record"]) + failed = relay.fatal(folder) + if failed and self.on_failure is not None: + self.on_failure(failed) + try: + names = os.listdir(folder) + except OSError: + return + positions = u.setdefault("error_positions", {}) + for name in sorted(names): + if not name.endswith(".jsonl"): + continue + try: + with open(os.path.join(folder, name), "rb") as f: + f.seek(positions.get(name, 0)) + got = f.read() + except OSError: + continue + end = got.rfind(b"\n") + 1 + positions[name] = positions.get(name, 0) + end + for line in got[:end].splitlines(): + try: + c = json.loads(line) + except ValueError: + continue + if not isinstance(c, dict) or not c.get("model") or relay._free(str(c.get("path") or "")): + continue + if isinstance(c.get("status"), int) and c["status"] >= 400: + u["failed_requests"] = u.get("failed_requests", 0) + 1 + # Public progress never contains provider text (it may quote a gated task). + role = name[:-6].split("-", 1)[-1] if "-" in name else "agent" + u["request_error"] = f"{role}: HTTP {c['status']}" + @staticmethod def _steps(u: dict) -> None: """The progress file's steps and limit, when it reads as one; the values before it otherwise.""" @@ -1122,6 +1166,23 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas self.local = threading.local() self.drivers: List[jsonl.Proc] = [] self._stopped = threading.Event() + self._fatal_event = threading.Event() + self.permanent_failure = None + + @property + def cancellation(self): + from ..protocols.cancellation import Either + event = getattr(self, "_fatal_event", None) + return Either(self._stopped, event) if event is not None else self._stopped + + def fail_provider(self, failure): + """End protocol waits and stop queued units on a permanent relay refusal.""" + with self._said: + if self.permanent_failure is None: + self.permanent_failure = failure + self.say("stopping: " + failure[1]) + self._fatal_event.set() + self._halt.set() def question_env(self) -> dict: """The selected questions of this job's dataset, for local or container drivers.""" @@ -1146,7 +1207,7 @@ def driver(self) -> jsonl.Proc: if s.get("to") == "driver" and s.get("kind") == "file" for h in [self.licences.get(s["name"])] if h] + list(self.file_env.values()) d = self.setup_driver.start(env, cwd, os.path.join(self.job_dir, ".work", f"driver-{threading.get_ident()}.log"), - files=files, stopped=self._stopped, + files=files, stopped=self.cancellation, servers=[s["name"] for s in definitions.secrets_of(self.bench) if s.get("to") == "driver" and s.get("kind") == "server"]) self.local.driver = d @@ -1169,7 +1230,7 @@ def driver(self) -> jsonl.Proc: cwd = os.path.join(self.job_dir, ".work", "driver") os.makedirs(cwd, exist_ok=True) cmd, env = limits.wrap(cmd, env, getattr(self, "scope_limits", {})) - d = jsonl.Proc(cmd, cwd, env, os.path.join(self.job_dir, ".work", f"driver-{threading.get_ident()}.log"), stopped=self._stopped).start() + d = jsonl.Proc(cmd, cwd, env, os.path.join(self.job_dir, ".work", f"driver-{threading.get_ident()}.log"), stopped=self.cancellation).start() self.local.driver = d self.drivers.append(d) return d @@ -1201,7 +1262,7 @@ def _start(self, lck, mine) -> str: + (["upstream"] if install.upstream_dir(self.bench) else []) + (["dataset"] if self.ds.get("url") else []) + (["driver"] if install.driver_dir(self.bench) else []) - + ([] if control or self.upstream else ["install"]) + ["units"])) + + ([] if control or self.upstream else ["install"]) + (["compatibility"] if self.base else []) + ["units"])) if (self.max_usd is not None or self.unit_max_usd is not None) and self.base: # one ledger for the job, in a folder of its own: all a unit's relay container is given of the job besides its record self.ledger = ledgers.Ledger.create(os.path.join(self.job_dir, ".work", "ledger", "ledger.json"), self.max_usd, self.unit_max_usd) @@ -1212,9 +1273,19 @@ def _start(self, lck, mine) -> str: with p.stage("models", start="checking the provider’s model list"): self.known_models() self.ready() - except Refused as e: - # said in the job, which holds nothing else: the runs list reads why there (progress.refusal) - p.emit("refused", detail=str(e)) + if self.base: + with p.stage("compatibility", start="checking captured upstream requests"): + self.compatibility() + except BaseException as e: + if isinstance(e, Refused): + # The launch page reads the refusal even before a unit exists. + p.emit("refused", detail=str(e)) + for driver in self.drivers: + driver.close() + if self.bench_relay is not None: + self.bench_relay.stop() + if self.backend == "container" or self.relay_container: + container.sweep(self.name) raise try: units = self.driver().request("units", dataset=self.ds["id"], timeout=300, @@ -1356,7 +1427,9 @@ def _start(self, lck, mine) -> str: if budget and budget.get("over_unit"): self.say(f"{len(budget['over_unit'])} of the {self.bench['units']['nouns']} reached the cap of " f"{ledgers.usd(budget['unit_max_usd'])} USD each and were cut off there") - if self.halted: + if self.permanent_failure: + self.say("stopped: " + self.permanent_failure[1]) + elif self.halted: self.say(self.halt_said(len(first) - len(results))) rewards = [(r.get("verifier_result") or {}).get("rewards", {}) for r in results] if self.bench["score"]["kind"] == "pass": @@ -1425,7 +1498,8 @@ def run_units(self, work: list, write: Callable[[List[dict], Optional[dict]], No self.loopback = None self.pace = pacing.Pace(self._stopped, self._halt) self._running = 0 - self.ticker = Ticker(self.feed) # each running unit's steps and calls, told to the live board + self.ticker = Ticker(self.feed, on_failure=self.fail_provider, + failure_records=[self.bench_relay.dir] if self.bench_relay is not None else []) again: Dict[str, dict] = {} # an attempt's last try, by its trial's name, when it was retried def work_unit(iur): @@ -1790,14 +1864,15 @@ def unit_ended(self, unit: str, ws: str) -> bool: return True return False - def task_given(self, unit: str, ws: str) -> None: + def task_given(self, unit: str, ws: str, rl=None, tag: str = "") -> None: """A driver that asks for it (``driver.task_given``) is told, and has answered, before the agent is sent its task: its first prompt, or its command, which holds it. A computer port closes its window before the task there. A failure ends the unit as its environment's, the task never sent.""" if self.other.get("_kind") != "agent" or not (self.bench.get("driver") or {}).get("task_given"): return try: - self.driver().request("task_given", unit=unit, dir=ws, timeout=END_SECONDS) + self.driver().request("task_given", unit=unit, dir=ws, timeout=END_SECONDS, + **(self.simulator(rl, tag) if rl is not None else {})) except jsonl.Failed as e: raise _Ended("EnvironmentSetupError", f"the benchmark was not told that the task is given: {e}", retryable=not isinstance(e, jsonl.NoReply)) @@ -1957,6 +2032,10 @@ def sent(): produce = (p0, p1 if p1 is not None else time.time()) if box is not None: # what the agent (or the control) left in the container, before the check changes = self.box_changes(box) + fatal = relay.fatal(rl.dir) if rl is not None else None + if fatal: + self.fail_provider(fatal) + raise _Ended(*fatal, trajectory=traj, retryable=False) cut = self.cap_reached(rl, tag) if cut and not (cut[0] == relay.CALLS_ERROR and clock.get("cut")): # cut off at a spending cap: nothing of it is checked, and its judge is asked nothing; at the cap on @@ -2039,6 +2118,14 @@ def sent(): late = [c for c in self.bench_relay.calls(self.embeddings_tag()) if c.get("refused") == "cap" and c.get("t0", 0) >= t0] if late: exc, score = (ledgers.ERROR, late[0].get("error") or ""), None + fatal = relay.fatal(rl.dir) if rl is not None else None + if not fatal and getattr(self, "bench_relay", None) is not None: + fatal = relay.fatal(self.bench_relay.dir) + if fatal: + self.fail_provider(fatal) + exc, score, retry_ok = fatal, None, False + elif getattr(self, "permanent_failure", None) and exc: + exc, score, retry_ok = (CANCELLED, "stopped after a permanent provider refusal: " + self.permanent_failure[1]), None, False if self._stopped.is_set() and score is None: # the Stop ended its agent, its relay or its containers under it: what it then failed with is # the Stop's doing, not the agent's nor the environment's @@ -2273,15 +2360,52 @@ def ledger_file(self) -> Optional[str]: return led.path if led is not None else None def benchmark_calls(self) -> List[dict]: - """The calls of the benchmark's own relay (an option's embeddings or reranking), every route of it.""" - folder = os.path.join(self.job_dir, ".work", "relay-benchmark") + """Preflight and benchmark calls (embeddings or reranking), outside the agent's task usage.""" calls = [] - for name in sorted(os.listdir(folder)) if os.path.isdir(folder) else []: - if name.endswith(".jsonl"): - with open(os.path.join(folder, name)) as f: - calls += [json.loads(line) for line in f if line.strip()] + for kind in ("relay-benchmark", "relay-preflight"): + folder = os.path.join(self.job_dir, ".work", kind) + for name in sorted(os.listdir(folder)) if os.path.isdir(folder) else []: + if name.endswith(".jsonl"): + with open(os.path.join(folder, name)) as f: + calls += [json.loads(line) for line in f if line.strip()] return calls + def compatibility(self) -> None: + """Check only requests the integration can capture before its task starts. + Every remaining role is explicitly unchecked; model-list lookup is not a + claim of protocol, native-tool or image support.""" + from ..calls import preflight + models = {role: model for role, model in (("agent", self.model if self.other["_kind"] != "control" else None), + ("judge", self.judge_model), ("simulator", self.simulator_model), + ("embeddings", self.embed_model), ("reranker", self.rerank_model)) if model} + for model in self.models_called(): + if model not in models.values(): + models[f"side-{len(models)}"] = model + requests = [] + if (self.bench.get("driver") or {}).get("preflight"): + try: + captured = self.driver().request("preflight", participant="setup" if self.upstream else self.other["_kind"], + setup=self.other["key"], model=self.asked, roles=list(models), timeout=300) + requests = captured.get("requests", []) + except jsonl.Failed as e: + raise Refused(f"compatibility request capture failed: {e}") from e + try: + results = preflight.check(requests, models, base=self.base, key=self.key, key_header=self.key_header, + folder=os.path.join(self.job_dir, ".work", "relay-preflight"), + identity=[self.bench, self.other, self.bench_options, self.options], + serving=self.serving, reasoning=self.reasoning, prices=self.prices, + ledger=self.ledger_file(), timeout=min(self.call_seconds, 60)) + except preflight.Rejected as e: + raise Refused(str(e)) from e + for role, model in models.items(): + state = results.get(role) + self.say(f"compatibility: {role} ({model}): " + (state if state else "not checked; no upstream request capture")) + checked = [role for role in models if role in results] + unchecked = [role for role in models if role not in results] + detail = "; ".join((["Checked: " + ", ".join(checked)] if checked else []) + + (["Not checked: " + ", ".join(unchecked) + " (no upstream request capture)"] if unchecked else [])) + self.progress.emit("compatibility", detail=detail) + def known_models(self) -> None: """Refused before anything is installed when the provider lists its models and one this run calls is not among them: every call to it @@ -2527,7 +2651,7 @@ def unit_vm(self, ws: str, home: str, trial: str, setup: dict): plan = setup.get("memory") or {} requests = 1 if self.other["_kind"] == "agent" else max(1, len(plan.get("add") or []) + len(plan.get("recall") or [])) try: - with self.boat.unit(trial, ws, home, stopped=self._stopped, inst=self.inst, here=self.other.get("_here"), + with self.boat.unit(trial, ws, home, stopped=self.cancellation, inst=self.inst, here=self.other.get("_here"), seconds=self.agent_limit(setup) * requests): yield except boat.Unavailable as e: @@ -2855,7 +2979,7 @@ def drive_agent(self, unit, ws, home, tag, setup, transcript, rl, box=None, name if self.backend == "local": # inside a container, its own PATH finds it cmd[0] = shutil.which(cmd[0], path=env["PATH"]) or cmd[0] cmd, env = self.place(rl, cmd, env, ws, home, box=box) - c = acp.Client(cmd, env, log, cwd=ws, grant=True, fs=box is None and self.backend == "local", stopped=self._stopped) + c = acp.Client(cmd, env, log, cwd=ws, grant=True, fs=box is None and self.backend == "local", stopped=self.cancellation) events: List[dict] = [] kinds, cut = self.scored_cuts(), None record = getattr(rl, "dir", None) @@ -2885,7 +3009,7 @@ def left() -> float: # a conversation's turns carry its simulated user's route and its judge's (each when it has one) sim = dict(self.simulator(rl, tag), **self.judge(rl, tag)) if "agent.conversation/v1" in self.bench["needs"] else {} opened = True - if self.simulator_model: + if self.simulator_model and "agent.conversation/v1" in self.bench["needs"]: # The simulated user speaks first: the first turn, asked with nothing said yet, # follows setup's prompt (what the agent is told before anyone speaks). first = self.driver().request("turn", unit=unit, dir=ws, transcript=[], timeout=600, **sim, **self.attempt_kw()) @@ -2893,7 +3017,7 @@ def left() -> float: if opened: prompt = prompt + "\n\n" + first["message"] if opened: - self.task_given(unit, ws) # before the first prompt: the window from the session's start closes + self.task_given(unit, ws, rl, tag) # before the first prompt: the window from the session's start closes if watch is not None: watch.start() for _ in range(self.max_turns if opened else 0): @@ -2952,12 +3076,12 @@ def left() -> float: def _command_agent(self, a, env, ws, home, setup, transcript, log, tag, unit, rl, box=None): cmd = install.words(a["start"]["command"], {"here": a["_here"], "install": self.inst, "prompt": setup["prompt"]}) cmd, env = self.place(rl, cmd, env, ws, home, interactive=False, box=box) - self.task_given(unit, ws) # its command holds its task: its session starts with no window + self.task_given(unit, ws, rl, tag) # its command holds its task: its session starts with no window transcript.append({"role": "user", "text": setup["prompt"]}) t = time.time() try: with open(log, "a") as err: - r = run_group(cmd, self.agent_limit(setup), stopped=self._stopped, cwd=ws, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + r = run_group(cmd, self.agent_limit(setup), stopped=self.cancellation, cwd=ws, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=err, text=True) except subprocess.TimeoutExpired: raise _Ended("AgentTimeoutError", f"the agent did not end in {int(self.agent_limit(setup))} s") @@ -2977,7 +3101,7 @@ def drive_feature(self, unit, ws, home, tag, setup, transcript, rl): cmd, env = self.place(rl, cmd, env, f["_here"], home) cwd = os.path.join(os.path.dirname(ws), ".work", "capability") # the unit's, never the catalogue folder os.makedirs(cwd, exist_ok=True) - proc = jsonl.Proc(cmd, cwd, env, os.path.join(os.path.dirname(ws), "agent", "capability.log"), stopped=self._stopped) + proc = jsonl.Proc(cmd, cwd, env, os.path.join(os.path.dirname(ws), "agent", "capability.log"), stopped=self.cancellation) os.makedirs(os.path.join(os.path.dirname(ws), "agent"), exist_ok=True) exchanges: List[dict] = [] # each add and each recall its own limit: a memory adds a unit's sessions one by one, each its own model calls, @@ -3080,4 +3204,4 @@ def run_and_report(bench: dict, other: dict, **kw) -> tuple: whatever it reached.""" r = Run(bench, other, **kw) job_dir = r.start() - return job_dir, bool(r.halted) or (r.n_ended > 0 and r.n_verdicts == 0 and not r.capped) + return job_dir, bool(r.halted or r.permanent_failure) or (r.n_ended > 0 and r.n_verdicts == 0 and not r.capped) diff --git a/app/static/builder/command-builder.css b/app/static/builder/command-builder.css index a275c8381..4415e5e76 100644 --- a/app/static/builder/command-builder.css +++ b/app/static/builder/command-builder.css @@ -215,13 +215,13 @@ #nullius-builder .nb-model-control input { padding: 6px 36px 6px 11px; min-height: 34px; font-size: 13px; } @media (max-width: 650px) { #nullius-builder .nb-model-control input { font-size: 16px; } } -/* A model and its reasoning on one line; the provider, model and Served by rows widen alike so a name is not cut. */ +/* A model and its reasoning on one line; provider, editable and fixed models, and Served by share a control column. */ #nullius-builder .nb-model-line { display: flex; gap: 8px; min-width: 0; } #nullius-builder .nb-model-line > .nb-model-control { flex: 1 1 auto; } #nullius-builder .nb-reasoning { flex: 0 0 12rem; } #nullius-builder .nb-reasoning:empty { display: none; } @media (max-width: 650px) { #nullius-builder .nb-model-line { flex-wrap: wrap; } #nullius-builder .nb-model-line > .nb-model-control { flex-basis: 100%; } } -@media (min-width: 651px) { #nullius-builder label.nb-field.ui-field-row:has(.nb-model-line), #nullius-builder label.nb-field.ui-field-row.std-served, #nullius-builder #nb-form:has(.nb-model-line) label.nb-field.ui-field-row:has([data-field="provider"]) { grid-template-columns: minmax(0, 1fr) minmax(180px, 56%); } } +@media (min-width: 651px) { #nullius-builder label.nb-field.ui-field-row:has(.nb-model-line), #nullius-builder label.nb-field.ui-field-row.std-served, #nullius-builder #nb-form:has(.nb-model-line) label.nb-field.ui-field-row:has([data-field="provider"], .nb-fixed) { grid-template-columns: minmax(0, 1fr) minmax(180px, 56%); } } /* Compact settings rows use one shared control column, including paired fields. */ #nullius-builder .nb-two:has(> .ui-field-row) { grid-template-columns: minmax(0, 1fr); gap: 0; } diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index 120294a76..86b0d64f1 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -873,7 +873,7 @@ // the benchmark's other models: the user simulator its conversations need, the judge that grades - each its official one // unless named; like the paper, the official one; like the leaderboard, its own and the options it fixes + (b.simulator ? (paper ? fixed('Model for the user simulator', lb && lb.simulator || b.simulator, lb && lb.simulator ? 'leaderboard' : 'official') : field('Model for the user simulator', 'simulator_model', rec.simulator_model || '', {list: 'nb-models', placeholder: b.simulator + ' (official)', after: reasoningLine(rec, 'simulator'), - hint: 'Plays the user in every conversation. Empty: ' + esc(b.label) + "'s official one; another compares only with runs that used it."})) + servedField(rec, 'simulator') : '') + hint: (b.needs.includes('agent.conversation/v1') ? 'Plays the user in every conversation.' : 'Plays the desktop’s chat contacts.') + ' Empty: ' + esc(b.label) + "'s official one; another compares only with runs that used it."})) + servedField(rec, 'simulator') : '') + (b.judge ? (paper ? fixed('Model for the judge', lb && lb.judge || b.judge, lb && lb.judge ? 'leaderboard' : 'official') : field('Model for the judge', 'judge_model', rec.judge_model || '', {list: 'nb-models', placeholder: b.judge_retired ? 'Search or enter a model ID' : b.judge + ' (official)', after: reasoningLine(rec, 'judge'), hint: b.judge_retired ? 'Grades the answers.' : 'Grades the answers. Empty: ' + esc(b.label) + "'s official judge; another compares only with runs that used it."})) + servedField(rec, 'judge') : '') // a judge beside the benchmark's score, never its own: run only when a model is named diff --git a/app/static/catalogue/marks.svg b/app/static/catalogue/marks.svg index 8aea777fc..947d13b14 100644 --- a/app/static/catalogue/marks.svg +++ b/app/static/catalogue/marks.svg @@ -33,6 +33,10 @@ + + + + diff --git a/app/static/runs/live-board.js b/app/static/runs/live-board.js index 1a5b7e89c..ef5fabcfd 100644 --- a/app/static/runs/live-board.js +++ b/app/static/runs/live-board.js @@ -66,8 +66,7 @@ return bar ? `${text}` : `${text}`; } - const callsCell = t => t.calls == null ? '—' - : `${esc(t.calls)}${t.calls_limit ? ' of ' + esc(t.calls_limit) : ''}`; + const callsCell = t => `${t.calls == null ? '—' : esc(t.calls)}${t.calls_limit ? ' of ' + esc(t.calls_limit) : ''}${t.failed_requests ? `
${esc(t.failed_requests)} failed requests` : ''}`; const ofLimit = t => `${clock(t.elapsed_sec)}${t.timeout_sec ? ' of ' + clock(t.timeout_sec) : ''}`; function stateOf(s) { const C = s.counts || {}; @@ -217,7 +216,7 @@ const doneRows = opts.showAll ? done : done.slice(-FLIGHT_SHOWN); const queuedRows = opts.showAll ? queued : queued.slice(0, FLIGHT_SHOWN); // a column appears once some trial reported it; a single missing cell is "—" - const has = {steps: trials.some(t => t.step != null), calls: trials.some(t => t.calls != null), tokens: trials.some(t => tokensOf(t) != null), line: trials.some(t => t.activity || t.last_line)}; + const has = {steps: trials.some(t => t.step != null), calls: trials.some(t => t.calls != null || t.failed_requests != null), tokens: trials.some(t => tokensOf(t) != null), line: trials.some(t => t.activity || t.last_line)}; const body = rows.map(t => { const k = PHASES.indexOf(t.phase), p = pressure(t), tok = tokensOf(t), line = t.activity || t.last_line; const dim = opts.filter && t.outcome !== opts.filter ? ' dim' : ''; @@ -281,6 +280,7 @@ }; const phases = PHASES.map(p => { const d = dur(p); return `${PHASE_LABEL[p]}${d == null ? '—' : clock(d)}${p === cur ? ' so far' : ''}`; }).join(''); const facts = [['Steps', t.step, v => esc(v) + (t.step_limit > 0 ? ' of ' + esc(t.step_limit) : '')], + ['Failed requests', t.failed_requests, count], ['Last request error', t.request_error, esc], ['Model calls', t.calls, v => esc(v) + (t.calls_limit ? ' of ' + esc(t.calls_limit) : '')], ['Input', t.n_input_tokens, count], ['Cached', t.n_cache_tokens, count], ['Output', t.n_output_tokens, count], ['Cost', t.cost_usd, v => '$' + Number(v).toFixed(2)], ['Reward', t.reward, v => Number(v).toFixed(2)], ['Score', t.score, v => Number(v).toFixed(2)]].filter(f => f[1] != null); const events = (s.tail || []).filter(e => e.trial === t.trial).slice(-6); diff --git a/app/templates/builder/agents.html b/app/templates/builder/agents.html index b5dc7c851..57331acd9 100644 --- a/app/templates/builder/agents.html +++ b/app/templates/builder/agents.html @@ -2,12 +2,13 @@ cards of the card toolkit (_cards.html), or its rows (`layout` 'table'), loaded by command-builder.js. -#} {% from '_cards.html' import cards %} {% set noun = 'agents' if kind == 'agent' else 'Modules' %} -{#- the card's slots as the Agents page's (agents/standard.html): its protocol, origin and source are filters and - columns, never on the card; in a table, why not after the name, fit and proves off until asked; Origin and Fit menus +{#- the card's slots as the Agents page's (agents/standard.html): protocol and origin are filters and columns; + a benchmark's own agent names its source on the card. In a table, why not after the name, fit and proves off until asked; Origin and Fit menus of their own, Fit on Can run it at first -#} {% set cols = [dict(key='icon', label='Logo', card='icon', table=false, class='std-mark small'), dict(key='title', label='Name', card='title', width='expand'), dict(key='alert', label='Why not', card='alert'), dict(key='protocol', label='Protocol', class='std-tag'), dict(key='origin', label='Origin', class='origin-tag', filter='dropdown', filter_icon='origin'), dict(key='ticks', label='Checks', card='badge', class='nb-tick'), dict(key='fit', label='Fit', filter='dropdown', filter_icon='puzzle', off=true), - dict(key='from', label='From'), dict(key='proves', label='Proves', class='std-tag', off=true)] %} + dict(key='from', label='From'), dict(key='benchmark', label='Benchmark', card='meta', table=false), + dict(key='proves', label='Proves', class='std-tag', off=true)] %} {{ cards('nb-agents', cols, items, search='Search ' ~ noun, choices=choices, empty='No ' ~ ('agent' if kind == 'agent' else 'Module') ~ ' matches.', noun=noun, layout=layout, default='cards', only={'fit': 'fit'}) }} diff --git a/app/tests/test_benchmark_agents.py b/app/tests/test_benchmark_agents.py index 0976e3a3c..871852a7c 100644 --- a/app/tests/test_benchmark_agents.py +++ b/app/tests/test_benchmark_agents.py @@ -224,6 +224,16 @@ def test_under_the_model_method_its_agent_is_asked_as_its_own_first_model(self): other, _ = definitions.setup(bench("gsm8k"), "original", "gpt-4o-mini", "openrouter") self.assertNotIn("agent", other) # a benchmark without agents of its own: nothing changes + def test_an_agent_with_vendor_tools_refuses_a_model_its_name_proves_is_anothers(self): + def why(model, provider, agent="claude_cuabash"): + return definitions.setup(bench("mypcbench"), "model", model, provider, agent)[1] + self.assertIn("only Anthropic models know", why("meta/muse-spark-1.3-contributor", "openrouter")) + self.assertIn("on OpenAI is not one", why("gpt-5.5", "openai")) + self.assertIn("only OpenAI models know", why("claude-sonnet-4-6", "anthropic", "openai_cuabash")) + self.assertEqual([why("anthropic/claude-sonnet-4.6", "openrouter"), why("claude-sonnet-4-6", "anthropic"), + why("my-model", "custom"), why("meta/muse-spark-1.3-contributor", "openrouter", "qwen_cuabash")], + ["", "", "", ""]) # a name of your own server, or an agent with no vendor, proves nothing + if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_catalog.py b/app/tests/test_catalog.py index f26e9cd48..5e07b2283 100644 --- a/app/tests/test_catalog.py +++ b/app/tests/test_catalog.py @@ -33,7 +33,7 @@ def test_shipped_catalogue_is_consistent(self): self.assertEqual(titles, sorted(titles, key=catalog.sort_key)) # what has a usable route is listed, whoever made it and whether or not it has run listed = {x.key for x in cat.listed_benchmarks} - self.assertEqual(sorted(listed), ["gaia", "gsm8k", "healthagentbench", "humaneval", "locomo", "longmemeval", "medagentbench", "open-telco", "osworld1", "osworld2", "swe-bench-verified", "tau3-bench", "terminal-bench", "vitabench"]) + self.assertEqual(sorted(listed), ["gaia", "gsm8k", "healthagentbench", "humaneval", "locomo", "longmemeval", "medagentbench", "mypcbench", "open-telco", "osworld1", "osworld2", "swe-bench-verified", "tau3-bench", "terminal-bench", "vitabench"]) self.assertEqual((cat.benchmark("longmemeval").origin, cat.benchmark("longmemeval").label), ("official", "Official")) self.assertEqual(cat.benchmark("tau3-bench").label, "Official") # τ³ files as "t3…", before "te…": a reader looking under T finds it diff --git a/app/tests/test_live.py b/app/tests/test_live.py index d05d94f67..b053314fc 100644 --- a/app/tests/test_live.py +++ b/app/tests/test_live.py @@ -111,6 +111,18 @@ def test_out_of_order_seq_is_folded_in_order_and_noted(self): class Fold(unittest.TestCase): + def test_failed_requests_are_visible_without_tokens_and_reset_on_retry(self): + lines = [ev(1, "trial.phase", phase="agent_run"), + ev(2, "trial.progress", calls=0, failed_requests=149, request_error="agent: HTTP 400")] + board = board_of(*lines) + t = board.trials[0].snapshot(NOW) + self.assertEqual((t["calls"], t["failed_requests"], t["request_error"]), (0, 149, "agent: HTTP 400")) + self.assertIsNone(t["n_input_tokens"]) + board = board_of(*lines, ev(3, "trial.end", outcome="infra_error"), ev(4, "trial.phase", phase="env_setup")) + t = board.trials[0].snapshot(NOW) + self.assertNotIn("request_error", t) + self.assertIsNone(t.get("failed_requests")) + def test_an_ordinary_run_with_named_tasks_keeps_automatic_retry_aggregates(self): board = board_of(ev(1, "job.start", trial=None, n_total=1, tasks=["task"]), ev(2, "trial.phase", task="task", phase="agent_run"), diff --git a/app/tests/test_mypcbench.py b/app/tests/test_mypcbench.py new file mode 100644 index 000000000..7b805add4 --- /dev/null +++ b/app/tests/test_mypcbench.py @@ -0,0 +1,289 @@ +"""MyPCBench's driver over a stand-in upstream and a stand-in docker: the container each unit's VM has is removed however +the unit ends, what the judge says is the score, and an agent's step reaches the upstream's loop.""" +from __future__ import annotations + +import base64 +import importlib.util +import io +import json +import re +import os +import shutil +import socket +import subprocess +import sys +import tempfile +import time +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +ENTRY = os.path.join(APP, "nullius", "catalogue", "benchmarks", "mypcbench") + +DOCKER = "#!/bin/sh\necho \"$*\" >> \"$DOCKER_LOG\"\n" +DOCKER += 'if [ "$1" = network ]; then echo 127.0.0.1; fi\n' +RUNNER = ''' +import argparse, json, os, time +def run_single_example(agent, env, task, max_steps, result_dir, sleep_after, timeout): + rows, obs = [], env.reset(task_config=task) + for n in range(max_steps): + response, actions = agent.predict(task["instruction"], obs) + if not actions: break + done = False + for action in actions: + obs, _, done, _ = env.step(action, sleep_after) + rows.append({"response": response, "action": action}) + if done: break + pack(result_dir, rows) +def pack(where, rows): + os.makedirs(where, exist_ok=True) + open(os.path.join(where, "traj.jsonl"), "w").write("".join(json.dumps(r) + "\\n" for r in rows)) + open(os.path.join(where, "rubric_bundle.json"), "w").write("{}") +if __name__ == "__main__": + p = argparse.ArgumentParser() + for a in ("backend", "agent_type", "model", "tasks_dir", "result_dir", "max_steps", "sleep_after", "container_name"): + p.add_argument("--" + a) + a = p.parse_args() + if a.model == "hang": time.sleep(60) + task = json.load(open(a.tasks_dir))[0] + where = os.path.join(a.result_dir, task["id"]) + if task["id"] == "broken": + os.makedirs(where); open(os.path.join(where, "incomplete.txt"), "w").write("errored: no VM") + else: + pack(where, [{"response": a.agent_type + " " + a.model + " " + os.environ.get("ANTHROPIC_BASE_URL", "none")}]) +''' +ENV = ''' +import base64, os +PNG = b"\\x89PNG" +class MyPCBenchEnv: + client_password = "password" + def __init__(self, **k): pass + def _start_container(self): pass + def _wait_for_ready(self): pass + def reset(self, task_config): return {"screenshot": PNG} + def step(self, action, pause): return {"screenshot": PNG}, 0.0, action in ("DONE", "FAIL"), {} + def _execute_command(self, command, shell=False): return {"returncode": 0, "output": "made\\n"} + def _get_screenshot(self): return PNG + def _execute_shell(self, command): + if "nullius.conf" in command: + if os.path.exists(os.path.join(os.path.dirname(os.environ["DOCKER_LOG"]), "fail-contacts")): + return {"returncode": 1} + open(os.path.join(os.path.dirname(os.environ["DOCKER_LOG"]), "contacts-command"), "w").write(command) + return {"returncode": 0} + if ".bash-output.json" not in command: return {"returncode": 44} + return {"returncode": 0, "output": base64.b64encode(b'[2, "hi\\\\n", "oops"]').decode()} +''' +JUDGE = ''' +import argparse, json, os +p = argparse.ArgumentParser(); p.add_argument("--result_dir"); p.add_argument("--force", action="store_true") +root = p.parse_args().result_dir +assert os.environ["OPENAI_BASE_URL"] == "http://relay/j/v1" and not os.environ["MYPCBENCH_RUBRIC_JUDGE_MODEL"].startswith("gemini") +unit = os.listdir(root)[0] +said = [l for l in open(os.path.join(root, unit, "traj.jsonl"))] +score = None if "nothing" in "".join(said) else 1.0 if "answer" in "".join(said) else 0.5 +rubrics = [{"criterion": "c", "weight": 1.0, "success": False, "reasoning": "Error judging rubric R1: 500"}] +json.dump({"rubric_results": rubrics}, open(os.path.join(root, unit, "osworld_full_traj_result.json"), "w")) +json.dump({"rows": [{"score": score, "status": "judge_error" if score is None else "judged"}]}, open(os.path.join(root, "scores.json"), "w")) +''' +GIVEN = {"model": "gemini", "base_url": "http://relay/j/v1", "key": "k"} + + +class RootlessContacts(unittest.TestCase): + def test_each_relay_has_an_image_and_a_keeper_even_when_start_fails(self): + from nullius.standard.backends import container + spec = importlib.util.spec_from_file_location("mypcbench_driver", os.path.join(ENTRY, "driver.py")) + driver = importlib.util.module_from_spec(spec) + with patch.object(sys, "argv", ["driver.py"]): + spec.loader.exec_module(driver) + started, keepers = [], [] + + def keeper(*args, **kwargs): + pipe = io.StringIO() + keepers.append(pipe) + return SimpleNamespace(stdin=pipe) + + def docker(args, **kwargs): + if args[0] == "run": + started.append(args) + raise container.Unavailable("relay startup failed") + return SimpleNamespace(returncode=0, stdout="", stderr="") + + with tempfile.TemporaryDirectory() as directory, \ + patch.object(container, "use_socket_doors", return_value=True), \ + patch.object(container, "base_image", return_value="nullius/base:test") as base, \ + patch.object(container, "SocketDoor", return_value=SimpleNamespace(path="/tmp/relay-socket", stop=lambda: None)), \ + patch.object(container, "make_bridge"), patch.object(container, "client_env", side_effect=lambda env: env), \ + patch.object(container, "_docker", side_effect=docker), \ + patch.object(container, "_user", return_value="0:0"), \ + patch.object(container, "_userns", return_value=[]), \ + patch.object(container, "way_out", return_value=[]), \ + patch.object(container, "_security_opt", return_value=[]), \ + patch.object(driver.subprocess, "Popen", side_effect=keeper), \ + patch.object(driver.subprocess, "run", return_value=SimpleNamespace(returncode=0)): + for _ in range(2): + with driver.VM() as vm: + with self.assertRaisesRegex(container.Unavailable, "relay startup failed"): + driver._contacts(vm, directory, GIVEN) + argv = started[-1] + name = argv[argv.index("--name") + 1] + self.assertEqual(argv[argv.index("python3") - 1], "nullius/base:test") + self.assertIn("container " + name + "\n", keepers[-1].getvalue()) + self.assertEqual(base.call_count, 2) + self.assertNotEqual(started[0][started[0].index("--name") + 1], + started[1][started[1].index("--name") + 1]) + + with patch.object(driver.sys, "stdin", ["123\n", "container relay-test\n"]), \ + patch.object(driver.os, "killpg") as kill, patch.object(driver.time, "sleep"), \ + patch.object(driver.subprocess, "run") as remove: + driver.keep("vm-test") + kill.assert_called_once_with(123, driver.signal.SIGKILL) + self.assertEqual([c.args[0][-1] for c in remove.call_args_list], ["vm-test", "relay-test"] * 3) + + +class MyPCBench(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.dir, ignore_errors=True) + for path, text in {"up/agent-harness/run_mypcbench.py": RUNNER, "up/agent-harness/env.py": ENV, + "up/agent-harness/judge_results.py": JUDGE, "up/agent-harness/agents/__init__.py": "", + "up/agent-harness/agents/prompts.py": "def build_mypcbench_context(has_bash): return 'the context'", + "bin/docker": DOCKER, "log": "", + "tasks.json": json.dumps([{"id": i, "instruction": "do " + i} for i in ("a", "broken")])}.items(): + where = os.path.join(self.dir, path) + os.makedirs(os.path.dirname(where), exist_ok=True) + with open(where, "w") as f: + f.write(text) + os.chmod(os.path.join(self.dir, "bin", "docker"), 0o755) + self.unit = os.path.join(self.dir, "trial", "workspace") + os.makedirs(self.unit) + self.env = dict(os.environ, NULLIUS_UPSTREAM=os.path.join(self.dir, "up"), DOCKER_LOG=os.path.join(self.dir, "log"), + NULLIUS_DATASET=os.path.join(self.dir, "tasks.json"), PYTHONPATH=APP, TMPDIR=self.dir, + MYPCBENCH_RUBRIC_JUDGE_MODEL="gemini-user", PATH=os.path.join(self.dir, "bin") + os.pathsep + os.environ["PATH"]) + self.start() + self.addCleanup(self._close) + + def start(self, image=None, images_file=None): + env = dict(self.env) + env.pop("NULLIUS_OPTION_VM_IMAGE", None) + if image is not None: + env["NULLIUS_OPTION_VM_IMAGE"] = image + with open(os.path.join(ENTRY, "standard.json")) as f: + command = json.load(f)["driver"]["command"] + if images_file: + command[-1] = images_file + self.p = subprocess.Popen([sys.executable, *(arg.replace("{here}", ENTRY) for arg in command[1:])], + env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + + def _close(self): + self.p.kill() + self.p.wait() + for f in (self.p.stdin, self.p.stdout): + f.close() + + def send(self, op, **kw): + self.p.stdin.write(json.dumps({"op": op, **kw}) + "\n") + self.p.stdin.flush() + + def ask(self, op, unit="a", **kw): + if op in ("task_given", "answer"): + kw.setdefault("simulator", dict(GIVEN, model="gpt-5.4-mini")) + self.send(op, unit=unit, dir=self.unit, **kw) + return json.loads(self.p.stdout.readline()) + + def docker(self, word, seconds=10): + until = time.time() + seconds + while time.time() < until: + with open(os.path.join(self.dir, "log")) as f: + said = [ln.split() for ln in f if ln.startswith(word)] + if said: + return said + time.sleep(0.05) + return [] + + def original(self, unit="a", model="claude-opus-4-6", setup="original"): + return self.ask("answer", unit, setup=setup, model=model, base_url="http://relay/u/v1", key="k") + + def test_a_setup_runs_the_upstream_through_the_relay_and_its_judge_scores_it(self): + self.assertEqual(self.original()["answer"], "claude_cuabash claude-opus-4-6 http://relay/u") + with open(os.path.join(self.dir, "contacts-command")) as f: + script = f.read() + self.assertIn("mypcbench-workbuzz.service.d/nullius.conf", script) + settings = base64.b64decode(re.search(r"echo ([A-Za-z0-9+/=]+) \|", script)[1]).decode() + self.assertIn('Environment="LLM_MODEL=gpt-5.4-mini"', settings) + self.assertIn('Environment="LLM_BASE_URL=http://127.0.0.1:', settings) + self.assertIn('Environment="OPENAI_API_KEY=' + GIVEN["key"] + '"', settings) + self.assertEqual(self.docker("run")[0][3], self.docker("rm")[0][2]) # the unit's own container + got = self.ask("score", setup="original", judge=GIVEN) + self.assertEqual((got["reward"], got["passed"], got["detail"]["judge_errors"]), (0.5, False, 1)) + self.assertEqual(self.original(model="any/model", setup="model")["answer"].split()[1], "claude-opus-4-6") + self.assertIn("not one of", self.original(model="any/model")["error"]) + + def test_chat_configuration_failure_stops_the_task_and_removes_its_vm(self): + with open(os.path.join(self.dir, "fail-contacts"), "w"): + pass + self.assertIn("chat services did not accept", self.original()["error"]) + self.assertEqual(self.docker("run")[0][3], self.docker("rm")[0][2]) + + def test_image_choice_reaches_upstream_and_external_agents(self): + images_file = os.path.join(self.dir, "images.json") + with open(images_file, "w") as f: + json.dump({"current": {"image": "test:current"}, "paper": {"image": "test:paper"}}, f) + for choice, image in ((None, "test:current"), ("paper", "test:paper")): + with self.subTest(image=choice): + self._close() + self.start(choice, images_file) + self.assertIn("answer", self.original()) + self.assertEqual(self.docker("run")[-1][-1], image) + self.assertIn("prompt", self.ask("setup", participant="agent")) + self.assertEqual(self.docker("run")[-1][-1], image) + self.assertEqual(self.ask("end"), {}) + + def test_no_result_and_no_judge_are_errors(self): + self.assertIn("errored: no VM", self.original("broken")["error"]) + self.assertIn("no judge route", self.ask("score", setup="original")["error"]) + + def test_a_driver_that_is_killed_leaves_no_container(self): + self.send("answer", unit="a", dir=self.unit, setup="model", model="m", base_url="http://relay/u/v1", key="k", simulator=dict(GIVEN, model="gpt-5.4-mini")) + self.docker("run") + self.p.kill() + self.assertTrue(self.docker("rm")) + + def test_an_agent_acts_in_the_upstream_loop_and_its_turn_is_scored(self): + setup = self.ask("setup", participant="agent") + self.assertIn("do a\n\nthe context", setup["prompt"]) + with socket.socket(socket.AF_UNIX) as s, socket.socket(socket.AF_UNIX) as t: + s.connect(setup["mcp"][0]["args"][1]) + t.connect(setup["mcp"][1]["args"][1]) + wire, shell = s.makefile("rw"), t.makefile("rw") + self.addCleanup(wire.close) + self.addCleanup(shell.close) + + def call(n, name, on=wire, method="tools/call", **args): + on.write(json.dumps({"jsonrpc": "2.0", "id": n, "method": method, + "params": {"name": name, "arguments": args}}) + "\n") + on.flush() + return json.loads(on.readline())["result"] + self.assertEqual([t["name"] for t in call(0, "", shell, "tools/list")["tools"]], ["bash"]) + self.assertTrue(call(1, "click", x=1, y=1).get("isError")) # no step before the task + self.assertTrue(call(1, "bash", shell, command="ls").get("isError")) + self.assertEqual(self.ask("task_given"), {}) + bash = call(5, "bash", shell, command="ls", max_output_tokens=9) # one step, as upstream's + self.assertEqual((bash["content"][0]["text"], bash["isError"]), ("hi\n\nstderr: oops\n(exit code 2)", True)) + self.assertFalse(call(2, "click", x=1, y=1).get("isError")) + self.assertFalse(call(3, "step", actions=["for i in range(2):\n pyautogui.press('a')"]).get("isError")) + self.assertFalse(call(4, "done", message="the answer").get("isError")) + got = self.ask("score", judge=GIVEN) + self.assertEqual((got["reward"], got["passed"], got["detail"]["ended"], got["detail"]["steps"]), + (1.0, True, "done", 4), got) + self.assertTrue(self.docker("rm")) + self.assertEqual(self.ask("end"), {}) + + def test_an_agent_that_never_acts_is_scored_as_the_desktop_stands(self): + self.ask("setup", participant="agent") + self.ask("task_given") + self.assertEqual(self.ask("score", judge=GIVEN)["detail"]["steps"], 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_standard_bench_options.py b/app/tests/test_standard_bench_options.py index da9dd0822..858e4818f 100644 --- a/app/tests/test_standard_bench_options.py +++ b/app/tests/test_standard_bench_options.py @@ -265,6 +265,24 @@ def test_an_untagged_pin_names_its_branch_and_reads_by_it(self): self.assertEqual(definitions.version_label({"upstream": dict(ok, tag="v1.0"), "_version": "v1.0"}), "v1.0") self.assertEqual(definitions.version_label({"upstream": ok, "_version": "x"}), "x") + def test_display_labels_distinguish_pins_without_changing_their_refs(self): + up = {"repository": "https://github.com/o/r", "branch": "main", "license": "MIT"} + d = {"key": "bench", "schema": "nullius.benchmark/v1", "upstream": up, + "default": "current", "versions": { + "current": {"upstream": {"label": "Current", "tested": "a" * 40}}, + "paper": {"upstream": {"label": "Paper release", "tested": "b" * 40}}}} + current, paper = definitions.resolve(d), definitions.resolve(d, "paper") + self.assertEqual(current["_labels"], {"current": "Current (aaaaaaa)", "paper": "Paper release (bbbbbbb)"}) + self.assertEqual(paper["_ref"], "bench@paper") + self.assertEqual(paper["upstream"]["branch"], "main") + self.assertEqual(recipe.procedure_label(dict(current, label="Bench")), "Bench · Current") + self.assertEqual(recipe.procedure_label(dict(paper, label="Bench")), "Bench · Paper release") + self.assertEqual(definitions._upstream(paper["upstream"]), []) + for label in ("", " ", 3): + self.assertIn("upstream.label: a non-empty display label", + definitions._upstream(dict(paper["upstream"], label=label))) + self.assertEqual(definitions.version_label(dict(paper, upstream=dict(paper["upstream"], label=label))), "main (bbbbbbb)") + class MachineDocker(unittest.TestCase): """OSWorld1's VMs run in Docker on the machine its driver runs on: whoever runs its tasks, a setup or the diff --git a/app/tests/test_standard_computer_port.py b/app/tests/test_standard_computer_port.py index f6fc4d7d4..6ba3aefbc 100644 --- a/app/tests/test_standard_computer_port.py +++ b/app/tests/test_standard_computer_port.py @@ -859,6 +859,31 @@ def sendall(self, data): closer.join(2) self.assertFalse(closer.is_alive(), "the close waited for a write in progress") + def test_flush_waits_for_the_last_reply_but_has_a_deadline(self): + entered, release, flushed = threading.Event(), threading.Event(), threading.Event() + self.addCleanup(release.set) + + class Delayed(FakeConnection): + def sendall(self, data): + entered.set() + release.wait(5) + super().sendall(data) + + wire = self.wire(Delayed()) + wire.send({"result": "done"}) + self.assertTrue(entered.wait(2)) + wire.flush(0) # an unread reply must not hold shutdown indefinitely + def finish(): + wire.flush(2) + flushed.set() + worker = threading.Thread(target=finish, daemon=True) + worker.start() + self.assertFalse(flushed.wait(0.05)) + release.set() + self.assertTrue(flushed.wait(2)) + self.assertEqual(wire.out_bytes, 0) + worker.join(2) + def test_answers_left_unread_past_the_bound_close_the_connection(self): release = threading.Event() self.addCleanup(release.set) diff --git a/app/tests/test_standard_preflight.py b/app/tests/test_standard_preflight.py new file mode 100644 index 000000000..61c9906a1 --- /dev/null +++ b/app/tests/test_standard_preflight.py @@ -0,0 +1,87 @@ +"""Synthetic upstream requests use the real relay routes; only successes are cached.""" +import json +import os +import tempfile +import threading +import unittest +from http.server import ThreadingHTTPServer +from unittest.mock import patch + +from nullius.standard.calls import preflight, relay +from tests.test_standard_relay import Upstream + + +class PreflightTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.env = patch.dict(os.environ, NULLIUS_HOME=self.tmp.name) + self.env.start() + self.addCleanup(self.env.stop) + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Upstream) + threading.Thread(target=self.server.serve_forever, daemon=True).start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.server.shutdown) + Upstream.seen = [] + self.kw = dict(base=f"http://127.0.0.1:{self.server.server_port}/v1", key="secret", key_header="authorization", + folder=os.path.join(self.tmp.name, "records"), identity=["source-pin", {"option": "value"}]) + self.request = {"role": "agent", "path": "/v1/chat/completions", "body": { + "model": "upstream-name", "messages": [{"role": "user", "content": "OK"}], "max_tokens": 8, + "tools": [{"type": "function", "function": {"name": "test", "parameters": {"type": "object"}}}]}} + + def check(self, **kw): + return preflight.check([self.request], {"agent": "selected-model"}, **dict(self.kw, **kw)) + + def test_exact_request_and_route_are_checked_once_and_changes_invalidate(self): + self.assertEqual(self.check(serving={"selected-model": ["provider-a"]}), {"agent": "checked"}) + self.assertEqual(Upstream.seen[-1][2]["model"], "selected-model") + self.assertEqual(Upstream.seen[-1][2]["tools"], self.request["body"]["tools"]) + self.assertEqual(self.check(serving={"selected-model": ["provider-a"]}), {"agent": "cached"}) + self.assertEqual(len(Upstream.seen), 1) + for change in ({"serving": {"selected-model": ["provider-b"]}}, {"key": "changed"}, + {"identity": ["new-pin"]}, {"reasoning": {"selected-model": "low"}}): + self.assertEqual(self.check(**change), {"agent": "checked"}) + self.request["body"]["tools"][0]["function"]["name"] = "other" + self.assertEqual(self.check(), {"agent": "checked"}) + self.assertEqual(len(Upstream.seen), 6) + + def test_rejection_is_recorded_and_never_cached(self): + self.request["body"]["mode"] = "400" + for _ in range(2): + with self.assertRaisesRegex(preflight.Rejected, "agent.*HTTP 400"): + self.check() + self.assertEqual(len(Upstream.seen), 2) + with open(os.path.join(self.kw["folder"], "preflight-agent.jsonl")) as f: + self.assertEqual([json.loads(line)["status"] for line in f], [400, 400]) + + def test_success_for_a_different_api_is_not_compatible(self): + self.request["path"] = "/v1/messages?beta=true" + with self.assertRaisesRegex(preflight.Rejected, "no successful model response"): + self.check() # fake provider answers in Chat Completions format + self.assertEqual(len(Upstream.seen), 1) + + def test_streamed_request_and_judge_route_are_supported(self): + self.request["body"]["stream"] = True + judge = dict(self.request, role="judge") + result = preflight.check([self.request, judge], {"agent": "a", "judge": "j"}, **self.kw) + self.assertEqual(result, {"agent": "checked", "judge": "checked"}) + self.assertEqual([body["model"] for _, _, body in Upstream.seen], ["a", "j"]) + + def test_missing_capture_is_not_a_pass_and_wrong_paths_are_not_sent(self): + self.assertEqual(preflight.check([], {"agent": "m"}, **self.kw), {}) + for path in ("https://elsewhere/v1/messages", "/v1/models", "/v1/messages/../models"): + self.request["path"] = path + with self.assertRaises(preflight.Rejected): + self.check() + self.assertEqual(Upstream.seen, []) + + def test_permanent_failures_exclude_recoverable_request_and_server_errors(self): + for status, error, expected in ( + (400, "Unknown server-tool shorthand", True), (422, "computer use is not supported", True), + (400, "unknown model", True), (401, "bad key", True), (402, "credit spent", True), + (429, "too fast", False), (500, "unknown model", False), + (400, "tool_result must follow tool_use", False), (400, "context window exceeded", False)): + with self.subTest(status=status, error=error): + self.assertEqual(relay.permanent({"status": status, "error": error}), expected) + self.assertFalse(relay.permanent({"status": 402, "refused": "calls"})) + self.assertTrue(relay.permanent({"status": 429, "error_code": "insufficient_quota"})) diff --git a/app/tests/test_standard_relay.py b/app/tests/test_standard_relay.py index 0d1de3d87..5e88719d4 100644 --- a/app/tests/test_standard_relay.py +++ b/app/tests/test_standard_relay.py @@ -67,6 +67,9 @@ def do_POST(self): mode = body.get("mode") if mode == "429": self.reply(429, b'{"error":{"message":"Rate limit reached"}}', "application/json") + elif mode == "unsupported-native-tools": + self.reply(400, json.dumps({"error": {"message": "Invalid Anthropic Messages API request", + "metadata": {"raw": [{"path": ["tools", 0, "type"], "message": "Unknown server-tool shorthand"}]}}}).encode(), "application/json") elif mode == "401": self.reply(401, b'{"error":{"message":"Incorrect API key"}}', "application/json") elif mode == "no-usage": @@ -286,6 +289,22 @@ def test_a_unit_that_ended_on_429_is_rate_limited(self): self.assertEqual(classify.from_verdict(exc, None), classify.RATE_LIMITED) self.assertIn("Rate limit", said) + def test_nested_tool_validation_failure_marks_a_permanent_refusal(self): + folder = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, folder, True) + r = relay.Relay(self.relay.base, "k", folder).start() + self.addCleanup(r.stop) + req = urllib.request.Request(r.url("u0-simulator") + "/messages", data=json.dumps( + {"model": "m", "mode": "unsupported-native-tools"}).encode(), headers={"Content-Type": "application/json"}) + with self.assertRaises(urllib.error.HTTPError) as caught: + urllib.request.urlopen(req) + self.assertEqual(caught.exception.code, 400) + self.assertTrue(r.calls("u0-simulator")[0]["permanent"]) + kind, reason = relay.fatal(folder) + self.assertEqual(kind, "ApiError") + self.assertIn("u0-simulator", reason) + self.assertNotIn("metadata", reason) + def test_a_refused_key_is_infrastructure(self): self.post("u5", "/chat/completions", {"model": "m", "mode": "401"}) exc, _ = relay.failure(self.relay.calls("u5")) diff --git a/app/tests/test_standard_run.py b/app/tests/test_standard_run.py index 0820c2c94..2632d60c8 100644 --- a/app/tests/test_standard_run.py +++ b/app/tests/test_standard_run.py @@ -239,8 +239,7 @@ def unit(self_, i, u, r): self.assertEqual(len(jobs), 1) def test_an_endpoint_that_refuses_the_key_stops_the_run_and_fails_it(self): - """A wrong key fails every unit the same way: after three in a row - nothing more is begun, and the run reports a failure.""" + """A wrong key stops at the first refusal, before queued units start.""" here = os.path.join(self.tmp, "calling") os.makedirs(here) with open(os.path.join(here, "driver.py"), "w") as f: @@ -253,9 +252,9 @@ def test_an_endpoint_that_refuses_the_key_stops_the_run_and_fails_it(self): env=self.env, say=said.append, unsandboxed=True, proving=True) trials = parse.parse_job(job_dir).trials self.assertTrue(failed) - self.assertEqual(len(trials), run.REFUSED_IN_A_ROW) # of eight units + self.assertEqual(len(trials), 1) # of eight units self.assertTrue(all(t.exception_type == "AgentAuthenticationError" for t in trials)) - self.assertTrue(any(s.startswith("stopped: the endpoint refused 3 units in a row") for s in said), said) + self.assertTrue(any(s.startswith("stopped: u0000: the model endpoint rejected") for s in said), said) Echo.status = 200 job_dir, failed = run.run_and_report(b, o, model="m-1", provider="custom", jobs_root=self.tmp, concurrency=1, env=self.env, say=lambda s: None, unsandboxed=True, proving=True, name="answered") @@ -901,6 +900,92 @@ def prompt(client, sid, text, timeout=600): self.assertGreaterEqual(len(spans), 2, spans) self.assertTrue(any(a[0] < b[1] and b[0] < a[1] for i, a in enumerate(spans) for b in spans[i + 1:]), spans) + def test_preflight_refuses_before_units_and_closes_its_driver(self): + here = os.path.join(self.tmp, "preflight") + os.makedirs(here) + with open(os.path.join(here, "driver.py"), "w") as f: + f.write("from nullius.standard.protocols.jsonl import serve\n" + "serve({'preflight': lambda **kw: {'requests': [{'role': 'agent', 'path': '/v1/messages', " + "'body': {'model': 'upstream', 'messages': [{'role': 'user', 'content': 'OK'}], " + "'tools': [{'type': 'computer_20251124'}]}}]}})\n") + b = dict(definitions.get("benchmark", "fakebench", ROOT), _here=here, + driver={"command": ["python3", "{here}/driver.py"], "preflight": True}) + o = definitions.get("agent", "fake", ROOT) + Echo.status, Echo.message = 400, "Unknown server-tool shorthand" + self.addCleanup(setattr, Echo, "message", "Rate limit reached for requests") + r = run.Run(b, o, model="m-1", provider="custom", jobs_root=self.tmp, name="before-units", + env=self.env, say=lambda s: None, unsandboxed=True) + with self.assertRaisesRegex(run.Refused, "compatibility check failed.*HTTP 400"): + r.start() + self.assertTrue(r.drivers) + self.assertTrue(all(d.p.poll() is not None for d in r.drivers)) + self.assertFalse(any("__u" in n for n in os.listdir(r.job_dir))) + + def test_permanent_refusal_interrupts_a_retrying_command_and_runs_cleanup(self): + here = os.path.join(self.tmp, "retry-loop") + os.makedirs(here) + with open(os.path.join(here, "driver.py"), "w") as f: + f.write(CALLING_DRIVER.replace('"score": lambda', + '"end": lambda unit, dir: open(dir + "/ended", "w").close() or {}, "score": lambda')) + with open(os.path.join(here, "agent.py"), "w") as f: + f.write("import json, os, time, urllib.request, urllib.error\n" + "while True:\n" + " try:\n" + " urllib.request.urlopen(urllib.request.Request(os.environ['OPENAI_BASE_URL'] + '/chat/completions', " + "data=json.dumps({'model':'m-1','messages':[{'role':'user','content':'OK'}]}).encode(), " + "headers={'Content-Type':'application/json'})).read()\n" + " except urllib.error.HTTPError: pass\n" + " time.sleep(.1)\n") + b = dict(definitions.get("benchmark", "fakebench", ROOT), _here=here, + driver={"command": ["python3", "{here}/driver.py"], "unit_end": True}, limits={"turn_seconds": 60}) + o = dict(definitions.get("agent", "fake", ROOT), _here=here, + start={"command": ["python3", "{here}/agent.py", "{prompt}"]}) + Echo.status, Echo.message = 400, "Unknown server-tool shorthand" + self.addCleanup(setattr, Echo, "message", "Rate limit reached for requests") + began = time.monotonic() + job_dir, failed = run.run_and_report(b, o, model="m-1", provider="custom", jobs_root=self.tmp, concurrency=1, + env=self.env, say=lambda s: None, unsandboxed=True, retries=2, proving=True) + self.assertLess(time.monotonic() - began, 20) + trials = parse.parse_job(job_dir).trials + self.assertTrue(failed) + self.assertEqual(len(trials), 1) + self.assertEqual(trials[0].exception_type, "ApiError") + names = [n for n in os.listdir(job_dir) if "__u" in n] + self.assertTrue(os.path.isfile(os.path.join(job_dir, names[0], "workspace", "ended"))) + with open(os.path.join(job_dir, "events.jsonl")) as f: + self.assertTrue(any(e.get("failed_requests", 0) > 0 for e in map(json.loads, f))) + + def test_permanent_refusal_interrupts_an_upstream_driver_retry_loop(self): + here = os.path.join(self.tmp, "upstream-loop") + os.makedirs(here) + with open(os.path.join(here, "driver.py"), "w") as f: + f.write("import json, time, urllib.request, urllib.error\n" + "from nullius.standard.protocols.jsonl import serve\n" + "def answer(base_url, **kw):\n" + " while True:\n" + " try:\n" + " urllib.request.urlopen(urllib.request.Request(base_url + '/messages', " + "data=json.dumps({'model':'m-1'}).encode(), headers={'Content-Type':'application/json'})).read()\n" + " except urllib.error.HTTPError: pass\n" + " time.sleep(.1)\n" + "serve({'units':lambda **kw:{'units':['a','b','c']}, 'answer':answer})\n") + b = dict(definitions.get("benchmark", "fakebench", ROOT), _here=here, + driver={"command": ["python3", "{here}/driver.py"]}, limits={"turn_seconds": 60}, + setups={"original": {"models": ["m-1"], "default": "m-1", "providers": {"custom": ""}, "summary": "fixture"}}) + o, why = definitions.setup(b, "original", "m-1", "custom") + self.assertFalse(why) + Echo.status, Echo.message = 400, "Unknown server-tool shorthand" + self.addCleanup(setattr, Echo, "message", "Rate limit reached for requests") + r = run.Run(b, o, model="m-1", provider="custom", jobs_root=self.tmp, concurrency=1, + env=self.env, say=lambda s: None, unsandboxed=True, retries=2, proving=True) + began = time.monotonic() + job_dir = r.start() + self.assertLess(time.monotonic() - began, 20) + self.assertTrue(all(d.p.poll() is not None for d in r.drivers)) + trials = parse.parse_job(job_dir).trials + self.assertEqual(len(trials), 1) + self.assertEqual(trials[0].exception_type, "ApiError") + def test_a_model_the_provider_does_not_list_is_refused_before_anything_starts(self): """Every call to it would be refused the same way: no install, no unit, the job saying why. A :suffix routes the model it follows; a provider @@ -1341,6 +1426,29 @@ def test_a_simulated_user_opens_the_conversation_and_speaks_through_its_route(se with open(os.path.join(job_dir, "config.json")) as f: self.assertNotIn("simulator", json.load(f)["standard"]) + def test_desktop_contacts_get_a_simulator_route_without_opening_a_conversation(self): + here = os.path.join(self.tmp, "desktop-contacts") + os.makedirs(here) + driver = CHAT_DRIVER.replace('def turn(unit, dir, transcript, simulator=None):', + 'def turn(unit, dir, transcript, simulator=None):\n raise AssertionError("no conversation")') + driver = driver.replace('"turn": turn,', + '"turn": turn, "task_given": lambda unit, dir, simulator: {"reply": ask(simulator, "contact")},') + with open(os.path.join(here, "driver.py"), "w") as f: + f.write(driver) + b = dict(definitions.get("benchmark", "fakebench", ROOT), _here=here, needs=["agent.computer/v1"], + driver={"command": ["python3", "{here}/driver.py"], "task_given": True}, + simulator={"model": "contact-model", "says": "desktop contacts"}) + o = definitions.get("agent", "fake", ROOT) + job_dir = run.run(b, o, model="m-1", provider="custom", jobs_root=self.tmp, concurrency=1, env=self.env, + say=lambda s: None, unsandboxed=True, proving=True, limit=1) + trial = os.path.join(job_dir, [t for t in os.listdir(job_dir) if "__u" in t][0]) + with open(os.path.join(trial, "verifier", "score.json")) as f: + detail = json.load(f)["detail"] + self.assertEqual(detail["said"], ["INTRO"]) + self.assertEqual(detail["routes"], ["contact-model"]) + with open(os.path.join(trial, ".work", "relay", "u0000-simulator.jsonl")) as f: + self.assertEqual([json.loads(line)["model"] for line in f], ["contact-model"]) + def test_a_conversation_the_upstream_starts_again_is_a_new_session(self): """A driver's ``turn`` may answer ``restart`` (its upstream retried the conversation): the agent gets a new session, told setup's prompt again @@ -1369,12 +1477,17 @@ def test_a_conversation_the_upstream_starts_again_is_a_new_session(self): with open(os.path.join(trial, "agent", "acp.jsonl")) as f: self.assertGreaterEqual(json.loads(f.readline())["t"], w["agent_execution"][0]) - def test_a_simulator_is_only_for_a_conversation(self): + def test_a_simulator_needs_a_conversation_or_a_desktop_hook(self): b = definitions.get("benchmark", "fakebench", ROOT) self.assertIn("simulator: only a benchmark that needs agent.conversation/v1", " ".join(definitions.problems(dict(b, simulator={"model": "u", "says": "x"}), "benchmark"))) self.assertIn("simulator: {model", " ".join(definitions.problems(dict(b, simulator={"model": "a user"}), "benchmark"))) + desktop = dict(b, needs=["agent.computer/v1"], simulator={"model": "u", "says": "contacts"}) + self.assertIn("simulator: a desktop benchmark needs driver.task_given", + " ".join(definitions.problems(desktop, "benchmark"))) + desktop["driver"] = dict(b["driver"], task_given=True) + self.assertEqual(definitions.problems(desktop, "benchmark"), []) for bad in ({"nowhere": "x/y"}, {"openrouter": "a user"}, {}): self.assertIn("score.judge.served_as: {provider", " ".join(definitions.problems(dict(b, score=dict(b["score"], judge={"model": "j", "says": "x", "served_as": bad})), "benchmark"))) @@ -1543,16 +1656,17 @@ def test_a_count_is_sent_when_it_changes_and_never_when_it_does_not(self): self.assertEqual(self.told(), [{"task": "u", "agent": "a", "step": 0, "step_limit": 100}]) self.call(cost=0.002) self.ticker.tick() - self.call(status=429) # refused by the provider: no call answered, nothing new + self.call(status=429) # no success, but the rejected request is visible self.write({"steps": 0, "steps_limit": 100, "ended": "", "open": 0}) # what the board does not show changed self.ticker.tick() self.write({"steps": 1, "steps_limit": 100, "ended": "", "open": 0}) self.ticker.tick() said = self.told() - self.assertEqual(len(said), 3) + self.assertEqual(len(said), 4) + self.assertEqual((said[2]["failed_requests"], said[2]["request_error"]), (1, "agent: HTTP 429")) self.assertEqual(said[1], {"task": "u", "agent": "a", "step": 0, "step_limit": 100, "calls": 1, "n_input_tokens": 10, "n_cache_tokens": 4, "n_output_tokens": 2, "cost_usd": 0.002}) - self.assertEqual((said[2]["step"], said[2]["calls"]), (1, 1)) + self.assertEqual((said[3]["step"], said[3]["calls"]), (1, 1)) def test_a_missing_half_written_or_unreadable_progress_file_gives_no_event_and_no_error(self): self.ticker.watch("x", task="u", agent="a", trial=self.trial, progress=".work/progress.json") diff --git a/app/tests/test_standard_served_by.py b/app/tests/test_standard_served_by.py index fcaacd73c..eed2f5944 100644 --- a/app/tests/test_standard_served_by.py +++ b/app/tests/test_standard_served_by.py @@ -581,7 +581,7 @@ def test_the_summary_counts_every_route_of_the_unit(self): r = self.make(judge_model="m-1", served_by={"m-1": ["prov-a"]}) call = lambda who: {"model": "m-1", "status": 200, "reply": {"served_by": who}} routes = {"u0000": [call("Prov A")], "u0000-judge": [call("Prov Z")], "u0000-simulator": [call("Prov A")]} - rr = mock.Mock(mcp_listeners=[], unit_image="") + rr = mock.Mock(mcp_listeners=[], unit_image="", dir=self.tmp) rr.calls.side_effect = lambda tag: routes.get(tag, []) driver = mock.Mock() driver.request.side_effect = lambda op, **kw: {} if op == "setup" else {"reward": 1} diff --git a/app/tests/test_standard_setups.py b/app/tests/test_standard_setups.py index 78e19e4e8..037b5d24a 100644 --- a/app/tests/test_standard_setups.py +++ b/app/tests/test_standard_setups.py @@ -131,6 +131,16 @@ def test_the_original_takes_only_the_papers_models_each_as_the_provider_spells_i self.assertIsNone(o) self.assertIn("not served by openai", why) + orig = dict(SETUPS["original"], providers={"openai": "", "openrouter": "", "custom": ""}, + served_as={"paper-1-16k": "openai/gpt-4o"}) + b = dict(self.b, setups=dict(SETUPS, original=orig)) + for provider, sent in (("openai", "gpt-4o"), ("openrouter", "openai/gpt-4o"), ("custom", "openai/gpt-4o")): + with self.subTest(provider=provider): + o, why = definitions.setup(b, "original", "paper-1-16k", provider) + self.assertEqual((o["asked"], o["sent"], why), ("paper-1-16k", sent, "")) + self.assertEqual(definitions.upstream_name(orig, sent, provider), "paper-1-16k") + self.assertEqual(recipe._bench_page(b)["setups"][0]["sent"][provider]["paper-1-16k"], sent) + def test_the_originals_side_models_go_as_the_provider_serves_them_and_never_as_the_reader(self): b = dict(self.b, setups=dict(SETUPS, original=dict(SETUPS["original"], side_models=["extractor"]))) o, _ = definitions.setup(b, "original", "paper-1", "openrouter") diff --git a/app/tests/test_standard_upstream_drivers.py b/app/tests/test_standard_upstream_drivers.py index 786ee0e84..9dbf1abcd 100644 --- a/app/tests/test_standard_upstream_drivers.py +++ b/app/tests/test_standard_upstream_drivers.py @@ -47,6 +47,10 @@ def bench(**driver) -> dict: class Schema(unittest.TestCase): + def test_preflight_is_an_explicit_driver_capability(self): + self.assertEqual(definitions.problems(bench(preflight=True), "benchmark"), []) + self.assertTrue(any("driver.preflight" in e for e in definitions.problems(bench(preflight="yes"), "benchmark"))) + def test_a_driver_install_is_checked_as_an_install_is(self): b = bench(command=["{install}/.venv/bin/python", "{here}/driver.py"], install={"python": "3.12", "pip": ["openai==1.35.1"], diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index 2a268f88c..580849031 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -155,7 +155,7 @@ def test_a_benchmarks_own_agents_are_listed_behind_the_origin_filter(self): self.assertIn('href="/benchmarks/osworld1"', card) self.assertIn('
computer-use-preview
', card) self.assertIn('
Computer use
', card) - self.assertIn('
OSWorld1
', card) # its benchmark; origin and protocol are filters + self.assertIn('
Benchmark agent · OSWorld1
', card) self.assertIn('data-f-protocol="Its own script "', card) self.assertNotIn("Ports proven", card) self.assertIn('id="osworld2-muse-spark"', table) diff --git a/app/ui_tests/test_builder_agents.py b/app/ui_tests/test_builder_agents.py index 023835874..58bf9b68d 100644 --- a/app/ui_tests/test_builder_agents.py +++ b/app/ui_tests/test_builder_agents.py @@ -48,7 +48,7 @@ def test_the_version_procedure_is_the_first_card_and_other_benchmarks_agents_are _, cards = self.grid("locomo@full") self.assertIn(">LoCoMo · full", cards["original"]) # the version's, no commit for c in cards.values(): # origin, protocol, source: filters - self.assertNotIn("origin-tag", c); self.assertNotIn("bench-harness", c); self.assertNotIn("std-tag", c) + self.assertNotIn("origin-tag", c); self.assertNotIn("std-tag", c) html, mem = self.grid("longmemeval") self.assertIn("mem0@2.2.1", mem) # each version its card self.assertNotIn("keyword-memory", html) # an example, there to read, never to choose @@ -57,6 +57,16 @@ def test_the_version_procedure_is_the_first_card_and_other_benchmarks_agents_are self.assertIn(" disabled", c) self.assertRegex(c, r">Belongs to OSWorld[12]") + def test_benchmark_agents_identify_their_source_on_the_card(self): + _, cards = self.grid("mypcbench") + for key in ("mypcbench:claude-cuabash", "mypcbench:openai-cuabash", "mypcbench:qwen-cuabash", "mypcbench:qwen-cua"): + self.assertIn('Benchmark agent · MyPCBench', cards[key]) + for key in ("claude-code", "codex"): + matches = [card for ref, card in cards.items() if ref.split("@", 1)[0] == key] + self.assertTrue(matches, key) + for card in matches: + self.assertNotIn("Benchmark agent", card) + def test_its_table_view_picks_as_its_cards_do(self): cards, _ = self.grid("osworld1") self.assertIn('href="/new-run/agents?benchmark=osworld1&view=table" aria-label="Table"', cards) # the toggle, cards by default diff --git a/app/ui_tests/test_builder_where.py b/app/ui_tests/test_builder_where.py index 14571eee9..ac91e97cf 100644 --- a/app/ui_tests/test_builder_where.py +++ b/app/ui_tests/test_builder_where.py @@ -109,7 +109,7 @@ def test_every_standard_benchmark_draws_its_where_step_and_says_why_docker_is_no for name, html in missing.items(): with self.subTest(name): self.assertTrue(html.startswith("]*data-std-backend="container"[^>]*>', html).group(0) @@ -134,7 +134,7 @@ def test_docker_names_the_public_web_proxy_only_for_an_agent_whose_environment_d tip = lambda html: re.search(r'