From 30dd6c1b0f35af0a799a4b0584a8ec8ae7e4c0a3 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 16:07:21 +0100 Subject: [PATCH 01/11] feat(standard): let the relay send a role's routes to its own provider --- app/nullius/standard/calls/relay.py | 114 +++++++++++++++++++++------- app/tests/test_standard_relay.py | 42 ++++++++++ 2 files changed, 130 insertions(+), 26 deletions(-) diff --git a/app/nullius/standard/calls/relay.py b/app/nullius/standard/calls/relay.py index cca8e9a75..bec6daefa 100644 --- a/app/nullius/standard/calls/relay.py +++ b/app/nullius/standard/calls/relay.py @@ -765,6 +765,29 @@ def close(self): c.close() +# The routes a provider of their own may answer, by the suffix of their tag (``-judge``): the run's judge and its user simulator. +ROLES = ("judge", "simulator") + + +def role_of(tag: str) -> str: + """The role a route's tag carries (``u0042-judge``: judge), or "" for any other: the agent's, a Module's.""" + role = tag.rpartition("-")[2] if "-" in tag else "" + return role if role in ROLES else "" + + +class _Upstream: + """A provider the relay sends calls to: its endpoint, its key, its kept connections, and + whether it routes a model to several serving providers and says who served it (OpenRouter).""" + + def __init__(self, base: str, key: str, timeout: float, routed: Optional[bool] = None, facts: Optional[bool] = None): + self.base, self.key = base.rstrip("/"), key + host = (urllib.parse.urlsplit(base).hostname or "").lower() + openrouter = host == "openrouter.ai" or host.endswith(".openrouter.ai") + self.routed = openrouter if routed is None else bool(routed) + self.facts = openrouter if facts is None else bool(facts) + self.pool = _Pool(self.base, timeout) + + class Relay: def __init__(self, base: str, key: str, record_dir: str, prices: Optional[Dict[str, dict]] = None, model: Optional[str] = None, side_models=(), key_header: str = "authorization", fields: bool = False, @@ -772,7 +795,8 @@ def __init__(self, base: str, key: str, record_dir: str, prices: Optional[Dict[s facts: Optional[bool] = None, timeout: float = TIMEOUT, max_calls: Optional[int] = None, exchanges: str = "off", exchanges_max_mb: int = exchange_store.MAX_MB, reasoning: Optional[Dict[str, str]] = None, routed: Optional[bool] = None, - booking: Optional[Callable[[bytes], Optional[float]]] = None): + booking: Optional[Callable[[bytes], Optional[float]]] = None, + upstreams: Optional[Dict[str, tuple]] = None): """``base``: the provider's endpoint (``https://api.openai.com/v1``). ``model``: when given, every call is sent as this model, whatever the caller named - the run's model is the recipe's, not the agent's. A @@ -804,22 +828,28 @@ def __init__(self, base: str, key: str, record_dir: str, prices: Optional[Dict[s ``routed``: ``base`` routes a model to several serving providers, by default when it is OpenRouter's. ``booking``: what a capped call is booked at, by the bytes it sends, in place of the ledger's estimate (:func:`ledgers.bound`): the most it can - cost, held whole until its reply; None, a call it cannot bound, refused unsent.""" + cost, held whole until its reply; None, a call it cannot bound, refused unsent. + ``upstreams``: by role (:data:`ROLES`), ``(base, key)`` of the provider that role's routes + call instead of ``base``, with a bearer key; a role not given calls ``base``.""" self.fields = fields self.booking = booking self.max_calls = max_calls if exchanges not in exchange_store.MODES: raise ValueError(f"exchanges {exchanges!r}: one of {', '.join(exchange_store.MODES)}") - self.exchanges = (exchange_store.Store(record_dir, exchanges, exchanges_max_mb, (key, (key or "").strip())) + self.upstream = _Upstream(base, key, timeout, routed, facts) + self.upstreams = {role: _Upstream(b, k, timeout) for role, (b, k) in (upstreams or {}).items()} + bad = [r for r in self.upstreams if r not in ROLES] + if bad: + raise ValueError(f"upstreams {', '.join(bad)}: a role is one of {', '.join(ROLES)}") + # every key this relay holds, cut out of whatever it records or says + self.secrets = tuple(x for u in (self.upstream, *self.upstreams.values()) for x in (u.key, (u.key or "").strip())) + self.exchanges = (exchange_store.Store(record_dir, exchanges, exchanges_max_mb, self.secrets) if exchanges != "off" else None) self.numbered: Dict[str, int] = {} # the calls each agent route was sent, for the record's n self.answered: Dict[str, int] = {} # the calls each agent route had answered, for max_calls self.serving = {m: list(s) for m, s in (serving or {}).items()} self.reasoning = dict(reasoning or {}) - host = (urllib.parse.urlsplit(base).hostname or "").lower() - openrouter = host == "openrouter.ai" or host.endswith(".openrouter.ai") - self.routed = openrouter if routed is None else bool(routed) - self.facts = openrouter if facts is None else bool(facts) + self.routed, self.facts = self.upstream.routed, self.upstream.facts self.ledger = ledgers.Ledger(ledger) if ledger else None # False for the benchmark's own relay: its calls (an option's embeddings) are no one unit's, so only the run's cap holds them self.unit_caps = unit_caps @@ -831,7 +861,7 @@ def __init__(self, base: str, key: str, record_dir: str, prices: Optional[Dict[s self.models: Dict[str, str] = {} self.embedding_models: Dict[str, str] = {} self.lock = threading.Lock() - self.pool = _Pool(self.base, timeout) + self.pool = self.upstream.pool self.server: Optional[ThreadingHTTPServer] = None os.makedirs(record_dir, exist_ok=True) @@ -879,13 +909,18 @@ def _said(self, e: Exception) -> str: quotes a header value it refuses (a key with a stray CR, a BOM), so the key itself is cut out of the text whatever else it says.""" text = f"{type(e).__name__}: {e}" - for k in exchange_store.secret_keys((self.key, self.key.strip())): + for k in exchange_store.secret_keys(self.secrets): text = text.replace(k, "[REDACTED]") return redact(text)[:200] + def _up(self, tag: str) -> _Upstream: + """The provider a route's calls go to: its role's own (``upstreams``), else ``base``.""" + return self.upstreams.get(role_of(tag)) or self.upstream + def _headers(self, caller, tag: str = "", facts: bool = False) -> Dict[str, str]: """The headers sent on: the key as ``key_header`` says on the agent's own routes; a route pinned - to a model of the benchmark's (a judge, a simulator, embeddings) speaks chat, so a bearer header. + to a model of the benchmark's (a judge, a simulator, embeddings) speaks chat, so a bearer header; + a role's own provider's key on its routes. ``facts``: a pinned Chat Completions or Responses request to OpenRouter, sent asking for its routing facts whatever the caller said of them.""" @@ -894,15 +929,17 @@ def _headers(self, caller, tag: str = "", facts: bool = False) -> Dict[str, str] out = {k: v for k, v in out.items() if k.lower() != "x-openrouter-metadata"} out["X-OpenRouter-Metadata"] = "enabled" has = {k.lower() for k in out} # a name in any case is the same header: never send it twice - x_api_key = self.key_header == "x-api-key" and tag not in self.models and tag not in self.embedding_models + up = self._up(tag) + x_api_key = (up is self.upstream and self.key_header == "x-api-key" and tag not in self.models + and tag not in self.embedding_models) for name, value in (("Content-Type", "application/json"), ("Accept", "*/*")) + \ (("anthropic-version", ANTHROPIC_VERSION),) * x_api_key: if name.lower() not in has: out[name] = value if x_api_key: - out["x-api-key"] = self.key + out["x-api-key"] = up.key else: - out["Authorization"] = "Bearer " + self.key + out["Authorization"] = "Bearer " + up.key return out def _asked(self) -> bool: @@ -928,6 +965,7 @@ def _forward(self, h: BaseHTTPRequestHandler): with self.lock: number = self.numbered[tag] = self.numbered.get(tag, 0) + 1 asked = req.get("model") if isinstance(req, dict) else None + up = self._up(tag) side = False routing_asked, pinned = None, None dumped = False # raw is json.dumps(req): what the store splits into parts @@ -948,7 +986,7 @@ def _forward(self, h: BaseHTTPRequestHandler): routing_asked = req.get("provider") req["provider"] = routing(pinned) if isinstance(req.get("model"), str) and self.reasoning.get(req["model"]): - think(req, rest, self.reasoning[req["model"]], self.routed) + think(req, rest, self.reasoning[req["model"]], up.routed) raw, dumped = json.dumps(req).encode(), True if not side and not self.models.get(tag) and self._asked(): h.send_error(400, "the unit was asked to stop") @@ -984,9 +1022,9 @@ def _forward(self, h: BaseHTTPRequestHandler): cut_off = None try: # a Responses reply names its provider in the routing facts alone; a Messages reply names it of itself - facts = bool(pinned) and self.facts and rest.split("?")[0].endswith(("/chat/completions", "/responses")) + facts = bool(pinned) and up.facts and rest.split("?")[0].endswith(("/chat/completions", "/responses")) sent_headers = self._headers(h.headers, tag, facts) - conn, r = self.pool.send(h.command, rest, raw if h.command == "POST" else None, sent_headers) + conn, r = up.pool.send(h.command, rest, raw if h.command == "POST" else None, sent_headers) status, kind, back = r.status, r.getheader("Content-Type") or "application/json", returned(r.headers) except Exception as e: status, kind = 502, "application/json" @@ -1019,9 +1057,9 @@ def record(body): rec["side"] = True if isinstance(req, dict) and req.get("provider") is not None: # the routing as sent, and the caller's own the pin replaced: recorded copies, cleaned - rec["request"]["routing"] = _clean(req["provider"], (self.key, self.key.strip())) + rec["request"]["routing"] = _clean(req["provider"], self.secrets) if pinned and routing_asked is not None: - rec["request"]["routing_asked"] = _clean(routing_asked, (self.key, self.key.strip())) + rec["request"]["routing_asked"] = _clean(routing_asked, self.secrets) if self.fields and isinstance(req, dict) and req: rec["fields"] = request_fields(req) cost = None @@ -1031,7 +1069,7 @@ def record(body): self.answered[tag] = self.answered.get(tag, 0) + 1 rec["reply"] = read_reply(rest, body, streamed) try: - rec["reply"].update({k: v for k, v in _clean(reply_facts(rest, body, streamed), (self.key, self.key.strip())).items() + rec["reply"].update({k: v for k, v in _clean(reply_facts(rest, body, streamed), self.secrets).items() if k not in rec["reply"]}) except Exception: pass @@ -1106,7 +1144,7 @@ def record(body): record(body) # before the caller has the reply, so a reader after it finds the call if conn is not None: # read whole: back to the pool before the caller can make its next call if whole: - self.pool.give(conn, r) + up.pool.give(conn, r) else: conn.close() conn = None @@ -1118,7 +1156,7 @@ def record(body): pass if conn is not None: if whole: - self.pool.give(conn, r) + up.pool.give(conn, r) else: conn.close() @@ -1214,7 +1252,8 @@ def stop(self): if self.server: self.server.shutdown() self.server.server_close() - self.pool.close() + for u in (self.upstream, *self.upstreams.values()): + u.pool.close() def agent_route(tag: str) -> bool: @@ -1316,9 +1355,10 @@ def serve(argv=None) -> int: """``python3 -m nullius.standard.calls.relay serve --listen HOST:PORT --base URL --record DIR --key-file PATH [--model M] [--route TAG=MODEL ...] [--side-model M ...] [--key-header NAME] [--public URL] [--prices JSON] [--ledger FILE] [--served-by MODEL=SLUG[,SLUG...] ...] [--reasoning MODEL=LEVEL ...] - [--exchanges whole|text|off] [--exchanges-max-mb N]``. + [--exchanges whole|text|off] [--exchanges-max-mb N] [--upstream ROLE=URL --upstream-key-file ROLE=PATH ...]``. ``--base``: provider endpoint. ``--route``: send a tag as another model. ``--public``: address returned by ``url``. + ``--upstream``: a role's own provider (``upstreams``), its key in ``--upstream-key-file``. The real key is read from ``--key-file`` and nowhere else: an argument or an environment variable is visible to anyone who lists processes or inspects a container. One JSON line, ``{"listening": "http://host:port"}``, says it @@ -1352,14 +1392,18 @@ def serve(argv=None) -> int: "the pictures' bytes (text), or not (off, the default)") ap.add_argument("--exchanges-max-mb", type=int, default=exchange_store.MAX_MB, metavar="N", help=f"the most MB a unit's exchanges take: past it a call's line says cut (default {exchange_store.MAX_MB})") + ap.add_argument("--upstream", action="append", default=[], metavar="ROLE=URL", + help=f"the provider a role's routes call instead of --base: ROLE one of {', '.join(ROLES)}") + ap.add_argument("--upstream-key-file", action="append", default=[], metavar="ROLE=PATH", + help="the file that holds that provider's key") a = ap.parse_args(argv) if a.exchanges_max_mb < 1: print(json.dumps({"error": f"--exchanges-max-mb {a.exchanges_max_mb}: a whole number of MB, at least 1"}), flush=True) return 2 serving, bad = parse_served_by(a.served_by, "") if serving and not bad: - host = (urllib.parse.urlsplit(a.base).hostname or "").lower() - if not (a.routing or host == "openrouter.ai" or host.endswith(".openrouter.ai")): + hosts = [(urllib.parse.urlsplit(u).hostname or "").lower() for u in [a.base, *(u.partition("=")[2] for u in a.upstream)]] + if not (a.routing or any(h == "openrouter.ai" or h.endswith(".openrouter.ai") for h in hosts)): bad.append(f"{a.base} routes no model to several serving providers (OpenRouter's does; --routing says another does)") sent = {a.model} | {r.partition("=")[2] for r in a.route} | {(s.partition("=")[2] or s) for s in a.side_model} stray = [m for m in serving if a.model and m not in sent] @@ -1381,10 +1425,28 @@ def serve(argv=None) -> int: if not key: print(json.dumps({"error": f"--key-file {a.key_file} contains no key"}), flush=True) return 2 + bases = dict(u.partition("=")[::2] for u in a.upstream) + files = dict(u.partition("=")[::2] for u in a.upstream_key_file) + if sorted(bases) != sorted(files) or any(r not in ROLES or not bases[r] for r in bases): + print(json.dumps({"error": f"--upstream ROLE=URL and --upstream-key-file ROLE=PATH, each ROLE one of {', '.join(ROLES)}, " + "given together"}), flush=True) + return 2 + upstreams = {} + for role, path in files.items(): + try: + with open(path) as f: + upstreams[role] = (bases[role], f.read().strip()) + except OSError as e: + print(json.dumps({"error": f"cannot read --upstream-key-file {role}: {e}"}), flush=True) + return 2 + if not upstreams[role][1]: + print(json.dumps({"error": f"--upstream-key-file {role} contains no key"}), flush=True) + return 2 host, _, port = a.listen.rpartition(":") r = Relay(a.base, key, a.record, prices=json.loads(a.prices) if a.prices else None, model=a.model, side_models=a.side_model, key_header=a.key_header, ledger=a.ledger, serving=serving, reasoning=reasoning, - routed=True if a.routing else None, timeout=a.timeout, max_calls=a.max_calls, exchanges=a.exchanges, exchanges_max_mb=a.exchanges_max_mb) + routed=True if a.routing else None, timeout=a.timeout, max_calls=a.max_calls, exchanges=a.exchanges, exchanges_max_mb=a.exchanges_max_mb, + upstreams=upstreams) for route in a.route: tag, _, model = route.partition("=") if not _TAG.match(tag) or not model: diff --git a/app/tests/test_standard_relay.py b/app/tests/test_standard_relay.py index 0d1de3d87..eef79283b 100644 --- a/app/tests/test_standard_relay.py +++ b/app/tests/test_standard_relay.py @@ -692,6 +692,30 @@ def test_serve_relays_with_the_key_from_its_file_and_stops_on_sigterm(self): p.kill() p.stdout.close() + def test_serve_sends_a_roles_calls_to_its_own_provider_with_the_key_from_its_own_file(self): + import signal + d = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, d, True) + with open(os.path.join(d, "judge-key"), "w") as f: + f.write("sk-judge\n") + p = self.serve("sk-from-file", "--route", "u1-judge=the-judge", + "--upstream", f"judge=http://127.0.0.1:{self.up.server_address[1]}/judge/v1", + "--upstream-key-file", "judge=" + os.path.join(d, "judge-key")) + try: + where = json.loads(p.stdout.readline())["listening"] + for tag, path, key in (("u1", "/v1/chat/completions", "Bearer sk-from-file"), + ("u1-judge", "/judge/v1/chat/completions", "Bearer sk-judge")): + req = urllib.request.Request(f"{where}/{tag}/v1/chat/completions", data=b'{"model":"asked"}', + headers={"Content-Type": "application/json"}) + urllib.request.urlopen(req).read() + self.assertEqual(Upstream.seen[-1][:2], (path, key)) + p.send_signal(signal.SIGTERM) + self.assertEqual(p.wait(timeout=10), 0) + finally: + if p.poll() is None: + p.kill() + p.stdout.close() + def test_serve_books_its_calls_in_the_runs_ledger(self): """A docker unit's relay: the ledger is a file it is given, shared with every other relay of the job.""" import signal @@ -910,6 +934,24 @@ def test_a_benchmark_route_beside_an_anthropic_agent_takes_a_bearer_key(self): self.assertEqual(sent["authorization"], "Bearer sk-real") self.assertFalse({"x-api-key", "anthropic-version"} & set(sent)) + def test_a_roles_routes_call_its_own_provider_with_its_own_key(self): + other = ThreadingHTTPServer(("127.0.0.1", 0), KeptAlive) + other.daemon_threads = True + threading.Thread(target=other.serve_forever, daemon=True).start() + self.addCleanup(other.shutdown) + r = self.relay(model="claude-x", key_header="x-api-key", + upstreams={"judge": (f"http://127.0.0.1:{other.server_address[1]}/judge/v1", "sk-judge")}) + r.url("u-judge", model="judge-x") + r.url("u-simulator", model="user-x") + for tag, path in (("u", "/messages"), ("u-judge", "/chat/completions"), ("u-simulator", "/chat/completions")): + self.assertEqual(self.post(r, tag, path, {"model": "any", "max_tokens": 5, "messages": []})[0], 200) + (agent, a_head, _), (judge, j_head, j_body), (user, u_head, _) = KeptAlive.seen + self.assertEqual((agent, a_head.get("x-api-key")), ("/v1/messages", "sk-real")) + self.assertEqual((judge, j_head.get("Authorization"), j_body["model"]), ("/judge/v1/chat/completions", "Bearer sk-judge", "judge-x")) + self.assertEqual((user, u_head.get("Authorization")), ("/v1/chat/completions", "Bearer sk-real")) # no provider of its own: the agent's + self.assertEqual((r.pool.opened, r.upstreams["judge"].pool.opened), (1, 1)) + self.assertNotIn("sk-judge", r._said(OSError("refused with sk-judge"))) + def test_anthropic_messages_take_the_key_as_x_api_key_and_their_usage_is_read(self): r = self.relay(model="claude-x", key_header="x-api-key") status, _, body = self.post(r, "u", "/messages", {"model": "claude-x", "max_tokens": 10, "messages": []}, From 375b5086418f609c9fb049ad31a1e78442c5faa5 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 16:07:59 +0100 Subject: [PATCH 02/11] feat(standard): give a unit's relay container a role's own provider and key file --- app/nullius/standard/backends/container.py | 36 ++++++++++++++-------- app/tests/test_standard_container.py | 13 ++++++++ 2 files changed, 37 insertions(+), 12 deletions(-) diff --git a/app/nullius/standard/backends/container.py b/app/nullius/standard/backends/container.py index 02d8261f8..6334c345f 100644 --- a/app/nullius/standard/backends/container.py +++ b/app/nullius/standard/backends/container.py @@ -731,7 +731,8 @@ def relay_argv(image: str, *, name: str, job: str, app: str, record: str, key_fi key_header: str = "authorization", hosts: Optional[Dict[str, str]] = None, ledger: Optional[str] = None, serving: Optional[Dict[str, List[str]]] = None, timeout: Optional[int] = None, max_calls: Optional[int] = None, exchanges: str = "off", - exchanges_max_mb: int = exchange_store.MAX_MB, reasoning: Optional[Dict[str, str]] = None) -> List[str]: + exchanges_max_mb: int = exchange_store.MAX_MB, reasoning: Optional[Dict[str, str]] = None, + upstreams: Optional[Dict[str, Tuple[str, str]]] = None) -> List[str]: """``docker run`` for a unit's relay: on the default bridge (its way to the provider), its port published on 127.0.0.1 only. The key is never given: ``key_file``, its file, is mounted read-only at ``RELAY_KEY_IN`` with @@ -744,13 +745,17 @@ def relay_argv(image: str, *, name: str, job: str, app: str, record: str, key_fi unit's own relay is given them (``relay.Relay``); ``reasoning`` the same, by model, the level its requests are sent with. ``exchanges`` and ``exchanges_max_mb``: whether its calls are kept whole in its record - folder, and the bound, always said.""" + folder, and the bound, always said. ``upstreams``: by role, ``(base, key + file)`` of the provider that role's routes call (``relay.Relay``), each + key file mounted as ``key_file`` is.""" a = [DOCKER, "run", "-d", "--name", name, "--label", f"{LABEL}={job}", *way_out(), *_userns(), "--user", _user(), "--cap-drop", "ALL", *_security_opt(), "--init", *capped(), *[w for n, ip in sorted((hosts or {}).items()) for w in ("--add-host", f"{n}:{ip}")], "-p", f"127.0.0.1::{RELAY_PORT}", "-v", f"{app}:{app}:ro", "-v", f"{record}:{record}:rw", *(["-v", f"{os.path.dirname(ledger)}:{os.path.dirname(ledger)}:rw"] if ledger else []), - "--mount", f"type=bind,source={key_file},target={RELAY_KEY_IN},readonly", "-w", app, + "--mount", f"type=bind,source={key_file},target={RELAY_KEY_IN},readonly", + *[w for role, (_, f) in sorted((upstreams or {}).items()) + for w in ("--mount", f"type=bind,source={f},target={RELAY_KEY_IN}-{role},readonly")], "-w", app, "-e", "PYTHONPATH=" + app, "-e", "PYTHONDONTWRITEBYTECODE=1", image, "python3", "-m", "nullius.standard.calls.relay", "serve", "--listen", f"0.0.0.0:{RELAY_PORT}", "--base", base, "--record", record, "--key-file", RELAY_KEY_IN, "--public", f"http://{RELAY_ALIAS}:{RELAY_PORT}"] @@ -779,6 +784,8 @@ def relay_argv(image: str, *, name: str, job: str, app: str, record: str, key_fi a += ["--key-header", key_header] if timeout: a += ["--timeout", str(timeout)] + for role, (b, _) in sorted((upstreams or {}).items()): + a += ["--upstream", f"{role}={b}", "--upstream-key-file", f"{role}={RELAY_KEY_IN}-{role}"] return a @@ -887,12 +894,15 @@ class Loopback: joins it, so a :class:`SocketDoor` (``door``) passes each connection instead, and one door container for the run reaches it, on the engine's default network as the relays are. The relays call it - ``host.docker.internal`` there too, at the door's address, on port 8000.""" + ``host.docker.internal`` there too, at the door's address, on port 8000. + ``role``: a door of a role's own provider (``relay.ROLES``), which the + relays call ``.host.docker.internal``, beside the agent's.""" NAME = "host.docker.internal" DOOR_PORT = 8000 # not the endpoint's: below 1024 needs a capability on podman - def __init__(self, base: str, *, image: str = "", job: str = ""): + def __init__(self, base: str, *, image: str = "", job: str = "", role: str = ""): + self.name, self.role = (f"{role}.{self.NAME}" if role else self.NAME), role self.target = urllib.parse.urlsplit(base) self.base, self.hosts = base, {} self.image, self.job = image, job # the door container's (use_socket_doors) @@ -902,13 +912,13 @@ def __init__(self, base: str, *, image: str = "", job: str = ""): def _url(self, port: Optional[int]) -> str: t = self.target - netloc = (t.netloc.rpartition("@")[0] + "@" if "@" in t.netloc else "") + self.NAME + (f":{port}" if port else "") + netloc = (t.netloc.rpartition("@")[0] + "@" if "@" in t.netloc else "") + self.name + (f":{port}" if port else "") return urllib.parse.urlunsplit((t.scheme, netloc, t.path, t.query, t.fragment)) def start(self) -> "Loopback": if use_socket_doors(): self.door = SocketDoor(*self._endpoint()) - self.container = f"nullius-{slug(self.job)}-model" + self.container = f"nullius-{slug(self.job)}-model" + (f"-{self.role}" if self.role else "") try: make_bridge() _docker(door_argv(self.image, name=self.container, job=self.job, port=self.DOOR_PORT, @@ -922,7 +932,7 @@ def start(self) -> "Loopback": except Exception: self.stop() raise - self.base, self.hosts = self._url(self.DOOR_PORT), {self.NAME: ip[0]} + self.base, self.hosts = self._url(self.DOOR_PORT), {self.name: ip[0]} return self gateway = bridge_gateway() try: @@ -930,9 +940,9 @@ def start(self) -> "Loopback": raise OSError("no bridge gateway") self._server = socket.create_server((gateway, 0)) except OSError: - self.base, self.hosts = self._url(self.target.port), {self.NAME: "host-gateway"} + self.base, self.hosts = self._url(self.target.port), {self.name: "host-gateway"} return self - self.base, self.hosts = self._url(self._server.getsockname()[1]), {self.NAME: gateway} + self.base, self.hosts = self._url(self._server.getsockname()[1]), {self.name: gateway} threading.Thread(target=_pass_each, args=(self._server, self._endpoint()), daemon=True).start() return self @@ -1056,8 +1066,9 @@ def __init__(self, job: str, tag: str, record_dir: str, *, image: str, app: str, ledger: Optional[str] = None, network_probe: Optional[str] = None, probe_now: bool = True, serving: Optional[Dict[str, List[str]]] = None, timeout: Optional[int] = None, max_calls: Optional[int] = None, exchanges: str = "off", exchanges_max_mb: int = exchange_store.MAX_MB, - reasoning: Optional[Dict[str, str]] = None): + reasoning: Optional[Dict[str, str]] = None, upstreams: Optional[Dict[str, Tuple[str, str]]] = None): self.job, self.tag, self.dir, self.image, self.app = job, tag, record_dir, image, app + self.upstreams = dict(upstreams or {}) # by role, (base, key) of the provider its routes call self.max_calls = max_calls self.exchanges, self.exchanges_max_mb = exchanges, exchanges_max_mb self.ledger = ledger @@ -1092,7 +1103,8 @@ def start(self) -> "Unit": hosts=self.hosts, ledger=self.ledger, serving=self.serving, timeout=self.timeout, max_calls=self.max_calls, exchanges=self.exchanges, exchanges_max_mb=self.exchanges_max_mb, - reasoning=self.reasoning) + reasoning=self.reasoning, + upstreams={role: (b, self._key_file("key-" + role, k)) for role, (b, k) in self.upstreams.items()}) self.started.append(self.names["relay"]) _docker(argv[1:]) _docker(["network", "connect", "--alias", RELAY_ALIAS, self.names["network"], self.names["relay"]]) diff --git a/app/tests/test_standard_container.py b/app/tests/test_standard_container.py index c45d4a06c..e9c6fd594 100644 --- a/app/tests/test_standard_container.py +++ b/app/tests/test_standard_container.py @@ -249,6 +249,14 @@ def test_the_relays_container_is_given_the_keys_file_never_the_key(self): self.assertEqual(a[a.index("--public") + 1], "http://relay:8080") self.assertEqual(a[a.index("--label") + 1], "nullius.job=j") self.assertNotIn("--ledger", a) + self.assertNotIn("--upstream", a) + # a role's own provider: its key a file of its own, mounted beside the agent's + a = container.relay_argv("img", name="r", job="j", app="/app", record="/rec", key_file="/k/key", base="b", model="m", + routes={}, upstreams={"judge": ("https://judge.example/v1", "/k/key-judge")}) + self.assertIn("type=bind,source=/k/key-judge,target=/opt/nullius/relay-key-judge,readonly", a) + self.assertEqual(a[a.index("--upstream") + 1:a.index("--upstream") + 4], + ["judge=https://judge.example/v1", "--upstream-key-file", "judge=/opt/nullius/relay-key-judge"]) + self.assertNotIn("judge.example", " ".join(a[:a.index("img")])) def test_the_relays_container_is_given_the_runs_ledger_and_its_folder_alone(self): a = container.relay_argv("img", name="r", job="j", app="/app", record="/rec", key_file="/key", base="b", model="m", routes={}, @@ -270,6 +278,11 @@ def test_an_endpoint_on_this_machines_loopback_is_reached_through_the_bridge(sel door.stop() self.assertEqual((door.base, door.hosts), ("http://user@host.docker.internal:11434/v1?x=1", {"host.docker.internal": "host-gateway"})) self.assertIsNone(door.door) + with mock.patch.object(container, "bridge_gateway", return_value=""), \ + mock.patch.object(container, "rootless", return_value=False): # a role's own server: a name of its own + door = container.Loopback("http://localhost:8001/v1", role="judge").start() + door.stop() + self.assertEqual((door.base, door.hosts), ("http://judge.host.docker.internal:8001/v1", {"judge.host.docker.internal": "host-gateway"})) def _rootless_loopback(self, fail=None, ip="10.88.0.7 \n"): said = [] From 510a350a25d264684bb52f7ad813684a10c2f857 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 16:27:31 +0100 Subject: [PATCH 03/11] feat(standard): run a judge or user simulator on a provider of its own --- app/nullius/providers.py | 6 ++ app/nullius/standard/cli.py | 51 +++++++++++----- app/nullius/standard/runner/job.py | 6 +- app/nullius/standard/runner/rerun.py | 13 ++-- app/nullius/standard/runner/run.py | 89 +++++++++++++++++++++------- app/tests/test_standard_recipe.py | 5 ++ app/tests/test_standard_served_by.py | 19 ++++++ 7 files changed, 146 insertions(+), 43 deletions(-) diff --git a/app/nullius/providers.py b/app/nullius/providers.py index f0dc8c496..67005d975 100644 --- a/app/nullius/providers.py +++ b/app/nullius/providers.py @@ -232,6 +232,12 @@ def endpoint_vars(endpoint: str = "") -> tuple: return ("MODEL_API_URL", "MODEL_API_KEY") if not endpoint else (f"MODEL_{endpoint}_API_URL", f"MODEL_{endpoint}_API_KEY") +def role_vars(role: str) -> tuple: + """(key name, endpoint name) a run started by Nullius is handed a role's own provider under + (``execution``'s launcher, ``standard.cli.run_env``): the judge's, the user simulator's.""" + return f"NULLIUS_{role.upper()}_API_KEY", f"NULLIUS_{role.upper()}_BASE_URL" + + def base_of(url_var: str, env=None) -> str: """The base a run's ``url_var`` names (``execution.Plan``): a custom provider's, from its record when it has one (MODEL__API_URL is its old setting), else the variable's own value.""" diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index 2c135b3fa..ef439a10f 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -81,7 +81,8 @@ Keys come from the process environment, then the saved user settings. Nothing is printed of them. With ``--from-run`` (a run the builder or a page started, ``standard/pages/recipe.py``) saved settings are not read: the key is the one the run was handed, ``OPENAI_API_KEY``, and the -endpoint ``OPENAI_BASE_URL`` when it names one (``run_env``). The licences a +endpoint ``OPENAI_BASE_URL`` when it names one (``run_env``); a role's own provider +(``--judge-provider``, ``--simulator-provider``) its own pair, ``providers.role_vars``. The licences a benchmark's environments declare are never in either: the run reads them from the benchmark's store (``nullius.secrets``) on this machine, or, on a host, from the one line its launcher handed it (``licences``). A data provider's token the @@ -131,21 +132,29 @@ def _other(key): return o -def run_env(provider: str, env=os.environ) -> dict: +def run_env(provider: str, env=os.environ, role: str = "") -> dict: """The environment a run started by Nullius reads its provider from: ``execution``'s launcher hands every run its one key as ``OPENAI_API_KEY`` and its endpoint as ``OPENAI_BASE_URL`` (empty for OpenAI's own), so they are named here as the provider's own settings and nothing else is - but the Boat key, handed the same way to a run on Boat: on a host, the only - way it has one.""" + way it has one. ``role``: a role's own provider, handed under its own + names (``providers.role_vars``).""" + key, url = providers.role_vars(role) if role else ("OPENAI_API_KEY", "OPENAI_BASE_URL") out = {k: v for k, v in env.items() if k in run.KEEP or k == boat.NAME} - if env.get("OPENAI_API_KEY"): - out[providers.key_setting(provider)] = env["OPENAI_API_KEY"] - if provider == "custom" and env.get("OPENAI_BASE_URL"): - out["MODEL_API_URL"] = env["OPENAI_BASE_URL"] + if env.get(key): + out[providers.key_setting(provider)] = env[key] + if provider == "custom" and env.get(url): + out["MODEL_API_URL"] = env[url] return out +def role_env(providers_: dict, from_run: bool, env=os.environ) -> dict: + """By role, the environment a role's own provider is read from: what the launcher handed it, for a run + started by Nullius; none otherwise, so the run reads the provider's settings as it does its own.""" + return {r: run_env(p, env, r) for r, p in providers_.items() if p} if from_run else {} + + def licences(bench: dict, env=os.environ, from_run: bool = False): """(``run.Licences``, the folder to remove after) for a run on a host, whose launcher handed it the benchmark's licences as one line @@ -642,6 +651,8 @@ def cmd_run(a): **({"start_with": start} if start else {}), **({"served_by": run.served_by(a.served_by, a.model or "")} if a.served_by else {}), **({"reasoning": run.reasoning(a.reasoning, a.model or "")} if a.reasoning else {}), + judge_provider=a.judge_provider, simulator_provider=a.simulator_provider, + role_env=role_env({"judge": a.judge_provider, "simulator": a.simulator_provider}, a.from_run), **({"env": run_env(a.provider)} if a.from_run else {})) except run.Refused as e: print("refused:", e) @@ -699,14 +710,19 @@ def set_units(benchmark: str, ref: str, dataset: str | None, flag: str) -> dict: def boat_credentials(a, bench, other, vals) -> dict: - """Only the selected provider and declared benchmark licences cross SSH stdin.""" + """Only the selected providers and declared benchmark licences cross SSH stdin.""" import base64 needs = definitions.option_needs(bench, vals) out = {} - if (other["_kind"] != "control" or (bench.get("score") or {}).get("judge") or needs["embeddings"] or needs["reranker"] - or (a.judge_model and (bench.get("score") or {}).get("experiment_judge"))): + judged = (bench.get("score") or {}).get("judge") or (a.judge_model and (bench.get("score") or {}).get("experiment_judge")) + if other["_kind"] != "control" or judged or needs["embeddings"] or needs["reranker"]: base, key = run.provider_endpoint(a.provider, run_env(a.provider) if a.from_run else os.environ) out.update(OPENAI_API_KEY=key, OPENAI_BASE_URL=base) + for role, p in (("judge", a.judge_provider if judged else None), + ("simulator", a.simulator_provider if bench.get("simulator") and other["_kind"] != "control" else None)): + if p: + base, key = run.provider_endpoint(p, run_env(p, os.environ, role) if a.from_run else os.environ) + out.update(zip(providers.role_vars(role), (key, base))) held, spill = licences(bench, from_run=a.from_run) try: held = held or run.Licences(bench) @@ -743,7 +759,7 @@ def _boat_units(a, b, other) -> int: return 2 words = [b["key"] if "_version" not in b else definitions.ref_of(b), a.other, "--provider", a.provider, "--dataset", ds, "--attempts", str(a.repeat), *(["--retries", str(a.retries)] if a.retries is not None else [])] - for field in ("model", "judge_model", "simulator_model", "max_usd_per_unit", "max_turns", "max_calls"): + for field in ("model", "judge_model", "simulator_model", "judge_provider", "simulator_provider", "max_usd_per_unit", "max_turns", "max_calls"): value = getattr(a, field) if value is not None: words += ["--" + field.replace("_", "-"), str(value)] @@ -752,8 +768,8 @@ def _boat_units(a, b, other) -> int: words += ["--" + field.replace("_", "-"), value] # Saved price overrides belong to the launching profile, not the fresh VM. needs = definitions.option_needs(b, vals) - models = [a.model, other.get("sent"), a.judge_model or providers.official_as((b.get("score", {}).get("judge") or {"model": ""}), a.provider), - a.simulator_model or providers.official_as((b.get("simulator") or {"model": ""}), a.provider), + models = [a.model, other.get("sent"), a.judge_model or providers.official_as((b.get("score", {}).get("judge") or {"model": ""}), a.judge_provider or a.provider), + a.simulator_model or providers.official_as((b.get("simulator") or {"model": ""}), a.simulator_provider or a.provider), *[providers.served_as(m, a.provider) for m in needs["embeddings"] + needs["reranker"]]] explicit = prices(a.price) for model, row in price_list.given(models, price_list.table()).items(): @@ -1132,7 +1148,9 @@ def cmd_rerun(a): chosen = set_units(str(std.get("benchmark") or "") if isinstance(std, dict) else "", a.task_set, ran or None, "--set ") got = rerun.rerun(a.job, ids, reason=a.reason or "", concurrency=a.concurrency, retries=a.retries, max_usd=a.max_usd, prices_unreachable=unreachable, licences=held, every_unfinished=a.unfinished, - count=a.next, task_set=chosen, **({"env": run_env(provider)} if a.from_run else {})) + count=a.next, task_set=chosen, **({"env": run_env(provider)} if a.from_run else {}), + role_env=role_env({r: std.get(r + "_provider") for r in ("judge", "simulator")} if isinstance(std, dict) else {}, + a.from_run)) except sets.NotFound as e: print("refused:", e, file=sys.stderr) return 3 @@ -1584,6 +1602,11 @@ def main(argv=None): p.add_argument("--judge-model", help="a benchmark scored by a model: this judge instead of its official one; " "one with an experiment judge (LoCoMo's): run it, as this model") p.add_argument("--simulator-model", help="a benchmark whose user a model plays: this model instead of its official one") + if name == "run": + p.add_argument("--judge-provider", choices=sorted(providers.PROVIDERS), + help="the judge's provider, its own key (default: --provider)") + p.add_argument("--simulator-provider", choices=sorted(providers.PROVIDERS), + help="the user simulator's provider, its own key (default: --provider)") p.add_argument("--attempts", "--repeat", dest="repeat", type=int, default=1, metavar="K", help="run each unit K times, each an attempt counted whatever its result " "(the upstream's --num-trials, pass^k); default 1") diff --git a/app/nullius/standard/runner/job.py b/app/nullius/standard/runner/job.py index 0b7dbb4df..d54edcc7a 100644 --- a/app/nullius/standard/runner/job.py +++ b/app/nullius/standard/runner/job.py @@ -610,7 +610,8 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str task_set: Optional[dict] = None, start_with: Optional[dict] = None, constraints: Optional[dict] = None, timeouts: Optional[dict] = None, max_turns: Optional[int] = None, max_calls: Optional[int] = None, served_by: Optional[Dict[str, List[str]]] = None, - exchanges: str = "", exchanges_max_mb: Optional[int] = None, reasoning: Optional[Dict[str, str]] = None): + exchanges: str = "", exchanges_max_mb: Optional[int] = None, reasoning: Optional[Dict[str, str]] = None, + role_providers: Optional[Dict[str, str]] = None): """``unsandboxed`` is true for an agent on the local backend only: in a container (``backend``, ``image``) it is not. ``standard.options`` holds every option's value, the defaults included, so two runs read side by side @@ -641,6 +642,8 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str ``exchanges`` and ``exchanges_max_mb``: what each unit's relay kept of its agent's calls (``run --exchanges``) and its bound in MB, said for every run that gives them. + ``role_providers``: by role, the provider its calls went to when not + ``provider`` (``judge_provider``, ``simulator_provider``), said only then. ``uuid``: the job's identity, made once; a run resumed into the same folder keeps the one already written when it is the same job (``job_uuid``).""" uid = job_uuid(job_dir, benchmark=bench["key"], plugged=other.get("_ref") or other["key"], model=model, @@ -651,6 +654,7 @@ def write_config(job_dir: str, *, job: str, bench: dict, other: dict, model: str "unsandboxed": granted and backend == "local", "backend": backend, **({"image": image} if image else {}), **({"boat_size": boat_size} if boat_size else {}), **({"judge": judge} if judge else {}), + **{f"{r}_provider": p for r, p in sorted((role_providers or {}).items())}, **({"simulator": simulator} if simulator else {}), **({"options": options} if options else {}), **({"benchmark_options": bench_options} if bench_options else {}), **_control(other), **_setup(other), **({"launch": launch} if launch else {}), **({"shard": shard} if shard else {}), **({"units_file": units_file} if units_file else {}), diff --git a/app/nullius/standard/runner/rerun.py b/app/nullius/standard/runner/rerun.py index abfd8e184..64129a29a 100644 --- a/app/nullius/standard/runner/rerun.py +++ b/app/nullius/standard/runner/rerun.py @@ -411,7 +411,7 @@ def chosen(job_dir: str, ids: List[str], trials: Dict[str, dict], empty: Optiona def rerun(job_dir: str, ids: List[str], *, reason: str = "", concurrency: Optional[int] = None, retries: int = 0, max_usd: Optional[float] = None, env=os.environ, say: Callable[[str], None] = print, licences=None, prices_unreachable: Optional[str] = None, root: Optional[str] = None, every_unfinished: bool = False, - count: Optional[int] = None, task_set: Optional[dict] = None) -> dict: + count: Optional[int] = None, task_set: Optional[dict] = None, role_env: Optional[dict] = None) -> dict: """Run the trials ``ids`` name (:func:`chosen`) of the ended job ``job_dir`` again, in that job. ``retries``: automatic retries of each re-run try, as a run's; ``max_usd``: the job's spending cap from now on; ``concurrency``: the job's unless given. ``root``: a catalogue folder to resolve the definitions in (the user's and the @@ -419,18 +419,19 @@ def rerun(job_dir: str, ids: List[str], *, reason: str = "", concurrency: Option result, or whose run its cap or a Stop interrupted (:func:`interrupted`). ``count`` or ``task_set``: in place of ``ids``, more of the planned tasks not yet run (:func:`more`). Returns the record added to the job's ``reruns`` (``halted`` beside it when the run stopped as ``Run.halted`` says), or {"job", "trials": []} - with nothing written when there is no such trial; ``run.Refused`` before anything moves.""" + with nothing written when there is no such trial; ``run.Refused`` before anything moves. ``role_env``: where + the judge's and the user simulator's own providers, as the job recorded them, are read (``run.Run``).""" job_dir = os.path.abspath(job_dir.rstrip("/")) if not os.path.isdir(job_dir): raise run.Refused(f"{job_dir}: not a job of the Nullius standard (no config.json naming it)") with _hold(job_dir): return _prepare(job_dir, ids, reason=reason, concurrency=concurrency, retries=retries, max_usd=max_usd, env=env, say=say, licences=licences, prices_unreachable=prices_unreachable, root=root, - every_unfinished=every_unfinished, count=count, task_set=task_set) + every_unfinished=every_unfinished, count=count, task_set=task_set, role_env=role_env) def _prepare(job_dir, ids, *, reason, concurrency, retries, max_usd, env, say, licences, - prices_unreachable, root, every_unfinished, count, task_set) -> dict: + prices_unreachable, root, every_unfinished, count, task_set, role_env=None) -> dict: """Read and validate the job while holding its lock, so all decisions use the same completed state.""" cfg, old = merge._read(os.path.join(job_dir, "config.json")), merge._read(os.path.join(job_dir, "result.json")) if cfg.get("runner") != "standard" or not isinstance(cfg.get("standard"), dict): @@ -489,7 +490,9 @@ def _prepare(job_dir, ids, *, reason, concurrency, retries, max_usd, env, say, l prices_unreachable=prices_unreachable, constraints=std.get("constraints") or None, timeouts=std.get("timeouts") or None, max_turns=std.get("max_turns"), max_calls=std.get("max_calls"), served_by=std.get("served_by") or None, reasoning=std.get("reasoning") or None, - exchanges=std.get("exchanges") or exchange_store.DEFAULT, exchanges_max_mb=std.get("exchanges_max_mb") or exchange_store.MAX_MB) + exchanges=std.get("exchanges") or exchange_store.DEFAULT, exchanges_max_mb=std.get("exchanges_max_mb") or exchange_store.MAX_MB, + judge_provider=std.get("judge_provider") or None, simulator_provider=std.get("simulator_provider") or None, + role_env=role_env) # each trial's unit, its place and its attempt, as the runner named it; the try it is run again as. # ``fresh``: a trial with no folder, begun now as the try after those kept (none, for a task never begun) work, first_try, fresh = [], {}, {} diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index d063cb598..f8e8e4179 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -756,7 +756,9 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas constraints: Optional[dict] = None, timeouts: Optional[dict] = None, max_turns: Optional[int] = None, max_calls: Optional[int] = None, served_by: Optional[Dict[str, List[str]]] = None, boat_size: str = boat.SIZE, relay_container: bool = False, exchanges: str = exchange_store.DEFAULT, - exchanges_max_mb: int = exchange_store.MAX_MB, reasoning: Optional[Dict[str, str]] = None): + exchanges_max_mb: int = exchange_store.MAX_MB, reasoning: Optional[Dict[str, str]] = None, + judge_provider: Optional[str] = None, simulator_provider: Optional[str] = None, + role_env: Optional[Dict[str, dict]] = None): """``proving``: the run is a conformance kit's, the one run that may start before the port it checks is proven - the family must still match. ``unsandboxed``: consent to execute code as the user: required for @@ -846,7 +848,11 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas (``exchanges``): ``whole``, the request as sent and the reply as it arrived; ``text``, without the pictures' bytes; ``off``, the call record alone. ``exchanges_max_mb``: a unit's bound on it, in MB. The - job's config records both.""" + job's config records both. + ``judge_provider``, ``simulator_provider``: the provider the judge's and the + user simulator's routes call, by default ``provider``; its key and endpoint + read from ``role_env`` by role, else ``env``. The job's config records each + that is not ``provider``.""" backend = definitions.names.backend(backend) if backend not in BACKENDS: raise Refused(f"backend {backend!r} is not one of {list(BACKENDS)}") @@ -922,12 +928,19 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas if other.get("_kind") != "control": raise Refused(f"{bench.get('label') or bench['key']}'s official judge, {j['model']}, is retired: name another with --judge-model") j = None - self.judge_model = ((judge_model or providers.official_as(j, provider)) if j + # each role's own provider, when the run names one that is not the agent's (or reads it from elsewhere) + role_env = dict(role_env or {}) + asked = {r: p for r, p in (("judge", judge_provider), ("simulator", simulator_provider)) + if p and (p != provider or r in role_env)} + self.judge_model = ((judge_model or providers.official_as(j, asked.get("judge", provider))) if j else judge_model or None if (bench.get("score") or {}).get("experiment_judge") else None) # A benchmark whose user a model plays: its driver's turns ask that model the same way, on -simulator. # A control holds no conversation, so it never asks it. sim = bench.get("simulator") - self.simulator_model = (simulator_model or providers.official_as(sim, provider)) if sim else None + self.simulator_model = (simulator_model or providers.official_as(sim, asked.get("simulator", provider))) if sim else None + for role, p in asked.items(): + if not getattr(self, role + "_model"): + raise Refused(f"--{role}-provider: {bench['label']} has no {'judge' if role == 'judge' else 'user simulator'}") # A control (definitions.control) calls no model: its run needs a key only for the benchmark's judge. ds = [d for d in bench["datasets"] if dataset in (None, d["id"])] if not ds: @@ -1012,8 +1025,10 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas if bad: raise Refused("--served-by: " + "; ".join(bad)) self.serving = {m: list(s) for m, s in self.serving.items()} - if provider != "openrouter": - raise Refused(f"--served-by: {provider} serves each model itself, with no serving providers to choose " + own = {getattr(self, r + "_model"): p for r, p in asked.items()} + serving = sorted({own.get(m, provider) for m in self.serving} - {"openrouter"}) + if serving: + raise Refused(f"--served-by: {', '.join(serving)} serves each model itself, with no serving providers to choose " "among; the option needs a provider that routes a model to several (openrouter)") # a control calls no model of its own and plays no user: only its judge and an option's models called = ([m for m in (self.judge_model, self.embed_model, self.rerank_model) if m] if other.get("_kind") == "control" @@ -1037,6 +1052,15 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas self.base, self.key = (None, None) if keyless else provider_endpoint(provider, env) self.provider_env = env # where the provider's model list is asked (``known_models``) self.key_header = "authorization" if keyless else key_header(provider, other, env) + # by role, its own provider: (base, key) its relay routes call (``relay.Relay``'s upstreams), and where it is read + self.role_providers, self.role_env, self.upstreams = {}, {}, {} + for role, p in asked.items(): + if role == "simulator" and other.get("_kind") == "control": + continue # a control plays no user: its provider is never called + e = role_env.get(role, env) + self.upstreams[role] = provider_endpoint(p, e) + key_header(p, {"key": "the judge" if role == "judge" else "the user simulator", "model": {"apis": ["chat"]}}, e) + self.role_providers[role], self.role_env[role] = p, e self.limit, self.concurrency = limit, limits.concurrency(max(1, int(concurrency)), self.constraints) if units_file and task_set: raise Refused("a run takes its units from a file or from a task set, not both") @@ -1320,7 +1344,8 @@ def _start(self, lck, mine) -> str: repeat=self.repeat, retries=self.retries, prices=self.prices_record(), constraints=self.constraints, served_by=self.serving, reasoning=self.reasoning, timeouts=self.timeouts, max_turns=self.forced_turns, max_calls=self.max_calls, exchanges=self.exchanges, exchanges_max_mb=self.exchanges_max_mb, - simulator=self.simulator_model if self.other["_kind"] in ("agent", "upstream") and self.simulator_model else "") + simulator=self.simulator_model if self.other["_kind"] in ("agent", "upstream") and self.simulator_model else "", + role_providers=self.role_providers) # every unit once, then every unit again: a repeat cut short still has each unit's first run work = [(i, u, r) for r in range(1, self.repeat + 1) for i, u in mine] # started on some of the plan: the plan's every trial queued, the start's begun; the rest stand planned for a re-run @@ -1419,6 +1444,7 @@ def run_units(self, work: list, write: Callable[[List[dict], Optional[dict]], No self._cut: List[str] = [] # units the spending cap cut off self._over: List[str] = [] # units that reached their own cap: cut off there, the run going on self.loopback = None + self.loopbacks: Dict[str, container.Loopback] = {} # by role, a door to its own provider on this machine's loopback 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 @@ -1449,6 +1475,9 @@ def work_unit(iur): # a model server on this machine's loopback, which the relays' containers cannot reach as written if (self.backend == "container" or self.relay_container) and self.base and container.on_loopback(self.base): self.loopback = container.Loopback(self.base, image=self.image, job=self.name).start() + for role, (base, _) in self.upstreams.items(): + if (self.backend == "container" or self.relay_container) and container.on_loopback(base): + self.loopbacks[role] = container.Loopback(base, image=self.image, job=self.name, role=role).start() for iur in work: futures.append(pool.submit(work_unit, iur) if first is None else pool.submit(first, iur, work_unit)) pending = set(futures) @@ -1483,6 +1512,8 @@ def work_unit(iur): self.boat.close() if self.loopback is not None: self.loopback.stop() + for door in self.loopbacks.values(): + door.stop() budget = self.budget([self.attempt_name(u, r) for n, (_, u, r) in enumerate(work) if n >= len(begun) or not begun[n]]) self.capped = bool(budget and budget["stopped"]) write(results, budget) @@ -2273,19 +2304,25 @@ def known_models(self) -> None: would be refused the same way. A list that cannot be read checks nothing; the first refusals then stop the run (``note_refusal``). A name's ``:suffix`` (OpenRouter's ``:nitro``, ``:floor``) routes the - model it follows.""" + model it follows. A role's own provider (``role_providers``) is asked + for that role's model alone.""" if not self.base: return - try: - listed = {m["id"] for m in providers.list_models( - self.provider, getattr(self, "provider_env", os.environ), - include_embeddings=bool(getattr(self, "embed_model", None)))} - except ValueError: - return - unknown = [m for m in self.models_called() if m not in listed and m.rpartition(":")[0] not in listed] - if listed and unknown: - raise Refused(f"{providers.label(self.provider, getattr(self, 'provider_env', os.environ))} lists no model " - f"{', '.join(unknown)}: check the name") + own = {getattr(self, r + "_model", None): r for r in getattr(self, "role_providers", {})} + asked: Dict[tuple, List[str]] = {} + for m in self.models_called(): + role = own.get(m) + asked.setdefault((self.role_providers[role], role) if role else (self.provider, ""), []).append(m) + for (provider, role), models in asked.items(): + env = self.role_env[role] if role else getattr(self, "provider_env", os.environ) + try: + listed = {m["id"] for m in providers.list_models( + provider, env, include_embeddings=not role and bool(getattr(self, "embed_model", None)))} + except ValueError: + continue + unknown = [m for m in models if m not in listed and m.rpartition(":")[0] not in listed] + if listed and unknown: + raise Refused(f"{providers.label(provider, env)} lists no model {', '.join(unknown)}: check the name") def models_called(self) -> List[str]: """Every model this run's relays may send a call to, as sent: the @@ -2313,23 +2350,29 @@ def unit_relay(self, tag: str, trial: str, setup: dict, env_def: Optional[dict] "reasoning": getattr(self, "reasoning", None)} side = tuple((self.other.get("model") or {}).get("side_models") or ()) key_header = self.key_header + upstreams = getattr(self, "upstreams", {}) if self.backend in ("local", "boat") and not getattr(self, "relay_container", False): # boat: the agent reaches it through its VM's tunnel rl = relay.Relay(self.base, self.key, record, prices=getattr(self, "prices", None), model=self.model, side_models=side, key_header=key_header, ledger=self.ledger_file(), serving=getattr(self, "serving", None), - timeout=self.call_seconds, max_calls=self.max_calls, **keep).start() + timeout=self.call_seconds, max_calls=self.max_calls, upstreams=upstreams, **keep).start() rl.unit_url = rl.url(tag) return rl routes = {tag + "-judge": self.judge_model} if self.judge_model else {} if self.simulator_model: routes[tag + "-simulator"] = self.simulator_model + # each role's own provider as the relay's container reaches it: through its door when on this machine's loopback + doors_of = getattr(self, "loopbacks", {}) + upstreams = {r: (doors_of[r].base if r in doors_of else b, k) for r, (b, k) in upstreams.items()} + role_hosts = {n: ip for d in doors_of.values() for n, ip in d.hosts.items()} if getattr(self, "relay_container", False): door = getattr(self, "loopback", None) rl = container.Unit(self.name, tag, record, image=self.image, app=APP, base=door.base if door else self.base, key=self.key, model=self.model, routes=routes, side_models=side, key_header=key_header, prices=price_list.given(self.models_called(), getattr(self, "prices", None)), - hosts=door.hosts if door else None, ledger=self.ledger_file(), - serving=self.serving, max_calls=self.max_calls, timeout=self.call_seconds, **keep).start() + hosts={**(door.hosts if door else {}), **role_hosts} or None, ledger=self.ledger_file(), + serving=self.serving, max_calls=self.max_calls, timeout=self.call_seconds, + upstreams=upstreams, **keep).start() rl.unit_url = rl.url(tag) # driver and agent run on this host, outside the relay container return rl doors, listeners = [], [] @@ -2354,8 +2397,8 @@ def unit_relay(self, tag: str, trial: str, setup: dict, env_def: Optional[dict] rl = container.Unit(self.name, tag, record, image=self.image, app=APP, base=door.base if door else self.base, key=self.key, model=self.model, routes=routes, side_models=side, key_header=key_header, prices=price_list.given(self.models_called(), getattr(self, "prices", None)), # a sidecar's argv: its models' rows - servers=self.agent_servers(env_def), doors=doors, hosts=door.hosts if door else None, - ledger=self.ledger_file(), serving=getattr(self, "serving", None), max_calls=self.max_calls, + servers=self.agent_servers(env_def), doors=doors, hosts={**(door.hosts if door else {}), **role_hosts} or None, + ledger=self.ledger_file(), serving=getattr(self, "serving", None), max_calls=self.max_calls, upstreams=upstreams, **keep, timeout=self.call_seconds if self.call_seconds != relay.TIMEOUT else None, network_probe=probe, probe_now=bool(probe) and self.first_probe()) rl.mcp_listeners = listeners diff --git a/app/tests/test_standard_recipe.py b/app/tests/test_standard_recipe.py index a4ab1e494..b270ab0ed 100644 --- a/app/tests/test_standard_recipe.py +++ b/app/tests/test_standard_recipe.py @@ -467,6 +467,11 @@ def test_the_handed_key_is_named_as_the_providers_own_and_nothing_else_is_kept(s self.assertEqual(cli.run_env("openrouter", env), {"OPENROUTER_API_KEY": "sk-handed", "PATH": "/bin"}) self.assertEqual(cli.run_env("custom", env), {"MODEL_API_KEY": "sk-handed", "MODEL_API_URL": "http://127.0.0.1:9/v1", "PATH": "/bin"}) self.assertEqual(cli.run_env("openai", env), {"OPENAI_API_KEY": "sk-handed", "PATH": "/bin"}) + # a role's own provider, handed under its own names: never the agent's key + env.update(NULLIUS_JUDGE_API_KEY="sk-judge", NULLIUS_JUDGE_BASE_URL="http://127.0.0.1:8/v1") + self.assertEqual(cli.run_env("custom", env, "judge"), {"MODEL_API_KEY": "sk-judge", "MODEL_API_URL": "http://127.0.0.1:8/v1", "PATH": "/bin"}) + self.assertEqual(cli.role_env({"judge": "openai", "simulator": None}, True, env), {"judge": {"OPENAI_API_KEY": "sk-judge", "PATH": "/bin"}}) + self.assertEqual(cli.role_env({"judge": "openai"}, False, env), {}) def test_the_boat_key_handed_to_a_run_on_boat_is_kept(self): # on a host, the key handed over stdin is the run's only one: no store there holds it diff --git a/app/tests/test_standard_served_by.py b/app/tests/test_standard_served_by.py index fcaacd73c..c4ec8d037 100644 --- a/app/tests/test_standard_served_by.py +++ b/app/tests/test_standard_served_by.py @@ -576,6 +576,25 @@ def test_a_run_without_the_option_sends_records_and_ends_as_before(self): self.assertEqual(c["reply"]["error"], {"code": 502, "message": "Provider returned error"}) self.assertNotIn("routing", c["request"]) + def test_a_judge_on_its_own_provider_is_named_listed_and_called_there_with_its_own_key(self): + judged = dict(self.b, score=dict(self.b["score"], judge={"model": "gpt-4o-mini", "says": "a judge"})) + own = {"judge_provider": "custom", "role_env": {"judge": {"MODEL_API_URL": self.base, "MODEL_API_KEY": "sk-judge"}}} + r = self.make(bench=judged, served_by={"m-1": ["prov-a"]}, **own) + # the official judge as its own provider names it, not OpenRouter's openai/gpt-4o-mini + self.assertEqual((r.judge_model, r.upstreams, r.role_providers), ("gpt-4o-mini", {"judge": (self.base, "sk-judge")}, {"judge": "custom"})) + asked = [] + with mock.patch.object(run.providers, "list_models", lambda p, env, **kw: asked.append((p, env.get("MODEL_API_KEY"))) or [{"id": "m-1"}, {"id": "gpt-4o-mini"}]): + r.known_models() + self.assertEqual(asked, [("openrouter", None), ("custom", "sk-judge")]) + rl = r.unit_relay("u0", os.path.join(self.tmp, "trial"), {}) + self.relays.append(rl) + post(rl.url("u0-judge", model=r.judge_model) + "/chat/completions", {"model": "asked", "messages": []}) + self.assertEqual((self.sent()["model"], Upstream.seen[-1][1]["authorization"]), ("gpt-4o-mini", "Bearer sk-judge")) + for kw, said in (({"served_by": {"gpt-4o-mini": ["prov-c"]}}, "custom serves each model itself"), + ({"simulator_provider": "custom"}, "has no user simulator")): + with self.subTest(kw=kw), self.assertRaisesRegex(run.Refused, said): + self.make(bench=judged, **{**own, **kw}) + def test_the_summary_counts_every_route_of_the_unit(self): """A judge on the pinned model, served by another provider than the agent's: the pin does not hold.""" r = self.make(judge_model="m-1", served_by={"m-1": ["prov-a"]}) From 02786d75da2d3f45b759b907fa012a725212ac04 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 16:27:33 +0100 Subject: [PATCH 04/11] feat(standard): compile a recipe's judge and simulator providers --- app/nullius/standard/pages/recipe.py | 51 +++++++++++++++------ app/tests/test_standard_recipe_served_by.py | 21 +++++++++ 2 files changed, 59 insertions(+), 13 deletions(-) diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 110216438..693335722 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -471,6 +471,10 @@ def compile(recipe: dict, defs: Optional[Dict[str, List[dict]]] = None, *, names have no price in the user's list (``nullius.prices``): a run with a cap is refused without one. + ``judge_provider``, ``simulator_provider``: a provider of that role's own, + as the Model step names one (``providers.choice``), compiled into + ``--judge-provider``, ``--simulator-provider``; empty or the agent's, + the agent's. ``roles`` says which a job calls, for the run's keys. ``served_by``: on OpenRouter, the serving providers each model field pins, ``{model|simulator|judge: [slug, ...]}``, checked as ``--served-by`` is and compiled into it for each job that calls that model, by the name @@ -486,7 +490,7 @@ def add(step, message, shown=False, field=None, unset=False): if not any(e["step"] == STEP[step] and e["message"] == message for e in errors): errors.append({"step": STEP[step], "message": message, **({"shown": True} if shown else {}), **({"field": field} if field else {}), **({"unset": True} if unset else {})}) out = {"errors": errors, "notes": notes, "review": [], "jobs": [], "confirm": "", "script": "", "parts": [], "model": "", - "served_models": {}, "own_reasoning": {}} + "served_models": {}, "own_reasoning": {}, "roles": {}} name = str(recipe.get("name") or "") if not _NAME.match(name): add("limits", "The recipe's name may hold letters, digits, dots, dashes and underscores.") @@ -746,6 +750,17 @@ def add(step, message, shown=False, field=None, unset=False): provider = recipe.get("provider") if provider not in PROVIDERS: add("model", CHOOSE_PROVIDER) + # the judge's and the user simulator's own providers, by role; one not named, or the agent's, is the agent's + agent_choice = providers.choice(str(provider or ""), str(recipe.get("endpoint") or "")) + role_choice: Dict[str, str] = {} + for role_ in ("judge", "simulator"): + c_ = str(recipe.get(role_ + "_provider") or "") + if c_ and c_ != agent_choice: + if providers.split(c_)[0] in PROVIDERS: + role_choice[role_] = c_ + else: + add("model", f"Choose the {SERVED_LABEL[role_]}'s provider: Same as agent, or one of the providers.") + prov = lambda role: providers.split(role_choice[role])[0] if role in role_choice else provider_ # what each part asks of the provider, as the builder reads it (command-builder-core.js, consumersOf): an agent its # apis, a setup chat; a judged benchmark's judge chat for pk in picks if provider in PROVIDERS else (): @@ -755,8 +770,10 @@ def add(step, message, shown=False, field=None, unset=False): judge_model = str(recipe.get("judge_model") or "").strip() # the judge the run asks: the official one, or an experiment judge whose model the recipe names judges = bool((b.get("score") or {}).get("judge") or (judge_model and (b.get("score") or {}).get("experiment_judge"))) - if provider in PROVIDERS and judges and provider not in providers.offered(["chat"]): - add("model", f"{providers.label(provider)} does not serve what {b['label']}'s judge speaks: choose another provider.") + for role_, used_ in (("judge", judges), ("simulator", bool(b.get("simulator")) and any(not p["control"] for p in picks))): + on_ = prov(role_) + if on_ in PROVIDERS and used_ and on_ not in providers.offered(["chat"]) and (role_ == "judge" or role_ in role_choice): + add("model", f"{providers.label(role_choice.get(role_, on_))} does not serve what {b['label']}'s {SERVED_LABEL[role_]} speaks: choose another provider.") model = str(recipe.get("model") or "").strip() if not _MODEL.match(model) and (needs_model or model): add("model", "Choose a model or enter its ID.", unset=not model) @@ -782,14 +799,14 @@ def add(step, message, shown=False, field=None, unset=False): for what, role, m in (("the user simulator's", "simulator", sim_model), ("the judge's", "judge", judge_model)): if m and not _MODEL.match(m): add("model", f"Enter {what} model as the provider lists it, or leave it empty for its official one.") - elif m and like and m not in (fixed[role], providers.served_as(fixed[role], provider_), - providers.official_as({"model": fixed[role], **({} if lb.get(role) else spec[role] or {})}, provider_)): + elif m and like and m not in (fixed[role], providers.served_as(fixed[role], prov(role)), + providers.official_as({"model": fixed[role], **({} if lb.get(role) else spec[role] or {})}, prov(role))): add("model", f"{like} uses {what} model {fixed[role]}: choose Any of your choice for {m}.") if ((b.get("score") or {}).get("judge") or {}).get("retired") and not judge_model and not like: add("model", f"{b['label']}'s official judge, {official['judge']}, is retired: enter a model for the judge.") # the leaderboard's own models, as the run's provider spells them; the official ones stay the run's default - sim_model = providers.served_as(lb["simulator"], provider_) if lb.get("simulator") else sim_model - judge_model = providers.served_as(lb["judge"], provider_) if lb.get("judge") else judge_model + sim_model = providers.served_as(lb["simulator"], prov("simulator")) if lb.get("simulator") else sim_model + judge_model = providers.served_as(lb["judge"], prov("judge")) if lb.get("judge") else judge_model # served_by is {model|simulator|judge: [slug, ...]}; an empty list pins nothing roles = {"model": "the model", "simulator": "the user simulator's model", "judge": "the judge's model"} pins = recipe.get("served_by") @@ -801,7 +818,7 @@ def add(step, message, shown=False, field=None, unset=False): served = {k: v for k, v in pins.items() if v not in (None, [], "")} for problem in relay.serving_problems({roles[k]: v for k, v in served.items()}): add("model", "Served by " + problem + ".") - if served and provider_ != "openrouter": + if any(prov(r) != "openrouter" for r in served): add("model", "Served by needs OpenRouter, the provider that routes a model to several: choose it, or leave Served by empty.") # reasoning is {model|simulator|judge: level}, one of the levels the builder asked the model for (relay.LEVELS) asked_levels = recipe.get("reasoning") @@ -939,8 +956,8 @@ def add(step, message, shown=False, field=None, unset=False): judge, sim = (b.get("score") or {}).get("judge"), b.get("simulator") called = [m for x in dss for p in picks for m in ledger.models( p["o"], None if p["control"] else (p["o"].get("sent") or p.get("model")) if p.get("setup") else model, - (judge_model or providers.official_as(judge, provider)) if judge else judge_model if judges else None, - (sim_model or providers.official_as(sim, provider)) if sim else None, + (judge_model or providers.official_as(judge, prov("judge"))) if judge else judge_model if judges else None, + (sim_model or providers.official_as(sim, prov("simulator"))) if sim else None, providers.served_as((definitions.option_needs(b, per_ds[x["id"]])["embeddings"] or [""])[0], provider), control=p["control"])] called += [providers.served_as(m, provider) for m in needs["reranker"]] missing = unpriced([m for m in dict.fromkeys(called) if isinstance(m, str) and m]) @@ -956,8 +973,8 @@ def add(step, message, shown=False, field=None, unset=False): def sent_of(p: dict) -> Dict[str, Optional[str]]: """Each model field's model as job ``p`` sends it; None where it has none (a control has no model of its own).""" return {"model": None if p["control"] else (p["o"].get("sent") or p.get("model")) if p.get("setup") else model, - "judge": (judge_model or providers.official_as(judge_def, provider)) if judge_def else judge_model if judges else None, - "simulator": (sim_model or providers.official_as(sim_def, provider)) if sim_def else None} + "judge": (judge_model or providers.official_as(judge_def, prov("judge"))) if judge_def else judge_model if judges else None, + "simulator": (sim_model or providers.official_as(sim_def, prov("simulator"))) if sim_def else None} def called_of(p: dict) -> List[str]: s = sent_of(p) @@ -1024,6 +1041,9 @@ def pinned(p: dict) -> Dict[str, List[str]]: add("model", f"Served by: no job of this recipe calls {roles[role]}; leave it empty.") if errors: return out + # the roles whose own provider a job calls: their keys are the run's too (execution.Plan.roles) + out["roles"] = {r: c for r, c in role_choice.items() + if (judges if r == "judge" else bool(b.get("simulator")) and any(not p["control"] for p in picks))} nouns = bench_nouns = (b.get("units") or {}).get("nouns", "units") # a dataset's count is always the benchmark's if picks and all(p.get("setup") for p in picks): # only setups: a unit is theirs (a conversation) nouns = picks[0]["o"]["units"]["nouns"] @@ -1074,7 +1094,9 @@ def command_for(d: dict, p: dict, index: int) -> str: *(["--exchanges", keep] if keep != exchanges.DEFAULT else []), *(["--exchanges-max-mb", str(keep_mb)] if keep_mb != exchanges.MAX_MB else []), *(["--simulator-model", sim_model] if sim_model and not p["control"] else []), + *(["--simulator-provider", prov("simulator")] if "simulator" in out["roles"] and not p["control"] else []), *(["--judge-model", judge_model] if judge_model else []), + *(["--judge-provider", prov("judge")] if "judge" in out["roles"] else []), "--name", job_of(d, p, index), *[w for k, v in given.items() for w in ("--option", f"{k}={v}")], *(["--backend", backend] if backend != "local" else []), *(["--boat-size", boat_size] if backend == "boat" and (whole or not control and not p.get("setup")) else []), @@ -1091,7 +1113,8 @@ def script_for(d: dict, p: dict, command: str, index: int) -> str: + (f": shard {index} of {of}.\n" if of > 1 else ".\n") + "# Uses installed nullius or --app PATH ($NULLIUS_STANDARD for an execution payload). The key and\n" "# endpoint come from the run's environment: OPENAI_API_KEY, and OPENAI_BASE_URL for an endpoint\n" - "# other than the provider's own.\n" + "# other than the provider's own; a judge's or user simulator's own provider, NULLIUS__API_KEY\n" + "# and NULLIUS__BASE_URL.\n" + _script(command)) out["shards"] = [] @@ -1198,8 +1221,10 @@ def row(p: dict) -> list: [STEP["model"], "Model", "none: a control calls no model" if out["keyless"] else f"{providers.label(providers.choice(provider, str(recipe.get('endpoint') or '')))} · " + (model if needs_model else ", ".join(p["o"]["sent"] for p in picks if p.get("setup")) or "the judge only") + (f" · user simulator {sim_model or (b.get('simulator') or {}).get('model')}" + (" (leaderboard)" if lb.get("simulator") else "" if sim_model else " (official)") if b.get("simulator") else "") + + (f" on {providers.label(out['roles']['simulator'])}" if "simulator" in out["roles"] else "") + (f" · judge {judge_model or b['score']['judge']['model']}" + ("" if judge_model else " (official)") if (b.get("score") or {}).get("judge") else "") + (f" · {b['score']['experiment_judge']['label']} {judge_model} (experiment)" if judges and not (b.get("score") or {}).get("judge") else "") + + (f" on {providers.label(out['roles']['judge'])}" if "judge" in out["roles"] else "") + "".join(f" · {SERVED_LABEL[r_]} served by {', '.join(s)}" for r_, s in served.items()) + "".join(f" · {SERVED_LABEL[r_]} reasoning {', '.join(out['own_reasoning'][r_])} ({'the agent' if r_ == 'model' else 'the benchmark'}'s)" if r_ in out["own_reasoning"] else f" · {SERVED_LABEL[r_]} reasoning {levels[r_]}" diff --git a/app/tests/test_standard_recipe_served_by.py b/app/tests/test_standard_recipe_served_by.py index 63d188e59..7f0f28768 100644 --- a/app/tests/test_standard_recipe_served_by.py +++ b/app/tests/test_standard_recipe_served_by.py @@ -70,6 +70,27 @@ def test_each_job_is_pinned_where_it_calls_the_model(self): for part in out["parts"]: self.assertIn("--served-by openai/gpt-4o-mini=prov-a", part["script"]) + def test_a_judge_on_its_own_provider_is_named_spelled_and_pinned_by_it(self): + d = defs(judged()) + r = a_recipe(provider="openai", model="gpt-5-mini", judge_provider="openrouter", served_by={"judge": ["prov-j"]}) + out = recipe.compile(r, d) + self.assertEqual(out["errors"], []) + self.assertEqual(out["roles"], {"judge": "openrouter"}) + self.assertIn("--provider openai ", out["script"]) + self.assertIn("--judge-provider openrouter", out["script"]) + self.assertIn("--served-by openai/gpt-4o-mini=prov-j", out["script"]) # the official judge, as OpenRouter names it + self.assertIn("judge gpt-4o-mini (official) on OpenRouter", next(row[2] for row in out["review"] if row[1] == "Model")) + for same in ({}, {"judge_provider": ""}, {"judge_provider": "openai"}): # a recipe from before, or the agent's own + plain = recipe.compile(a_recipe(provider="openai", model="gpt-5-mini", **same), d) + self.assertEqual((plain["errors"], plain["roles"]), ([], {})) + self.assertNotIn("--judge-provider", plain["script"]) + for kw, said in (({"judge_provider": "anthropic"}, "does not serve what Fake bench's judge speaks"), + ({"judge_provider": "nowhere"}, "Choose the judge's provider"), + ({"served_by": {"model": ["a"]}}, "needs OpenRouter")): + with self.subTest(kw=kw): + bad = recipe.compile(a_recipe(**{**r, **kw}), d) + self.assertTrue(any(said in e["message"] for e in bad["errors"]), bad["errors"]) + def test_a_pin_is_refused_as_the_option_is(self): for kw, said in (({"provider": "openai", "model": "gpt-5-mini", "served_by": {"model": ["deepinfra"]}}, "needs OpenRouter"), ({"served_by": {"model": ["bad slug"]}}, "not a serving provider's slug"), From f3fd2ee5b68e6dcba88649e9535877052c073f7c Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 16:27:33 +0100 Subject: [PATCH 05/11] feat(execution): hand a run the keys of the providers it uses --- app/nullius/execution.py | 35 +++++++++++++++++++++++++++++------ app/tests/test_execution.py | 15 +++++++++++++++ app/web/api.py | 4 ++-- app/web/builder.py | 10 ++++++---- app/web/execute.py | 21 +++++++++++++++++++-- 5 files changed, 71 insertions(+), 14 deletions(-) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index e4e9da758..0c6c6c7b8 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -78,6 +78,9 @@ optional: without it the run is sent ``settings.MODEL_KEY_PLACEHOLDER``, for a server that checks no key - and a run without that endpoint fails before it starts. +A standard recipe whose judge or user simulator has a provider of its own +(``Plan.roles``) is handed that provider's key and endpoint too, as +``providers.role_vars`` names them, and those of no other provider. They are read on this machine and handed to the run as environment (API_TOKEN, OPENAI_API_KEY, LLM_API_KEY; API_URL, OPENAI_BASE_URL, LLM_BASE_URL) - over stdin to the launcher, never in argv (the key to a @@ -134,6 +137,7 @@ # The names the launcher gives a run's key and its endpoint (_launch), read # from stdin: the only credentials a run's commands get. KEY_NAMES = ("API_TOKEN", "OPENAI_API_KEY", "LLM_API_KEY") +ROLES = ("judge", "simulator") # the standard's roles a provider of their own may serve (``Plan.roles``) URL_NAMES = ("API_URL", "OPENAI_BASE_URL", "LLM_BASE_URL") # The line the launcher's stdin ends with, after the key and the endpoint: # either may be empty, so only this line says the two arrived whole. @@ -261,6 +265,7 @@ class Plan: keyless: bool = False # nothing in it calls a model (the standard's controls): handed no key and no endpoint at all licences: dict = field(default_factory=dict) # the standard's on a host: {"benchmark", "names", "providers"} - what it is sent of that benchmark's licences caps: dict = field(default_factory=dict) # a job's spending cap set on its page, {job: USD}: it holds from the job's next run + roles: dict = field(default_factory=dict) # by role, its own provider's {key_var, url_var, base_url}: the standard's judge or user simulator def steps(self) -> List[dict]: return [p for p in self.parts if p.get("script")] or [{"id": "run", "label": "the run", "script": self.script}] @@ -340,7 +345,8 @@ def withheld() -> List[str]: run gets its own endpoint's key alone. A data provider's token name is not one.""" secret = {v.name for v in settings.VARIABLES if v.secret or v.kind in ("endpoint", "provider")} | set(settings.endpoint_names()) return sorted(secret | {old for old, new in settings.INSTEAD.items() if new in secret} - | set(KEY_NAMES + URL_NAMES) | {"GITHUB_TOKEN", "GH_TOKEN", "BOAT_API_KEY"} | set(settings.agent_key_names()) + | set(KEY_NAMES + URL_NAMES) | {n for r in ROLES for n in providers.role_vars(r)} + | {"GITHUB_TOKEN", "GH_TOKEN", "BOAT_API_KEY"} | set(settings.agent_key_names()) | set(_licence_names())) @@ -448,6 +454,14 @@ def _credentials(self, key: Optional[str], url: Optional[str], env, agent_keys: self._url = url if url is not None else (providers.base_of(plan.url_var, env) if plan.url_var else plan.base_url) if plan.keyless: # a run that calls no model is given nothing it could leak self._key, self._url = "", "" + # each role's own provider, as the launcher hands it: {name: value}, names from providers.role_vars + self._roles: Dict[str, str] = {} + for role, c in sorted((plan.roles or {}).items()): + if role not in ROLES or plan.keyless: + continue + k, u = providers.role_vars(role) + self._roles[k] = env.get(c.get("key_var", ""), "") or (settings.MODEL_KEY_PLACEHOLDER if c.get("url_var") else "") + self._roles[u] = providers.base_of(c["url_var"], env) if c.get("url_var") else c.get("base_url", "") # the agent keys Settings holds (CURSOR_API_KEY, ...): a Harbor run's agent may need its own vendor's; the standard's never gets one self._agent_keys = dict(agent_keys) if agent_keys is not None else (settings.agent_key_values(env) if plan.runner == "harbor" else {}) if plan.runner == "standard" and (plan.recipe or {}).get("backend") == "boat": @@ -506,8 +520,9 @@ def log(self, line: str) -> None: if line.startswith("** ") and ("post-quantum" in line or "store now, decrypt later" in line or "openssh.com/pq" in line): return # ssh's own warning about the host's key exchange, not the run's clean = redact.redact(line.rstrip("\n")) - if self._key and self._key != settings.MODEL_KEY_PLACEHOLDER: # the placeholder is no secret, and a common word - clean = clean.replace(self._key, "[REDACTED]") + for key in (self._key, *(v for n, v in self._roles.items() if n.endswith("_KEY"))): + if key and key != settings.MODEL_KEY_PLACEHOLDER: # the placeholder is no secret, and a common word + clean = clean.replace(key, "[REDACTED]") for value in list(self._agent_keys.values()) + self._redact: if len(value) >= 8: clean = clean.replace(value, "[REDACTED]") @@ -804,6 +819,12 @@ def _missing(self) -> Optional[str]: return f"{self.plan.key_var} is not set in Settings; the producers and the judge would have no model key" if not self._url and self.plan.url_var and not self.plan.keyless and (harbor_model or self.plan.runner != "harbor"): return f"{self.plan.url_var} is not set in Settings; an OpenAI-compatible endpoint has no default, so the run would have nowhere to send its calls" + for role, c in sorted((self.plan.roles or {}).items()): + k, u = providers.role_vars(role) + if k in self._roles and not self._roles[k]: + return f"{c.get('key_var')} is not set in Settings; the {role} would have no model key" + if k in self._roles and not self._roles[u] and c.get("url_var"): + return f"{c['url_var']} is not set in Settings; the {role}'s endpoint has no default" return self._line_break() def again(self, part: dict, env=os.environ) -> "Execution": @@ -1471,11 +1492,12 @@ def _await_start(self, names: List[str], part: dict) -> Optional[tuple]: return look def _stdin(self) -> str: - """What the launcher reads: the key, the endpoint, the agent keys as - NAME=value, the benchmark's licences as one more (a standard run on a + """What the launcher reads: the key, the endpoint, the agent keys and + each role's own provider as NAME=value, the benchmark's licences as one more (a standard run on a host), the end line.""" lic = self._licence_line() return "".join(f"{line}\n" for line in [self._key, self._url, *(f"{n}={v}" for n, v in self._agent_keys.items()), + *(f"{n}={v}" for n, v in self._roles.items() if v), *([f"{secrets.HANDED}={lic}"] if lic else []), STDIN_END]) def _licence_dir(self) -> str: @@ -1524,7 +1546,8 @@ def _line_break(self) -> Optional[str]: (``_launch``), would take in pieces. Settings refuses one, so only the environment Nullius was started in can hold it. The variable is named, never its value.""" - for value, var in ((self._key, self.plan.key_var), (self._url, self.plan.url_var or "the endpoint"), *((v, n) for n, v in self._agent_keys.items())): + for value, var in ((self._key, self.plan.key_var), (self._url, self.plan.url_var or "the endpoint"), + *((v, n) for n, v in self._agent_keys.items()), *((v, n) for n, v in self._roles.items())): if "\n" in value or "\r" in value: return (f"{var} holds a line break; a key or an endpoint is one line, and the run's launcher would take this one " f"in pieces. Set it again on one line in the environment Nullius was started in (Settings refuses a line break)") diff --git a/app/tests/test_execution.py b/app/tests/test_execution.py index c103e8edd..353118c2f 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -440,6 +440,21 @@ def test_only_a_standard_run_on_boat_is_handed_the_boat_key(self): self.assertEqual(marker.read_text().strip(), f"boat={secret}" if backend == "boat" else "boat=none") self.assertNotIn(secret, "\n".join(ex.lines)) + def test_a_judge_on_its_own_provider_is_handed_that_key_alone_and_never_inherits_it(self): + secret, other = "sk-judge-0123456789abcdef", "sk-other-0123456789abcdef" + for target in ("here", "host"): + with self.subTest(target): + name = f"roles-{target}"; root = self.tmp / name; marker = root / "seen" + parts = [{"id": "a", "label": "a", "script": f'echo "judge=${{NULLIUS_JUDGE_API_KEY:-none}} ${{NULLIUS_JUDGE_BASE_URL:-none}} ' + f'sim=${{NULLIUS_SIMULATOR_API_KEY:-none}} or=${{OPENROUTER_API_KEY:-none}}" > {marker}; echo "$NULLIUS_JUDGE_API_KEY"'}] + plan = execution.Plan(name=name, script="", parts=parts) if target == "here" else self.plan(parts, name) + plan.runner, plan.roles = "standard", {"judge": {"key_var": "OPENROUTER_API_KEY", "url_var": "", "base_url": "https://openrouter.ai/api/v1"}} + with patch.dict(os.environ, {"OPENROUTER_API_KEY": secret, "NULLIUS_SIMULATOR_API_KEY": other}): + ex = self.wait(execution.Execution(plan, root=str(root), key=self.KEY, url=self.URL).start()) + self.assertEqual(ex.state, "done", ex.lines) + self.assertEqual(marker.read_text().strip(), f"judge={secret} https://openrouter.ai/api/v1 sim=none or=none") + self.assertNotIn(secret, "\n".join(ex.lines)) + def test_a_standard_run_on_a_host_is_handed_its_benchmarks_licences_and_here_none(self): # on a host: the declared names that are set, one stdin line, in the part's environment and never on disk # but for the in-memory folder a licence file is written to, which the part's shell removes when it ends; diff --git a/app/web/api.py b/app/web/api.py index be7c66d84..12de18bc2 100644 --- a/app/web/api.py +++ b/app/web/api.py @@ -452,8 +452,8 @@ def _checked(recipe: dict) -> tuple: machines = {"machines": [], "ready": False, "errors": [], "notes": []} provider, endpoint = recipe.get("provider"), recipe.get("endpoint") if not doc["errors"]: - missing = execute.provider_problem(provider, endpoint) - if missing and not standard_recipe.compile(recipe).get("keyless"): # controls alone call no model + missing = execute.providers_problem(recipe, standard_recipe.compile(recipe)) # controls alone call no model + if missing: doc["errors"].append(missing) if not doc["errors"]: choice = providers.choice(str(provider or ""), str(endpoint or "")) diff --git a/app/web/builder.py b/app/web/builder.py index 0eb9ccf27..e5bdda578 100644 --- a/app/web/builder.py +++ b/app/web/builder.py @@ -285,10 +285,12 @@ def machine(w): # one ssh probe per host, all at once: an unreachable host can hold a probe for 8–12 s with ThreadPoolExecutor(max(1, min(8, len(wheres)))) as pool: machines = list(pool.map(machine, wheres)) - # a notice, not a refusal: the provider's last test in Settings failed (providers.test) - choice = str(body.get("provider") or "") - last = providers.tests().get(choice) - notes = [f"{providers.label(choice)} failed its last test in Settings: {providers.said(last)}"] if isinstance(last, dict) and not last.get("ok") else [] + # a notice, not a refusal: a provider's last test in Settings failed (providers.test), the agent's and each role's own + tests, notes = providers.tests(), [] + for choice in dict.fromkeys([str(body.get("provider") or ""), *(str(recipe.get(r + "_provider") or "") for r in ("judge", "simulator"))]): + last = tests.get(choice) if choice else None + if isinstance(last, dict) and not last.get("ok"): + notes.append(f"{providers.label(choice)} failed its last test in Settings: {providers.said(last)}") return jsonify(machines=machines, ready=prerequisites.ready(machines), errors=[], notes=notes) diff --git a/app/web/execute.py b/app/web/execute.py index 05ee28fe8..b9d0e037b 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -114,6 +114,23 @@ def provider_problem(provider, endpoint=None) -> str: return why + " Choose " + " or ".join(providers.label(x) for x in have) + " on the Model step, or set it in Settings." +def roles_for(out: dict) -> dict: + """By role, where its own provider's key and endpoint come from (``Plan.roles``): each the compiled + recipe calls on a provider that is not the agent's (``recipe.compile``'s ``roles``).""" + return {r: credentials_for(*providers.split(c)) for r, c in (out.get("roles") or {}).items()} + + +def providers_problem(recipe: dict, out: dict) -> str: + """Why a run of the compiled recipe cannot start here on one of its providers (``provider_problem``): + the agent's, unless nothing calls a model, then each role's own.""" + for p, e in ([] if out.get("keyless") else [(recipe.get("provider"), recipe.get("endpoint"))]) \ + + [providers.split(c) for c in (out.get("roles") or {}).values()]: + why = provider_problem(p, e) + if why: + return why + return "" + + def standard_plans(recipe: dict, out: dict, known) -> tuple: """([Plan], error): one plan per machine the standard recipe's *Where* names - its shard there - each a run of its own, or the error that keeps @@ -127,7 +144,7 @@ def standard_plans(recipe: dict, out: dict, known) -> tuple: if host.entry not in known: return [], f"{sh['where']} is not one of the hosts in Settings" plans.append(execution.Plan(name=sh["name"], script=sh["script"], host=host, runner=standard_recipe.HARNESS, - **credentials_for(recipe.get("provider"), recipe.get("endpoint")), model=out["model"], jobs=sh["jobs"], + **credentials_for(recipe.get("provider"), recipe.get("endpoint")), roles=roles_for(out), model=out["model"], jobs=sh["jobs"], parts=sh["parts"], recipe=recipe, docker=bool(out.get("docker")), keyless=bool(out.get("keyless")), licences=dict(out.get("licences") or {}) if host else {})) return plans, "" @@ -144,7 +161,7 @@ def _start_standard(recipe: dict, into: str = ""): if out["errors"]: return jsonify(ok=False, error=" ".join(e["message"] for e in out["errors"])), 400 # a run of controls calls no model: it is handed no key, so none need be set - missing = "" if out.get("keyless") else provider_problem(recipe.get("provider"), recipe.get("endpoint")) + missing = providers_problem(recipe, out) if missing: return jsonify(ok=False, error=missing), 400 plans, problem = standard_plans(recipe, out, {h.entry for h in _hosts()}) From 4b9fdcba8f24aa76e9f0352abe072fda9b228d03 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 16:27:33 +0100 Subject: [PATCH 06/11] feat(builder): a line per role on the Model step, each with its provider --- app/static/builder/command-builder-core.js | 50 ++++++++++++---- app/static/builder/command-builder.css | 30 ++++++---- app/static/builder/command-builder.js | 59 +++++++++++++------ app/static/controls.js | 2 +- app/static/model-picker.js | 8 ++- .../test_command_builder_providers.py | 11 ++++ app/ui_tests/test_served_by_builder.py | 10 ++++ 7 files changed, 124 insertions(+), 46 deletions(-) diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index 57650784c..d4a1fc44f 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -120,9 +120,7 @@ // tried; a field per model the run calls - the model, the user simulator's and the judge's when the benchmark has them. const SERVED_ROLES = ['model', 'simulator', 'judge']; function servedRoles(r) { - const b = standardBench(r); - if (!b || r.provider !== 'openrouter' || standardKeyless(r)) return []; - return SERVED_ROLES.filter(k => k === 'model' || (k === 'simulator' && b.simulator) || (k === 'judge' && (b.judge || judgesRun(r)))); + return reasoningRoles(r).filter(k => kindOf(roleChoiceOf(r, k)) === 'openrouter'); } // A field's text, "deepinfra, together", as the pin's list, every part kept for the server to check ("a,,b" is // refused in sight, as the option refuses it); a field with nothing in it pins nothing. @@ -308,6 +306,7 @@ } if (PROVIDERS.includes(raw.provider)) r.provider = raw.provider; keepEndpoint(r, raw); + for (const role of ['judge', 'simulator']) if (isChoice(raw[role + '_provider'])) setRoleChoice(r, role, raw[role + '_provider']); if ((Number.isInteger(raw.limit) && raw.limit >= 1) || raw.limit === '') r.limit = raw.limit; if ((Number.isInteger(raw.concurrency) && raw.concurrency >= 1) || raw.concurrency === '') r.concurrency = raw.concurrency; // attempts per unit, retries after an error, and the judge's and user simulator's models: a reopened recipe runs as it was saved @@ -412,13 +411,13 @@ const needsOf = c => endpointOf(c) ? 'MODEL_' + endpointOf(c) + '_API_URL' : PROVIDER_NEEDS[c] || PROVIDER_NEEDS.custom; const available = () => ((schema.credentials || {}).available || []).filter(p => PROVIDERS.includes(kindOf(p))); const firstAvailable = (offered, otherwise) => available().find(p => offered.includes(p)) || otherwise; - // What each part of a run that calls the model speaks: a Harbor run and a benchmark's own scripts or judge - // chat, an agent of the standard its definition's apis. A provider is offered when it may serve every part. + // What each part of a run that calls the model speaks: a Harbor run and a benchmark's own scripts chat, an agent + // of the standard its definition's apis. A provider is offered when it may serve every part. A judge speaks chat + // too, on its own provider or, Same as agent, on the agent's (blockedRole). function consumersOf(r) { if (!isStandard(r)) return [['chat']]; const b = standardBench(r), all = standard().agents.concat(standard().modules); const out = chosenOf(r).filter(k => !((b && b.controls) || []).some(c => c.key === k)).map(k => (all.find(o => o.key === k) || {}).apis || ['chat']); - if (judgesRun(r)) out.push(['chat']); return out.length ? out : [['chat']]; } const serving = (p, apis) => !PROVIDER_INFO[p].protocols || apis.some(a => PROVIDER_INFO[p].protocols.includes(a)); @@ -427,11 +426,40 @@ const choiceOf = r => recipeProvider(r) === 'custom' && r.endpoint ? 'custom:' + r.endpoint : recipeProvider(r); // The Model step's choice into the recipe: its provider, and for a named endpoint its id. // a provider that routes no model to several takes no Served by: a pin made for OpenRouter is dropped with it - function setChoice(r, c) { r.provider = kindOf(c); keepEndpoint(r, {endpoint: endpointOf(c)}); if (r.provider !== 'openrouter') delete r.served_by; } - // Why Run cannot start this recipe here, or '': its provider is not one of those. A recipe naming one keeps it, - // said, until another is chosen - never switched behind the person's back. The server refuses the same - // (web/execute.py, provider_problem). + function setChoice(r, c) { + r.provider = kindOf(c); keepEndpoint(r, {endpoint: endpointOf(c)}); + for (const role of ['judge', 'simulator']) setRoleChoice(r, role, r[role + '_provider'] || ''); + for (const role of SERVED_ROLES) if (kindOf(roleChoiceOf(r, role)) !== 'openrouter' && r.served_by) setServed(r, role, []); + } + // A judge's or user simulator's own provider (recipe.py: judge_provider, simulator_provider), a choice as the Model + // step offers it; none, or the agent's, is the agent's. Both speak chat. Its pin goes when it leaves OpenRouter. + const isChoice = c => typeof c === 'string' && PROVIDERS.includes(kindOf(c)) && (c === kindOf(c) || (kindOf(c) === 'custom' && ENDPOINT_ID.test(endpointOf(c)))); + const ownRole = (r, role) => role !== 'model' && !!r[role + '_provider']; + const roleChoiceOf = (r, role) => ownRole(r, role) ? r[role + '_provider'] : choiceOf(r); + const roleProvidersOf = () => PROVIDERS.filter(p => serving(p, ['chat'])); + function setRoleChoice(r, role, c) { + if (!c || c === choiceOf(r) || !isChoice(c)) delete r[role + '_provider']; else r[role + '_provider'] = c; + if (kindOf(roleChoiceOf(r, role)) !== 'openrouter' && r.served_by) setServed(r, role, []); + return r; + } + // The role Run waits for, or '': one on its own provider not set here, or a judge on the agent's that serves no chat + // (recipe.py says the same). + const unserved = r => !ownRole(r, 'judge') && judgesRun(r) && PROVIDERS.includes(r.provider) && !serving(r.provider, ['chat']); + const blockedRole = r => !isStandard(r) || standardKeyless(r) ? '' : unserved(r) ? 'judge' + : schema.credentials && reasoningRoles(r).find(x => ownRole(r, x) && !available().includes(roleChoiceOf(r, x))) || ''; + // The provider Run waits for: the agent's, else that role's. + const blockedProvider = r => agentBlocker(r) || !blockedRole(r) ? choiceOf(r) : roleChoiceOf(r, blockedRole(r)); + // Why Run cannot start this recipe here, or '': one of its providers is not one of those. A recipe naming one keeps + // it, said, until another is chosen - never switched behind the person's back. The server refuses the same + // (web/execute.py, providers_problem). function providerBlocker(r) { + const role = agentBlocker(r) ? '' : blockedRole(r), c = role && roleChoiceOf(r, role); + if (!role) return agentBlocker(r); + if (!ownRole(r, role)) return labelOf(c) + ' does not serve what the judge speaks. Choose a provider for the judge on the Model step.'; + return 'The ' + (role === 'judge' ? 'judge' : 'user simulator') + ' runs on ' + labelOf(c) + ', and ' + needsOf(c) + + ' is not set in Settings. Choose another provider for it on the Model step, or set it in Settings.'; + } + function agentBlocker(r) { if (!schema.credentials || (!isStandard(r) && !needsCredentials(r))) return ''; if (isStandard(r) && standardKeyless(r)) return ''; // a control of an unjudged benchmark is handed no key (execution.Plan.keyless) const offered = providersOf(r), have = available().filter(p => offered.includes(kindOf(p))), p = choiceOf(r); @@ -980,5 +1008,5 @@ // A recipe nobody changed: Start over has nothing to ask about. A new one, or that one as a reloaded draft holds it // (fromJSON fills in what a new one leaves out). The page's own values are compared as they are: reading would drop the bad ones. const atDefaults = r => { const s = JSON.stringify(r); return s === JSON.stringify(prefill({})) || s === JSON.stringify(fromJSON(prefill({}))); }; - return {setTaskSet,keepTaskSets,setStartWith,keepStartWith,nestedDatasets,wholeOf,swapDataset,STANDARD_PHASES,STEPS,STEP,runners,RUNNER_GONE,isStandard,standard,standardBase,standardBench,standardOthers,ownAgentsOf,ownChosen,runsOf,standardKeyless,paperModels,paperListed,paperOffered,leaderboard,setModelChoice,servedRoles,servedList,setServed,reasoningRoles,setReasoning,LEVEL_NAMES,addServed,removeServed,setModelOf,servedModelOf,servedKey,servedCompiled,servedRow,stepShown,chosenOf,toggleParticipant,datasetsOf,whereList,machineLabel,createStandard,setStandardBenchmark,openingStep,runnersOf,runnerFor,benchKey,whereLabel,create,benchmarks,routeBlocker,dataset,sources,setBenchmark,parameters,scopes,validate,compile,runnable,fromJSON,fromJob,prefill,atDefaults,deleteAsk,review,copy,packDraft,unpackDraft,adapterPath,taskCount,PROVIDERS,PROVIDER_LABEL,PROVIDER_NEEDS,available,labelOf,needsOf,choiceOf,setChoice,providersOf,recipeProvider,providerBlocker,providerOf,bareModel,settleModel,agentModel,quote:q,path,defaults,needsCredentials,credentialBindings,declaredTimeouts,effectiveTimeouts,setPhaseMinutes,PHASES,harborExecutable,harborPin,harborProblem,harborKey,harborRepoUrl,harborLabel,repoLabel,agents,mergeAgents,setScanned,COMMON,agentById}; + return {setTaskSet,keepTaskSets,setStartWith,keepStartWith,nestedDatasets,wholeOf,swapDataset,STANDARD_PHASES,STEPS,STEP,runners,RUNNER_GONE,isStandard,standard,standardBase,standardBench,standardOthers,ownAgentsOf,ownChosen,runsOf,standardKeyless,paperModels,paperListed,paperOffered,leaderboard,setModelChoice,servedRoles,servedList,setServed,reasoningRoles,setReasoning,LEVEL_NAMES,addServed,removeServed,setModelOf,servedModelOf,servedKey,servedCompiled,servedRow,stepShown,chosenOf,toggleParticipant,datasetsOf,whereList,machineLabel,createStandard,setStandardBenchmark,openingStep,runnersOf,runnerFor,benchKey,whereLabel,create,benchmarks,routeBlocker,dataset,sources,setBenchmark,parameters,scopes,validate,compile,runnable,fromJSON,fromJob,prefill,atDefaults,deleteAsk,review,copy,packDraft,unpackDraft,adapterPath,taskCount,PROVIDERS,PROVIDER_LABEL,PROVIDER_NEEDS,available,labelOf,needsOf,choiceOf,setChoice,providersOf,recipeProvider,providerBlocker,blockedProvider,roleChoiceOf,setRoleChoice,roleProvidersOf,ownRole,providerOf,bareModel,settleModel,agentModel,quote:q,path,defaults,needsCredentials,credentialBindings,declaredTimeouts,effectiveTimeouts,setPhaseMinutes,PHASES,harborExecutable,harborPin,harborProblem,harborKey,harborRepoUrl,harborLabel,repoLabel,agents,mergeAgents,setScanned,COMMON,agentById}; }); diff --git a/app/static/builder/command-builder.css b/app/static/builder/command-builder.css index dcffd1c10..04cdc6ccd 100644 --- a/app/static/builder/command-builder.css +++ b/app/static/builder/command-builder.css @@ -216,13 +216,21 @@ #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. */ -#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%); } } +/* The Model step: a line per role, under one head - its name, provider, model, reasoning and Served by. On a phone the + lines stack, each cell under its own word. */ +#nullius-builder .std-roles { display: grid; grid-template-columns: minmax(84px, max-content) minmax(0, .9fr) minmax(0, 1.5fr) minmax(0, .75fr) minmax(0, 1fr); gap: 10px; align-items: start; margin: 22px 0 8px; } +#nullius-builder .std-roles-head, #nullius-builder .std-role { display: contents; } +#nullius-builder .std-role-name { display: flex; align-items: center; min-height: 34px; overflow-wrap: anywhere; } +#nullius-builder .std-role-cell.nb-field { margin: 0; gap: 6px; min-width: 0; } +#nullius-builder .std-role-cell > .nb-fixed { display: flex; align-items: center; min-height: 34px; overflow-wrap: anywhere; } +#nullius-builder .std-role-word { display: none; } +@media (max-width: 650px) { + #nullius-builder .std-roles { grid-template-columns: minmax(0, 1fr); gap: 8px; } + #nullius-builder .std-roles-head { display: none; } + #nullius-builder .std-role-name { margin-top: 12px; min-height: 0; } + #nullius-builder .std-role-word { display: block; } + #nullius-builder .std-role-word:empty { display: none; } +} /* 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; } @@ -238,16 +246,14 @@ #nullius-builder .std-boat-sizes .nb-tile:not([disabled]) .nb-tile-note { color: var(--nb-muted); } @media (max-width: 760px) { #nullius-builder .std-boat-sizes { grid-template-columns: repeat(2, minmax(0, 180px)); } } @media (max-width: 560px) { #nullius-builder .std-backends { grid-template-columns: minmax(0, 320px); } #nullius-builder .std-boat-sizes { grid-template-columns: repeat(2, minmax(0, 1fr)); } } -/* Served by: a row after its model's row, as that row is: the label left, the picker right, the providers chosen - under the picker in their order */ -#nullius-builder .std-served-list { grid-column: 2; min-width: 0; } +/* Served by: the picker, the providers chosen under it in their order */ +#nullius-builder .std-served { display: grid; gap: 6px; min-width: 0; } +#nullius-builder .std-served-list { min-width: 0; } #nullius-builder .std-served-list:empty { display: none; } -#nullius-builder label.std-served:has(.std-served-list:not(:empty)) > .ui-field-copy { grid-row: span 2; align-self: start; margin-top: 6px; } #nullius-builder .std-served-pick { cursor: default; gap: 2px; padding: 3px 3px 3px 11px; font: 12.5px/1.4 var(--mono); border-color: var(--nb-blue); background: var(--nb-tint); max-width: 100%; } /* a slug is never cut: a long one wraps inside its chip, which stays inside its row */ #nullius-builder .std-served-slug { min-width: 0; overflow-wrap: anywhere; } #nullius-builder .std-served-pick .nb-remove { flex: none; padding: 0 6px; font-size: 14px; line-height: 1; } -@media (max-width: 650px) { #nullius-builder .std-served-list { grid-column: 1; } #nullius-builder label.std-served:has(.std-served-list:not(:empty)) > .ui-field-copy { grid-row: auto; margin-top: 0; } } /* a limit the benchmark or the agent declares: its placeholder reads as a value; Nullius's default stays grey */ #nullius-builder .nb-field input.nb-declared::placeholder { color: var(--nb-text); opacity: 1; } diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index 96f98aea8..513c84697 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -36,8 +36,8 @@ const chips = (role, chosen) => chosen.map((slug, i) => `${esc(slug) || '“”'}` + button('', `data-served-remove="${i}" data-served-role="${role}" aria-label="Remove ${esc(slug)} from Served by, ${NAME[role]}"`, 'nb-remove') + '').join(''); const field = (rec, role) => { if (!C.servedRoles(rec).includes(role)) return ''; const s = row(rec, role); - return ``; }; + return `` + + `${chips(role, s.chosen)}`; }; // each Served by drawn again in place, as the recipe holds it now: its list, and the model its providers are listed // for. The rest of the form stays as it is: the keyboard stays where it is, and an open menu stays open. function sync() { @@ -63,7 +63,7 @@ // the model a field names, else the benchmark's official one const modelOf = (rec, role) => String(rec[FIELD[role]] || (role === 'model' ? '' : (C.standardBench(rec) || {})[role]) || '').trim(); function levelsOf(rec, role) { - const provider = C.choiceOf(rec), model = modelOf(rec, role), key = provider + '\n' + model; + const provider = C.roleChoiceOf(rec, role), model = modelOf(rec, role), key = provider + '\n' + model; if (!model) return null; if (!asked.has(key)) { const entry = {result: null}; @@ -489,10 +489,30 @@ const shown = !have.length ? offered : [...have, ...(have.includes(current) ? [] : [current])]; return select('Provider', 'provider', current, shown.map(p => [p, have.length && !have.includes(p) ? C.labelOf(p) + ' · not set in Settings' : C.labelOf(p)])); }; + // The standard's, a role's on its line, the same choices; the judge's and the user simulator's are Same as the + // agent, or another that serves chat. + const roleProvider = (rec, role, who) => { + const own = role !== 'model', offered = own ? C.roleProvidersOf() : C.providersOf(rec), agent = C.choiceOf(rec); + const have = C.available().filter(p => offered.includes(p.split(':')[0])), current = own ? (C.ownRole(rec, role) ? C.roleChoiceOf(rec, role) : '') : agent; + const shown = (!have.length ? offered : [...have, ...(have.includes(current) || !current ? [] : [current])]).filter(p => !own || p !== agent); + const name = p => !p ? 'Same as ' + who.toLowerCase().replace('module', 'Module') : have.length && !have.includes(p) ? C.labelOf(p) + ' · not set in Settings' : C.labelOf(p); + const options = (own ? ['', ...shown] : shown).map(p => [p, name(p)]); + if (options.length === 1 && options[0][0] === current) return `${esc(options[0][1])}`; + return ``; + }; + // A role's model field, listing its own provider's models (model-picker.js), or its fixed model like the paper. + const modelInput = (rec, role, key, value, placeholder, name) => ``; + const fixedModel = (value, whose) => `${esc(value)} (${whose})`; + // One line of the Model step: the role, what it does on hover, its provider, model, reasoning and Served by. Each + // cell's own word shows where the lines stack (a phone), the heads above them elsewhere. + const cell = (word, html) => `${word}${html}`; + const roleLine = (rec, role, name, tip, model, who) => `
${esc(name)}` + + cell('Provider', roleProvider(rec, role, who)) + cell('Model', model) + cell('Reasoning', reasoningLine(rec, role)) + + cell(C.servedRoles(rec).includes(role) ? 'Served by' : '', servedField(rec, role)) + '
'; // Show only a missing-provider blocker; configured credentials need no confirmation line. const keyLine = rec => { const blocked = C.providerBlocker(rec), at = name => button('Settings', `data-href="/settings#${name}"`, 'nb-inlinebutton'); - if (blocked) return note('Not set in Settings', esc(blocked) + ' ' + at(C.needsOf(C.choiceOf(rec)))); + if (blocked) return note('Not set in Settings', esc(blocked) + ' ' + at(C.needsOf(C.blockedProvider(rec)))); return ''; }; // The Nullius standard (C.isStandard): a benchmark, then an agent or a Module among every one there is - the @@ -866,19 +886,19 @@ return `

Choose the model.

` + note('No model needed', 'A control calls no model, and its run is handed no key at all.'); if (step === S.model) { const lb = rec.model_choice === 'leaderboard' ? C.leaderboard(rec) : null, paper = rec.model_choice === 'paper' || !!lb; + // a line per role: the agent's model, the user simulator its conversations need, the judge that grades - each its + // official one unless named; like the paper, the official one; like the leaderboard, its own and the options it fixes + const who = b.family === 'agent' ? 'Agent' : b.kind || 'Module'; + const lines = [roleLine(rec, 'model', who, '', modelInput(rec, 'model', 'model', rec.model, paper && C.paperListed(rec) ? 'Choose a paper model' : 'Search or enter a model ID', who), who)]; + if (b.simulator) lines.push(roleLine(rec, 'simulator', 'User simulator', 'Plays the user in every conversation. Empty: ' + b.label + "'s official one; another compares only with runs that used it.", + paper ? fixedModel(lb && lb.simulator || b.simulator, lb && lb.simulator ? 'leaderboard' : 'official') : modelInput(rec, 'simulator', 'simulator_model', rec.simulator_model || '', b.simulator + ' (official)', 'User simulator'), who)); + if (b.judge) lines.push(roleLine(rec, 'judge', 'Judge', b.judge_retired ? 'Grades the answers.' : 'Grades the answers. Empty: ' + b.label + "'s official judge; another compares only with runs that used it.", + paper ? fixedModel(lb && lb.judge || b.judge, lb && lb.judge ? 'leaderboard' : 'official') : modelInput(rec, 'judge', 'judge_model', rec.judge_model || '', b.judge_retired ? 'Search or enter a model ID' : b.judge + ' (official)', 'Judge'), who)); + // a judge beside the benchmark's score, never its own: run only when a model is named + if (b.experiment_judge && !paper) lines.push(roleLine(rec, 'judge', b.experiment_judge.label + ' (experiment)', 'A second score beside ' + b.label + "'s, never in its place. Empty: none. Its source used " + b.experiment_judge.model + '.', + modelInput(rec, 'judge', 'judge_model', rec.judge_model || '', 'None', b.experiment_judge.label), who)); return `

Choose the model.

` + modelChoiceCards(rec) - + providerField(rec, C.providersOf(rec)) - + field('Model', 'model', rec.model, {list:'nb-models', placeholder:paper && C.paperListed(rec) ? 'Choose a paper model' : 'Search or enter a model ID', after: reasoningLine(rec, 'model')}) - + servedField(rec, 'model') - // the benchmark's other models: the user simulator its conversations need, the judge that grades - each its official one - // unless named; like the paper, the official one; like the leaderboard, its own and the options it fixes - + (b.simulator ? (paper ? fixed('Model for the user simulator', lb && lb.simulator || b.simulator, lb && lb.simulator ? 'leaderboard' : 'official') : field('Model for the user simulator', 'simulator_model', rec.simulator_model || '', {list: 'nb-models', placeholder: b.simulator + ' (official)', after: reasoningLine(rec, 'simulator'), - hint: 'Plays the user in every conversation. Empty: ' + esc(b.label) + "'s official one; another compares only with runs that used it."})) + servedField(rec, 'simulator') : '') - + (b.judge ? (paper ? fixed('Model for the judge', lb && lb.judge || b.judge, lb && lb.judge ? 'leaderboard' : 'official') : field('Model for the judge', 'judge_model', rec.judge_model || '', {list: 'nb-models', placeholder: b.judge_retired ? 'Search or enter a model ID' : b.judge + ' (official)', after: reasoningLine(rec, 'judge'), - hint: b.judge_retired ? 'Grades the answers.' : 'Grades the answers. Empty: ' + esc(b.label) + "'s official judge; another compares only with runs that used it."})) + servedField(rec, 'judge') : '') - // a judge beside the benchmark's score, never its own: run only when a model is named - + (b.experiment_judge && !paper ? field(esc(b.experiment_judge.label) + ' (experiment)', 'judge_model', rec.judge_model || '', {list: 'nb-models', placeholder: 'None', after: reasoningLine(rec, 'judge'), - hint: 'A second score beside ' + esc(b.label) + "'s, never in its place. Empty: none. Its source used " + esc(b.experiment_judge.model) + '.'}) + servedField(rec, 'judge') : '') + + `
${lines.join('')}
` + (lb ? Object.entries(lb.bench_options || {}).map(([k, v]) => fixed((b.options[k] || {}).label || k, ((b.options[k] || {}).names || {})[v] || v, 'leaderboard')).join('') : '') + keyLine(rec); } @@ -1097,7 +1117,7 @@ // the number of units a run takes, as typed: a number past the most the field takes is that most const atMost = (el, value) => el.max !== '' && value !== '' && Number(value) > Number(el.max) ? Number(el.max) : value; // after: what sits on the input's line, after it (a model's reasoning) - const field = (label,key,value,{type='text',hint='',list='',min='',max='',placeholder='',declared=false,after=''}={}) => { const input = ``; return ``; }; + const field = (label,key,value,{type='text',hint='',list='',min='',max='',placeholder='',declared=false}={}) => { const input = ``; return ``; }; const select = (label,key,value,options) => ``; const fixed = (label,value,whose='official') => ``; const note = (title,text) => `
${title}${text}
`; @@ -1295,7 +1315,7 @@ if(!schema.local)return note('Run from the application host','Runs start from a browser on the machine Nullius runs on.'); // A provider not set in Settings: Run waits and says why. const blocked=C.providerBlocker(rec); - if(blocked)return `
${button('▶ Run on '+esc(where),'id="nb-run" disabled data-held title="'+esc(blocked)+'"','nb-button nb-primary')}

${esc(blocked)} ${button('Model step','data-step="'+S.model+'"','nb-inlinebutton')} · ${button('Settings','data-href="/settings#'+C.needsOf(C.choiceOf(rec))+'"','nb-inlinebutton')}

`; + if(blocked)return `
${button('▶ Run on '+esc(where),'id="nb-run" disabled data-held title="'+esc(blocked)+'"','nb-button nb-primary')}

${esc(blocked)} ${button('Model step','data-step="'+S.model+'"','nb-inlinebutton')} · ${button('Settings','data-href="/settings#'+C.needsOf(C.blockedProvider(rec))+'"','nb-inlinebutton')}

`; if(C.isStandard(rec)){ const out=runnerOut||{errors:[{message:'Compiling the recipe…'}]}, noun=C.isStandard(rec)?unitsOf(rec).noun:'item'; return `
${(out.errors||[]).length?(runnerOut?[]:out.errors).map(e=>`

${esc(e.message)}

`).join(''):`
${button('▶ Run on '+esc(where),'id="nb-run"','nb-button nb-primary')}
`+(out.confirm?`

${/^Run /.test(out.confirm)?`No ${esc(noun)} limit: `+esc(out.confirm.replace(/^Run /,'').replace(/\?$/,'')):esc(out.confirm.replace(/\?$/,''))}. Run asks before it starts.

`:'')}
`; @@ -1460,7 +1480,8 @@ else if(d.field.startsWith('adapterPath:')){const id=d.field.slice(12);if(String(value).trim())rec.adapterPaths[id]=String(value).trim();else delete rec.adapterPaths[id];} else if(!d.providerModel&&['model','userModel','evalModel'].includes(d.field)&&/^(openrouter|openai)\//.test(String(value))){rec.provider=C.providerOf(rec,value);rec[d.field]=C.bareModel(value); renderForm();refreshPlan();const f=root.querySelector(`[data-field="${d.field}"]`);if(f){f.focus();f.setSelectionRange(f.value.length,f.value.length);}return;} // the provider the prefix named, and whether it is set - else if(d.field==='provider'){C.setChoice(rec,value);renderForm();refreshPlan();return;} // whether it is set in Settings, and the names a runner's models are sent as, follow the provider + else if(d.field==='provider'){C.setChoice(rec,value);renderForm();refreshPlan();return;} + else if(d.field==='judge_provider'||d.field==='simulator_provider'){C.setRoleChoice(rec,d.field.split('_')[0],value);renderForm();refreshPlan();return;} // its models, levels and Served by follow it // whether it is set in Settings, and the names a runner's models are sent as, follow the provider else rec[d.field]=value; if(el.list?.id==='nb-paths')completeDirectory(el.value); }else if(d.stdMinutes){const t=Object.assign({},rec.timeouts);if(el.value===''||!(Number(el.value)>0))delete t[d.stdMinutes];else t[d.stdMinutes]=Number(el.value);if(Object.keys(t).length)rec.timeouts=t;else delete rec.timeouts;refreshPlan();return; diff --git a/app/static/controls.js b/app/static/controls.js index 714ac6b29..9c372beda 100644 --- a/app/static/controls.js +++ b/app/static/controls.js @@ -118,7 +118,7 @@ // Labels and help stay together on the left; compact fields sit on the right. // Benchmark option controls already sit below their section heading. document.querySelectorAll('label.nb-field:not(.ui-field-row):not(.std-optselect)').forEach(label => { - if (![...label.children].some(n => n.matches('select,input:not([type=checkbox]):not([type=radio]),textarea,.nb-model-control,.nb-model-line'))) return; + if (![...label.children].some(n => n.matches('select,input:not([type=checkbox]):not([type=radio]),textarea,.nb-model-control'))) return; const copy = document.createElement('span'); copy.className = 'ui-field-copy'; [...label.childNodes].filter(n => n.nodeType === Node.TEXT_NODE || n.nodeType === Node.ELEMENT_NODE && n.matches('small')).forEach(n => copy.append(n)); label.prepend(copy); label.classList.add('ui-field-row'); diff --git a/app/static/model-picker.js b/app/static/model-picker.js index 3268fbeed..aa08e62e2 100644 --- a/app/static/model-picker.js +++ b/app/static/model-picker.js @@ -38,8 +38,10 @@ const providers = root && (window.NulliusServingProviders = servingProviders(nulliusFetch, csrf)); const cache = new Map(); let active = null, serial = 0, choosing = false; const severalOf = input => input.dataset.pickerSeveral === 'true'; + // in the builder, the provider of the field's own role (data-model-provider), else the recipe's + const providerOf = input => input.dataset.modelProvider || root?.dataset.modelProvider; const placeOf = input => { - if (root) return {url: '/new-run/models', provider: root.dataset.modelProvider}; + if (root) return {url: '/new-run/models', provider: providerOf(input)}; return sourceOf([input.closest('[data-judge-card]'), input.closest('form')].map(at => at?.querySelector(input.dataset.modelPicker)).find(Boolean)?.selectedOptions[0]); }; function close() { @@ -131,7 +133,7 @@ // a press in the menu leaves the keyboard in the field for (const press of ['pointerdown', 'mousedown']) menu.addEventListener(press, e => e.preventDefault()); document.body.append(menu); - const state = {input, menu, wrap: input.parentElement, several, provider: root?.dataset.modelProvider, model: input.dataset.servedModel || '', query: all ? '' : input.value, result: null, items: [], index: -1}; + const state = {input, menu, wrap: input.parentElement, several, provider: providerOf(input), model: input.dataset.servedModel || '', query: all ? '' : input.value, result: null, items: [], index: -1}; active = state; input.setAttribute('aria-expanded', 'true'); paint(); if (menu.showPopover) menu.showPopover(); if (several) { @@ -148,7 +150,7 @@ if (active === state) paint(); } function scan() { - if (active && (!active.input.isConnected || active.input.closest('[hidden]') || active.provider !== root?.dataset.modelProvider)) close(); + if (active && (!active.input.isConnected || active.input.closest('[hidden]') || active.provider !== providerOf(active.input))) close(); // the model a Served by lists the providers of has moved (the server named the one the run sends): its rows follow else if (active && active.several && active.model !== (active.input.dataset.servedModel || '')) void open(active.input, !active.query); (root || document).querySelectorAll(root ? 'input[list="nb-models"], input[list="nb-served"]' : 'input[data-model-picker]:not([role])').forEach(input => { diff --git a/app/ui_tests/test_command_builder_providers.py b/app/ui_tests/test_command_builder_providers.py index cd3c08bc0..bdd383da4 100644 --- a/app/ui_tests/test_command_builder_providers.py +++ b/app/ui_tests/test_command_builder_providers.py @@ -161,6 +161,17 @@ def test_run_waits_for_a_provider_that_is_set_and_never_switches_one(self): self.assertTrue(why.startswith('Run needs a model key, and none is set in Settings: set OPENROUTER_API_KEY, OPENAI_API_KEY or MODEL_API_URL there.')) # a local endpoint is available by its URL, and needs no key self.assertEqual(self.on(['custom'], state % "'custom'", model_key=False)[1:3], ['', []]) + # Claude Code speaks Anthropic Messages, a judge chat: Anthropic serves the agent, and Run waits for a judge's + # provider that serves chat, then for its key + judged = ("const b=C.standard().benchmarks.find(x=>x.judge);const r=C.createStandard(b.key,'claude-code');r.model='x';" + "C.setChoice(r,'anthropic');C.setRoleChoice(r,'judge',%s);" + "process.stdout.write(JSON.stringify([C.providersOf(r),C.providerBlocker(r),C.blockedProvider(r)]))") + self.assertEqual(self.on(['anthropic', 'openrouter'], judged % "''"), + [['anthropic', 'custom'], 'Anthropic does not serve what the judge speaks. Choose a provider for the judge on the Model step.', 'anthropic']) + self.assertEqual(self.on(['anthropic', 'openrouter'], judged % "'openrouter'"), [['anthropic', 'custom'], '', 'anthropic']) + self.assertEqual(self.on(['anthropic'], judged % "'openrouter'")[1:], + ['The judge runs on OpenRouter, and OPENROUTER_API_KEY is not set in Settings. ' + 'Choose another provider for it on the Model step, or set it in Settings.', 'openrouter']) # a recipe of controls alone calls no model: nothing to wait for self.assertEqual(self.on([], "const r=C.create();r.agents=['nop','oracle'];C.setBenchmark(r,'terminal-bench');r.source='local';r.path='/t';" "process.stdout.write(JSON.stringify(C.providerBlocker(r)))"), '') diff --git a/app/ui_tests/test_served_by_builder.py b/app/ui_tests/test_served_by_builder.py index 0a98b1e21..bed927b0d 100644 --- a/app/ui_tests/test_served_by_builder.py +++ b/app/ui_tests/test_served_by_builder.py @@ -331,6 +331,16 @@ def test_the_fields_show_on_openrouter_alone(self): self.assertEqual(roles['openrouter'], ['model'] + (['simulator'] if simulated else []) + ['judge']) self.assertEqual((roles['openai'], roles['custom']), ([], [])) + def test_a_role_on_its_own_provider_takes_its_own_pin_and_same_as_agent_is_none(self): + out = self.js('const b=C.standard().benchmarks.find(x=>x.judge);const r=C.createStandard(b.key);r.model_choice="any";' + 'C.setChoice(r,"openai");C.setRoleChoice(r,"judge","openrouter");const got=[C.servedRoles(r),r.judge_provider];' + 'C.setServed(r,"judge",["j"]);C.setChoice(r,"custom");got.push(r.served_by);' # the agent's change leaves it + 'C.setRoleChoice(r,"judge","custom");got.push(r.judge_provider||null,r.served_by||null);' # the agent's own: none + 'got.push(C.fromJSON(JSON.stringify({...r,judge_provider:"openrouter",simulator_provider:"nowhere"})).judge_provider);' + 'C.setChoice(r,"openrouter");C.setRoleChoice(r,"judge","openai");got.push(C.servedRoles(r).includes("judge"));' + 'process.stdout.write(JSON.stringify(got));') + self.assertEqual(out, [['judge'], 'openrouter', {'judge': ['j']}, None, None, 'openrouter', False]) + def test_an_experiment_judge_gets_its_fields_once_named(self): out = self.js('const b=C.standard().benchmarks.find(x=>x.experiment_judge&&!x.judge);' 'const r=C.createStandard(b.key);r.model_choice="any";C.setChoice(r,"openrouter");const got=[];' From bfb8dda070235e6fa5e00a1a6271af789c4a8938 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 16:27:57 +0100 Subject: [PATCH 07/11] docs: a provider per role in a standard run --- .claude/rules/running.md | 2 +- docs/builder.md | 8 ++++---- docs/cli/run.md | 12 +++++++----- docs/standard.md | 2 +- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/.claude/rules/running.md b/.claude/rules/running.md index a1c0187c4..bab71f8ec 100644 --- a/.claude/rules/running.md +++ b/.claude/rules/running.md @@ -9,7 +9,7 @@ setup. - **Harbor** runs through `uvx` with a pinned PyPI release or locally built repository commit. A Harbor run needs `docker ps` to answer. - **The standard** runs from the current checkout or installed package; a host gets the running backend and effective catalogue, source edits and user entries included, never configuration or credentials. Several machines run one shard each. -- **Keys**: a run gets only its provider's key and endpoint; logs are +- **Keys**: a run gets only its providers' keys and endpoints (the agent's, a judge's or simulator's own); logs are redacted. The standard's agents and upstream scripts get only the relay's word, never a key. - What a recipe needs of each machine is asked before Run and again as it diff --git a/docs/builder.md b/docs/builder.md index bf01e6efc..7125c3ee0 100644 --- a/docs/builder.md +++ b/docs/builder.md @@ -26,7 +26,7 @@ Then [read its results](results.md). | Runner | **Nullius**, [the standard](standard.md#from-the-app), or **Harbor** with its pin ([Which Harbor](#which-harbor)). Only when both are supported. Default: Nullius | | Dataset | One or more; each dataset with each agent is a job of its own. Each runs all its tasks or one [task set](cli/task-sets.md), its benchmark's own lists (`subset_of`) included. **Start with**: all of it, or the tasks ticked, the rest left for the job's page ([`--start-with`](cli/run.md#plan-the-whole-start-with-some-of-it)). A benchmark option its datasets need is asked here, for the datasets it applies to. | | Agent (*Memory* on a memory benchmark) | The selected version's procedure is the first card, on by default; agents, memory Modules and checks run beside it, a job each, and it comes back when nothing is left. The procedure's own settings (LoCoMo's retrieval) are in its tab while it runs. A benchmark with [agents of its own](standard.md#a-benchmarks-own-agents) (OSWorld's) lists them first; several may be chosen, a job each. | -| Model | **Like the paper** keeps what the paper fixed: the model picker shows only documented paper models when the benchmark lists them, and the user simulator and judge are their official models. A benchmark that lists no paper models but has an official simulator or judge leaves the model to you. **Like the leaderboard**, on a benchmark that declares its leaderboard's rules, leaves the model to you and fixes what the leaderboard does: its user simulator and judge, the options it sets and at least its attempts per unit. **Any of your choice** opens the provider's full list and lets the simulator and judge be changed. Nothing fixed by the paper: the paper choice is disabled. **Served by**, on OpenRouter, chooses the serving providers that may answer that model, tried in their order and no other ([Run a benchmark](cli/run.md#serving-providers)). Empty: any of them. **Reasoning**, beside each model, offers the levels that model offers; greyed when the agent or the benchmark sets its own ([Run a benchmark](cli/run.md#reasoning)). | +| Model | **Like the paper** keeps what the paper fixed: the model picker shows only documented paper models when the benchmark lists them, and the user simulator and judge are their official models. A benchmark that lists no paper models but has an official simulator or judge leaves the model to you. **Like the leaderboard**, on a benchmark that declares its leaderboard's rules, leaves the model to you and fixes what the leaderboard does: its user simulator and judge, the options it sets and at least its attempts per unit. **Any of your choice** opens the provider's full list and lets the simulator and judge be changed. Nothing fixed by the paper: the paper choice is disabled. One line per role: the agent, the user simulator, the judge, each with its **Provider**; the simulator's and the judge's are **Same as agent** by default. **Served by**, on a line on OpenRouter, chooses the serving providers that may answer that model, tried in their order and no other ([Run a benchmark](cli/run.md#serving-providers)). Empty: any of them. **Reasoning**, beside each model, offers the levels that model offers; greyed when the agent or the benchmark sets its own ([Run a benchmark](cli/run.md#reasoning)). | | Limits | Task limit (empty is every task), a task-name glob, concurrency, attempts per unit (each one scored), retries after an error (never after a failed task), timeouts in minutes. On the Nullius runner, a [spending cap](cli/run.md#a-spending-cap) for the run and one per unit, turns per conversation for a benchmark that holds conversations, a [cap on model calls](cli/run.md#a-cap-on-model-calls) per unit, what each trial keeps of its model calls ([`--exchanges`](cli/run.md#the-exchange-record)), [time limits](cli/run.md#time-limits) per phase in minutes, forced on every participant (empty: the benchmark's or agent's own value, else Nullius's default), then the benchmark's own bounds; a [list of units](cli/run.md#a-list-of-units) is set only on the command line | | Where | **Hosts**: this machine or Settings hosts. **Sandboxes**: Boat VMs, within the account’s sizes and capacity. Choose isolation where available; VM benchmarks keep their own VM provider | | Review | One row per decision and the prerequisites. **Run** | @@ -48,11 +48,11 @@ Checked on each machine when Review opens, on *Check again*, and as the run star | A benchmark option's machine setup | Its programs | The chosen value; the install commands are shown | | `harbor` on PATH | `command -v` | A Harbor recipe without a pin | -If the recipe's provider failed its last [test in Settings](settings/model-providers.md#test-a-provider), Review shows a notice. Run still starts. +If one of the recipe's providers failed its last [test in Settings](settings/model-providers.md#test-a-provider), Review shows a notice. Run still starts. ### Which providers -A provider is *set* when Settings holds its key, or the base URL of a custom provider. Each custom provider is a choice of its own, listed by its name. The Model step offers a provider only where it serves what the recipe's agents speak ([protocols](settings/model-providers.md#protocols)): Anthropic for an agent of the standard that speaks `messages`, never for a Harbor recipe. +A provider is *set* when Settings holds its key, or the base URL of a custom provider. Each custom provider is a choice of its own, listed by its name. The Model step offers a provider only where it serves what the recipe's agents speak ([protocols](settings/model-providers.md#protocols)): Anthropic for an agent of the standard that speaks `messages`, never for a Harbor recipe. A judge and a user simulator speak chat: on Anthropic, give the judge a provider of its own. Run waits for each provider the recipe uses, and the run gets those keys alone. | Set in Settings | Model stage | Run | | --- | --- | --- | @@ -73,7 +73,7 @@ A recipe of controls alone needs no key unless the benchmark uses a judge or emb Renaming a custom endpoint keeps its recipes. A recipe without an `endpoint` uses the one at `MODEL_API_URL`. If an endpoint was removed, choose another to enable Run. -The Model step searches the selected provider's catalogue. +Each line's model field searches its provider's catalogue. Keys stay on the Nullius host. Choose a result to use its exact model ID, or enter an ID manually if the catalogue is unavailable. An Original setup with a declared model list keeps those published choices. diff --git a/docs/cli/run.md b/docs/cli/run.md index d8e2f9a0f..5b660276e 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -8,7 +8,8 @@ nullius standard run [@version] [--model M] [--dataset D] [-- [--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H][/TOKENS=INPUT,OUTPUT...]]... [--max-usd USD] [--max-usd-per-unit USD] [--timeout PHASE=SECONDS]... [--max-turns N] [--max-calls N] \ [--constraint KEY=VALUE]... \ [--served-by [MODEL=]SLUG[,SLUG...]]... [--reasoning [MODEL=]LEVEL]... [--exchanges whole|text|off] [--exchanges-max-mb N] \ - [--attempts K] [--retries N] [--remove-images] [--judge-model M] [--simulator-model M] [--name NAME] [--jobs DIR] [--provider P] + [--attempts K] [--retries N] [--remove-images] [--judge-model M] [--simulator-model M] [--name NAME] [--jobs DIR] [--provider P] \ + [--judge-provider P] [--simulator-provider P] ``` ```bash title="Examples" @@ -27,6 +28,7 @@ nullius standard run locomo model --model gpt-4o-mini | `` | `KEY` or `KEY@VERSION`; `nop` or `oracle`; `original` or `model` | | `--model` | None for a control; `original` defaults to the paper's first | | `--provider` | `anthropic`, `custom`, `openai` or `openrouter` | +| `--judge-provider`, `--simulator-provider` | The judge's, the simulated user's own provider and key; default `--provider`. It must serve chat | | `--dataset`, `--limit`, `-j` | One dataset, the first N units, N at a time | | `--units FILE` | Only the units the file lists: [below](#a-list-of-units) | | `--set NAME` | Only the units of a [task set](task-sets.md), in its dataset | @@ -51,13 +53,13 @@ nullius standard run locomo model --model gpt-4o-mini | `--simulator-model` | Instead of the official simulated user | | `--name` | The job's name | | `--jobs` | Where jobs are written (default `jobs_standard/` relative to the current directory) | -| `--from-run` | Started by Nullius: `OPENAI_API_KEY` and `OPENAI_BASE_URL` only, saved settings unread | +| `--from-run` | Started by Nullius: `OPENAI_API_KEY` and `OPENAI_BASE_URL` only, and a role's own `NULLIUS_JUDGE_API_KEY`, `NULLIUS_JUDGE_BASE_URL` (`SIMULATOR` alike); saved settings unread | | `--shard I/N`, `--launch` | One shard of a launch: [Shard and merge](shard-and-merge.md) | | Rule | Detail | | --- | --- | | The pair must fit | Else refused, naming the missing port | -| The model | Refused when the provider's model list lacks it | +| The model | Refused when its provider's model list lacks it | | Keys | Environment, then user `settings.json`; the agent never gets one | | A data provider's token | `HF_TOKEN` from the environment, then Settings → Data providers, for a benchmark that declares Hugging Face; only its driver gets it. Not with `--from-run` | | A control | No `--model`, no `--unsandboxed`; only a judge is called | @@ -203,13 +205,13 @@ nullius standard run humaneval goose --provider openrouter --model meta-llama/ll | A slug | As the model's page on OpenRouter names its provider: `deepinfra`, or a provider and its variant, a quantisation (`deepinfra/fp8`), a speed (`deepinfra/turbo`) or a region (`google-vertex/us-central1`). Several are tried in their order, and no other provider answers | | Without `MODEL=` | The run's model. With it, any model the run calls: its judge, its simulated user, an option's embeddings | | What is sent | `provider: {"order": [...], "allow_fallbacks": false}` on every request sent as that model, on every route, in place of the agent's own routing field. | -| Refused before any unit | A provider other than `openrouter`; a model the run does not call; a slug that is empty, malformed or given twice; a model named twice | +| Refused before any unit | A model whose provider is not `openrouter`; a model the run does not call; a slug that is empty, malformed or given twice; a model named twice | | No provider can serve it | OpenRouter answers 404 (no endpoint found) and nothing else is tried; the call fails as any refused call does | | The record | `config.json`: `standard.served_by`, the slugs by model. Each call in `agent/calls.jsonl`: `request.routing`, `request.routing_asked` when the agent sent its own, `reply.served_by`, `reply.end` and `reply.error` ([Who served a call](../standard.md#a-run)) | | Who served the run | Each trial's `result.json`, `standard.served`, and the job's `result.json`, `served`: the answered calls of every route (the agent's, the judge's, the simulated user's, the benchmark's own relay's) by serving provider, those that named none, and for each pinned model `held`: `true` when every answered call names a provider that reads as a pinned slug, `unknown` when one names none or another name, `null` with no answered call. The tokens and the cost stay the agent's own calls' | | What `held` reads | The provider's name alone: a reply names no endpoint variant, and `held` for `deepinfra/fp8` is true for any endpoint of `deepinfra`. A reply gives the provider's display name. Where that name is not the slug once lowercased, `held` reads `unknown` though the provider served the call (`Google` for `google-vertex`, `SambaNova` for `sambanova-turbo`) | | Shards | `merge` refuses shards whose pins differ, unless `--force`; a model pinned differently in the merged shards reads `held: unknown` | -| The builder | *Model* step, **Served by** after each model field, on OpenRouter alone: the recipe's `served_by`, by field (`model`, `simulator`, `judge`), compiled into `--served-by` for each job that calls that model. | +| The builder | *Model* step, **Served by** on each role's line whose provider is OpenRouter: the recipe's `served_by`, by field (`model`, `simulator`, `judge`), compiled into `--served-by` for each job that calls that model. | ## Reasoning diff --git a/docs/standard.md b/docs/standard.md index c69f2e7fc..c28f98445 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -137,7 +137,7 @@ record); verifier/reward.txt and score.json | Rule | Detail | | --- | --- | | Units | Run `-j` at a time, each with its own workspace (a git repository of its own), home and relay | -| A relay per unit | Its record is the trial's `.work/relay`; the judge and simulated user are routes on it (`-judge`, `-simulator`). An embedding option's relay is recorded in `.work/relay-benchmark` as the benchmark's cost. A call refused with 400, 413 or 422 records its inline images' types and sizes as `images`, never their bytes | +| A relay per unit | Its record is the trial's `.work/relay`; the judge and simulated user are routes on it (`-judge`, `-simulator`), each on its own provider and key when the run names one (`--judge-provider`, `--simulator-provider`). An embedding option's relay is recorded in `.work/relay-benchmark` as the benchmark's cost. A call refused with 400, 413 or 422 records its inline images' types and sizes as `images`, never their bytes | | 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)) | From 506358e23043695619f9012c67e31a80459b14b4 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 16:31:05 +0100 Subject: [PATCH 08/11] fix(standard): keep the relay's own pool and read boat options a caller may leave out --- app/nullius/standard/calls/relay.py | 11 ++++++----- app/nullius/standard/cli.py | 6 +++--- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/app/nullius/standard/calls/relay.py b/app/nullius/standard/calls/relay.py index bec6daefa..a737355b5 100644 --- a/app/nullius/standard/calls/relay.py +++ b/app/nullius/standard/calls/relay.py @@ -966,6 +966,7 @@ def _forward(self, h: BaseHTTPRequestHandler): number = self.numbered[tag] = self.numbered.get(tag, 0) + 1 asked = req.get("model") if isinstance(req, dict) else None up = self._up(tag) + pool = self.pool if up is self.upstream else up.pool side = False routing_asked, pinned = None, None dumped = False # raw is json.dumps(req): what the store splits into parts @@ -1024,7 +1025,7 @@ def _forward(self, h: BaseHTTPRequestHandler): # a Responses reply names its provider in the routing facts alone; a Messages reply names it of itself facts = bool(pinned) and up.facts and rest.split("?")[0].endswith(("/chat/completions", "/responses")) sent_headers = self._headers(h.headers, tag, facts) - conn, r = up.pool.send(h.command, rest, raw if h.command == "POST" else None, sent_headers) + conn, r = pool.send(h.command, rest, raw if h.command == "POST" else None, sent_headers) status, kind, back = r.status, r.getheader("Content-Type") or "application/json", returned(r.headers) except Exception as e: status, kind = 502, "application/json" @@ -1144,7 +1145,7 @@ def record(body): record(body) # before the caller has the reply, so a reader after it finds the call if conn is not None: # read whole: back to the pool before the caller can make its next call if whole: - up.pool.give(conn, r) + pool.give(conn, r) else: conn.close() conn = None @@ -1156,7 +1157,7 @@ def record(body): pass if conn is not None: if whole: - up.pool.give(conn, r) + pool.give(conn, r) else: conn.close() @@ -1252,8 +1253,8 @@ def stop(self): if self.server: self.server.shutdown() self.server.server_close() - for u in (self.upstream, *self.upstreams.values()): - u.pool.close() + for p in (self.pool, *(u.pool for u in self.upstreams.values())): + p.close() def agent_route(tag: str) -> bool: diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index ef439a10f..50447b59b 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -714,12 +714,12 @@ def boat_credentials(a, bench, other, vals) -> dict: import base64 needs = definitions.option_needs(bench, vals) out = {} - judged = (bench.get("score") or {}).get("judge") or (a.judge_model and (bench.get("score") or {}).get("experiment_judge")) + judged = (bench.get("score") or {}).get("judge") or (getattr(a, "judge_model", None) and (bench.get("score") or {}).get("experiment_judge")) if other["_kind"] != "control" or judged or needs["embeddings"] or needs["reranker"]: base, key = run.provider_endpoint(a.provider, run_env(a.provider) if a.from_run else os.environ) out.update(OPENAI_API_KEY=key, OPENAI_BASE_URL=base) - for role, p in (("judge", a.judge_provider if judged else None), - ("simulator", a.simulator_provider if bench.get("simulator") and other["_kind"] != "control" else None)): + for role, p in (("judge", getattr(a, "judge_provider", None) if judged else None), + ("simulator", getattr(a, "simulator_provider", None) if bench.get("simulator") and other["_kind"] != "control" else None)): if p: base, key = run.provider_endpoint(p, run_env(p, os.environ, role) if a.from_run else os.environ) out.update(zip(providers.role_vars(role), (key, base))) From b7b93b170136a534c0a7f56caf4e9833576dc71e Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Tue, 1 Dec 2026 16:50:53 +0100 Subject: [PATCH 09/11] docs: drop what the builder and flags already say of role providers --- docs/builder.md | 2 +- docs/standard.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/builder.md b/docs/builder.md index 7125c3ee0..d74962a9a 100644 --- a/docs/builder.md +++ b/docs/builder.md @@ -52,7 +52,7 @@ If one of the recipe's providers failed its last [test in Settings](settings/mod ### Which providers -A provider is *set* when Settings holds its key, or the base URL of a custom provider. Each custom provider is a choice of its own, listed by its name. The Model step offers a provider only where it serves what the recipe's agents speak ([protocols](settings/model-providers.md#protocols)): Anthropic for an agent of the standard that speaks `messages`, never for a Harbor recipe. A judge and a user simulator speak chat: on Anthropic, give the judge a provider of its own. Run waits for each provider the recipe uses, and the run gets those keys alone. +A provider is *set* when Settings holds its key, or the base URL of a custom provider. Each custom provider is a choice of its own, listed by its name. The Model step offers a provider only where it serves what the recipe's agents speak ([protocols](settings/model-providers.md#protocols)): Anthropic for an agent of the standard that speaks `messages`, never for a Harbor recipe. | Set in Settings | Model stage | Run | | --- | --- | --- | diff --git a/docs/standard.md b/docs/standard.md index c28f98445..c69f2e7fc 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -137,7 +137,7 @@ record); verifier/reward.txt and score.json | Rule | Detail | | --- | --- | | Units | Run `-j` at a time, each with its own workspace (a git repository of its own), home and relay | -| A relay per unit | Its record is the trial's `.work/relay`; the judge and simulated user are routes on it (`-judge`, `-simulator`), each on its own provider and key when the run names one (`--judge-provider`, `--simulator-provider`). An embedding option's relay is recorded in `.work/relay-benchmark` as the benchmark's cost. A call refused with 400, 413 or 422 records its inline images' types and sizes as `images`, never their bytes | +| A relay per unit | Its record is the trial's `.work/relay`; the judge and simulated user are routes on it (`-judge`, `-simulator`). An embedding option's relay is recorded in `.work/relay-benchmark` as the benchmark's cost. A call refused with 400, 413 or 422 records its inline images' types and sizes as `images`, never their bytes | | 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)) | From 69cc5873332384bae7138979948e4e8abc23f5f5 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Wed, 2 Dec 2026 01:25:46 +0100 Subject: [PATCH 10/11] fix(standard): check each role on its own provider and keep its choice --- app/nullius/standard/calls/preflight.py | 10 +++++--- app/nullius/standard/calls/relay.py | 5 ++-- app/nullius/standard/pages/recipe.py | 2 +- app/nullius/standard/runner/run.py | 3 ++- app/static/builder/command-builder-core.js | 25 +++++++++++-------- app/static/builder/command-builder.js | 2 +- app/tests/test_standard_preflight.py | 11 ++++++++ app/tests/test_standard_recipe_served_by.py | 10 ++++++++ app/tests/test_standard_relay.py | 3 +++ .../test_command_builder_providers.py | 16 +++++++++++- app/ui_tests/test_rerun_page.py | 13 ++++++++-- app/web/builder.py | 2 +- app/web/execute.py | 2 ++ 13 files changed, 81 insertions(+), 23 deletions(-) diff --git a/app/nullius/standard/calls/preflight.py b/app/nullius/standard/calls/preflight.py index 2622fff8b..91b7dbe18 100644 --- a/app/nullius/standard/calls/preflight.py +++ b/app/nullius/standard/calls/preflight.py @@ -41,9 +41,10 @@ def response_matches(path, body, streamed): def check(requests, models, *, base, key, key_header, folder, identity, serving=None, - reasoning=None, prices=None, ledger=None, timeout=60): + reasoning=None, prices=None, ledger=None, timeout=60, upstreams=None): """Return each role's checked/cached status. Calls are recorded and budgeted; - missing roles are reported by the caller, never inferred compatible.""" + missing roles are reported by the caller, never inferred compatible. A role in + ``upstreams`` ({role: (base, key)}, ``relay.Relay``'s) is asked on its own provider.""" if not isinstance(requests, list): raise Rejected("preflight requests must be a list") cache = os.path.join(paths.cache_dir(), "standard", "preflight") @@ -60,7 +61,8 @@ def check(requests, models, *, base, key, key_header, folder, identity, serving= 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, + on_base, on_key = (upstreams or {}).get(role, (base, key)) + fingerprint = json.dumps([identity, on_base, hashlib.sha256(on_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: @@ -75,7 +77,7 @@ def check(requests, models, *, base, key, key_header, folder, identity, serving= 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() + timeout=timeout, upstreams=upstreams or None).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}) diff --git a/app/nullius/standard/calls/relay.py b/app/nullius/standard/calls/relay.py index c8d27e2da..7a54f560a 100644 --- a/app/nullius/standard/calls/relay.py +++ b/app/nullius/standard/calls/relay.py @@ -915,8 +915,9 @@ def _said(self, e: Exception) -> str: return redact(text)[:200] def _up(self, tag: str) -> _Upstream: - """The provider a route's calls go to: its role's own (``upstreams``), else ``base``.""" - return self.upstreams.get(role_of(tag)) or self.upstream + """The provider a route's calls go to: its role's own (``upstreams``) on a route the run pinned for it, else + ``base``: a tag merely ending in -judge reaches no role's key.""" + return self.upstreams.get(role_of(tag)) if tag in self.models and role_of(tag) in self.upstreams else self.upstream def _headers(self, caller, tag: str = "", facts: bool = False) -> Dict[str, str]: """The headers sent on: the key as ``key_header`` says on the agent's own routes; a route pinned diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 8bf83b69b..ccd7b09c2 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -778,7 +778,7 @@ def add(step, message, shown=False, field=None, unset=False): judges = bool((b.get("score") or {}).get("judge") or (judge_model and (b.get("score") or {}).get("experiment_judge"))) for role_, used_ in (("judge", judges), ("simulator", bool(b.get("simulator")) and any(not p["control"] for p in picks))): on_ = prov(role_) - if on_ in PROVIDERS and used_ and on_ not in providers.offered(["chat"]) and (role_ == "judge" or role_ in role_choice): + if on_ in PROVIDERS and used_ and on_ not in providers.offered(["chat"]): add("model", f"{providers.label(role_choice.get(role_, on_))} does not serve what {b['label']}'s {SERVED_LABEL[role_]} speaks: choose another provider.") model = str(recipe.get("model") or "").strip() if not _MODEL.match(model) and (needs_model or model): diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index 956e17ea5..c92317526 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -2425,7 +2425,8 @@ def compatibility(self) -> None: 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)) + ledger=self.ledger_file(), timeout=min(self.call_seconds, 60), + upstreams=getattr(self, "upstreams", {})) except preflight.Rejected as e: raise Refused(str(e)) from e for role, model in models.items(): diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index dfd9284c4..755251bcc 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -428,7 +428,6 @@ // a provider that routes no model to several takes no Served by: a pin made for OpenRouter is dropped with it function setChoice(r, c) { r.provider = kindOf(c); keepEndpoint(r, {endpoint: endpointOf(c)}); - for (const role of ['judge', 'simulator']) setRoleChoice(r, role, r[role + '_provider'] || ''); for (const role of SERVED_ROLES) if (kindOf(roleChoiceOf(r, role)) !== 'openrouter' && r.served_by) setServed(r, role, []); } // A judge's or user simulator's own provider (recipe.py: judge_provider, simulator_provider), a choice as the Model @@ -442,21 +441,27 @@ if (kindOf(roleChoiceOf(r, role)) !== 'openrouter' && r.served_by) setServed(r, role, []); return r; } - // The role Run waits for, or '': one on its own provider not set here, or a judge on the agent's that serves no chat - // (recipe.py says the same). - const unserved = r => !ownRole(r, 'judge') && judgesRun(r) && PROVIDERS.includes(r.provider) && !serving(r.provider, ['chat']); - const blockedRole = r => !isStandard(r) || standardKeyless(r) ? '' : unserved(r) ? 'judge' - : schema.credentials && reasoningRoles(r).find(x => ownRole(r, x) && !available().includes(roleChoiceOf(r, x))) || ''; - // The provider Run waits for: the agent's, else that role's. - const blockedProvider = r => agentBlocker(r) || !blockedRole(r) ? choiceOf(r) : roleChoiceOf(r, blockedRole(r)); + // The judge and user simulator a run calls: a control never asks the simulator (recipe.py, roles). + const rolesRun = r => { + const b = standardBench(r); + return [...(judgesRun(r) ? ['judge'] : []), ...(b && b.simulator && chosenOf(r).some(k => !(b.controls || []).some(c => c.key === k)) ? ['simulator'] : [])]; + }; + // The role Run waits for, or '': one on the agent's provider that serves no chat, or one on its own provider not + // set here (recipe.py says the same). + const unserved = r => PROVIDERS.includes(r.provider) && !serving(r.provider, ['chat']) && rolesRun(r).find(x => !ownRole(r, x)) || ''; + const blockedRole = r => !isStandard(r) || standardKeyless(r) ? '' : unserved(r) + || schema.credentials && rolesRun(r).find(x => ownRole(r, x) && !available().includes(roleChoiceOf(r, x))) || ''; + // The provider whose key Run waits for: the agent's, else that role's; none when a provider serves no chat. + const blockedProvider = r => agentBlocker(r) || !blockedRole(r) ? choiceOf(r) : unserved(r) ? '' : roleChoiceOf(r, blockedRole(r)); // Why Run cannot start this recipe here, or '': one of its providers is not one of those. A recipe naming one keeps // it, said, until another is chosen - never switched behind the person's back. The server refuses the same // (web/execute.py, providers_problem). function providerBlocker(r) { const role = agentBlocker(r) ? '' : blockedRole(r), c = role && roleChoiceOf(r, role); if (!role) return agentBlocker(r); - if (!ownRole(r, role)) return labelOf(c) + ' does not serve what the judge speaks. Choose a provider for the judge on the Model step.'; - return 'The ' + (role === 'judge' ? 'judge' : 'user simulator') + ' runs on ' + labelOf(c) + ', and ' + needsOf(c) + const name = role === 'judge' ? 'judge' : 'user simulator'; + if (!ownRole(r, role)) return labelOf(c) + ' does not serve what the ' + name + ' speaks. Choose a provider for the ' + name + ' on the Model step.'; + return 'The ' + name + ' runs on ' + labelOf(c) + ', and ' + needsOf(c) + ' is not set in Settings. Choose another provider for it on the Model step, or set it in Settings.'; } function agentBlocker(r) { diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index f8b474fbe..dfed68ffb 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -512,7 +512,7 @@ // Show only a missing-provider blocker; configured credentials need no confirmation line. const keyLine = rec => { const blocked = C.providerBlocker(rec), at = name => button('Settings', `data-href="/settings#${name}"`, 'nb-inlinebutton'); - if (blocked) return note('Not set in Settings', esc(blocked) + ' ' + at(C.needsOf(C.blockedProvider(rec)))); + if (blocked) return note('Not set in Settings', esc(blocked) + (C.blockedProvider(rec) ? ' ' + at(C.needsOf(C.blockedProvider(rec))) : '')); return ''; }; // The Nullius standard (C.isStandard): a benchmark, then an agent or a Module among every one there is - the diff --git a/app/tests/test_standard_preflight.py b/app/tests/test_standard_preflight.py index 61c9906a1..b1b236f6a 100644 --- a/app/tests/test_standard_preflight.py +++ b/app/tests/test_standard_preflight.py @@ -67,6 +67,17 @@ def test_streamed_request_and_judge_route_are_supported(self): self.assertEqual(result, {"agent": "checked", "judge": "checked"}) self.assertEqual([body["model"] for _, _, body in Upstream.seen], ["a", "j"]) + def test_a_role_on_its_own_provider_is_checked_there_with_its_key(self): + judge = dict(self.request, role="judge") + own = {"judge": (self.kw["base"].replace("/v1", "/judge/v1"), "judge-secret")} + result = preflight.check([self.request, judge], {"agent": "a", "judge": "j"}, **self.kw, upstreams=own) + self.assertEqual(result, {"agent": "checked", "judge": "checked"}) + self.assertEqual([(path, auth) for path, auth, _ in Upstream.seen], + [("/v1/chat/completions", "Bearer secret"), ("/judge/v1/chat/completions", "Bearer judge-secret")]) + # its pass is its provider's: the judge on another is checked again + again = preflight.check([judge], {"judge": "j"}, **self.kw) + self.assertEqual((again, Upstream.seen[-1][1]), ({"judge": "checked"}, "Bearer secret")) + 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"): diff --git a/app/tests/test_standard_recipe_served_by.py b/app/tests/test_standard_recipe_served_by.py index 7f0f28768..556f66a41 100644 --- a/app/tests/test_standard_recipe_served_by.py +++ b/app/tests/test_standard_recipe_served_by.py @@ -91,6 +91,16 @@ def test_a_judge_on_its_own_provider_is_named_spelled_and_pinned_by_it(self): bad = recipe.compile(a_recipe(**{**r, **kw}), d) self.assertTrue(any(said in e["message"] for e in bad["errors"]), bad["errors"]) + def test_a_user_simulator_left_on_the_agents_provider_must_speak_chat_there(self): + """Claude Code on Anthropic with the judge moved to OpenRouter: τ³-bench's user simulator, still on Anthropic, + speaks chat, which Anthropic does not serve.""" + sets = definitions.find(definitions.load("benchmark")[0], "tau3-bench")["datasets"] + r = a_recipe(benchmark="tau3-bench", dataset=sets[0]["id"], other="claude-code", provider="anthropic", + model="claude-sonnet-4-6", judge_provider="openrouter") + said = lambda out: [e["message"] for e in out["errors"] if "user simulator speaks" in e["message"]] + self.assertTrue(said(recipe.compile(r))) + self.assertEqual(said(recipe.compile(dict(r, simulator_provider="openrouter"))), []) + def test_a_pin_is_refused_as_the_option_is(self): for kw, said in (({"provider": "openai", "model": "gpt-5-mini", "served_by": {"model": ["deepinfra"]}}, "needs OpenRouter"), ({"served_by": {"model": ["bad slug"]}}, "not a serving provider's slug"), diff --git a/app/tests/test_standard_relay.py b/app/tests/test_standard_relay.py index 164a0c362..a7376ca61 100644 --- a/app/tests/test_standard_relay.py +++ b/app/tests/test_standard_relay.py @@ -970,6 +970,9 @@ def test_a_roles_routes_call_its_own_provider_with_its_own_key(self): self.assertEqual((user, u_head.get("Authorization")), ("/v1/chat/completions", "Bearer sk-real")) # no provider of its own: the agent's self.assertEqual((r.pool.opened, r.upstreams["judge"].pool.opened), (1, 1)) self.assertNotIn("sk-judge", r._said(OSError("refused with sk-judge"))) + # a tag that merely ends in -judge, not one the run pinned, never reaches the judge's provider or key + self.post(r, "x-judge", "/messages", {"model": "any", "max_tokens": 5, "messages": []}) + self.assertEqual((KeptAlive.seen[-1][0], KeptAlive.seen[-1][1].get("x-api-key")), ("/v1/messages", "sk-real")) def test_anthropic_messages_take_the_key_as_x_api_key_and_their_usage_is_read(self): r = self.relay(model="claude-x", key_header="x-api-key") diff --git a/app/ui_tests/test_command_builder_providers.py b/app/ui_tests/test_command_builder_providers.py index bdd383da4..8f7bc8c78 100644 --- a/app/ui_tests/test_command_builder_providers.py +++ b/app/ui_tests/test_command_builder_providers.py @@ -167,8 +167,22 @@ def test_run_waits_for_a_provider_that_is_set_and_never_switches_one(self): "C.setChoice(r,'anthropic');C.setRoleChoice(r,'judge',%s);" "process.stdout.write(JSON.stringify([C.providersOf(r),C.providerBlocker(r),C.blockedProvider(r)]))") self.assertEqual(self.on(['anthropic', 'openrouter'], judged % "''"), - [['anthropic', 'custom'], 'Anthropic does not serve what the judge speaks. Choose a provider for the judge on the Model step.', 'anthropic']) + [['anthropic', 'custom'], 'Anthropic does not serve what the judge speaks. Choose a provider for the judge on the Model step.', '']) self.assertEqual(self.on(['anthropic', 'openrouter'], judged % "'openrouter'"), [['anthropic', 'custom'], '', 'anthropic']) + # a user simulator left on the agent's provider speaks chat there too; a control never asks it + sim = ("const r=C.createStandard('tau3-bench','claude-code');r.model='x';C.setChoice(r,'anthropic');%s" + "process.stdout.write(JSON.stringify([C.providerBlocker(r),C.blockedProvider(r)]))") + self.assertEqual(self.on(['anthropic', 'openrouter'], sim % "C.setRoleChoice(r,'judge','openrouter');"), + ['Anthropic does not serve what the user simulator speaks. Choose a provider for the user simulator on the Model step.', '']) + self.assertEqual(self.on(['anthropic', 'openrouter'], sim % "C.setRoleChoice(r,'judge','openrouter');C.setRoleChoice(r,'simulator','openrouter');"), + ['', 'anthropic']) + controls = ("const r=C.createStandard('tau3-bench','nop');r.model='x';C.setChoice(r,'openrouter');C.setRoleChoice(r,'simulator','openai');" + "process.stdout.write(JSON.stringify(C.providerBlocker(r)))") + self.assertEqual(self.on(['openrouter'], controls), '') + # a role keeps its own provider when the agent's changes, the agent's included + kept = ("const r=C.createStandard('tau3-bench','codex');r.model='x';C.setChoice(r,'openrouter');C.setRoleChoice(r,'judge','openai');" + "C.setChoice(r,'openai');C.setChoice(r,'openrouter');process.stdout.write(JSON.stringify(r.judge_provider||''))") + self.assertEqual(self.on(['openrouter', 'openai'], kept), 'openai') self.assertEqual(self.on(['anthropic'], judged % "'openrouter'")[1:], ['The judge runs on OpenRouter, and OPENROUTER_API_KEY is not set in Settings. ' 'Choose another provider for it on the Model step, or set it in Settings.', 'openrouter']) diff --git a/app/ui_tests/test_rerun_page.py b/app/ui_tests/test_rerun_page.py index d622a73f0..ec30b3e07 100644 --- a/app/ui_tests/test_rerun_page.py +++ b/app/ui_tests/test_rerun_page.py @@ -71,11 +71,11 @@ def setUp(self): self.held = None self.stack.enter_context(patch.object(execution.Execution, "holds", lambda ex, job_id: self.held)) - def run_of(self, name="r1", host=None, state="done", **std): + def run_of(self, name="r1", host=None, state="done", recipe=None, roles=None, **std): d = self.tmp / "runs" / name standard_job(d / "jobs" / name, name, **std) plan = execution.Plan(name=name, script="", runner="standard", host=hosts.parse(host) if host else None, model="m-1", - key_var="OPENAI_API_KEY", url_var="", recipe={"provider": "openai"}, + key_var="OPENAI_API_KEY", url_var="", recipe=recipe or {"provider": "openai"}, roles=roles or {}, parts=[{"id": "fake", "label": "Fake", "script": "true"}], jobs=[{"name": name, "agent": "fake"}]) (d / "run.json").write_text(json.dumps({"id": f"{name}-1", "plan": plan.to_dict(), "state": state, "step": "run", "ends": {"fake": {"rc": 0, "at": 1_760_000_060.0, "label": "Fake"}}})) @@ -143,6 +143,15 @@ def test_what_the_route_refuses_starts_nothing(self): self.assertEqual(r.status_code, 400); self.assertIn("OPENAI_API_KEY", r.json["error"]) self.assertEqual(self.asked, []) + def test_a_judge_on_its_own_provider_needs_its_key_to_run_again(self): + d = self.run_of(recipe={"provider": "openai", "judge_provider": "openrouter"}, + roles={"judge": {"key_var": "OPENROUTER_API_KEY", "url_var": "", "base_url": "https://openrouter.ai/api/v1"}}) + self.open(d.parent) + with patch.dict(os.environ, {"OPENROUTER_API_KEY": ""}): + r = self.post("r1", {"trials": [trial_name(0)]}) + self.assertEqual(r.status_code, 400); self.assertIn("OPENROUTER_API_KEY", r.json["error"]) + self.assertEqual(self.asked, []) + def test_a_job_on_a_host_goes_back_there_and_a_host_without_it_is_refused(self): d = self.run_of(host="bench") self.open(d.parent) diff --git a/app/web/builder.py b/app/web/builder.py index f1324db2e..9eda152ee 100644 --- a/app/web/builder.py +++ b/app/web/builder.py @@ -288,7 +288,7 @@ def machine(w): machines = list(pool.map(machine, wheres)) # a notice, not a refusal: a provider's last test in Settings failed (providers.test), the agent's and each role's own tests, notes = providers.tests(), [] - for choice in dict.fromkeys([str(body.get("provider") or ""), *(str(recipe.get(r + "_provider") or "") for r in ("judge", "simulator"))]): + for choice in dict.fromkeys([str(body.get("provider") or ""), *(out["roles"].values() if runner == "standard" else ())]): last = tests.get(choice) if choice else None if isinstance(last, dict) and not last.get("ok"): notes.append(f"{providers.label(choice)} failed its last test in Settings: {providers.said(last)}") diff --git a/app/web/execute.py b/app/web/execute.py index a15801065..6a042b5ed 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -323,6 +323,8 @@ def job_rerun(job_id): return jsonify(ok=False, error=said[0].upper() + said[1:]), 409 recipe = ex.plan.recipe or {} missing = "" if ex.plan.keyless else provider_problem(recipe.get("provider") or "openai", recipe.get("endpoint")) + for role in () if ex.plan.keyless else (ex.plan.roles or {}): # each role's own provider, as Run asked + missing = missing or provider_problem(*providers.split(str(recipe.get(role + "_provider") or ""))) if missing: return jsonify(ok=False, error=missing), 400 gone = ex.holds(job_id) From 6358bbe2676c77f871347632ee546931e630b3f2 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Wed, 2 Dec 2026 02:20:28 +0100 Subject: [PATCH 11/11] fix(standard): close the provider-per-role gaps the review left open --- app/nullius/leaderboard/board.py | 4 ++- app/nullius/runs/parse.py | 5 +-- app/nullius/standard/cli.py | 22 ++++++++---- app/nullius/standard/pages/recipe.py | 27 +++++++++----- app/nullius/standard/runner/run.py | 35 +++++++++++++------ app/static/builder/command-builder-core.js | 3 ++ app/static/builder/command-builder.css | 1 + app/static/builder/command-builder.js | 4 ++- app/templates/runs/job.html | 1 + app/tests/test_leaderboard_service.py | 11 ++++++ app/tests/test_standard_recipe_served_by.py | 13 +++++++ app/tests/test_standard_served_by.py | 16 +++++++++ .../test_command_builder_providers.py | 5 +++ app/ui_tests/test_rerun_page.py | 11 ++++-- app/web/execute.py | 18 ++++++---- docs/cli/run.md | 2 +- 16 files changed, 141 insertions(+), 37 deletions(-) diff --git a/app/nullius/leaderboard/board.py b/app/nullius/leaderboard/board.py index eeca3cb3e..24c40cb0e 100644 --- a/app/nullius/leaderboard/board.py +++ b/app/nullius/leaderboard/board.py @@ -34,7 +34,9 @@ def row_identity(job): return {"agent": agent, "version": version or identity.get("agent_version", job.agent_version), "model": identity.get("model", job.model_name), "effort": job.reasoning_effort, "provider": identity.get("provider"), "options": identity.get("agent_options"), - "backend": identity.get("backend") or job.launch.get("environment"), "limits": limits} + "backend": identity.get("backend") or job.launch.get("environment"), "limits": limits, + # a judge or user simulator on a provider of its own is another row; a run without one keeps its key + **({"role_providers": identity["role_providers"]} if identity.get("role_providers") else {})} def key_for(identity): diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index b0cc4c479..f1d1a76c7 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -34,7 +34,7 @@ # The shape this module produces. A workspace caches parsed Jobs keyed on it, # so bump it when a Trial or Job field is added, renamed or means something # new — otherwise a cache written by the old parse is read back as current. -SCHEMA = "30" +SCHEMA = "31" # 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 — @@ -1253,7 +1253,7 @@ def identity_of(cfg: dict, res: dict, agent_version: str = "") -> dict: (``cfg``) and its ``result.json`` (``res``): the benchmark, its version and options; the agent as the run named it, the version its trials report (``agent_version``) and its options, defaults included; the backend its units ran on; the model; the - provider; the serving providers pinned by model (``served_by``) and who + provider, and a judge's or user simulator's own (``role_providers``); the serving providers pinned by model (``served_by``) and who served (``served``); and the limits in force: time limits by phase, turns, model calls, attempts of each unit, retries, units at a time, and the spending caps and resource constraints. A fact the job does not record is not a key, never an @@ -1273,6 +1273,7 @@ def identity_of(cfg: dict, res: dict, agent_version: str = "") -> dict: # a control asks no model unless it has a judge or a simulated user; the provider it records is then a default asks = out["model"] or std.get("judge") or std.get("simulator") or std.get("kind") != "control" out["provider"] = word(std.get("provider")) if asks else "" + out["role_providers"] = {r: word(std[r + "_provider"]) for r in ("judge", "simulator") if isinstance(std.get(r + "_provider"), str)} pins = std.get("served_by") if isinstance(std.get("served_by"), dict) else {} out["served_by"] = {redact(str(m)): [word(s) for s in slugs if isinstance(s, str)] for m, slugs in pins.items() if isinstance(slugs, list) and slugs} diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index bbbe73fc1..f6a853793 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -144,11 +144,20 @@ def run_env(provider: str, env=os.environ, role: str = "") -> dict: out = {k: v for k, v in env.items() if k in run.KEEP or k == boat.NAME} if env.get(key): out[providers.key_setting(provider)] = env[key] - if provider == "custom" and env.get(url): - out["MODEL_API_URL"] = env[url] + kind, endpoint = providers.split(provider) + if kind == "custom" and env.get(url): + out[providers.endpoint_vars(endpoint)[0]] = env[url] return out +def _role_provider(value: str) -> str: + """A role's provider on the command line: a run provider, or ``custom:ID`` for a named endpoint + (MODEL__API_URL, MODEL__API_KEY).""" + if providers.split(value)[0] not in providers.PROVIDERS: + raise argparse.ArgumentTypeError(f"{value!r}: one of {', '.join(sorted(providers.PROVIDERS))}, or custom:ID") + return value + + def role_env(providers_: dict, from_run: bool, env=os.environ) -> dict: """By role, the environment a role's own provider is read from: what the launcher handed it, for a run started by Nullius; none otherwise, so the run reads the provider's settings as it does its own.""" @@ -1607,10 +1616,11 @@ def main(argv=None): "one with an experiment judge (LoCoMo's): run it, as this model") p.add_argument("--simulator-model", help="a benchmark whose user a model plays: this model instead of its official one") if name == "run": - p.add_argument("--judge-provider", choices=sorted(providers.PROVIDERS), - help="the judge's provider, its own key (default: --provider)") - p.add_argument("--simulator-provider", choices=sorted(providers.PROVIDERS), - help="the user simulator's provider, its own key (default: --provider)") + p.add_argument("--judge-provider", type=_role_provider, metavar="PROVIDER", + help="the judge's provider, its own key (default: --provider): " + f"{', '.join(sorted(providers.PROVIDERS))}, or custom:ID for a named endpoint") + p.add_argument("--simulator-provider", type=_role_provider, metavar="PROVIDER", + help="the user simulator's provider, its own key (default: --provider); as --judge-provider") p.add_argument("--attempts", "--repeat", dest="repeat", type=int, default=1, metavar="K", help="run each unit K times, each an attempt counted whatever its result " "(the upstream's --num-trials, pass^k); default 1") diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index ccd7b09c2..f3cea665b 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -474,7 +474,9 @@ def compile(recipe: dict, defs: Optional[Dict[str, List[dict]]] = None, *, ``judge_provider``, ``simulator_provider``: a provider of that role's own, as the Model step names one (``providers.choice``), compiled into ``--judge-provider``, ``--simulator-provider``; empty or the agent's, - the agent's. ``roles`` says which a job calls, for the run's keys. + the agent's. ``roles`` says which a job calls, for the run's keys; + ``provider`` the agent's choice, the judge's for controls alone whose + judge has its own: the run's one provider then. ``served_by``: on OpenRouter, the serving providers each model field pins, ``{model|simulator|judge: [slug, ...]}``, checked as ``--served-by`` is and compiled into it for each job that calls that model, by the name @@ -490,7 +492,7 @@ def add(step, message, shown=False, field=None, unset=False): if not any(e["step"] == STEP[step] and e["message"] == message for e in errors): errors.append({"step": STEP[step], "message": message, **({"shown": True} if shown else {}), **({"field": field} if field else {}), **({"unset": True} if unset else {})}) out = {"errors": errors, "notes": notes, "review": [], "jobs": [], "confirm": "", "script": "", "parts": [], "model": "", - "served_models": {}, "own_reasoning": {}, "roles": {}} + "served_models": {}, "own_reasoning": {}, "roles": {}, "provider": ""} name = str(recipe.get("name") or "") if not _NAME.match(name): add("limits", "The recipe's name may hold letters, digits, dots, dashes and underscores.") @@ -766,6 +768,15 @@ def add(step, message, shown=False, field=None, unset=False): role_choice[role_] = c_ else: add("model", f"Choose the {SERVED_LABEL[role_]}'s provider: Same as agent, or one of the providers.") + judge_model = str(recipe.get("judge_model") or "").strip() + # the judge the run asks: the official one, or an experiment judge whose model the recipe names + judges = bool((b.get("score") or {}).get("judge") or (judge_model and (b.get("score") or {}).get("experiment_judge"))) + # controls alone call no model of the agent's: a judge on a provider of its own is then the run's one provider, + # and the agent's key is neither asked nor handed (execute.providers_problem, Plan) + if only_controls and judges and "judge" in role_choice and not needs["embeddings"] and not needs["reranker"]: + agent_choice = role_choice.pop("judge") + provider = provider_ = providers.split(agent_choice)[0] + out["provider"] = agent_choice prov = lambda role: providers.split(role_choice[role])[0] if role in role_choice else provider_ # what each part asks of the provider, as the builder reads it (command-builder-core.js, consumersOf): an agent its # apis, a setup chat; a judged benchmark's judge chat @@ -773,9 +784,6 @@ def add(step, message, shown=False, field=None, unset=False): apis = None if pk["control"] else (pk["o"].get("model") or {}).get("apis") or ["chat"] if apis and provider not in providers.offered(apis): add("model", f"{providers.label(provider)} does not serve what {pk['o']['label']} speaks: choose another provider.") - judge_model = str(recipe.get("judge_model") or "").strip() - # the judge the run asks: the official one, or an experiment judge whose model the recipe names - judges = bool((b.get("score") or {}).get("judge") or (judge_model and (b.get("score") or {}).get("experiment_judge"))) for role_, used_ in (("judge", judges), ("simulator", bool(b.get("simulator")) and any(not p["control"] for p in picks))): on_ = prov(role_) if on_ in PROVIDERS and used_ and on_ not in providers.offered(["chat"]): @@ -997,6 +1005,9 @@ def called_of(p: dict) -> List[str]: if m in by_model and by_model[m] != list(slugs): add("model", f"Served by pins {m} twice, with different providers: give its fields the same ones.") by_model[m] = list(slugs) + # the pin goes with the name: a field on another provider calling the same model would take it there too + if any(sent_of(p).get(r) == m and role_choice.get(r, agent_choice) != role_choice.get(role, agent_choice) for r in roles): + add("model", f"Served by: {m} is called on two providers, so a pin would reach both: leave it empty, or give both fields one provider.") # each field's model as the run sends it, for the builder to ask its providers under that name out["served_models"] = {role: next((sent_of(p)[role] for p in sorted(picks, key=lambda q: q["control"]) if _MODEL.match(sent_of(p)[role] or "")), None) for role in roles} @@ -1097,9 +1108,9 @@ def command_for(d: dict, p: dict, index: int) -> str: *(["--exchanges", keep] if keep != exchanges.DEFAULT else []), *(["--exchanges-max-mb", str(keep_mb)] if keep_mb != exchanges.MAX_MB else []), *(["--simulator-model", sim_model] if sim_model and not p["control"] else []), - *(["--simulator-provider", prov("simulator")] if "simulator" in out["roles"] and not p["control"] else []), + *(["--simulator-provider", out["roles"]["simulator"]] if "simulator" in out["roles"] and not p["control"] else []), *(["--judge-model", judge_model] if judge_model else []), - *(["--judge-provider", prov("judge")] if "judge" in out["roles"] else []), + *(["--judge-provider", out["roles"]["judge"]] if "judge" in out["roles"] else []), "--name", job_of(d, p, index), *[w for k, v in given.items() for w in ("--option", f"{k}={v}")], *(["--backend", backend] if backend != "local" else []), *(["--boat-size", boat_size] if backend == "boat" and (whole or not control and not p.get("setup")) else []), @@ -1177,7 +1188,7 @@ def row(p: dict) -> list: for k, v in p["opts"].items())] for p in picks if p["opts"]], [STEP["model"], "Model", "none: a control calls no model" if keyless and all(p["control"] for p in listed) - else (f"{providers.label(providers.choice(provider, str(recipe.get('endpoint') or '')))} · " if provider in PROVIDERS else "") + else (f"{providers.label(agent_choice)} · " if provider in PROVIDERS else "") + ((model or "not chosen") if not listed or any(not p["control"] for p in listed) else ", ".join(p["o"]["sent"] for p in picks if p.get("setup")) or "the judge only") + (f" · user simulator {sim_model or (b.get('simulator') or {}).get('model')}" + (" (leaderboard)" if lb.get("simulator") else "" if sim_model else " (official)") if b.get("simulator") else "") + (f" on {providers.label(out['roles']['simulator'])}" if "simulator" in out["roles"] else "") diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index c92317526..809bb6c47 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -168,14 +168,16 @@ def setup_request(bench: dict, kind: str, attempt: Optional[int] = None) -> tupl def provider_endpoint(provider: str, env=os.environ) -> tuple: """(base, key) of a run provider (``providers.PROVIDERS``), from its record: ``custom`` is the one at - MODEL_API_URL, which a run's launcher fills from the run's own provider (``cli.run_env``).""" - if provider not in providers.PROVIDERS: + MODEL_API_URL, which a run's launcher fills from the run's own provider (``cli.run_env``); ``custom:ID`` + a named one, a role's (MODEL__API_URL).""" + kind, endpoint = providers.split(provider) + if kind not in providers.PROVIDERS: raise Refused(f"provider {provider!r} is not one of {list(providers.PROVIDERS)}") rec = providers.record(provider, env) base = rec["base"] - key = env.get(rec["key"]) or (settings.MODEL_KEY_PLACEHOLDER if provider == "custom" else "") + key = env.get(rec["key"]) or (settings.MODEL_KEY_PLACEHOLDER if kind == "custom" else "") if not base: - raise Refused("MODEL_API_URL is not set in Settings") + raise Refused(f"{providers.endpoint_vars(endpoint)[0]} is not set in Settings") if not key: raise Refused(f"{rec['key']} is not set in Settings") if not key.isprintable() or any(ord(c) > 255 for c in key) or key != key.strip(): @@ -234,7 +236,7 @@ def key_header(provider: str, other: dict, env=os.environ) -> str: """How the agent's relay sends the key: by the protocol the agent (or Module) speaks on this provider. Refused on a provider that serves none of them.""" apis = (other.get("model") or {}).get("apis") or ["chat"] - if provider not in providers.offered(apis, env): + if providers.split(provider)[0] not in providers.offered(apis, env): raise Refused(f"{providers.label(provider, env)} does not serve what {other.get('key') or 'the agent'} speaks " f"({', '.join(apis)}): choose another provider") return providers.PROTOCOLS[providers.protocol_for(provider, apis, env)]["auth"] @@ -1069,6 +1071,14 @@ def __init__(self, bench: dict, other: dict, *, model: str, provider: str, datas if bad: raise Refused("--served-by: " + "; ".join(bad)) self.serving = {m: list(s) for m, s in self.serving.items()} + # the pin goes with the name: a model called on the agent's provider and on a role's own would take it on both + theirs = lambda r: None if r in asked else getattr(self, r + "_model") + control = other.get("_kind") == "control" + mine = {None if control else self.model, theirs("judge"), None if control else theirs("simulator"), self.embed_model, self.rerank_model} + twice = sorted(m for m in self.serving if m in mine and m in {getattr(self, r + "_model") for r in asked}) + if twice: + raise Refused(f"--served-by {', '.join(twice)}: called on the agent's provider and on a role's own, so a pin " + "would reach both: pin none, or give both one provider") own = {getattr(self, r + "_model"): p for r, p in asked.items()} serving = sorted({own.get(m, provider) for m in self.serving} - {"openrouter"}) if serving: @@ -2448,11 +2458,16 @@ def known_models(self) -> None: for that role's model alone.""" if not self.base: return - own = {getattr(self, r + "_model", None): r for r in getattr(self, "role_providers", {})} - asked: Dict[tuple, List[str]] = {} - for m in self.models_called(): - role = own.get(m) - asked.setdefault((self.role_providers[role], role) if role else (self.provider, ""), []).append(m) + roles = getattr(self, "role_providers", {}) + own = {getattr(self, r + "_model", None) for r in roles} + # the agent's provider: every model but one only a role on its own calls; a name both call is asked of both + control = (getattr(self, "other", None) or {}).get("_kind") == "control" + agents = {None if control else getattr(self, "model", None), getattr(self, "embed_model", None), getattr(self, "rerank_model", None), + *(getattr(self, r + "_model", None) for r in ("judge", "simulator") if r not in roles)} + asked: Dict[tuple, List[str]] = {(self.provider, ""): [m for m in self.models_called() if m not in own or m in agents]} + for role, p in roles.items(): + if getattr(self, role + "_model", None): + asked.setdefault((p, role), []).append(getattr(self, role + "_model")) for (provider, role), models in asked.items(): env = self.role_env[role] if role else getattr(self, "provider_env", os.environ) try: diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index 755251bcc..0b05d3049 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -446,6 +446,8 @@ const b = standardBench(r); return [...(judgesRun(r) ? ['judge'] : []), ...(b && b.simulator && chosenOf(r).some(k => !(b.controls || []).some(c => c.key === k)) ? ['simulator'] : [])]; }; + // Controls alone whose judge runs on its own provider: nothing calls the agent's, and the run is the judge's alone. + const agentIdle = r => { const b = standardBench(r), c = chosenOf(r); return !!b && judgesRun(r) && ownRole(r, 'judge') && c.length > 0 && c.every(k => (b.controls || []).some(x => x.key === k)); }; // The role Run waits for, or '': one on the agent's provider that serves no chat, or one on its own provider not // set here (recipe.py says the same). const unserved = r => PROVIDERS.includes(r.provider) && !serving(r.provider, ['chat']) && rolesRun(r).find(x => !ownRole(r, x)) || ''; @@ -467,6 +469,7 @@ function agentBlocker(r) { if (!schema.credentials || (!isStandard(r) && !needsCredentials(r))) return ''; if (isStandard(r) && standardKeyless(r)) return ''; // a control of an unjudged benchmark is handed no key (execution.Plan.keyless) + if (isStandard(r) && agentIdle(r)) return ''; // controls whose judge has its own provider: the run's one (recipe.py) const offered = providersOf(r), have = available().filter(p => offered.includes(kindOf(p))), p = choiceOf(r); const or = xs => xs.slice(0, -1).join(', ') + (xs.length > 1 ? ' or ' : '') + xs[xs.length - 1]; if (have.includes(p)) return ''; diff --git a/app/static/builder/command-builder.css b/app/static/builder/command-builder.css index 4e16ff0ab..7620708cd 100644 --- a/app/static/builder/command-builder.css +++ b/app/static/builder/command-builder.css @@ -229,6 +229,7 @@ #nullius-builder .std-role-name { margin-top: 12px; min-height: 0; } #nullius-builder .std-role-word { display: block; } #nullius-builder .std-role-word:empty { display: none; } + #nullius-builder .std-role-cell:has(> .std-served[hidden]) > .std-role-word { display: none; } } /* Compact settings rows use one shared control column, including paired fields. */ diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index dfed68ffb..f167cd74f 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -494,7 +494,9 @@ const roleProvider = (rec, role, who) => { const own = role !== 'model', offered = own ? C.roleProvidersOf() : C.providersOf(rec), agent = C.choiceOf(rec); const have = C.available().filter(p => offered.includes(p.split(':')[0])), current = own ? (C.ownRole(rec, role) ? C.roleChoiceOf(rec, role) : '') : agent; - const shown = (!have.length ? offered : [...have, ...(have.includes(current) || !current ? [] : [current])]).filter(p => !own || p !== agent); + // the recipe's own choice stays listed, and shown, when Settings has none of it (a named endpoint, say) + const shown = [...(!have.length ? offered : have), ...(!current || (!have.length ? offered : have).includes(current) ? [] : [current])] + .filter(p => !own || p !== agent); const name = p => !p ? 'Same as ' + who.toLowerCase().replace('module', 'Module') : have.length && !have.includes(p) ? C.labelOf(p) + ' · not set in Settings' : C.labelOf(p); const options = (own ? ['', ...shown] : shown).map(p => [p, name(p)]); if (options.length === 1 && options[0][0] === current) return `${esc(options[0][1])}`; diff --git a/app/templates/runs/job.html b/app/templates/runs/job.html index 8f1ab17fa..c08d56218 100644 --- a/app/templates/runs/job.html +++ b/app/templates/runs/job.html @@ -19,6 +19,7 @@ {%- for k, v in (facts.benchmark_options or {}).items() if v is not none %}{% set _ = benchmark_rows.append((names.benchmark_options[k], fact_value(v))) %}{% endfor %} {%- for k, v in (facts.agent_options or {}).items() if v is not none %}{% set _ = agent_rows.append((names.agent_options[k], fact_value(v))) %}{% endfor %} {%- if facts.provider %}{% set _ = agent_rows.append(('Provider', facts.provider|provider)) %}{% endif %} +{%- for role, name in [('judge', 'Judge provider'), ('simulator', 'User simulator provider')] if (facts.role_providers or {})[role] %}{% set _ = agent_rows.append((name, facts.role_providers[role]|provider)) %}{% endfor %} {%- if facts.served_by %}{% set requested %}{% for m, slugs in facts.served_by.items() %}{% if not loop.first %} · {% endif %}{% if facts.served_by|length > 1 %}{{ m }}: {% endif %}{{ slugs|join(', ') }}{% endfor %}{% endset %}{% set _ = agent_rows.append(('Requested', requested)) %}{% endif %} {%- if facts.served and (facts.served.calls or facts.served.unnamed) %}{% set answered %}{% for name, n in facts.served.calls.items() %}{% if not loop.first %}, {% endif %}{{ name }} · {{ calls(n) }}{% endfor %}{% if facts.served.unnamed %}{% if facts.served.calls %}, {% endif %}unnamed · {{ calls(facts.served.unnamed) }}{% endif %}{% endset %}{% set _ = agent_rows.append(('Answered by', answered)) %}{% endif %} {%- for key, name in [('concurrency', 'Concurrent'), ('repeat', 'Attempts'), ('retries', 'Retries'), ('max_turns', 'Turns'), ('max_calls', 'Model calls')] if key in lim %}{% set _ = limit_rows.append((name, lim[key])) %}{% endfor %} diff --git a/app/tests/test_leaderboard_service.py b/app/tests/test_leaderboard_service.py index facc5a322..546053808 100644 --- a/app/tests/test_leaderboard_service.py +++ b/app/tests/test_leaderboard_service.py @@ -18,6 +18,17 @@ class RecordedIdentity(unittest.TestCase): + def test_a_judge_on_its_own_provider_is_part_of_what_tells_runs_apart(self): + from types import SimpleNamespace + from nullius.leaderboard import board + cfg = lambda **own: {"standard": {"benchmark": "b", "provider": "openai", "kind": "agent", **own}, "agents": [{"model_name": "m"}]} + own, plain = parse.identity_of(cfg(judge_provider="openrouter"), {}), parse.identity_of(cfg(), {}) + self.assertEqual((own["role_providers"], "role_providers" in plain), ({"judge": "openrouter"}, False)) + row = lambda identity: board.row_identity(SimpleNamespace(identity=identity, agent_name="a", agent_version="", model_name="m", + reasoning_effort=None, launch={})) + self.assertNotEqual(board.key_for(row(own)), board.key_for(row(plain))) + self.assertNotIn("role_providers", row(plain)) # a run from before keeps its row + def test_new_standard_runs_record_the_resolved_source_pin(self): for key in ("gaia", "osworld1"): bench = definitions.get("benchmark", key) diff --git a/app/tests/test_standard_recipe_served_by.py b/app/tests/test_standard_recipe_served_by.py index 556f66a41..984e27883 100644 --- a/app/tests/test_standard_recipe_served_by.py +++ b/app/tests/test_standard_recipe_served_by.py @@ -101,6 +101,19 @@ def test_a_user_simulator_left_on_the_agents_provider_must_speak_chat_there(self self.assertTrue(said(recipe.compile(r))) self.assertEqual(said(recipe.compile(dict(r, simulator_provider="openrouter"))), []) + def test_controls_alone_run_on_their_judges_own_provider_and_a_named_endpoint_is_named(self): + d = defs(judged()) + alone = recipe.compile(a_recipe(provider="openai", model="", other="", others=["nop"], judge_provider="openrouter"), d) + self.assertEqual((alone["errors"], alone["provider"], alone["roles"], alone["keyless"]), ([], "openrouter", {}, False)) + self.assertIn("--provider openrouter ", alone["script"]) + self.assertNotIn("--judge-provider", alone["script"]) + lab = recipe.compile(a_recipe(judge_provider="custom:LAB"), d) + self.assertEqual((lab["errors"], lab["provider"], lab["roles"]), ([], "openrouter", {"judge": "custom:LAB"})) + self.assertIn("--judge-provider custom:LAB", lab["script"]) + # a pin goes with the name: the agent's model as the judge's too, on another provider, would take it on both + twice = recipe.compile(a_recipe(model="openai/gpt-4o-mini", judge_model="openai/gpt-4o-mini", judge_provider="custom:LAB", served_by={"model": ["a"]}), d) + self.assertTrue(any("called on two providers" in e["message"] for e in twice["errors"]), twice["errors"]) + def test_a_pin_is_refused_as_the_option_is(self): for kw, said in (({"provider": "openai", "model": "gpt-5-mini", "served_by": {"model": ["deepinfra"]}}, "needs OpenRouter"), ({"served_by": {"model": ["bad slug"]}}, "not a serving provider's slug"), diff --git a/app/tests/test_standard_served_by.py b/app/tests/test_standard_served_by.py index fe8e58de1..c3569ac88 100644 --- a/app/tests/test_standard_served_by.py +++ b/app/tests/test_standard_served_by.py @@ -595,6 +595,22 @@ def test_a_judge_on_its_own_provider_is_named_listed_and_called_there_with_its_o with self.subTest(kw=kw), self.assertRaisesRegex(run.Refused, said): self.make(bench=judged, **{**own, **kw}) + def test_a_role_names_an_endpoint_by_id_and_each_provider_lists_its_own_models(self): + judged = dict(self.b, score=dict(self.b["score"], judge={"model": "m-1", "says": "a judge"})) + env = {"OPENROUTER_API_KEY": "or-test", "MODEL_LAB_API_URL": self.base, "MODEL_LAB_API_KEY": "sk-lab"} + r = self.make(bench=judged, env=env, judge_provider="custom:LAB") + # by hand, no --from-run: the named endpoint's own settings + self.assertEqual((r.upstreams, r.role_providers), ({"judge": (self.base, "sk-lab")}, {"judge": "custom:LAB"})) + self.assertEqual(cli.run_env("custom:LAB", {"NULLIUS_JUDGE_API_KEY": "k", "NULLIUS_JUDGE_BASE_URL": "u"}, "judge"), + {"MODEL_LAB_API_KEY": "k", "MODEL_LAB_API_URL": "u"}) + asked = [] + with mock.patch.object(run.providers, "list_models", lambda p, env, **kw: asked.append(p) or [{"id": "m-1"}]): + r.known_models() + self.assertEqual(asked, ["openrouter", "custom:LAB"]) # m-1 on both: each lists it + # a pin goes with the name: one called on two providers would reach both, and is refused + with self.assertRaisesRegex(run.Refused, "m-1: called on the agent's provider and on a role's own"): + self.make(bench=judged, env=env, judge_provider="custom:LAB", served_by={"m-1": ["prov-a"]}) + def test_the_summary_counts_every_route_of_the_unit(self): """A judge on the pinned model, served by another provider than the agent's: the pin does not hold.""" r = self.make(judge_model="m-1", served_by={"m-1": ["prov-a"]}) diff --git a/app/ui_tests/test_command_builder_providers.py b/app/ui_tests/test_command_builder_providers.py index 8f7bc8c78..96536cf30 100644 --- a/app/ui_tests/test_command_builder_providers.py +++ b/app/ui_tests/test_command_builder_providers.py @@ -179,6 +179,11 @@ def test_run_waits_for_a_provider_that_is_set_and_never_switches_one(self): controls = ("const r=C.createStandard('tau3-bench','nop');r.model='x';C.setChoice(r,'openrouter');C.setRoleChoice(r,'simulator','openai');" "process.stdout.write(JSON.stringify(C.providerBlocker(r)))") self.assertEqual(self.on(['openrouter'], controls), '') + # controls alone whose judge has its own provider: the run's one, the agent's key unasked + idle = ("const b=C.standard().benchmarks.find(x=>x.judge&&(x.controls||[]).some(c=>c.key==='nop'));const r=C.createStandard(b.key,'nop');" + "C.setChoice(r,'openai');C.setRoleChoice(r,'judge','openrouter');process.stdout.write(JSON.stringify(C.providerBlocker(r)))") + self.assertEqual(self.on(['openrouter'], idle), '') + self.assertIn('OPENROUTER_API_KEY', self.on(['openai'], idle)) # a role keeps its own provider when the agent's changes, the agent's included kept = ("const r=C.createStandard('tau3-bench','codex');r.model='x';C.setChoice(r,'openrouter');C.setRoleChoice(r,'judge','openai');" "C.setChoice(r,'openai');C.setChoice(r,'openrouter');process.stdout.write(JSON.stringify(r.judge_provider||''))") diff --git a/app/ui_tests/test_rerun_page.py b/app/ui_tests/test_rerun_page.py index ec30b3e07..f4e8a9423 100644 --- a/app/ui_tests/test_rerun_page.py +++ b/app/ui_tests/test_rerun_page.py @@ -23,6 +23,7 @@ from nullius.standard.runner import job from ui_tests.test_capped_job import AGENT, BENCH from .test_routes import web +from web import execute UNITS = ["t-0", "t-1", "t-2"] @@ -147,10 +148,16 @@ def test_a_judge_on_its_own_provider_needs_its_key_to_run_again(self): d = self.run_of(recipe={"provider": "openai", "judge_provider": "openrouter"}, roles={"judge": {"key_var": "OPENROUTER_API_KEY", "url_var": "", "base_url": "https://openrouter.ai/api/v1"}}) self.open(d.parent) - with patch.dict(os.environ, {"OPENROUTER_API_KEY": ""}): + compiled = {"provider": "openai", "roles": {"judge": "openrouter"}} + with patch.dict(os.environ, {"OPENROUTER_API_KEY": ""}), patch.object(execute.standard_recipe, "compile", lambda r: compiled): r = self.post("r1", {"trials": [trial_name(0)]}) self.assertEqual(r.status_code, 400); self.assertIn("OPENROUTER_API_KEY", r.json["error"]) - self.assertEqual(self.asked, []) + # controls alone with the judge on its own provider: the run's one provider is the judge's, the agent's unasked + compiled = {"provider": "openrouter", "roles": {}} + with patch.dict(os.environ, {"OPENROUTER_API_KEY": "sk-or", "OPENAI_API_KEY": ""}), \ + patch.object(execute.standard_recipe, "compile", lambda r: compiled): + self.assertEqual(self.post("r1", {"trials": [trial_name(0)]}).status_code, 200) + self.assertEqual(len(self.asked), 1) def test_a_job_on_a_host_goes_back_there_and_a_host_without_it_is_refused(self): d = self.run_of(host="bench") diff --git a/app/web/execute.py b/app/web/execute.py index 6a042b5ed..1696f7031 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -120,10 +120,16 @@ def roles_for(out: dict) -> dict: return {r: credentials_for(*providers.split(c)) for r, c in (out.get("roles") or {}).items()} +def run_provider(recipe: dict, out: dict) -> tuple: + """(provider, endpoint) the compiled recipe's run calls as its own: the agent's, or for controls alone the + judge's when it has one of its own (``recipe.compile``).""" + return providers.split(out["provider"]) if out.get("provider") else (recipe.get("provider"), recipe.get("endpoint")) + + def providers_problem(recipe: dict, out: dict) -> str: """Why a run of the compiled recipe cannot start here on one of its providers (``provider_problem``): - the agent's, unless nothing calls a model, then each role's own.""" - for p, e in ([] if out.get("keyless") else [(recipe.get("provider"), recipe.get("endpoint"))]) \ + the run's own (``recipe.compile``'s ``provider``), unless nothing calls a model, then each role's own.""" + for p, e in ([] if out.get("keyless") else [run_provider(recipe, out)]) \ + [providers.split(c) for c in (out.get("roles") or {}).values()]: why = provider_problem(p, e) if why: @@ -144,7 +150,7 @@ def standard_plans(recipe: dict, out: dict, known) -> tuple: if host.entry not in known: return [], f"{sh['where']} is not one of the hosts in Settings" plans.append(execution.Plan(name=sh["name"], script=sh["script"], host=host, runner=standard_recipe.HARNESS, - **credentials_for(recipe.get("provider"), recipe.get("endpoint")), roles=roles_for(out), model=out["model"], jobs=sh["jobs"], + **credentials_for(*run_provider(recipe, out)), roles=roles_for(out), model=out["model"], jobs=sh["jobs"], parts=sh["parts"], recipe=recipe, docker=bool(out.get("docker")), keyless=bool(out.get("keyless")), licences=dict(out.get("licences") or {}) if host else {})) return plans, "" @@ -322,9 +328,9 @@ def job_rerun(job_id): said = rerun.spent_out(budget, "change it to run more.") return jsonify(ok=False, error=said[0].upper() + said[1:]), 409 recipe = ex.plan.recipe or {} - missing = "" if ex.plan.keyless else provider_problem(recipe.get("provider") or "openai", recipe.get("endpoint")) - for role in () if ex.plan.keyless else (ex.plan.roles or {}): # each role's own provider, as Run asked - missing = missing or provider_problem(*providers.split(str(recipe.get(role + "_provider") or ""))) + # the providers Run asked for, as the recipe compiles now: the run's own and each role's + missing = "" if ex.plan.keyless else providers_problem(dict(recipe, provider=recipe.get("provider") or "openai"), + standard_recipe.compile(recipe)) if missing: return jsonify(ok=False, error=missing), 400 gone = ex.holds(job_id) diff --git a/docs/cli/run.md b/docs/cli/run.md index b750dff5a..b576d636b 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -28,7 +28,7 @@ nullius standard run locomo model --model gpt-4o-mini | `` | `KEY` or `KEY@VERSION`; `nop` or `oracle`; `original` or `model` | | `--model` | None for a control; `original` defaults to the paper's first | | `--provider` | `anthropic`, `custom`, `openai` or `openrouter` | -| `--judge-provider`, `--simulator-provider` | The judge's, the simulated user's own provider and key; default `--provider`. It must serve chat | +| `--judge-provider`, `--simulator-provider` | The judge's, the simulated user's own provider and key; default `--provider`; `custom:ID` for a named endpoint. It must serve chat. A pin (`--served-by`) on a model both providers are asked is refused | | `--dataset`, `--limit`, `-j` | One dataset, the first N units, N at a time | | `--units FILE` | Only the units the file lists: [below](#a-list-of-units) | | `--set NAME` | Only the units of a [task set](task-sets.md), in its dataset |