diff --git a/AGENTS.md b/AGENTS.md
index ad99e5e7..1f3e0bd9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -168,6 +168,7 @@ Short and plain: issues, pull requests, their comments, docs.
| The run builder | `docs/builder.md`; `app/nullius/recipes/launch.py`; `app/static/builder/command-builder-core.js` |
| A whole design | Docstrings of `execution.py`, `catalogue/catalog.py`, `harbor/source.py`, `runs/live.py` |
| A command | `docs/cli/README.md` |
+| The API, its client, `nullius remote`, MCP | `docs/api.md`; docstring of `app/web/api.py` |
| Settings and storage | `docs/settings/README.md`; `app/nullius/settings.py` |
| Judgement; the PR judge | `docs/judgement.md`; docstring of `.github/scripts/judge_pr.py` |
| A run that looks wrong, comparing runs | `/run-analysis` |
diff --git a/README.md b/README.md
index c6d8647c..73506ff6 100644
--- a/README.md
+++ b/README.md
@@ -139,6 +139,7 @@ site](app/site/README.md).
| [Quickstart](docs/getting-started.md) | Launch, open results, a first run |
| [Core concepts](docs/concepts.md) | Benchmarks, agents, recipes, trials, evidence |
| [Run builder](docs/builder.md) | The stages, the run, Harbor's pin |
+| [From another machine](docs/api.md) | Tokens, the Python client, `nullius remote`, MCP, the routes |
| [Read results](docs/results.md) | Failures, controls, comparisons |
| [Judgement](docs/judgement.md) | What a judge model is asked |
| [The Nullius standard](docs/standard.md) | Ports, kits, setups, controls, proofs; importing |
diff --git a/app/app.py b/app/app.py
index 101100cb..25c61e33 100644
--- a/app/app.py
+++ b/app/app.py
@@ -28,11 +28,11 @@
if __package__: # the wheel's private web namespace
from .web.core import app
from .web import shared
- from .web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure
+ from .web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure, api
else: # python app/app.py, and the source route suite
from web.core import app
from web import shared
- from web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure
+ from web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure, api
from nullius import execution, workspace # noqa: E402 - recorded runs, picked up again at start; the workspace left open
diff --git a/app/nullius/access.py b/app/nullius/access.py
new file mode 100644
index 00000000..e7aa4066
--- /dev/null
+++ b/app/nullius/access.py
@@ -0,0 +1,189 @@
+"""API tokens: who may ask this server over HTTP (``/api/v1``, ``web/api.py``).
+
+ nullius access create NAME [--scope read|run] [--days N] # prints the token, once
+ nullius access list [--json]
+ nullius access revoke ID
+
+One owner-only file, ``api-tokens.json`` in the user configuration directory,
+holds each token's id, name, scope, creation time, the day it expires when it
+has one, and the SHA-256 of its secret, never the secret: a token is shown when
+it is created and cannot be read back. With no token in the file the API
+answers nothing; an expired token is refused as a revoked one is.
+
+``read`` reads what the pages show: the catalogue, jobs, trials, comparisons,
+saved recipes, runs. ``run`` also checks, starts, continues and stops runs,
+asks a judge and saves recipes. No scope reads or writes Settings, keys or licences.
+Standard library only.
+"""
+from __future__ import annotations
+
+import argparse
+import calendar
+import contextlib
+import hashlib
+import hmac
+import json
+import os
+import re
+import secrets
+import sys
+import time
+from typing import List, Optional
+
+from nullius import ondisk, paths
+
+SCOPES = ("read", "run") # each includes the ones before it
+PREFIX = "nls"
+MAX_DAYS = 3650
+_STAMP = "%Y-%m-%dT%H:%M:%SZ"
+_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9 ._-]{0,63}")
+_TOKEN = re.compile(PREFIX + r"_([0-9a-f]{12})_([A-Za-z0-9_-]{40,})")
+_SHA256 = re.compile(r"[0-9a-f]{64}")
+
+
+def file(env=None) -> str:
+ return os.path.join(paths.config_dir(env), "api-tokens.json")
+
+
+def listing() -> List[dict]:
+ """Every token's record, oldest first; a file that is missing or unreadable holds none."""
+ try:
+ rows = _kept()
+ except ValueError:
+ return []
+ return [r for r in rows if isinstance(r, dict) and isinstance(r.get("id"), str) and r.get("scope") in SCOPES
+ and isinstance(r.get("sha256"), str) and _SHA256.fullmatch(r["sha256"])]
+
+
+def _kept() -> list:
+ """The file's rows as they are, [] without a file; ValueError when it cannot be read."""
+ try:
+ with open(file(), encoding="utf-8") as fh:
+ rows = json.load(fh)["tokens"]
+ except FileNotFoundError:
+ return []
+ except (OSError, ValueError, KeyError, TypeError):
+ rows = None
+ if not isinstance(rows, list):
+ raise ValueError(f"the tokens' file cannot be read: repair or remove {file()}")
+ return rows
+
+
+@contextlib.contextmanager
+def _changing():
+ """The rows to change, written back on leaving: one change at a time, the page's and the command's. A file that
+ cannot be read is left as it is (ValueError), never written over."""
+ os.makedirs(os.path.dirname(file()), mode=0o700, exist_ok=True)
+ with ondisk.locked(file() + ".lock"):
+ rows = _kept()
+ yield rows
+ ondisk.write_whole(file(), json.dumps({"tokens": rows}, indent=2) + "\n", mode=0o600)
+
+
+def _digest(secret: str) -> str:
+ return hashlib.sha256(secret.encode()).hexdigest()
+
+
+def create(name: str, scope: str = "read", days: Optional[int] = None) -> tuple:
+ """(token, record): a new token of that scope, good for ``days`` days or until revoked.
+ The token is returned here and kept nowhere."""
+ if not isinstance(name, str) or not _NAME.fullmatch(name):
+ raise ValueError("a token's name is 1 to 64 letters, digits, spaces, '.', '_' or '-'")
+ if scope not in SCOPES:
+ raise ValueError(f"a token's scope is one of: {', '.join(SCOPES)}")
+ if days is not None and (isinstance(days, bool) or not isinstance(days, int) or not 1 <= days <= MAX_DAYS):
+ raise ValueError(f"a token expires after 1 to {MAX_DAYS} days, or never")
+ token_id, secret = secrets.token_hex(6), secrets.token_urlsafe(32)
+ record = {"id": token_id, "name": name, "scope": scope, "sha256": _digest(secret),
+ "created": time.strftime(_STAMP, time.gmtime()),
+ "expires": time.strftime(_STAMP, time.gmtime(time.time() + days * 86400)) if days else None}
+ with _changing() as rows:
+ if any(isinstance(r, dict) and r.get("name") == name for r in rows):
+ raise ValueError(f"a token is named {name!r} already: revoke it first, or choose another name")
+ rows.append(record)
+ return f"{PREFIX}_{token_id}_{secret}", record
+
+
+def revoke(token_id: str) -> bool:
+ with _changing() as rows:
+ kept = [r for r in rows if not (isinstance(r, dict) and r.get("id") == token_id)]
+ gone = len(kept) < len(rows)
+ rows[:] = kept
+ return gone
+
+
+def expired(record: dict, now: Optional[float] = None) -> bool:
+ """Whether a token's day has passed; an expiry that cannot be read has."""
+ if not record.get("expires"):
+ return False
+ try:
+ return calendar.timegm(time.strptime(record["expires"], _STAMP)) <= (time.time() if now is None else now)
+ except (TypeError, ValueError):
+ return True
+
+
+def verify(token) -> Optional[dict]:
+ """The record of a token this server issued, has not revoked and that has not expired, or None."""
+ m = _TOKEN.fullmatch(token) if isinstance(token, str) else None
+ if not m:
+ return None
+ digest = _digest(m.group(2))
+ for r in listing():
+ if r["id"] == m.group(1) and hmac.compare_digest(r["sha256"], digest):
+ return None if expired(r) else r
+ return None
+
+
+def allows(record: Optional[dict], scope: str) -> bool:
+ """Whether a token's scope includes ``scope``: ``run`` reads too."""
+ return bool(record) and record.get("scope") in SCOPES and SCOPES.index(record["scope"]) >= SCOPES.index(scope)
+
+
+def shown(record: dict) -> dict:
+ """A record without its hash, and whether its day has passed: what a listing prints."""
+ return {**{k: record.get(k) for k in ("id", "name", "scope", "created", "expires")}, "expired": expired(record)}
+
+
+def main(argv=None) -> int:
+ ap = argparse.ArgumentParser(prog="nullius access", description="The tokens this server's HTTP API accepts.")
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ c = sub.add_parser("create", help="a new token, printed once")
+ c.add_argument("name")
+ c.add_argument("--scope", choices=SCOPES, default="read", help="read: results only (default). run: also start and stop runs, ask a judge, save recipes")
+ c.add_argument("--days", type=int, help="expires after this many days (default: never)")
+ ls = sub.add_parser("list", help="the tokens, never their secrets")
+ ls.add_argument("--json", action="store_true")
+ r = sub.add_parser("revoke", help="stop accepting a token")
+ r.add_argument("id")
+ a = ap.parse_args(argv)
+ if a.cmd == "create":
+ try:
+ token, record = create(a.name, a.scope, a.days)
+ except ValueError as e:
+ print(e, file=sys.stderr)
+ return 2
+ print(f"{record['name']} ({record['scope']}{', until ' + record['expires'][:10] if record['expires'] else ''}), shown once:", file=sys.stderr)
+ print(token)
+ return 0
+ if a.cmd == "list":
+ rows = [shown(r) for r in listing()]
+ if a.json:
+ print(json.dumps(rows, indent=1))
+ else:
+ for row in rows:
+ until = "expired" if row["expired"] else (row["expires"] or "")[:10] or "never"
+ print(f"{row['id']} {row['scope']:<4} {(row['created'] or '')[:10]:<10} {until:<10} {row['name']}")
+ return 0
+ try:
+ gone = revoke(a.id)
+ except ValueError as e:
+ print(e, file=sys.stderr)
+ return 2
+ if not gone:
+ print(f"no token with id {a.id!r}", file=sys.stderr)
+ return 3
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/app/nullius/cli.py b/app/nullius/cli.py
index aa960909..62d3fb23 100644
--- a/app/nullius/cli.py
+++ b/app/nullius/cli.py
@@ -22,6 +22,9 @@
"paths": "show persistent storage locations",
"prices": "show and update model prices",
"migrate": "copy legacy storage into the user profile",
+ "access": "create and revoke the tokens of this server's HTTP API",
+ "remote": "ask a Nullius server on another machine",
+ "mcp": "a Nullius server as MCP tools, over stdio",
}
MODULES = {
"runs": "nullius.runs.cli",
@@ -33,6 +36,9 @@
"paths": "nullius.paths",
"prices": "nullius.prices",
"migrate": "nullius.migrate",
+ "access": "nullius.access",
+ "remote": "nullius.client",
+ "mcp": "nullius.mcp_server",
}
diff --git a/app/nullius/client.py b/app/nullius/client.py
new file mode 100644
index 00000000..aa172eab
--- /dev/null
+++ b/app/nullius/client.py
@@ -0,0 +1,328 @@
+"""A Nullius server from another machine: its HTTP API (``/api/v1``) as Python, and as ``nullius remote``.
+
+ from nullius.client import Client
+
+ nx = Client("http://bench.internal:5057", token) # or NULLIUS_SERVER and NULLIUS_TOKEN
+ check = nx.check("nightly") # a saved recipe by name, or a recipe as a dict
+ run = nx.start("nightly", confirm=True)["runs"][0]
+ for line in nx.follow(run["id"]):
+ print(line)
+ job = nx.job(run["job_ids"][0])
+ job["adjusted_solve_rate"], job["counts"]
+
+Every method returns the server's JSON document as it is: a job is what
+``nullius runs show --json`` prints, a comparison what ``nullius compare
+--json`` prints. A refusal raises :class:`ApiError` with the server's sentence,
+its status and its document. The token is the server's (``nullius access
+create``); no model key is sent or read.
+
+Standard library only, and nothing else of Nullius: this file works copied alone.
+"""
+from __future__ import annotations
+
+import argparse
+import http.client
+import json
+import os
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from typing import Iterator, Optional, Union
+
+ENDED = ("done", "failed", "stopped") # a run's states that no longer change
+
+
+class ApiError(Exception):
+ """The server refused, or could not be reached: ``status`` (0 when unreachable) and its ``document``."""
+
+ def __init__(self, status: int, message: str, document: Optional[dict] = None):
+ super().__init__(message)
+ self.status, self.document = status, document or {}
+
+
+class _Stay(urllib.request.HTTPRedirectHandler):
+ """No redirect is followed: it would hand the token to another address, and make a GET of a POST."""
+
+ def redirect_request(self, *args, **kwargs):
+ return None
+
+
+class Client:
+ def __init__(self, url: Optional[str] = None, token: Optional[str] = None, timeout: float = 120.0):
+ self.url = (url or os.environ.get("NULLIUS_SERVER") or "").rstrip("/")
+ self.token = (token or os.environ.get("NULLIUS_TOKEN") or "").strip()
+ self.timeout = timeout
+ if not self.url.startswith(("http://", "https://")):
+ raise ValueError("the server's address is an http(s) URL: Client(url, token), or NULLIUS_SERVER")
+ if not self.token:
+ raise ValueError("the server's token is missing: Client(url, token), or NULLIUS_TOKEN")
+ if not (self.token.isascii() and self.token.isprintable()):
+ raise ValueError("the server's token holds a character no token has")
+ self._open = urllib.request.build_opener(_Stay).open
+
+ def request(self, method: str, path: str, body=None, wait: Optional[float] = None, **query):
+ """One call: the JSON document the server answers, or :class:`ApiError`. ``wait``: this call's own timeout."""
+ pairs = [(k, v) for k, value in query.items() if value is not None and value is not False and value != ""
+ for v in (value if isinstance(value, (list, tuple)) else [1 if value is True else value])]
+ url = f"{self.url}/api/v1{path}" + ("?" + urllib.parse.urlencode(pairs) if pairs else "")
+ try:
+ return self._sent(method, url, body, wait)
+ except (urllib.error.URLError, http.client.HTTPException, OSError, ValueError) as e:
+ raise ApiError(0, f"{self.url} did not answer: {getattr(e, 'reason', None) or e or type(e).__name__}") from None
+
+ def _sent(self, method: str, url: str, body, wait):
+ req = urllib.request.Request(url, method=method, data=None if body is None else json.dumps(body).encode(),
+ headers={"Authorization": f"Bearer {self.token}", "Accept": "application/json",
+ **({"Content-Type": "application/json"} if body is not None else {})})
+ try:
+ with self._open(req, timeout=wait or self.timeout) as response:
+ return json.loads(response.read().decode("utf-8"))
+ except urllib.error.HTTPError as e:
+ with e:
+ try:
+ raw = e.read().decode("utf-8", "replace")
+ except (OSError, http.client.HTTPException):
+ raw = ""
+ if 300 <= e.code < 400:
+ raise ApiError(e.code, f"{self.url} sends this request to {e.headers.get('Location')}: use that server's address") from None
+ try:
+ doc = json.loads(raw)
+ except ValueError:
+ doc = {}
+ doc = doc if isinstance(doc, dict) else {}
+ raise ApiError(e.code, str(doc.get("error") or f"HTTP {e.code} from {self.url}"), doc) from None
+
+ @staticmethod
+ def _q(*parts: str) -> str:
+ return "".join("/" + urllib.parse.quote(str(p), safe="") for p in parts)
+
+ # what the pages read
+
+ def info(self) -> dict:
+ """The server's version, this token's scope and where a run can go."""
+ return self.request("GET", "")
+
+ def catalogue(self) -> dict:
+ return self.request("GET", "/catalogue")
+
+ def workspaces(self) -> list:
+ return self.request("GET", "/workspaces")
+
+ def jobs(self, workspace: Optional[str] = None) -> list:
+ return self.request("GET", "/jobs", workspace=workspace)
+
+ def job(self, job_id: str, workspace: Optional[str] = None) -> dict:
+ return self.request("GET", self._q("jobs", job_id), workspace=workspace)
+
+ def live(self, job_id: str) -> dict:
+ return self.request("GET", self._q("jobs", job_id, "live"))
+
+ def trial(self, job_id: str, trial: str, workspace: Optional[str] = None) -> dict:
+ return self.request("GET", self._q("jobs", job_id, "trials", trial), workspace=workspace)
+
+ def conversation(self, job_id: str, trial: str, **query) -> dict:
+ """The trial's conversation, paged: ``q``, ``kind``, ``page``, ``step``."""
+ return self.request("GET", self._q("jobs", job_id, "trials", trial, "conversation"), **query)
+
+ def trace(self, job_id: str, trial: str) -> dict:
+ return self.request("GET", self._q("jobs", job_id, "trials", trial, "trace"))
+
+ def artifacts(self, job_id: str, trial: str) -> list:
+ return self.request("GET", self._q("jobs", job_id, "trials", trial, "artifacts"))
+
+ def artifact(self, job_id: str, trial: str, key: str) -> dict:
+ return self.request("GET", self._q("jobs", job_id, "trials", trial, "artifacts", key))
+
+ def compare(self, *job_ids: str, matched: bool = False, workspace: Optional[str] = None) -> dict:
+ return self.request("GET", "/compare", job=list(job_ids), matched=matched, workspace=workspace)
+
+ # judgements: reading one is free, asking is a paid model call for each trial
+
+ def judgements(self, job_id: str, lane: str = "decision") -> dict:
+ """One judge's records for a job: ``judged``, ``trials``, ``records`` by trial."""
+ return self.request("GET", self._q("jobs", job_id, "judgements"), lane=lane)
+
+ def judgement(self, job_id: str, trial: str, lane: str = "decision") -> dict:
+ return self.request("GET", self._q("jobs", job_id, "trials", trial, "judgement"), lane=lane)
+
+ def judge(self, job_id: str, trial: str, lane: str = "decision") -> dict:
+ """Ask a judge (``decision`` or ``llm``) about one trial: the record as stored."""
+ return self.request("POST", self._q("jobs", job_id, "trials", trial, "judge"), {"lane": lane}, wait=600)
+
+ def judge_job(self, job_id: str, lane: str = "decision", confirm: bool = False) -> dict:
+ """Ask about every trial of the job that judge has not judged. Without ``confirm`` it is refused with
+ ``todo``, how many it would ask; the call returns when all are asked."""
+ return self.request("POST", self._q("jobs", job_id, "judge"), {"lane": lane, **({"confirm": True} if confirm else {})}, wait=6 * 3600)
+
+ # recipes and runs
+
+ def recipes(self) -> list:
+ return self.request("GET", "/recipes")
+
+ def recipe(self, id_or_name: str) -> dict:
+ return self.request("GET", self._q("recipes", id_or_name))
+
+ def save_recipe(self, recipe: dict, recipe_id: Optional[str] = None) -> dict:
+ return self.request("POST", "/recipes", {"recipe": recipe, "id": recipe_id})
+
+ @staticmethod
+ def _run_body(recipe: Union[dict, str], where=None, **more) -> dict:
+ return {"recipe": recipe, **({"where": where} if where else {}), **{k: v for k, v in more.items() if v}}
+
+ def check(self, recipe: Union[dict, str], where=None) -> dict:
+ """What Review shows for a recipe (a dict, or a saved one's id or name): ``ready``, ``errors``, ``confirm``, ``machines``."""
+ return self.request("POST", "/runs/check", self._run_body(recipe, where))
+
+ def start(self, recipe: Union[dict, str], where=None, name: Optional[str] = None, confirm: bool = False) -> dict:
+ """Start a recipe; ``runs`` holds one run per machine. ``confirm``: the yes to the question ``check`` returns."""
+ return self.request("POST", "/runs", self._run_body(recipe, where, name=name, confirm=confirm))
+
+ def runs(self) -> list:
+ return self.request("GET", "/runs")
+
+ def run(self, run_id: str, since: int = 0) -> dict:
+ """A run's state and stages, with its log lines from ``since`` on."""
+ return self.request("GET", self._q("runs", run_id), since=since or None)
+
+ def stop(self, run_id: str) -> dict:
+ return self.request("POST", self._q("runs", run_id, "stop"))
+
+ def continue_(self, run_id: str) -> dict:
+ """The answer to a run that paused with a ``question``: go on."""
+ return self.request("POST", self._q("runs", run_id, "continue"))
+
+ def follow(self, run_id: str, every: float = 2.0) -> Iterator[str]:
+ """The run's log lines as they come, until it ends or pauses with a question."""
+ seen = 0
+ while True:
+ got = self.run(run_id, since=seen)
+ yield from got["log"]
+ seen += len(got["log"])
+ if got["state"] in ENDED or got.get("question"):
+ return
+ time.sleep(every)
+
+ def wait(self, run_id: str, every: float = 2.0, timeout: Optional[float] = None) -> dict:
+ """The run once it has ended (or paused with a question): its last summary."""
+ until = None if timeout is None else time.monotonic() + timeout
+ while True:
+ got = self.run(run_id, since=1 << 30)
+ if got["state"] in ENDED or got.get("question"):
+ return got
+ if until is not None and time.monotonic() > until:
+ raise TimeoutError(f"run {run_id} is still {got['state']} after {timeout} s")
+ time.sleep(every)
+
+
+# nullius remote: the same calls from a shell, one JSON document on stdout.
+
+EXIT_OK, EXIT_USAGE, EXIT_NOT_FOUND, EXIT_FAILED = 0, 2, 3, 4
+
+EPILOG = """\
+The server and its token: --server and --token, or NULLIUS_SERVER and NULLIUS_TOKEN.
+RECIPE is a recipe file (JSON, as the builder saves one), or a saved recipe's id or name on the server.
+
+exit codes:
+ 0 done
+ 2 usage
+ 3 not found on the server
+ 4 refused, unreachable, or the run did not end done
+"""
+
+
+def _recipe_arg(value: str):
+ if os.path.isfile(value):
+ with open(value, encoding="utf-8") as fh:
+ got = json.load(fh)
+ return got["recipe"] if isinstance(got, dict) and isinstance(got.get("recipe"), dict) and "version" not in got else got
+ return value
+
+
+def main(argv=None) -> int:
+ ap = argparse.ArgumentParser(prog="nullius remote", description="Ask a Nullius server on another machine.",
+ epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--server", help="the server's address (NULLIUS_SERVER)")
+ ap.add_argument("--token", help="its token (NULLIUS_TOKEN)")
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ sub.add_parser("info", help="the server's version, the token's scope, where a run can go")
+ sub.add_parser("catalogue", help="benchmarks, agents and capabilities")
+ sub.add_parser("workspaces")
+ p = sub.add_parser("jobs", help="the jobs of the open workspace")
+ p.add_argument("--workspace")
+ p = sub.add_parser("job", help="one job, or one of its trials")
+ p.add_argument("job_id")
+ p.add_argument("trial", nargs="?")
+ p.add_argument("--workspace")
+ p = sub.add_parser("compare", help="two or more jobs side by side")
+ p.add_argument("job_ids", nargs="+")
+ p.add_argument("--matched", action="store_true")
+ p.add_argument("--workspace")
+ p = sub.add_parser("judgements", help="a judge's records for a job")
+ p.add_argument("job_id")
+ p.add_argument("--lane", choices=("decision", "llm"), default="decision")
+ p = sub.add_parser("judge", help="ask a judge about one trial, or a job's unjudged trials: a paid call each")
+ p.add_argument("job_id")
+ p.add_argument("trial", nargs="?")
+ p.add_argument("--lane", choices=("decision", "llm"), default="decision")
+ p.add_argument("--yes", action="store_true", help="ask about every unjudged trial of the job")
+ sub.add_parser("recipes", help="the saved recipes")
+ p = sub.add_parser("check", help="what Review shows for a recipe; starts nothing")
+ p.add_argument("recipe", metavar="RECIPE")
+ p.add_argument("--where")
+ p = sub.add_parser("run", help="start a recipe")
+ p.add_argument("recipe", metavar="RECIPE")
+ p.add_argument("--where")
+ p.add_argument("--name", help="the run's name (default: the recipe's name and the second)")
+ p.add_argument("--yes", action="store_true", help="answer yes to the question the check returns")
+ p.add_argument("--follow", action="store_true", help="print the log until the run ends; exit 4 unless it ends done")
+ sub.add_parser("runs", help="the runs the server follows")
+ p = sub.add_parser("status", help="one run: its state, stages and log")
+ p.add_argument("run_id")
+ p.add_argument("--since", type=int, default=0)
+ for name, text in (("stop", "stop a run"), ("continue", "answer a paused run: go on")):
+ p = sub.add_parser(name, help=text)
+ p.add_argument("run_id")
+ a = ap.parse_args(argv)
+ try:
+ nx = Client(a.server, a.token)
+ except ValueError as e:
+ print(e, file=sys.stderr)
+ return EXIT_USAGE
+ try:
+ if a.cmd == "run":
+ out = nx.start(_recipe_arg(a.recipe), where=a.where, name=a.name, confirm=a.yes)
+ if a.follow:
+ ok = True
+ for r in out["runs"]:
+ for line in nx.follow(r["id"]):
+ print(line, file=sys.stderr)
+ r.update(nx.run(r["id"], since=1 << 30))
+ ok = ok and r["state"] == "done"
+ print(json.dumps(out, indent=1))
+ return EXIT_OK if ok else EXIT_FAILED
+ else:
+ out = {"info": nx.info, "catalogue": nx.catalogue, "workspaces": nx.workspaces, "recipes": nx.recipes, "runs": nx.runs,
+ "jobs": lambda: nx.jobs(a.workspace),
+ "job": lambda: nx.trial(a.job_id, a.trial, a.workspace) if a.trial else nx.job(a.job_id, a.workspace),
+ "compare": lambda: nx.compare(*a.job_ids, matched=a.matched, workspace=a.workspace),
+ "judgements": lambda: nx.judgements(a.job_id, a.lane),
+ "judge": lambda: nx.judge(a.job_id, a.trial, a.lane) if a.trial else nx.judge_job(a.job_id, a.lane, confirm=a.yes),
+ "check": lambda: nx.check(_recipe_arg(a.recipe), a.where),
+ "status": lambda: nx.run(a.run_id, a.since), "stop": lambda: nx.stop(a.run_id),
+ "continue": lambda: nx.continue_(a.run_id)}[a.cmd]()
+ except ApiError as e:
+ print(e, file=sys.stderr)
+ if e.document and set(e.document) - {"error"}:
+ print(json.dumps(e.document, indent=1))
+ return EXIT_NOT_FOUND if e.status == 404 else EXIT_FAILED
+ except (OSError, ValueError) as e: # a recipe file that cannot be read
+ print(e, file=sys.stderr)
+ return EXIT_USAGE
+ print(json.dumps(out, indent=1))
+ return EXIT_OK
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/app/nullius/mcp_server.py b/app/nullius/mcp_server.py
new file mode 100644
index 00000000..56d571bf
--- /dev/null
+++ b/app/nullius/mcp_server.py
@@ -0,0 +1,144 @@
+"""A Nullius server as MCP tools, for an assistant: ``nullius mcp``, over stdio.
+
+ NULLIUS_SERVER=http://bench.internal:5057 NULLIUS_TOKEN=... nullius mcp
+
+Each tool is one call of ``nullius.client.Client`` and answers its JSON
+document. What a tool may do is the token's scope: with a ``read`` token the
+run tools answer the server's refusal. ``start_run`` starts only when
+``confirm`` answers the question ``check_run`` returned, as Review asks it.
+Standard library only.
+"""
+from __future__ import annotations
+
+import json
+import sys
+
+from nullius.client import ApiError, Client
+
+PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05") # ours first
+
+_S, _I, _B = {"type": "string"}, {"type": "integer"}, {"type": "boolean"}
+_JOB = {"job_id": dict(_S, description="a job id, as list_jobs returns it")}
+_TRIAL = {**_JOB, "trial": dict(_S, description="a trial name of that job, as get_job returns it")}
+_RECIPE = {"recipe": {"description": "a saved recipe's id or name (list_recipes), or a whole recipe object"}}
+_RUN = {"run_id": dict(_S, description="a run id, as start_run or list_runs returns it")}
+
+# name: (description, properties, required, the call)
+TOOLS = {
+ "server_info": ("The server's version, this token's scope, and the machines a run can go to.", {}, [],
+ lambda nx, a: nx.info()),
+ "catalogue": ("Benchmarks with their datasets and what fits each, agents and capabilities.", {}, [],
+ lambda nx, a: nx.catalogue()),
+ "list_jobs": ("The jobs of the open workspace: dataset, agent, model, outcome counts, raw and adjusted solve rate.", {}, [],
+ lambda nx, a: nx.jobs()),
+ "get_job": ("One job with every trial: outcome, reward, cost, tokens, exception. Read the adjusted rate and the "
+ "outcome counts first: the raw rate counts infrastructure failures as misses.", _JOB, ["job_id"],
+ lambda nx, a: nx.job(a["job_id"])),
+ "get_trial": ("One trial: outcome, checks, usage, exception and the steps of its trajectory with their tool calls.",
+ _TRIAL, ["job_id", "trial"], lambda nx, a: nx.trial(a["job_id"], a["trial"])),
+ "get_conversation": ("A page of one trial's conversation: messages, tool arguments and observations.",
+ {**_TRIAL, "page": _I, "q": dict(_S, description="text to search for")}, ["job_id", "trial"],
+ lambda nx, a: nx.conversation(a["job_id"], a["trial"], page=a.get("page"), q=a.get("q"))),
+ "compare_jobs": ("Two or more jobs side by side, by task.",
+ {"job_ids": {"type": "array", "items": _S, "minItems": 2},
+ "matched": dict(_B, description="only the tasks every job ran")}, ["job_ids"],
+ lambda nx, a: nx.compare(*a["job_ids"], matched=a.get("matched") is True)),
+ "get_judgements": ("A judge model's stored answers about a job's trials (lane: decision or llm). Free to read.",
+ {**_JOB, "lane": _S}, ["job_id"], lambda nx, a: nx.judgements(a["job_id"], a.get("lane") or "decision")),
+ "judge_trial": ("Ask a judge model about one trial. A paid model call: ask only when the person wants it.",
+ {**_TRIAL, "lane": _S}, ["job_id", "trial"], lambda nx, a: nx.judge(a["job_id"], a["trial"], a.get("lane") or "decision")),
+ "list_recipes": ("The saved recipes: id, name and the recipe.", {}, [], lambda nx, a: nx.recipes()),
+ "check_run": ("What Review shows for a recipe, without starting it: errors, the prerequisites of each machine, "
+ "and the question to confirm.", {**_RECIPE, "where": _S}, ["recipe"],
+ lambda nx, a: nx.check(a["recipe"], a.get("where"))),
+ "start_run": ("Start a recipe. It spends model tokens and machine time: call check_run first, and set confirm only "
+ "when the person has agreed to the question it returned.", {**_RECIPE, "where": _S, "confirm": _B}, ["recipe"],
+ lambda nx, a: nx.start(a["recipe"], a.get("where"), confirm=a.get("confirm") is True)),
+ "list_runs": ("The runs the server follows: state, stages, job ids.", {}, [], lambda nx, a: nx.runs()),
+ "get_run": ("One run: state, stages, and its log lines from `since` on.", {**_RUN, "since": _I}, ["run_id"],
+ lambda nx, a: nx.run(a["run_id"], a.get("since") or 0)),
+ "stop_run": ("Stop a run.", _RUN, ["run_id"], lambda nx, a: nx.stop(a["run_id"])),
+}
+
+
+def listed() -> list:
+ return [{"name": name, "description": text, "inputSchema": {"type": "object", "properties": props, "required": need}}
+ for name, (text, props, need, _) in TOOLS.items()]
+
+
+_TYPES = {"string": str, "integer": int, "boolean": bool, "array": list}
+
+
+def _is(value, prop) -> bool:
+ if not isinstance(value, _TYPES[prop["type"]]) or (prop["type"] == "integer" and isinstance(value, bool)):
+ return False
+ return prop["type"] != "array" or all(_is(v, prop["items"]) for v in value)
+
+
+def _error(rid, code: int, message: str) -> dict:
+ return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}}
+
+
+def handle(m, nx):
+ """One JSON-RPC message in, its reply out (None for a notification, or a response)."""
+ if not isinstance(m, dict):
+ return _error(None, -32600, "one JSON-RPC message at a time")
+ if "id" not in m or "method" not in m:
+ return None
+ method, rid, params = m["method"], m["id"], m.get("params") or {}
+ if not isinstance(params, dict):
+ return _error(rid, -32602, "params is an object")
+ if method == "initialize":
+ asked = params.get("protocolVersion")
+ result = {"protocolVersion": asked if asked in PROTOCOLS else PROTOCOLS[0],
+ "capabilities": {"tools": {}}, "serverInfo": {"name": "nullius", "version": "1"}}
+ elif method == "tools/list":
+ result = {"tools": listed()}
+ elif method == "tools/call":
+ name, args = params.get("name"), params.get("arguments") or {}
+ if not isinstance(name, str) or name not in TOOLS:
+ return _error(rid, -32602, f"unknown tool {name!r}")
+ if not isinstance(args, dict):
+ return _error(rid, -32602, "arguments is an object")
+ args = {k: v for k, v in args.items() if v is not None}
+ wrong = [f"{k}: {p['type']}" for k, p in TOOLS[name][1].items() if k in args and "type" in p and not _is(args[k], p)]
+ if wrong:
+ return _error(rid, -32602, f"{name} takes {', '.join(wrong)}")
+ missing = [k for k in TOOLS[name][2] if k not in args]
+ try:
+ if missing:
+ raise ApiError(400, f"{name} needs {', '.join(missing)}")
+ text, err = json.dumps(TOOLS[name][3](nx, args), ensure_ascii=False), False
+ except ApiError as e:
+ text, err = json.dumps({"error": str(e), **e.document}, ensure_ascii=False), True
+ result = {"content": [{"type": "text", "text": text}], "isError": err}
+ elif method == "ping":
+ result = {}
+ elif method in ("resources/list", "prompts/list"):
+ result = {method.split("/")[0]: []}
+ else:
+ return _error(rid, -32601, f"no {method}")
+ return {"jsonrpc": "2.0", "id": rid, "result": result}
+
+
+def main(argv=None) -> int:
+ if argv:
+ print(__doc__.strip(), file=sys.stderr)
+ return 0 if argv[0] in ("-h", "--help") else 2
+ try:
+ nx = Client()
+ except ValueError as e:
+ print(e, file=sys.stderr)
+ return 2
+ for line in sys.stdin:
+ try:
+ reply = handle(json.loads(line), nx)
+ except (ValueError, RecursionError):
+ reply = _error(None, -32700, "a line that is not JSON")
+ if reply is not None:
+ print(json.dumps(reply), flush=True)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/app/site/mkdocs.yml b/app/site/mkdocs.yml
index 2e465487..cfbea310 100644
--- a/app/site/mkdocs.yml
+++ b/app/site/mkdocs.yml
@@ -78,6 +78,7 @@ nav:
- Core concepts: concepts.md
- Run evaluations:
- Run builder: builder.md
+ - From another machine: api.md
- Understand results:
- Read results: results.md
- Judgement: judgement.md
diff --git a/app/static/settings/api-access.js b/app/static/settings/api-access.js
new file mode 100644
index 00000000..a8e61ec1
--- /dev/null
+++ b/app/static/settings/api-access.js
@@ -0,0 +1,80 @@
+// The API access section: the tokens of the HTTP API, a new one shown once, a revoke asked in place.
+// The server sends the tokens with the page and again after each change; this draws them.
+(() => {
+ const section = document.getElementById('api-access');
+ if (!section) return;
+ const $ = sel => section.querySelector(sel);
+ const csrf = section.dataset.csrf;
+ const tell = (message, error = false) => window.nulliusNotify ? window.nulliusNotify(message, {error}) : null;
+ const post = async (url, fields) => {
+ try {
+ const r = await nulliusFetch(url, {method: 'POST', headers: {'X-CSRF-Token': csrf}, body: new URLSearchParams(fields)});
+ const j = await r.json();
+ return j.ok ? j : {ok: false, error: j.error || 'HTTP ' + r.status};
+ } catch (err) { return {ok: false, error: String(err)}; }
+ };
+ const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; };
+ const ACCESS = {read: 'Read', run: 'Read and run'};
+ const day = stamp => (stamp || '').slice(0, 10);
+
+ const show = tokens => {
+ $('[data-api-rows]').replaceChildren(...tokens.map(t => {
+ const row = el('div', 'st-row'), value = el('span', 'st-value');
+ const said = el('span', '', [ACCESS[t.scope] || t.scope, t.expired ? 'expired ' + day(t.expires) : t.expires ? 'until ' + day(t.expires) : ''].filter(Boolean).join(' · '));
+ if (t.expired) said.classList.add('st-bad');
+ value.append(said);
+ if (csrf) {
+ const revoke = el('button', 'btn sm ghost', 'Revoke'); revoke.type = 'button';
+ revoke.setAttribute('aria-label', `Revoke ${t.name}`);
+ // one line of yes or no, asked in place
+ const ask = el('span', 'st-value st-api-ask'); ask.hidden = true; ask.setAttribute('role', 'group'); ask.setAttribute('aria-label', `Revoke ${t.name}`);
+ const yes = el('button', 'btn sm danger', 'Yes, revoke'), keep = el('button', 'btn sm ghost', 'Keep it'); yes.type = keep.type = 'button';
+ ask.append(yes, keep);
+ revoke.addEventListener('click', () => { revoke.hidden = true; ask.hidden = false; keep.focus(); });
+ keep.addEventListener('click', () => { ask.hidden = true; revoke.hidden = false; revoke.focus(); });
+ yes.addEventListener('click', async () => {
+ yes.disabled = true;
+ const got = await post(section.dataset.revoke, {id: t.id});
+ if (got.ok) show(got.tokens); else { yes.disabled = false; tell(got.error, true); }
+ });
+ value.append(revoke, ask);
+ }
+ row.append(el('span', 'st-row-label', t.name), value);
+ return row;
+ }));
+ $('[data-api-list]').hidden = tokens.length === 0; // nothing to list, no list
+ };
+
+ // Access and Expires: one choice each, as small cards
+ const groups = [...section.querySelectorAll('[data-api-choice]')];
+ const choose = (group, b) => group.querySelectorAll('.st-tab').forEach(x => { x.classList.toggle('on', x === b); x.setAttribute('aria-pressed', x === b ? 'true' : 'false'); });
+ groups.forEach(group => group.addEventListener('click', e => { const b = e.target.closest('.st-tab'); if (b) choose(group, b); }));
+ const chosen = field => $(`[data-api-choice="${field}"] .st-tab.on`).dataset.value;
+
+ const fresh = $('[data-api-new]');
+ const done = () => { fresh.hidden = true; $('[data-api-new-token]').textContent = ''; };
+ $('[data-api-done]').addEventListener('click', done);
+ $('[data-api-copy]').addEventListener('click', async () => {
+ try { await navigator.clipboard.writeText($('[data-api-new-token]').textContent); tell('Copied'); }
+ catch (err) { tell('Select the token and copy it', true); }
+ });
+
+ const form = $('[data-api-add]');
+ if (form) form.addEventListener('submit', async e => {
+ e.preventDefault();
+ const button = form.querySelector('[type=submit]');
+ button.disabled = true;
+ const got = await post(section.dataset.create, {name: new FormData(form).get('name'), scope: chosen('scope'), days: chosen('days')});
+ button.disabled = false;
+ if (!got.ok) return tell(got.error, true);
+ form.reset();
+ groups.forEach(group => choose(group, group.querySelector('.st-tab'))); // the next token starts from the least: read, never
+ $('[data-api-new-name]').textContent = got.token.name;
+ $('[data-api-new-token]').textContent = got.value;
+ fresh.hidden = false;
+ show(got.tokens);
+ $('[data-api-copy]').focus();
+ });
+
+ try { show(JSON.parse(section.dataset.state)); } catch (err) { show([]); }
+})();
diff --git a/app/static/settings/settings.css b/app/static/settings/settings.css
index f1d5793b..1e6f692d 100644
--- a/app/static/settings/settings.css
+++ b/app/static/settings/settings.css
@@ -139,6 +139,10 @@
.st-tab { background: none; border: 0; border-radius: 6px; color: var(--text-dim); font: inherit; font-size: 12px; padding: 5px 12px; cursor: pointer; overflow-wrap: anywhere; }
.st-tab.on { background: var(--surface); color: var(--text); box-shadow: 0 1px 2px rgba(0, 0, 0, .25); }
.st-tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
+/* a new token: one boxed line while it fits, whole when it wraps, its buttons beside or under it */
+.st-api-shown { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 10px; }
+.st-api-token { flex: 1 1 30ch; min-width: 0; box-sizing: border-box; padding: 10px 12px; border: 1px solid var(--border); border-radius: 8px; background: var(--bg); user-select: all; overflow-wrap: anywhere; }
+.st-api-new { border-color: var(--accent); }
.st-warn { color: var(--warn, #b8860b); }
.st-constraints .st-input { font: 13px var(--mono); padding: 0 12px; } /* numbers and lists alike */
.st-constraint { --unit-w: 6.25rem; display: grid; grid-template-columns: minmax(0, 1fr) 5.5rem var(--unit-w) 28px; align-items: center; column-gap: 12px; min-width: 0; }
diff --git a/app/templates/_icons.svg b/app/templates/_icons.svg
index 29618160..691aaab2 100644
--- a/app/templates/_icons.svg
+++ b/app/templates/_icons.svg
@@ -132,6 +132,8 @@
+
+
diff --git a/app/templates/settings/api_access.html b/app/templates/settings/api_access.html
new file mode 100644
index 00000000..bfae5beb
--- /dev/null
+++ b/app/templates/settings/api_access.html
@@ -0,0 +1,28 @@
+{# The HTTP API's tokens (nullius.access), outside the form: api-access.js draws the state and answers the buttons. #}
+
+
API access
Tokens for scripts and assistants on other machines.