From 813ae3a4c49a844e090fa63e7dbeb9265405abf1 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Mon, 30 Nov 2026 20:38:52 +0100 Subject: [PATCH 01/14] feat(catalogue): integrate MyPCBench --- .../benchmarks/mypcbench/agents.json | 83 +++ .../benchmarks/mypcbench/benchmark.json | 41 ++ .../benchmarks/mypcbench/contacts.py | 33 ++ .../catalogue/benchmarks/mypcbench/driver.py | 402 ++++++++++++++ .../benchmarks/mypcbench/proofs.json | 53 ++ .../catalogue/benchmarks/mypcbench/runner.py | 193 +++++++ .../benchmarks/mypcbench/standard.json | 258 +++++++++ .../mypcbench/upstream-settings.json | 506 ++++++++++++++++++ app/nullius/standard/contract/definitions.py | 18 +- app/nullius/standard/pages/recipe.py | 6 +- .../standard/protocols/computer_port.py | 11 +- app/nullius/standard/runner/run.py | 11 +- app/static/catalogue/marks.svg | 4 + app/tests/test_catalog.py | 2 +- app/tests/test_mypcbench.py | 208 +++++++ app/tests/test_standard_computer_port.py | 25 + app/tests/test_standard_run.py | 30 +- app/tests/test_standard_setups.py | 10 + app/ui_tests/test_builder_where.py | 4 +- app/ui_tests/test_catalogue_routes.py | 2 +- docs/agents/supported/README.md | 28 +- docs/agents/supported/codex.md | 6 +- docs/agents/supported/digitalmate.md | 6 +- docs/agents/supported/goose.md | 4 +- docs/agents/supported/jiuwenswarm.md | 8 +- docs/agents/supported/mini-swe-agent.md | 4 +- docs/agents/supported/opencode.md | 4 +- docs/agents/supported/swe-agent.md | 4 +- docs/agents/supported/terminus-2.md | 4 +- docs/benchmarks/supported/README.md | 2 + docs/benchmarks/supported/mypcbench.md | 82 +++ docs/standard.md | 6 +- 32 files changed, 2001 insertions(+), 57 deletions(-) create mode 100644 app/nullius/catalogue/benchmarks/mypcbench/agents.json create mode 100644 app/nullius/catalogue/benchmarks/mypcbench/benchmark.json create mode 100644 app/nullius/catalogue/benchmarks/mypcbench/contacts.py create mode 100644 app/nullius/catalogue/benchmarks/mypcbench/driver.py create mode 100644 app/nullius/catalogue/benchmarks/mypcbench/proofs.json create mode 100644 app/nullius/catalogue/benchmarks/mypcbench/runner.py create mode 100644 app/nullius/catalogue/benchmarks/mypcbench/standard.json create mode 100644 app/nullius/catalogue/benchmarks/mypcbench/upstream-settings.json create mode 100644 app/tests/test_mypcbench.py create mode 100644 docs/benchmarks/supported/mypcbench.md diff --git a/app/nullius/catalogue/benchmarks/mypcbench/agents.json b/app/nullius/catalogue/benchmarks/mypcbench/agents.json new file mode 100644 index 000000000..9f00a6bdc --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/agents.json @@ -0,0 +1,83 @@ +{ + "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", + "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", + "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..49e54b667 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/benchmark.json @@ -0,0 +1,41 @@ +{ + "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; the VM image is 5 GB to download and needs /dev/kvm." + ], + "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": [ + "The default uses upstream's revised August rubrics; legacy offers the earlier rubrics. The paper's VM build has not been identified.", + "Boat is untested." + ], + "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": [] +} 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..82a1364f9 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/driver.py @@ -0,0 +1,402 @@ +"""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", "") +# driver.py AGENTS_JSON RUNNER_PY CONTACTS_PY: the definition's command names them, so a host's runner snapshot carries them +_ARGS = sys.argv[1:4] 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") +# the driver's environment pulls it as it installs (standard.json, driver.install.commands) +IMAGE = "ljang/mypcbench-qemu@sha256:1648bfe424202a84a4bed1d62cb1812e3eb8113a209cf878e6846677bb5b4f60" +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 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): + """The keeper: reads the process groups the driver names, one a line; when the pipe closes, ends them and removes + the container, again a little later for one whose creation the engine had already accepted.""" + groups = [int(ln) for ln in sys.stdin if ln.strip()] + for pgid in groups: + try: + os.killpg(pgid, signal.SIGKILL) + except OSError: + pass + for wait in (0, 3, 10): + time.sleep(wait) + subprocess.run(["docker", "rm", "-f", name], 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): + 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 __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 + door = Loopback(simulator["base_url"]) + 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, + "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/proofs.json b/app/nullius/catalogue/benchmarks/mypcbench/proofs.json new file mode 100644 index 000000000..c60a03992 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/proofs.json @@ -0,0 +1,53 @@ +{ + "schema": "nullius.proofs/v1", + "kind": "benchmark", + "key": "mypcbench", + "versions": { + "": { + "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..ce23763d0 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/mypcbench/standard.json @@ -0,0 +1,258 @@ +{ + "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" + ], + "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" + ], + "commands": [ + [ + "docker", + "pull", + "-q", + "ljang/mypcbench-qemu@sha256:1648bfe424202a84a4bed1d62cb1812e3eb8113a209cf878e6846677bb5b4f60" + ] + ] + }, + "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": { + "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." + } +} 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..8eb300aaf --- /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": "fixed:the image's digest of 2026-11-09 - pinned; the upstream's latest moves" + }, + { + "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/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 83c8b0996..fd6bce927 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1203,10 +1203,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) @@ -1412,8 +1417,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] @@ -1734,8 +1738,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 3e55228e0..994fb5599 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -203,8 +203,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 @@ -690,7 +690,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/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/run.py b/app/nullius/standard/runner/run.py index ce79f91ab..4ddca249a 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -1640,14 +1640,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)) @@ -2716,7 +2717,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()) @@ -2724,7 +2725,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): @@ -2783,7 +2784,7 @@ 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: diff --git a/app/static/catalogue/marks.svg b/app/static/catalogue/marks.svg index 6f6ec6736..003015300 100644 --- a/app/static/catalogue/marks.svg +++ b/app/static/catalogue/marks.svg @@ -33,6 +33,10 @@ + + + + diff --git a/app/tests/test_catalog.py b/app/tests/test_catalog.py index d54f19ef0..161008152 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", "humaneval", "locomo", "longmemeval", "medagentbench", "open-telco", "osworld1", "osworld2", "swe-bench-verified", "tau3-bench", "terminal-bench", "vitabench"]) + self.assertEqual(sorted(listed), ["gaia", "gsm8k", "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_mypcbench.py b/app/tests/test_mypcbench.py new file mode 100644 index 000000000..c13ae1aef --- /dev/null +++ b/app/tests/test_mypcbench.py @@ -0,0 +1,208 @@ +"""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 json +import re +import os +import shutil +import socket +import subprocess +import sys +import tempfile +import time +import unittest + +APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +ENTRY = os.path.join(APP, "nullius", "catalogue", "benchmarks", "mypcbench") + +DOCKER = "#!/bin/sh\necho \"$1 $2 $3 $4\" >> \"$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 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) + 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.p = subprocess.Popen([sys.executable, os.path.join(ENTRY, "driver.py"), os.path.join(ENTRY, "agents.json"), + os.path.join(ENTRY, "runner.py")], env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + self.addCleanup(self._close) + + 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_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_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_run.py b/app/tests/test_standard_run.py index 55fd7675f..cd5dd9502 100644 --- a/app/tests/test_standard_run.py +++ b/app/tests/test_standard_run.py @@ -1283,6 +1283,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 @@ -1311,12 +1334,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"))) diff --git a/app/tests/test_standard_setups.py b/app/tests/test_standard_setups.py index ff82fd191..6ff0bb09b 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/ui_tests/test_builder_where.py b/app/ui_tests/test_builder_where.py index 0c4bc36c2..22fb12ea4 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'", 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", mem) 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/web/agents.py b/app/web/agents.py index 792daf549..d189d91c5 100644 --- a/app/web/agents.py +++ b/app/web/agents.py @@ -78,6 +78,11 @@ def _runs_on(e: dict) -> list: return [{"text": f["label"], "value": f["key"]} for f in e["fits"] if not f["why"]] +def benchmark_agent_label(d: dict) -> str: + """The source shown on a benchmark agent's catalogue and builder cards.""" + return f"Benchmark agent · {d['benchmark_label']}" if d.get("benchmark") else "" + + def _card(kind: str, e: dict) -> dict: """An agent's or a Module's card on its list (templates/_cards.html). A benchmark's own agent's opens its benchmark's page and shows its published models in place of ports, installs and versions.""" @@ -88,7 +93,7 @@ def _card(kind: str, e: dict) -> dict: return {"href": url_for("benchmark_page", key=d["benchmark"]), "id": d["_ref"].replace(":", "-"), "search": " ".join([d["label"], d["key"], d["benchmark_label"], e["protocol"], d.get("summary", "")]), "protocol": e["protocol"], "origin": origin_tags(d), "icon": agent_mark_url(d["key"]), "title": d["label"], "summary": d.get("summary"), - "from": {"text": d["benchmark_label"], "value": "benchmark"}, "benchmark": d["benchmark_label"], + "from": {"text": d["benchmark_label"], "value": "benchmark"}, "benchmark": benchmark_agent_label(d), "uses": "Computer use" if computer else None, "models": ", ".join(d.get("models") or []), "runs_on": _runs_on(e), "unless": {"origin": "runs_on"}, "hide": ["ports", "runs", "installs"]} version, n = (d.get("upstream") or {}).get("version"), len(d.get("_versions") or ()) diff --git a/app/web/builder.py b/app/web/builder.py index 0eb9ccf27..6c34364cf 100644 --- a/app/web/builder.py +++ b/app/web/builder.py @@ -30,7 +30,7 @@ from . import shared from . import execute from . import catalogue -from .agents import ORIGINS, origin_tag +from .agents import ORIGINS, origin_tag, benchmark_agent_label @app.route("/new-run") @@ -151,6 +151,7 @@ def _pick_card(b: dict, e: dict) -> dict: "protocol": {"text": e["protocol"], "value": e["protocol"]}, "origin": origin_tag("benchmark" if d.get("benchmark") else definitions.origin_of(d)), "fit": {"text": "Cannot" if why else "Can run it", "value": "unfit" if why else "fit"}, "from": there, + "benchmark": benchmark_agent_label(d), "proves": [{"text": r["label"], "value": r["port"]} for r in rows.values()], "ticks": ticks, "alert": {"text": note, "title": "; ".join(why)} if why else None} diff --git a/docs/benchmarks/supported/mypcbench.md b/docs/benchmarks/supported/mypcbench.md index 1971bc710..41665166b 100644 --- a/docs/benchmarks/supported/mypcbench.md +++ b/docs/benchmarks/supported/mypcbench.md @@ -66,7 +66,7 @@ Personal-assistant tasks on one person's desktop: 17 logged-in web apps, mail an ## Nullius limitations -- For the original published harness, rubrics and VM, select main (14533b5), the June paper release. The default uses August rubrics; legacy includes July fixes. Selecting Paper baseline VM alone changes only the image. +- 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. ## Cite diff --git a/docs/standard.md b/docs/standard.md index 56bbde534..8c5b34854 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -556,6 +556,7 @@ An agent or a Module may keep several versions in its one file: an older release | In jobs | `…__KEY-VERSION__…` in the name; `standard.benchmark_version` and `standard.benchmark_ref` in `config.json` | | A fork is a version | `versions..upstream = {repository, tag, tested}`, never a patch of ours; cloned at its commit (`upstreams///`), its datasets checked by their own `sha256`; a private repository uses the machine's git credentials. It proves its own controls (`cli prove KEY@NAME`) | | A release is the default | An earlier untagged pin stays as a version with `upstream.branch` (`main`): shown as `main (044bc33)` | +| Display name | Optional `upstream.label` distinguishes versions from the same branch; the full label retains the commit. CLI version keys and source pins stay unchanged | | Its page | `benchmark.json` `versions.`: whole `good_to_know`, `upstream_limitations`, `limitations`, and `datasets.` `tasks`, `notes`, `verifier`; the page and builder switch all of it with the version | ### Options From 6a3cbd88d207c9353c90b6e2ad98bce0c24e019c Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 13:35:20 +0100 Subject: [PATCH 07/14] fix(catalogue): classify MyPCBench guidance correctly --- .../benchmarks/mypcbench/benchmark.json | 18 ++++++++++-------- docs/benchmarks/supported/mypcbench.md | 5 +---- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/app/nullius/catalogue/benchmarks/mypcbench/benchmark.json b/app/nullius/catalogue/benchmarks/mypcbench/benchmark.json index 26d5a6c73..b5806ca74 100644 --- a/app/nullius/catalogue/benchmarks/mypcbench/benchmark.json +++ b/app/nullius/catalogue/benchmarks/mypcbench/benchmark.json @@ -12,15 +12,14 @@ "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." + "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": [ - "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." - ], + "limitations": [], "datasets": [ { "key": "mypcbench", @@ -46,15 +45,18 @@ "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": [ - "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." - ], + "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/docs/benchmarks/supported/mypcbench.md b/docs/benchmarks/supported/mypcbench.md index 41665166b..661f9d4e0 100644 --- a/docs/benchmarks/supported/mypcbench.md +++ b/docs/benchmarks/supported/mypcbench.md @@ -58,16 +58,13 @@ Personal-assistant tasks on one person's desktop: 17 logged-in web apps, mail an - 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. -## Nullius limitations - -- 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. - ## Cite ??? citation "BibTeX" From e97a6e967d38ab0a94b04364f643c60b027ce1d1 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 13:38:00 +0100 Subject: [PATCH 08/14] fix(builder): align fixed model rows with model controls --- app/static/builder/command-builder.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/static/builder/command-builder.css b/app/static/builder/command-builder.css index 6e9e5b4a0..4dd96b81d 100644 --- a/app/static/builder/command-builder.css +++ b/app/static/builder/command-builder.css @@ -223,13 +223,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; } From 2438da9e1d76bcb88c27177a884466e98a432869 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 13:47:36 +0100 Subject: [PATCH 09/14] fix(runs): return waiting state before live feed exists --- app/ui_tests/test_live_board.py | 23 ++++++++++++++++++++++- app/web/runs.py | 22 ++++++++++++++-------- 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/app/ui_tests/test_live_board.py b/app/ui_tests/test_live_board.py index 6592bad89..183637b6c 100644 --- a/app/ui_tests/test_live_board.py +++ b/app/ui_tests/test_live_board.py @@ -210,7 +210,28 @@ def test_a_launched_job_is_listed_as_preparing_and_its_page_waits_for_the_feed(s self.assertIn('data-state="unknown"', body) # hidden until the first event self.assertNotIn("location.reload()", body) live = self.client.get("/job/launched-run/live"); self.addCleanup(live.close) - self.assertEqual(live.status_code, 404) # what the page polls until the feed lands + self.assertEqual(live.status_code, 200) + self.assertEqual(live.get_json(), {"state": "preparing", "running": False}) + self.assertEqual(live.headers["Cache-Control"], "no-store") + + def test_a_known_launch_can_be_polled_before_it_writes_any_job_files(self): + from nullius import execution + plan = execution.Plan(name="before-source", script="true", jobs=[{"name": "before-source"}]) + ex = execution.Execution(plan, root=str(self.root / "before-source-record"), run=lambda *a, **k: (0, "")) + ex.jobs = str(self.root) + with patch.object(workspace, "load_jobs", return_value=[]), patch.dict(execution.EXECUTIONS, {ex.id: ex}, clear=True): + for state in ("preparing", "running", "failed", "stopped", "done"): + with self.subTest(state=state): + ex.state = state + ex.finished = None if state in execution.ALIVE else 1789773420.0 + response = self.client.get("/job/before-source/live") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.headers["Cache-Control"], "no-store") + snap = response.get_json() + self.assertEqual(snap["state"], "preparing" if state in execution.ALIVE else "finished") + self.assertFalse(snap["running"]) + self.assertNotIn("counts", snap) # keep the live board waiting for its real feed + self.assertEqual(self.client.get("/job/not-launched/live").status_code, 404) def test_benchmark_ending_before_its_feed_stops_the_preparing_poll(self): from nullius import execution diff --git a/app/web/runs.py b/app/web/runs.py index ba7dce526..4c80d919b 100644 --- a/app/web/runs.py +++ b/app/web/runs.py @@ -994,16 +994,22 @@ def job_live(job_id): Folding a few thousand lines is cheap enough to do every second. """ j = shared._job_for_request(job_id) - if not j: - abort(404) - if not live.has_feed(j.dir): - ended = shared.ended_for(job_id, j) + if not j or not live.has_feed(j.dir): + ex = shared.run_on_page(job_id, j) + ended = ex.job_state(job_id) if ex is not None else None + if not ended and ex is not None and ex.state not in execution.ALIVE: + ended = (ex.state, ex.finished) if ended: # The preparing page must settle even if the runner never wrote a feed. - response = jsonify({"state": "finished", "running": False, "ended_by": ended[0]}) - response.headers["Cache-Control"] = "no-store" - return response - abort(404) + pending = {"state": "finished", "running": False, "ended_by": ended[0]} + elif ex is not None or (j is not None and j.is_preparing): + # A known launch may still be fetching its source, before any job files exist. + pending = {"state": "preparing", "running": False} + else: + abort(404) + response = jsonify(pending) + response.headers["Cache-Control"] = "no-store" + return response try: snap = live.snapshot(j.dir, ended=shared.ended_for(j.job_id, j), with_timeline=True) except live.FeedError as e: From ee354451262e6effa391eb0cea49702f999de598 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 14:34:53 +0100 Subject: [PATCH 10/14] fix(standard): prevent incompatible model retry loops --- .../catalogue/benchmarks/mypcbench/driver.py | 68 +++++++- .../benchmarks/mypcbench/standard.json | 1 + app/nullius/progress.py | 2 +- app/nullius/runs/live.py | 10 +- app/nullius/runs/parse.py | 2 +- app/nullius/standard/calls/preflight.py | 103 +++++++++++ app/nullius/standard/calls/relay.py | 39 ++++- app/nullius/standard/contract/definitions.py | 2 + .../standard/protocols/cancellation.py | 10 ++ app/nullius/standard/runner/run.py | 163 +++++++++++++++--- app/static/runs/live-board.js | 6 +- app/tests/test_live.py | 12 ++ app/tests/test_standard_preflight.py | 87 ++++++++++ app/tests/test_standard_relay.py | 19 ++ app/tests/test_standard_run.py | 100 ++++++++++- app/tests/test_standard_served_by.py | 2 +- app/tests/test_standard_upstream_drivers.py | 4 + app/ui_tests/test_live_board.py | 7 + docs/cli/run.md | 3 +- docs/field-guide.md | 2 + docs/standard.md | 6 +- 21 files changed, 609 insertions(+), 39 deletions(-) create mode 100644 app/nullius/standard/calls/preflight.py create mode 100644 app/tests/test_standard_preflight.py diff --git a/app/nullius/catalogue/benchmarks/mypcbench/driver.py b/app/nullius/catalogue/benchmarks/mypcbench/driver.py index 04d6f3993..1a5b2c9d6 100644 --- a/app/nullius/catalogue/benchmarks/mypcbench/driver.py +++ b/app/nullius/catalogue/benchmarks/mypcbench/driver.py @@ -67,6 +67,72 @@ 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} @@ -380,7 +446,7 @@ def score(unit, dir, setup=None, judge=None, **_): "judge_errors": sum(r["reasoning"].startswith("Error judging rubric") for r in rubrics)}} -HANDLERS = {"units": units, "setup": setup, "answer": answer, "score": score, +HANDLERS = {"units": units, "setup": setup, "answer": answer, "score": score, "preflight": preflight, "task_given": task_given, "end": end} diff --git a/app/nullius/catalogue/benchmarks/mypcbench/standard.json b/app/nullius/catalogue/benchmarks/mypcbench/standard.json index fd65ee005..2b2dbe3ea 100644 --- a/app/nullius/catalogue/benchmarks/mypcbench/standard.json +++ b/app/nullius/catalogue/benchmarks/mypcbench/standard.json @@ -33,6 +33,7 @@ "pillow==12.3.0" ] }, + "preflight": true, "participant": true, "unit_end": true, "task_given": true 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 849eb5471..28e31dd89 100644 --- a/app/nullius/runs/live.py +++ b/app/nullius/runs/live.py @@ -79,7 +79,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 @@ -148,7 +148,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) @@ -210,6 +210,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 @@ -257,6 +259,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, @@ -618,6 +621,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) @@ -633,6 +637,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 ccadf358f..8d2c8cb85 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -32,7 +32,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 = "25" +SCHEMA = "26" # 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 862f21090..11e990e44 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1683,6 +1683,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): 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/runner/run.py b/app/nullius/standard/runner/run.py index 717e42be0..3c59b3c25 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -504,7 +504,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] = [] @@ -553,6 +554,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, [] @@ -567,8 +572,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"]: @@ -579,6 +586,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.""" @@ -1087,6 +1131,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.""" @@ -1111,7 +1172,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 @@ -1134,7 +1195,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 @@ -1165,7 +1226,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) @@ -1176,9 +1237,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, @@ -1280,7 +1351,8 @@ def _start(self, lck, mine) -> str: 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): @@ -1364,7 +1436,9 @@ def work_unit(iur): 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: why = ("the agent's first call was longer than the model's context window in" if self.halted[0] == relay.CONTEXT_ERROR else "the endpoint refused") self.say(f"stopped: {why} {REFUSED_IN_A_ROW} units in a row ({self.halted[0]}: " @@ -1805,6 +1879,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 @@ -1887,6 +1965,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 @@ -2117,15 +2203,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=60) + 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 @@ -2371,7 +2494,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: @@ -2699,7 +2822,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) @@ -2801,7 +2924,7 @@ def _command_agent(self, a, env, ws, home, setup, transcript, log, tag, unit, rl 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") @@ -2821,7 +2944,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, @@ -2923,4 +3046,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/runs/live-board.js b/app/static/runs/live-board.js index 478a64bb3..4403ba486 100644 --- a/app/static/runs/live-board.js +++ b/app/static/runs/live-board.js @@ -63,8 +63,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 || {}; @@ -207,7 +206,7 @@ const rows = opts.showAll ? order : order.slice(0, FLIGHT_SHOWN); const doneRows = opts.showAll ? done : done.slice(-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' : ''; @@ -263,6 +262,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/tests/test_live.py b/app/tests/test_live.py index b81e198c3..225068601 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_the_last_phase_event_wins_and_time_in_phase_is_now_minus_its_ts(self): b = board_of(ev(1, "trial.phase", phase="env_setup", timeout_sec=300), ev(2, "trial.phase", phase="agent_run", timeout_sec=540), 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 d711ad32f..8b0a86d2c 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") @@ -852,6 +851,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 @@ -1522,16 +1607,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 7f349f52d..2a31bac82 100644 --- a/app/tests/test_standard_served_by.py +++ b/app/tests/test_standard_served_by.py @@ -563,7 +563,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_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_live_board.py b/app/ui_tests/test_live_board.py index 183637b6c..2056e9f63 100644 --- a/app/ui_tests/test_live_board.py +++ b/app/ui_tests/test_live_board.py @@ -562,6 +562,13 @@ def test_renderer_draws_the_steps_of_the_limit_and_the_calls_of_a_running_trial( full = self.running_with(step=120, step_limit=100) # past its limit: a full bar, never more self.assertIn('width:100.0%', full["flight"]); self.assertIn("120 of 100", visible(full["flight"])) + def test_failed_requests_show_even_without_successful_calls_or_tokens(self): + out = self.running_with(calls=0, failed_requests=149, request_error="agent: HTTP 400", + n_input_tokens=0, n_output_tokens=0) + self.assertIn("149 failed requests", visible(out["flight"])) + self.assertIn("Failed requests 149", visible(out["drawer"])) + self.assertIn("Last request error agent: HTTP 400", visible(out["drawer"])) + def test_renderer_says_the_calls_with_and_without_a_cap(self): for fields, said in (({"calls": 41}, "41"), ({"calls": 1}, "1"), ({"calls": 0}, "0"), ({"calls": 41, "calls_limit": 100}, "41 of 100"), ({"calls": 1, "calls_limit": 100}, "1 of 100")): diff --git a/docs/cli/run.md b/docs/cli/run.md index a08286753..ecabe02a7 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -138,7 +138,8 @@ A benchmark that names a cut in `limits.scored_cuts` still scores an agent's uni | Rate limit | After the [pause](../standard.md#a-run) | | Provider, network or setup error; agent crash; setup timeout | Yes | | Run or check out of time | Only if the provider was refusing the calls | -| Wrong key, spent credit, an agent's first call over the model's context window | No; three in a row stop the run | +| Wrong key, spent credit, unavailable model or explicit native-tool incompatibility | No; the first permanent refusal stops the run | +| An agent's first call over the model's context window | No; three in a row stop the run | | A setup this machine lacks, a missing secret, a cap reached, Stop, a unit a guard asked to stop, a full context window, failed task | No | `conform` and `prove` retry a rate limit once. diff --git a/docs/field-guide.md b/docs/field-guide.md index d05001195..de5eadb20 100644 --- a/docs/field-guide.md +++ b/docs/field-guide.md @@ -186,6 +186,8 @@ How the agent worked, not whether it won. Computed over layer 3. | `exception_type` | What ended the trial, if anything. It decides the infra / agent split. | measured | any | | `ended_by` | What ended the agent's work: `agent`, the benchmark's own end, or a limit (`time`, `calls`, `end`). | measured | standard | | `n_retries` | Retries a standard run's attempt took. | measured | any | +| `failed_requests` | Live count of rejected model requests across the unit's agent, judge and simulator routes, including local cap refusals. Separate from successful model calls; token-count requests are excluded. | measured | standard live feed | +| `request_error` | The latest observed failed request's role and HTTP status. Provider text stays in the evidence. | measured | standard live feed | | `n_rate_limited_retries` | 429s counted in `agent/gateway.log`: on Harbor, the ones the agent's SDK retried and survived; on a standard run, every model call the relay saw refused with 429. No log: no count, never 0. | inferred | any | ## Standard run records diff --git a/docs/standard.md b/docs/standard.md index 8c5b34854..2d1bbb4a6 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -141,8 +141,10 @@ record); verifier/reward.txt and score.json | The exchange record (`--exchanges`) | Each call of a unit's agent, kept whole and unredacted by its relay ([Run a benchmark](cli/run.md#the-exchange-record)) | | Job name | One run at a time per job name: another is refused before it writes anything. A later run under the same name moves each trial's earlier record aside to the trial's `.work/earlier.` | | Backends (`--backend`) | `local`: processes on this machine. `container`: each unit's agent or Module in a container, its relay beside it, on Docker, else Podman 4.7 or later. Podman needs no Docker API socket and no `containers.conf` change. `docker` is accepted as an alias for `container`. For agent and Module runs the driver stays on the machine; Original setups instead containerize the driver and its answerer; in a container a check that runs what the agent left (the workspace kit's test) runs it in a throwaway, network-less container of the unit's image, and no check reads through a link the agent planted; `config.json` records the backend and the image. `boat`: each unit's agent or Module in a boat.dev VM of its own ([The boat backend](#the-boat-backend)) | -| Progress | One line per stage on stderr and in `progress.jsonl`: `[nullius] stage=install agent=codex@2.2.2 state=done seconds=41 at=...` (`start`, `done`, `cached`, `failed`; a download's bytes every 5 s) for the base image, an environment, the upstream, a dataset, `driver.install` and the agent; then `stage=units n=10`, `stage=unit i=3 of=10 unit=... outcome=passed`, `stage=done`; `stage=refused` alone for a run refused first. From `stage=units` the job also writes `events.jsonl`, Harbor's live feed, with `trial.progress`: each running unit's steps, model calls, tokens and cost | +| Progress | One line per stage on stderr and in `progress.jsonl`: `[nullius] stage=install agent=codex@2.2.2 state=done seconds=41 at=...` (`start`, `done`, `cached`, `failed`; a download's bytes every 5 s) for the base image, an environment, the upstream, a dataset, `driver.install` and the agent; then `stage=units n=10`, `stage=unit i=3 of=10 unit=... outcome=passed`, `stage=done`; `stage=refused` alone for a run refused first. From `stage=units` the job also writes `events.jsonl`, Harbor's live feed, with `trial.progress`: each running unit's steps, successful model calls, failed requests, tokens and cost | | Outcomes | A last model call that got a 429 is `rate_limited`, a refused key an API error, both outside the agent's rate, unless the unit passed; a unit asked to stop keeps the score its driver gave despite the agent's own last 429; the agent's own last call over the model's context window is `ContextWindowExceededError`, the agent's; an agent past its limit for the unit, every turn included, is the agent's timeout ([time limits](cli/run.md#time-limits)), unless the benchmark [scores the cut](cli/run.md#a-unit-cut-at-a-limit). `"kind": "score"` leaves a score and no pass | +| Compatibility | Before units start, drivers declaring `preflight` capture synthetic requests from the published clients. The selected model, serving route and reasoning setting are checked through the relay. Success is cached for one hour per request, source, options, credentials and route. Roles without a capture say **Not checked**; a model listing alone proves no API or tool support. Checks may be billed and count against the run's spending cap. | +| Permanent provider refusals | Wrong credentials, exhausted credit, unavailable models and explicit native-tool incompatibilities stop queued units and interrupt active protocol waits. The refusing unit is an infrastructure error, never a failed task. Rate limits, server failures and repairable request errors retain their retry behavior. | | Rate limits | After a `rate_limited` end no unit starts for 60 s, or the provider's `Retry-After`, doubling to 300 s while units keep ending so | | The relay | Headers pass through except the credentials, replaced by the relay's key; `agent/calls.jsonl` names them, never their values. A 429 reaches the agent as it came, never retried. Every call goes as the run's model, the one asked recorded as `model_asked`, except `model.side_models`, sent as asked and recorded `side`. Provider `anthropic` serves `messages` only ([protocols](settings/model-providers.md#protocols)) | | Constraints (`--constraint KEY=VALUE`) | What the machine allows Nullius, from Settings ([constraints](settings/run-hosts.md#constraints)): flags on every container the run starts on the machine, on either backend; a systemd scope for each process the run starts there (its drivers, and its agents and Modules on the local backend); the most units at a time; the CPU affinity; the driver's `CUDA_VISIBLE_DEVICES`. The local backend refuses a cap that no scope holds. `config.json` records the values under `standard.constraints` | @@ -429,6 +431,7 @@ local proof records; saved runs and credentials remain. | Op | Sent | Replies | | --- | --- | --- | | `units` | `dataset`, `setup` | Every unit id | +| `preflight` | `participant` (`setup`, `agent`, `capability` or `control`), `setup`, upstream `model`, selected `roles`; with `driver.preflight` | `{requests: [{role, path, body, headers?}]}` captured from the published clients on synthetic input, with no task environment or network calls. Paths are `/v1/messages`, `/v1/chat/completions` or `/v1/responses`, with any required query. Preserve tools, images and request settings; headers retain `anthropic-beta` and `anthropic-version`. Return only roles that can be captured. | | `describe` | `dataset`, with `driver.describe` | `{units: {ID: {title, text, categories: {FIELD: VALUE}}}}`, from the dataset's files alone, for [listings](cli/task-sets.md) | | `setup` | `unit`, `dir`; `attempt` with `limits.attempts`; `participant` (`agent`, `capability` or `control`) with `driver.participant` | `{prompt}`, any `mcp` servers, `environment`, an own image's `image`, `prepare`, `mount`, `internet` and `verify`, and `agent_seconds`, the unit's own agent timeout (up to 6 hours, instead of `limits.turn_seconds`); `progress`, a file in the trial the driver rewrites: `{steps, steps_limit, ended}` | | `turn` | The transcript so far; `simulator: {model, base_url, key}` when there is one; `judge` for an upstream that grades as the conversation ends; `attempt` with `limits.attempts` | The next message, `{done: true}`, or `restart` | @@ -457,6 +460,7 @@ An `answer` or `score` error that begins `EnvironmentSetupError: `, `VerifierErr | `driver.participant` | `true`: `setup` is also sent `participant`, the kind of what runs the unit, for a driver that starts something only an agent uses | | `driver.unit_end` | `true`: the driver is sent `end` (`unit`, `dir`) once each unit an agent ran has ended, scored or not, so that what its setup started for the agent ends with the unit. A control's or a setup's unit gets none | | `driver.questions` | `true`, with `describe`: each unit may list `questions: [{id, text}]`. A task set can select these; the driver receives `NULLIUS_TASK_QUESTIONS`, a JSON mapping from unit id to selected question ids, and refuses unknown or excluded questions before running. Units absent from the mapping keep all their questions. | +| `driver.preflight` | `true`: the driver answers `preflight` before any unit. A failed capture refuses launch; an omitted role is explicitly unchecked. | | `driver.describe` | `true`: the driver answers `describe`; without it a listing gives ids alone | | `driver.list_command` | A start of the driver for listings alone, needing only the standard library and the dataset's files; `{here}` its one slot | | `driver.task_given` | `true`: the driver is sent `task_given` before each agent is given its task, and the task waits for its answer: [the computer port](ports/agent-computer-v1.md#the-window-before-the-task) closes its window before the task there. A control's or a setup's unit gets none | From 8d4bbfd38ae3ba2d2728e08d0e9a8617efa8925f Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 15:45:03 +0100 Subject: [PATCH 11/14] fix(standard): give compatibility capture time to start --- app/nullius/standard/runner/run.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index 3c59b3c25..6531b246c 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -2228,7 +2228,7 @@ def compatibility(self) -> None: 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=60) + 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 From bcf7c81f6bae42ce259a20c87134f746b4021721 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 15:45:03 +0100 Subject: [PATCH 12/14] feat(catalogue): refuse models a MyPCBench agent's tools do not fit --- app/nullius/catalogue/benchmarks/mypcbench/agents.json | 6 ++++++ app/nullius/standard/contract/definitions.py | 8 ++++++++ app/tests/test_benchmark_agents.py | 10 ++++++++++ docs/standard.md | 1 + 4 files changed, 25 insertions(+) diff --git a/app/nullius/catalogue/benchmarks/mypcbench/agents.json b/app/nullius/catalogue/benchmarks/mypcbench/agents.json index 9f00a6bdc..c3b2d03c6 100644 --- a/app/nullius/catalogue/benchmarks/mypcbench/agents.json +++ b/app/nullius/catalogue/benchmarks/mypcbench/agents.json @@ -5,6 +5,9 @@ "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" @@ -24,6 +27,9 @@ "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", diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 11e990e44..acabb3e32 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1459,6 +1459,11 @@ 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"]: + return None, (f"{mine['label']} sends tools only {', '.join(mine['vendors'])} models know: " + f"{model}{' on ' + 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), @@ -1497,6 +1502,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 diff --git a/app/tests/test_benchmark_agents.py b/app/tests/test_benchmark_agents.py index 0976e3a3c..589aefeb2 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/docs/standard.md b/docs/standard.md index 2d1bbb4a6..e44467977 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -677,6 +677,7 @@ it is published with. It speaks no port, so it has no `offers` or `proven`. | Derived, never written | Where it comes from (`from`: `benchmark`; a catalogue agent's is `bundled` or `yours`) and `only_for`, its benchmark. A written `only_for` names that benchmark alone | | `options.agent` | `standard.json` writes its `label`, `summary` and `setups`; the loader rebuilds `values` (each entry's `start.driver.agent`, in order), `names`, `about` and `default` (the first) | | Checked | Each entry's `models` are among `setups.original.models`; each upstream name once | +| `vendors` | Optional. Sends a vendor's built-in tools (Claude's `computer_…`): a model its name proves another vendor's (OpenRouter's prefix, or the OpenAI or Anthropic provider) is refused. A name of your own server proves nothing | | Offered | On the Agents page and in the builder, for its benchmark only | | Run | As the Original setup, its upstream name as the agent option: `nullius standard run osworld1 original --bench-option agent=openai_cua`. Its jobs name it by its key (`openai-cua`) | From 583c11dc12576f521349cc34535a081d9a5aa005 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 15:50:46 +0100 Subject: [PATCH 13/14] fix(catalogue): name vendors in the model refusal --- app/nullius/standard/contract/definitions.py | 6 ++++-- app/tests/test_benchmark_agents.py | 6 +++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index acabb3e32..cc9a94408 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1462,8 +1462,10 @@ def setup(bench: dict, which: str, model: str = "", provider: str = "", agent: s # 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"]: - return None, (f"{mine['label']} sends tools only {', '.join(mine['vendors'])} models know: " - f"{model}{' on ' + provider if provider in ('openai', 'anthropic') else ''} is not one") + 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), diff --git a/app/tests/test_benchmark_agents.py b/app/tests/test_benchmark_agents.py index 589aefeb2..871852a7c 100644 --- a/app/tests/test_benchmark_agents.py +++ b/app/tests/test_benchmark_agents.py @@ -227,9 +227,9 @@ def test_under_the_model_method_its_agent_is_asked_as_its_own_first_model(self): 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.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 From 5603d6fb4cbb2eb167af2b080c204bf2722202b0 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Wed, 2 Dec 2026 01:00:44 +0100 Subject: [PATCH 14/14] docs(standard): shorten the MyPCBench integration's doc rows --- docs/cli/run.md | 2 +- docs/field-guide.md | 4 ++-- docs/standard.md | 18 +++++++++--------- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/cli/run.md b/docs/cli/run.md index f545484be..748e0d5e6 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -141,7 +141,7 @@ A benchmark that names a cut in `limits.scored_cuts` still scores an agent's uni | Rate limit | After the [pause](../standard.md#a-run) | | Provider, network or setup error; agent crash; setup timeout | Yes | | Run or check out of time | Only if the provider was refusing the calls | -| Wrong key, spent credit, unavailable model or explicit native-tool incompatibility | No; the first permanent refusal stops the run | +| Wrong key, spent credit, unavailable model, unsupported tools | No; the first stops the run | | An agent's first call over the model's context window | No; three in a row stop the run | | A setup this machine lacks, a missing secret, a cap reached, Stop, a unit a guard asked to stop, a full context window, failed task | No | diff --git a/docs/field-guide.md b/docs/field-guide.md index be4fbd6fd..ee15386ec 100644 --- a/docs/field-guide.md +++ b/docs/field-guide.md @@ -187,8 +187,8 @@ How the agent worked, not whether it won. Computed over layer 3. | `exception_type` | What ended the trial, if anything. It decides the infra / agent split. | measured | any | | `ended_by` | What ended the agent's work: `agent`, the benchmark's own end, or a limit (`time`, `calls`, `end`). | measured | standard | | `n_retries` | Retries a standard run's attempt took, runs again by hand included. | measured | any | -| `failed_requests` | Live count of rejected model requests across the unit's agent, judge and simulator routes, including local cap refusals. Separate from successful model calls; token-count requests are excluded. | measured | standard live feed | -| `request_error` | The latest observed failed request's role and HTTP status. Provider text stays in the evidence. | measured | standard live feed | +| `failed_requests` | Refused model requests, every route of the unit. | measured | standard live feed | +| `request_error` | The last refusal's role and HTTP status. | measured | standard live feed | | `n_rate_limited_retries` | 429s counted in `agent/gateway.log`: on Harbor, the ones the agent's SDK retried and survived; on a standard run, every model call the relay saw refused with 429. No log: no count, never 0. | inferred | any | ## Standard run records diff --git a/docs/standard.md b/docs/standard.md index 154eeb598..15d9e01c3 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -141,10 +141,10 @@ record); verifier/reward.txt and score.json | The exchange record (`--exchanges`) | Each call of a unit's agent, kept whole and unredacted by its relay ([Run a benchmark](cli/run.md#the-exchange-record)) | | Job name | One run at a time per job name: another is refused before it writes anything. A later run under the same name moves each trial's earlier record aside to the trial's `.work/earlier.` | | Backends (`--backend`) | `local`: processes on this machine. `container`: each unit's agent or Module in a container, its relay beside it, on Docker, else Podman 4.7 or later. Podman needs no Docker API socket and no `containers.conf` change. `docker` is accepted as an alias for `container`. For agent and Module runs the driver stays on the machine; Original setups instead containerize the driver and its answerer; in a container a check that runs what the agent left (the workspace kit's test) runs it in a throwaway, network-less container of the unit's image, and no check reads through a link the agent planted; `config.json` records the backend and the image. `boat`: each unit's agent or Module in a boat.dev VM of its own ([The boat backend](#the-boat-backend)) | -| Progress | One line per stage on stderr and in `progress.jsonl`: `[nullius] stage=install agent=codex@2.2.2 state=done seconds=41 at=...` (`start`, `done`, `cached`, `failed`; a download's bytes every 5 s) for the base image, an environment, the upstream, a dataset, `driver.install` and the agent; then `stage=units n=10`, `stage=unit i=3 of=10 unit=... outcome=passed`, `stage=done`; `stage=refused` alone for a run refused first. From `stage=units` the job also writes `events.jsonl`, Harbor's live feed, with `trial.progress`: each running unit's steps, successful model calls, failed requests, tokens and cost | +| Progress | One line per stage on stderr and in `progress.jsonl`: `[nullius] stage=install agent=codex@2.2.2 state=done seconds=41 at=...` (`start`, `done`, `cached`, `failed`; a download's bytes every 5 s) for the base image, an environment, the upstream, a dataset, `driver.install` and the agent; then `stage=units n=10`, `stage=unit i=3 of=10 unit=... outcome=passed`, `stage=done`; `stage=refused` alone for a run refused first. From `stage=units` the job also writes `events.jsonl`, Harbor's live feed, with `trial.progress`: each running unit's steps, model calls, failed requests, tokens and cost | | Outcomes | A last model call that got a 429 is `rate_limited`, a refused key an API error, both outside the agent's rate, unless the unit passed; a unit asked to stop keeps the score its driver gave despite the agent's own last 429; the agent's own last call over the model's context window is `ContextWindowExceededError`, the agent's; an agent past its limit for the unit, every turn included, is the agent's timeout ([time limits](cli/run.md#time-limits)), unless the benchmark [scores the cut](cli/run.md#a-unit-cut-at-a-limit). `"kind": "score"` leaves a score and no pass | -| Compatibility | Before units start, drivers declaring `preflight` capture synthetic requests from the published clients. The selected model, serving route and reasoning setting are checked through the relay. Success is cached for one hour per request, source, options, credentials and route. Roles without a capture say **Not checked**; a model listing alone proves no API or tool support. Checks may be billed and count against the run's spending cap. | -| Permanent provider refusals | Wrong credentials, exhausted credit, unavailable models and explicit native-tool incompatibilities stop queued units and interrupt active protocol waits. The refusing unit is an infrastructure error, never a failed task. Rate limits, server failures and repairable request errors retain their retry behavior. | +| Compatibility | Before the units, each role's captured request (`preflight`) is sent once through the relay; a refusal refuses the run. Billed, under the cap; a pass is kept an hour | +| Permanent provider refusals | Stop the run; the unit is an infra error, not a failed task. Rate limits and server errors are retried | | Rate limits | After a `rate_limited` end no unit starts for 60 s, or the provider's `Retry-After`, doubling to 300 s while units keep ending so | | The relay | Headers pass through except the credentials, replaced by the relay's key; `agent/calls.jsonl` names them, never their values. A 429 reaches the agent as it came, never retried. Every call goes as the run's model, the one asked recorded as `model_asked`, except `model.side_models`, sent as asked and recorded `side`. Provider `anthropic` serves `messages` only ([protocols](settings/model-providers.md#protocols)) | | Constraints (`--constraint KEY=VALUE`) | What the machine allows Nullius, from Settings ([constraints](settings/run-hosts.md#constraints)): flags on every container the run starts on the machine, on either backend; a systemd scope for each process the run starts there (its drivers, and its agents and Modules on the local backend); the most units at a time; the CPU affinity; the driver's `CUDA_VISIBLE_DEVICES`. The local backend refuses a cap that no scope holds. `config.json` records the values under `standard.constraints` | @@ -431,7 +431,7 @@ its local proof records, saved runs and credentials remain. Proofs the bundled e | Op | Sent | Replies | | --- | --- | --- | | `units` | `dataset`, `setup` | Every unit id | -| `preflight` | `participant` (`setup`, `agent`, `capability` or `control`), `setup`, upstream `model`, selected `roles`; with `driver.preflight` | `{requests: [{role, path, body, headers?}]}` captured from the published clients on synthetic input, with no task environment or network calls. Paths are `/v1/messages`, `/v1/chat/completions` or `/v1/responses`, with any required query. Preserve tools, images and request settings; headers retain `anthropic-beta` and `anthropic-version`. Return only roles that can be captured. | +| `preflight` | `participant`, `setup`, `model`, `roles`; with `driver.preflight` | `{requests: [{role, path, body, headers?}]}`: each role's first request from the upstream's own client, captured offline. A role left out is Not checked | | `describe` | `dataset`, with `driver.describe` | `{units: {ID: {title, text, categories: {FIELD: VALUE}}}}`, from the dataset's files alone, for [listings](cli/task-sets.md) | | `setup` | `unit`, `dir`; `attempt` with `limits.attempts`; `participant` (`agent`, `capability` or `control`) with `driver.participant` | `{prompt}`, any `mcp` servers, `environment`, an own image's `image`, `prepare`, `mount`, `internet` and `verify`, and `agent_seconds`, the unit's own agent timeout (up to 6 hours, instead of `limits.turn_seconds`); `progress`, a file in the trial the driver rewrites: `{steps, steps_limit, ended}` | | `turn` | The transcript so far; `simulator: {model, base_url, key}` when there is one; `judge` for an upstream that grades as the conversation ends; `attempt` with `limits.attempts` | The next message, `{done: true}`, or `restart` | @@ -449,7 +449,7 @@ An `answer` or `score` error that begins `EnvironmentSetupError: `, `VerifierErr | `gated` | `true` for a benchmark whose tasks are gated: a unit's failing model endpoint (the agent's, the judge's, the simulated user's) is kept as its status and class, never the provider's words | | `score.judge` | `{model, says, retired?, served_as?}`: the official judge. Its route (`-judge`) is asked as that model, recorded beside the unit's calls, never as the agent's. `cli run --judge-model` asks another. `retired: true`: no default; an agent's run without `--judge-model` is refused, a control's gets no judge. `served_as`: `{provider: name}` where a provider lists the model under another name | | `score.experiment_judge` | `{label, model, says}`: a judge beside the score, never in its place, on a benchmark with no official one. Runs only on `--judge-model`, on the same route; `model` is the one its source used, never a default | -| `simulator` | `{model, says, served_as?}`, with `agent.conversation/v1` or `agent.computer/v1`: the simulated people’s model, on `-simulator`. A conversation opens with a `turn` on an empty transcript, its message after `setup`'s prompt and a blank line. A desktop receives the route through `task_given` (required), without an opening turn; an upstream setup receives it through `answer`. A control never asks it. `cli run --simulator-model` asks another | +| `simulator` | `{model, says, served_as?}`, with `agent.conversation/v1` or `agent.computer/v1`: the simulated people's model, on `-simulator`. A conversation opens with a `turn` on an empty transcript, its message after `setup`'s prompt and a blank line; a desktop gets the route in `task_given`. A control never asks it. `cli run --simulator-model` asks another | | `leaderboard` | `{says, simulator?, judge?, bench_options?, repeat?}`: what the upstream's leaderboard fixes besides the ranked model, from its own submission rules - the user simulator's and judge's models, the benchmark's options it sets and the fewest attempts per unit. The builder then offers **Like the leaderboard** | | `agent_options` | `{option: value}`: what every agent that has the option runs with on this benchmark, as its rules require (`web_tools: off`). A run giving another value is refused; the builder shows it fixed. An agent without the option runs as it is | | `limits.turns` | At most this many agent turns in a conversation (default 20; `cli run --max-turns` forces another) | @@ -460,7 +460,7 @@ An `answer` or `score` error that begins `EnvironmentSetupError: `, `VerifierErr | `driver.participant` | `true`: `setup` is also sent `participant`, the kind of what runs the unit, for a driver that starts something only an agent uses | | `driver.unit_end` | `true`: the driver is sent `end` (`unit`, `dir`) once each unit an agent ran has ended, scored or not, so that what its setup started for the agent ends with the unit. A control's or a setup's unit gets none | | `driver.questions` | `true`, with `describe`: each unit may list `questions: [{id, text}]`. A task set can select these; the driver receives `NULLIUS_TASK_QUESTIONS`, a JSON mapping from unit id to selected question ids, and refuses unknown or excluded questions before running. Units absent from the mapping keep all their questions. | -| `driver.preflight` | `true`: the driver answers `preflight` before any unit. A failed capture refuses launch; an omitted role is explicitly unchecked. | +| `driver.preflight` | `true`: the driver answers `preflight`; a failed capture refuses the run | | `driver.describe` | `true`: the driver answers `describe`; without it a listing gives ids alone | | `driver.list_command` | A start of the driver for listings alone, needing only the standard library and the dataset's files; `{here}` its one slot | | `driver.task_given` | `true`: the driver is sent `task_given` before each agent is given its task, and the task waits for its answer: [the computer port](ports/agent-computer-v1.md#the-window-before-the-task) closes its window before the task there. A control's or a setup's unit gets none | @@ -561,7 +561,7 @@ An agent or a Module may keep several versions in its one file: an older release | In jobs | `…__KEY-VERSION__…` in the name; `standard.benchmark_version` and `standard.benchmark_ref` in `config.json` | | A fork is a version | `versions..upstream = {repository, tag, tested}`, never a patch of ours; cloned at its commit (`upstreams///`), its datasets checked by their own `sha256`; a private repository uses the machine's git credentials. It proves its own controls (`cli prove KEY@NAME`) | | A release is the default | An earlier untagged pin stays as a version with `upstream.branch` (`main`): shown as `main (044bc33)` | -| Display name | Optional `upstream.label` distinguishes versions from the same branch; the full label retains the commit. CLI version keys and source pins stay unchanged | +| Display name | `upstream.label`: a version's name on pages; the key stays | | Its page | `benchmark.json` `versions.`: whole `good_to_know`, `upstream_limitations`, `limitations`, and `datasets.` `tasks`, `notes`, `verifier`; the page and builder switch all of it with the version | ### Options @@ -645,7 +645,7 @@ already accepts arbitrary models needs only the `original` method. | Rule | Detail | | --- | --- | -| `original` driver method | A model of `models` only, by the name the upstream knows; the relay sends it as `served_as` says, with the prefix `providers` gives. Direct OpenAI drops an `openai/` prefix. A provider not in `providers` is refused. A model the upstream asks besides the answerer is a `side_models` entry. Without `models`, any model: its own agent runs as the run's model | +| `original` driver method | A model of `models` only, by the name the upstream knows; the relay sends it as `served_as` says, with the prefix `providers` gives. A provider not in `providers` is refused. A model the upstream asks besides the answerer is a `side_models` entry. Without `models`, any model: its own agent runs as the run's model | | `model` driver method | The upstream is told `runs_as` (its window, batching and token budget) while the relay sends the model chosen. A model that reasons by default can spend that budget thinking: a last reply with neither text nor a tool call is `OutputLengthExceededError`. A last Responses reply that `failed` is an API error. A runner that fails after the unit is asked to stop is `CancelledError` | | `units` | A setup may count its own units; `units` is sent `setup` | | `answer` | Runs the upstream's answerer through the unit's relay; `score` is sent `setup` too. Local processes or the Original setup driver container | @@ -679,7 +679,7 @@ it is published with. It speaks no port, so it has no `offers` or `proven`. | Derived, never written | Where it comes from (`from`: `benchmark`; a catalogue agent's is `bundled` or `yours`) and `only_for`, its benchmark. A written `only_for` names that benchmark alone | | `options.agent` | `standard.json` writes its `label`, `summary` and `setups`; the loader rebuilds `values` (each entry's `start.driver.agent`, in order), `names`, `about` and `default` (the first) | | Checked | Each entry's `models` are among `setups.original.models`; each upstream name once | -| `vendors` | Optional. Sends a vendor's built-in tools (Claude's `computer_…`): a model its name proves another vendor's (OpenRouter's prefix, or the OpenAI or Anthropic provider) is refused. A name of your own server proves nothing | +| `vendors` | The vendors whose built-in tools it sends: another vendor's model is refused | | Offered | On the Agents page and in the builder, for its benchmark only | | Run | As the Original setup, its upstream name as the agent option: `nullius standard run osworld1 original --bench-option agent=openai_cua`. Its jobs name it by its key (`openai-cua`) |