From e061a35b5e69641f682b04caf11feafaa8788c67 Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Wed, 25 Nov 2026 14:58:45 +0100 Subject: [PATCH] feat(web): open Nullius to another machine over an HTTP API with tokens, a client and MCP tools --- AGENTS.md | 1 + README.md | 1 + app/app.py | 4 +- app/nullius/access.py | 189 ++++++++ app/nullius/cli.py | 6 + app/nullius/client.py | 328 +++++++++++++ app/nullius/mcp_server.py | 144 ++++++ app/site/mkdocs.yml | 1 + app/static/settings/api-access.js | 80 ++++ app/static/settings/settings.css | 4 + app/templates/_icons.svg | 2 + app/templates/settings/api_access.html | 28 ++ app/templates/settings/settings.html | 3 + app/tests/test_access.py | 136 ++++++ app/tests/test_client.py | 364 ++++++++++++++ app/tests/test_settings.py | 1 + app/ui_tests/test_api.py | 625 +++++++++++++++++++++++++ app/ui_tests/test_every_route.py | 14 +- app/web/api.py | 481 +++++++++++++++++++ app/web/builder.py | 6 +- app/web/execute.py | 7 +- app/web/filters.py | 4 +- app/web/settings.py | 37 +- app/web/shared.py | 3 +- docs/api.md | 149 ++++++ docs/cli/README.md | 1 + docs/cli/exit-codes.md | 1 + docs/cli/pages.md | 9 +- docs/settings/README.md | 1 + 29 files changed, 2617 insertions(+), 13 deletions(-) create mode 100644 app/nullius/access.py create mode 100644 app/nullius/client.py create mode 100644 app/nullius/mcp_server.py create mode 100644 app/static/settings/api-access.js create mode 100644 app/templates/settings/api_access.html create mode 100644 app/tests/test_access.py create mode 100644 app/tests/test_client.py create mode 100644 app/ui_tests/test_api.py create mode 100644 app/web/api.py create mode 100644 docs/api.md 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.

+ + + {% if writable %} +
+ New token +
+
+
+ {% for field, label, choices in [('scope', 'Access', [('read', 'Read', 'Results, recipes and runs'), ('run', 'Read and run', 'Also start and stop runs, ask a judge, save recipes')]), + ('days', 'Expires', [('', 'Never', ''), ('30', '30 days', ''), ('90', '90 days', ''), ('365', '1 year', '')])] %} +
{{ label }} +
{% for value, text, tip in choices %}{% endfor %}
+ {% endfor %} +
+
+
+ {% endif %} +
diff --git a/app/templates/settings/settings.html b/app/templates/settings/settings.html index 92fd9257..6cd66e70 100644 --- a/app/templates/settings/settings.html +++ b/app/templates/settings/settings.html @@ -90,6 +90,7 @@
Application
+ {{ section_link('api-access', 'API access', 'api', 'api token tokens remote access another machine client sdk script mcp assistant') }} {{ section_link('storage', 'Local data', 'disk', 'settings.json config catalogue workspaces runs cache licences storage paths file') }}
@@ -391,6 +392,7 @@

Judges

{% endfor %}{% endfor %} {% endif %} {% include 'settings/data_providers.html' %} + {% include 'settings/api_access.html' %}

Sandbox

Where agents run, apart from this machine.

@@ -481,6 +483,7 @@

General

+ {% if writable %} diff --git a/app/tests/test_access.py b/app/tests/test_access.py new file mode 100644 index 00000000..2ba5c565 --- /dev/null +++ b/app/tests/test_access.py @@ -0,0 +1,136 @@ +"""API tokens (``nullius.access``): shown once, kept as a hash in one owner-only +file, checked by id and secret, revoked by id; ``run`` reads too, ``read`` does +not run; and the ``nullius access`` command.""" +from __future__ import annotations + +import calendar +import contextlib +import io +import json +import os +import shutil +import stat +import tempfile +import time +import unittest +from concurrent.futures import ThreadPoolExecutor +from unittest import mock + +from nullius import access, cli + + +class Tokens(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp, True) + patch = mock.patch.dict(os.environ, {"NULLIUS_HOME": self.tmp}) + patch.start() + self.addCleanup(patch.stop) + + def test_tokens_created_at_once_are_all_kept(self): + with ThreadPoolExecutor(8) as pool: + list(pool.map(lambda n: access.create(f"t{n}"), range(24))) + self.assertEqual({r["name"] for r in access.listing()}, {f"t{n}" for n in range(24)}) + + def test_a_token_is_verified_and_its_secret_is_kept_nowhere(self): + token, record = access.create("ci", "run") + self.assertEqual(access.verify(token), record) + path = os.path.join(self.tmp, "config", "api-tokens.json") + self.assertEqual(access.file(), path) + self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o600) + with open(path) as fh: + text = fh.read() + self.assertNotIn(token, text) + self.assertNotIn(token.split("_", 2)[2], text) + self.assertEqual(sorted(json.loads(text)["tokens"][0]), ["created", "expires", "id", "name", "scope", "sha256"]) + self.assertEqual(sorted(access.shown(record)), ["created", "expired", "expires", "id", "name", "scope"]) + self.assertEqual((record["expires"], access.shown(record)["expired"]), (None, False)) # until revoked + + def test_what_is_not_a_token_of_this_server(self): + token, record = access.create("ci") + other, _ = access.create("other") + prefix, token_id, secret = token.split("_", 2) + for bad in ("", None, 7, "Bearer " + token, token + "x", token[:-1], f"{prefix}_{token_id}_{other.split('_', 2)[2]}", + f"{prefix}_{'0' * 12}_{secret}", secret): + self.assertIsNone(access.verify(bad), bad) + self.assertTrue(access.revoke(record["id"])) + self.assertIsNone(access.verify(token)) + self.assertIsNotNone(access.verify(other)) # the other token still stands + self.assertFalse(access.revoke(record["id"])) + + def test_no_file_or_a_broken_one_holds_no_token(self): + self.assertEqual(access.listing(), []) + token, _ = access.create("ci") + with open(access.file(), "w") as fh: + fh.write("{not json") + self.assertEqual(access.listing(), []) + self.assertIsNone(access.verify(token)) + for change in (lambda: access.create("other"), lambda: access.revoke("x")): # never written over + with self.assertRaisesRegex(ValueError, "cannot be read"): + change() + with open(access.file()) as fh: + self.assertEqual(fh.read(), "{not json") + with open(access.file(), "w") as fh: # a record with no hash, or a scope this does not know + json.dump({"tokens": [{"id": "a", "scope": "read"}, {"id": "b", "sha256": "x", "scope": "admin"}]}, fh) + self.assertEqual(access.listing(), []) + + def test_run_reads_too_and_read_does_not_run(self): + _, reader = access.create("reader", "read") + _, runner = access.create("runner", "run") + self.assertEqual([access.allows(reader, s) for s in access.SCOPES], [True, False]) + self.assertEqual([access.allows(runner, s) for s in access.SCOPES], [True, True]) + self.assertFalse(access.allows(None, "read")) + + def test_a_token_with_days_is_refused_once_they_have_passed(self): + token, record = access.create("ci", "run", days=30) + made = calendar.timegm(time.strptime(record["created"], "%Y-%m-%dT%H:%M:%SZ")) + self.assertEqual(calendar.timegm(time.strptime(record["expires"], "%Y-%m-%dT%H:%M:%SZ")) - made, 30 * 86400) + self.assertEqual(access.verify(token), record) + with mock.patch.object(access.time, "time", lambda: made + 30 * 86400 - 1): + self.assertEqual(access.verify(token), record) + with mock.patch.object(access.time, "time", lambda: made + 30 * 86400): + self.assertIsNone(access.verify(token)) + self.assertTrue(access.shown(record)["expired"]) + self.assertEqual([r["id"] for r in access.listing()], [record["id"]]) # still listed, to be revoked + self.assertTrue(access.expired({"expires": "next week"})) # an expiry that cannot be read has passed + for days in (0, -1, access.MAX_DAYS + 1, 1.5, "30", True): + with self.assertRaises(ValueError, msg=days): + access.create("x", "read", days=days) + + def test_names_and_scopes_refused(self): + access.create("ci") + for name, scope in (("ci", "read"), ("", "read"), ("a/b", "read"), ("x" * 65, "read"), ("ok", "admin")): + with self.assertRaises(ValueError, msg=(name, scope)): + access.create(name, scope) + self.assertEqual([r["name"] for r in access.listing()], ["ci"]) + + def run_cli(self, *argv): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = cli.main(["access", *argv]) + return code, out.getvalue(), err.getvalue() + + def test_the_command_prints_the_token_once_and_lists_no_secret(self): + code, out, err = self.run_cli("create", "laptop", "--scope", "run") + token = out.strip() + self.assertEqual(code, 0) + self.assertEqual(access.verify(token)["scope"], "run") + self.assertIn("shown once", err) + code, out, _ = self.run_cli("list", "--json") + rows = json.loads(out) + self.assertEqual([(r["name"], r["scope"]) for r in rows], [("laptop", "run")]) + self.assertNotIn("sha256", out) + self.assertNotIn(token.split("_", 2)[2], out) + self.assertEqual(self.run_cli("create", "laptop")[0], 2) # the name is taken + code, out, err = self.run_cli("create", "ci", "--days", "7") + self.assertEqual(code, 0) + self.assertIn("until " + access.verify(out.strip())["expires"][:10], err) + self.assertIn(" never ", self.run_cli("list")[1]) + self.assertEqual(self.run_cli("create", "soon", "--days", "0")[0], 2) + self.assertEqual(self.run_cli("revoke", "nope")[0], 3) + self.assertEqual(self.run_cli("revoke", rows[0]["id"])[0], 0) + self.assertIsNone(access.verify(token)) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_client.py b/app/tests/test_client.py new file mode 100644 index 00000000..cf241094 --- /dev/null +++ b/app/tests/test_client.py @@ -0,0 +1,364 @@ +"""The client of the HTTP API (``nullius.client``) against a server of this +test's own on the loopback: what each call sends - the token, the path, the +query, the body - what a refusal raises, how a run is followed; the ``nullius +remote`` command's output and exit codes; and the MCP tools over the same client +(``nullius.mcp_server``). The routes themselves are the route suite's +(``ui_tests/test_api.py``).""" +from __future__ import annotations + +import ast +import contextlib +import io +import json +import os +import tempfile +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from unittest import mock + +from nullius import cli, client, mcp_server + +TOKEN = "the-test-token" + + +class Server: + """Answers each request from ``answers`` ({(method, path): (status, document) | callable}) and keeps what it was asked.""" + + def __init__(self): + self.asked, self.answers, self.headers = [], {}, {} + outer = self + + class Handler(BaseHTTPRequestHandler): + def _serve(self): + path, _, query = self.path.partition("?") + body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) + asked = {"method": self.command, "path": path, "query": query, "auth": self.headers.get("Authorization"), + "body": json.loads(body) if body else None} + outer.asked.append(asked) + answer = outer.answers.get((self.command, path), (404, {"error": f"no {path}"})) + status, doc = answer(asked) if callable(answer) else answer + raw = doc if isinstance(doc, bytes) else json.dumps(doc).encode() + self.send_response(status) + for name, value in outer.headers.items(): + self.send_header(name, value) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(raw))) + self.end_headers() + self.wfile.write(raw) + do_GET = do_POST = _serve + + def log_message(self, *a): + pass + + self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.url = f"http://127.0.0.1:{self.httpd.server_address[1]}" + threading.Thread(target=self.httpd.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True).start() + + def close(self): + self.httpd.shutdown() + self.httpd.server_close() + + +class Case(unittest.TestCase): + def setUp(self): + self.server = Server() + self.addCleanup(self.server.close) + self.nx = client.Client(self.server.url, TOKEN) + + def answer(self, method, path, doc, status=200): + self.server.answers[(method, "/api/v1" + path)] = (status, doc) + + def last(self): + return self.server.asked[-1] + + +class Calls(Case): + def test_every_call_carries_the_token_and_asks_its_route(self): + for call, method, path, query, body in ( + (lambda: self.nx.info(), "GET", "", "", None), + (lambda: self.nx.catalogue(), "GET", "/catalogue", "", None), + (lambda: self.nx.workspaces(), "GET", "/workspaces", "", None), + (lambda: self.nx.jobs(), "GET", "/jobs", "", None), + (lambda: self.nx.jobs("nightly"), "GET", "/jobs", "workspace=nightly", None), + (lambda: self.nx.job("run a/b"), "GET", "/jobs/run%20a%2Fb", "", None), + (lambda: self.nx.live("j"), "GET", "/jobs/j/live", "", None), + (lambda: self.nx.trial("j", "t__1"), "GET", "/jobs/j/trials/t__1", "", None), + (lambda: self.nx.conversation("j", "t", page=2, q="apply patch"), "GET", "/jobs/j/trials/t/conversation", "page=2&q=apply+patch", None), + (lambda: self.nx.conversation("j", "t", step=0), "GET", "/jobs/j/trials/t/conversation", "step=0", None), + (lambda: self.nx.trace("j", "t"), "GET", "/jobs/j/trials/t/trace", "", None), + (lambda: self.nx.artifacts("j", "t"), "GET", "/jobs/j/trials/t/artifacts", "", None), + (lambda: self.nx.artifact("j", "t", "result"), "GET", "/jobs/j/trials/t/artifacts/result", "", None), + (lambda: self.nx.compare("a", "b", matched=True), "GET", "/compare", "job=a&job=b&matched=1", None), + (lambda: self.nx.compare("a", "b"), "GET", "/compare", "job=a&job=b", None), + (lambda: self.nx.judgements("j"), "GET", "/jobs/j/judgements", "lane=decision", None), + (lambda: self.nx.judgement("j", "t", lane="llm"), "GET", "/jobs/j/trials/t/judgement", "lane=llm", None), + (lambda: self.nx.judge("j", "t"), "POST", "/jobs/j/trials/t/judge", "", {"lane": "decision"}), + (lambda: self.nx.judge_job("j", lane="llm"), "POST", "/jobs/j/judge", "", {"lane": "llm"}), # no yes unless asked for + (lambda: self.nx.judge_job("j", confirm=True), "POST", "/jobs/j/judge", "", {"lane": "decision", "confirm": True}), + (lambda: self.nx.recipes(), "GET", "/recipes", "", None), + (lambda: self.nx.recipe("nightly"), "GET", "/recipes/nightly", "", None), + (lambda: self.nx.save_recipe({"version": 1}), "POST", "/recipes", "", {"recipe": {"version": 1}, "id": None}), + (lambda: self.nx.check("nightly"), "POST", "/runs/check", "", {"recipe": "nightly"}), + (lambda: self.nx.check({"version": 1}, where="bench"), "POST", "/runs/check", "", {"recipe": {"version": 1}, "where": "bench"}), + (lambda: self.nx.start("nightly"), "POST", "/runs", "", {"recipe": "nightly"}), # no yes unless asked for + (lambda: self.nx.start("nightly", where=["local", "bench"], name="n-1", confirm=True), "POST", "/runs", "", + {"recipe": "nightly", "where": ["local", "bench"], "name": "n-1", "confirm": True}), + (lambda: self.nx.runs(), "GET", "/runs", "", None), + (lambda: self.nx.run("r1"), "GET", "/runs/r1", "", None), + (lambda: self.nx.run("r1", since=40), "GET", "/runs/r1", "since=40", None), + (lambda: self.nx.stop("r1"), "POST", "/runs/r1/stop", "", None), + (lambda: self.nx.continue_("r1"), "POST", "/runs/r1/continue", "", None)): + self.answer(method, path, {"ok": path}) + self.assertEqual(call(), {"ok": path}) + self.assertEqual(self.last(), {"method": method, "path": "/api/v1" + path, "query": query, + "auth": "Bearer " + TOKEN, "body": body}) + + def test_a_refusal_raises_with_the_server_s_sentence_its_status_and_its_document(self): + self.answer("POST", "/runs", {"error": "A machine lacks what this recipe needs: see machines.", "machines": [{"where": "local"}]}, 409) + with self.assertRaises(client.ApiError) as c: + self.nx.start("nightly") + self.assertEqual((c.exception.status, str(c.exception)), (409, "A machine lacks what this recipe needs: see machines.")) + self.assertEqual(c.exception.document["machines"], [{"where": "local"}]) + self.server.answers[("GET", "/api/v1/jobs")] = (502, b"bad gateway") # not this server's JSON + with self.assertRaises(client.ApiError) as c: + self.nx.jobs() + self.assertEqual((c.exception.status, c.exception.document), (502, {})) + self.assertIn("HTTP 502", str(c.exception)) + + def test_a_server_that_does_not_answer_is_an_error_with_status_zero(self): + self.server.close() + with self.assertRaises(client.ApiError) as c: + client.Client(self.server.url, TOKEN, timeout=2).info() + self.assertEqual(c.exception.status, 0) + self.assertIn("did not answer", str(c.exception)) + self.server = Server() # for the cleanup + + def test_a_redirect_is_refused_and_the_token_goes_nowhere_else(self): + other = Server(); self.addCleanup(other.close) + self.server.headers = {"Location": other.url + "/api/v1/runs"} + for status in (301, 302, 303, 307, 308): + self.answer("POST", "/runs", {}, status) + with self.assertRaises(client.ApiError) as e: + self.nx.start("nightly", confirm=True) + self.assertEqual(e.exception.status, status) + self.assertIn(other.url, str(e.exception)) + self.assertEqual(other.asked, []) + + def test_a_token_from_a_file_with_line_ends_and_one_that_is_no_token(self): + self.assertEqual(client.Client("http://h", TOKEN + "\r\n").token, TOKEN) + with self.assertRaises(ValueError) as e: + client.Client("http://h", "nls_a\r\nb") + self.assertNotIn("nls_a", str(e.exception)) + + def test_what_is_not_an_http_answer_is_an_error_too(self): + for url in ("http://127.0.0.1:abc", "http://a b"): + with self.assertRaises(client.ApiError) as e: + client.Client(url, TOKEN).jobs() + self.assertEqual(e.exception.status, 0, url) + self.answer("GET", "/jobs", b"") + with self.assertRaises(client.ApiError): + self.nx.jobs() + + def test_the_address_and_token_come_from_the_environment_or_are_asked_for(self): + with mock.patch.dict(os.environ, {"NULLIUS_SERVER": self.server.url + "/", "NULLIUS_TOKEN": "from-env"}): + nx = client.Client() + self.assertEqual((nx.url, nx.token), (self.server.url, "from-env")) + with mock.patch.dict(os.environ): + os.environ.pop("NULLIUS_SERVER", None), os.environ.pop("NULLIUS_TOKEN", None) + for url, token in ((None, "t"), ("bench:5057", "t"), (self.server.url, None)): + with self.assertRaises(ValueError, msg=(url, token)): + client.Client(url, token) + + def test_the_client_is_one_file_of_the_standard_library(self): + """It works copied alone to a machine without Nullius: it imports nothing else of the package.""" + tree = ast.parse(Path(client.__file__).read_text()) + names = {a.name.split(".")[0] for n in ast.walk(tree) if isinstance(n, ast.Import) for a in n.names} \ + | {(n.module or "").split(".")[0] for n in ast.walk(tree) if isinstance(n, ast.ImportFrom)} + self.assertEqual(names, {"__future__", "argparse", "http", "json", "os", "sys", "time", "typing", "urllib"}) + + +class Following(Case): + def run_of(self, states): + """A run whose log grows by one line a call, through ``states``.""" + calls = [] + + def answer(asked): + since = int(dict(p.split("=") for p in asked["query"].split("&") if p).get("since", 0)) + i = min(len(calls), len(states) - 1) + calls.append(since) + state, question = states[i] if isinstance(states[i], tuple) else (states[i], None) + lines = [f"line {n}" for n in range(i + 1)] + return 200, {"id": "r1", "state": state, "question": question, "lines": len(lines), "log": lines[since:]} + self.server.answers[("GET", "/api/v1/runs/r1")] = answer + return calls + + def test_follow_yields_each_line_once_until_the_run_ends(self): + calls = self.run_of(["preparing", "running", "running", "done"]) + self.assertEqual(list(self.nx.follow("r1", every=0)), ["line 0", "line 1", "line 2", "line 3"]) + self.assertEqual(calls, [0, 1, 2, 3]) # each call asks from where the last ended + + def test_follow_and_wait_return_at_a_question(self): + self.run_of(["running", ("paused", "nop exited 1. Continue with oracle, or stop?")]) + self.assertEqual(list(self.nx.follow("r1", every=0)), ["line 0", "line 1"]) + self.run_of(["running", ("paused", "nop exited 1. Continue with oracle, or stop?")]) + got = self.nx.wait("r1", every=0) + self.assertEqual((got["state"], got["log"]), ("paused", [])) # the summary, without the log again + + def test_wait_returns_the_ended_run_or_times_out(self): + self.run_of(["running", "running", "failed"]) + self.assertEqual(self.nx.wait("r1", every=0)["state"], "failed") + self.run_of(["running"]) + with self.assertRaises(TimeoutError): + self.nx.wait("r1", every=0.01, timeout=0.05) + + +class Remote(Case): + """``nullius remote``: one JSON document on stdout, the rest on stderr, the exit codes of ``docs/cli/exit-codes.md``.""" + + def remote(self, *argv, env=True): + out, err = io.StringIO(), io.StringIO() + vars_ = {"NULLIUS_SERVER": self.server.url, "NULLIUS_TOKEN": TOKEN} if env else {} + with mock.patch.dict(os.environ, vars_), contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + if not env: + os.environ.pop("NULLIUS_SERVER", None), os.environ.pop("NULLIUS_TOKEN", None) + code = cli.main(["remote", *argv]) + return code, out.getvalue(), err.getvalue() + + def test_a_read_prints_the_server_s_document(self): + self.answer("GET", "/jobs", [{"job_id": "a"}]) + self.answer("GET", "/jobs/a", {"job_id": "a", "trials": []}) + self.answer("GET", "/jobs/a/trials/t", {"trial": {"trial_name": "t"}}) + self.answer("GET", "/compare", {"columns": []}) + self.assertEqual(self.remote("jobs")[:2], (0, json.dumps([{"job_id": "a"}], indent=1) + "\n")) + self.assertEqual(json.loads(self.remote("job", "a")[1]), {"job_id": "a", "trials": []}) + self.assertEqual(json.loads(self.remote("job", "a", "t")[1]), {"trial": {"trial_name": "t"}}) + self.assertEqual(self.remote("compare", "a", "b", "--matched")[0], 0) + self.assertEqual(self.last()["query"], "job=a&job=b&matched=1") + + def test_the_flags_name_the_server_too(self): + self.answer("GET", "", {"api": 1}) + code, out, _ = self.remote("--server", self.server.url, "--token", TOKEN, "info", env=False) + self.assertEqual((code, json.loads(out)), (0, {"api": 1})) + code, out, err = self.remote("info", env=False) + self.assertEqual((code, out), (2, "")) + self.assertIn("NULLIUS_SERVER", err) + + def test_not_found_is_three_and_a_refusal_is_four_with_its_document(self): + code, out, err = self.remote("job", "nope") + self.assertEqual((code, out), (3, "")) + self.assertIn("no /api/v1/jobs/nope", err) + self.answer("POST", "/runs", {"error": "Run all problems of GSM8K? Send \"confirm\": true to start it.", "confirm": "Run all problems of GSM8K?"}, 409) + code, out, err = self.remote("run", "nightly") + self.assertEqual(code, 4) + self.assertEqual(json.loads(out)["confirm"], "Run all problems of GSM8K?") + self.assertIn("Run all problems of GSM8K?", err) + + def test_run_sends_a_recipe_file_or_a_saved_name_and_the_yes_only_when_given(self): + self.answer("POST", "/runs", {"runs": [{"id": "r1", "state": "preparing"}]}) + self.remote("run", "nightly") + self.assertEqual(self.last()["body"], {"recipe": "nightly"}) + recipe = {"version": 1, "harness": "standard", "name": "g"} + with tempfile.TemporaryDirectory() as tmp: + for doc in (recipe, {"id": "0" * 16, "name": "G", "saved": "2026-01-01T00:00:00Z", "recipe": recipe}): # as exported, or as the store keeps it + path = os.path.join(tmp, "r.json") + with open(path, "w") as fh: + json.dump(doc, fh) + self.remote("run", path, "--where", "bench", "--name", "g-1", "--yes") + self.assertEqual(self.last()["body"], {"recipe": recipe, "where": "bench", "name": "g-1", "confirm": True}) + with open(path, "w") as fh: + fh.write("{not json") + self.assertEqual(self.remote("run", path)[0], 2) + + def test_judge_asks_one_trial_or_a_job_and_the_job_only_with_yes(self): + self.answer("POST", "/jobs/a/trials/t/judge", {"answers": {}}) + self.answer("POST", "/jobs/a/judge", {"error": "This asks the judge about 4 trial(s), a paid call each.", "todo": 4}, 409) + self.assertEqual(self.remote("judge", "a", "t", "--lane", "llm")[0], 0) + self.assertEqual(self.last()["body"], {"lane": "llm"}) + code, out, _ = self.remote("judge", "a") + self.assertEqual((code, json.loads(out)["todo"], self.last()["body"]), (4, 4, {"lane": "decision"})) + self.remote("judge", "a", "--yes") + self.assertEqual(self.last()["body"], {"lane": "decision", "confirm": True}) + self.answer("GET", "/jobs/a/judgements", {"judged": 0, "records": {}}) + self.assertEqual(self.remote("judgements", "a")[0], 0) + + def test_run_follow_prints_the_log_and_exits_by_how_the_run_ended(self): + for state, code in (("done", 0), ("failed", 4)): + self.answer("POST", "/runs", {"runs": [{"id": "r1", "state": "preparing"}]}) + self.answer("GET", "/runs/r1", {"id": "r1", "state": state, "question": None, "lines": 2, "log": ["one", "two"]}) + got, out, err = self.remote("run", "nightly", "--follow") + self.assertEqual(got, code) + self.assertEqual(json.loads(out)["runs"][0]["state"], state) + self.assertIn("one\ntwo\n", err) + + +class McpTools(Case): + def call(self, name, arguments=None, rid=1): + return mcp_server.handle({"jsonrpc": "2.0", "id": rid, "method": "tools/call", "params": {"name": name, "arguments": arguments or {}}}, self.nx) + + def test_it_initialises_and_lists_its_tools(self): + got = mcp_server.handle({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {"protocolVersion": "2025-03-26"}}, self.nx) + self.assertEqual(got["result"]["protocolVersion"], "2025-03-26") + self.assertEqual(got["result"]["capabilities"], {"tools": {}}) + self.assertIsNone(mcp_server.handle({"jsonrpc": "2.0", "method": "notifications/initialized"}, self.nx)) + tools = mcp_server.handle({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, self.nx)["result"]["tools"] + self.assertEqual({t["name"] for t in tools}, set(mcp_server.TOOLS)) + for t in tools: + self.assertEqual(t["inputSchema"]["type"], "object", t["name"]) + self.assertLessEqual(set(t["inputSchema"]["required"]), set(t["inputSchema"]["properties"]), t["name"]) + self.assertEqual(mcp_server.handle({"jsonrpc": "2.0", "id": 2, "method": "nope"}, self.nx)["error"]["code"], -32601) + + def test_a_tool_is_one_call_of_the_client(self): + self.answer("GET", "/jobs/a", {"job_id": "a", "adjusted_solve_rate": 0.5}) + got = self.call("get_job", {"job_id": "a"})["result"] + self.assertEqual((got["isError"], json.loads(got["content"][0]["text"])), (False, {"job_id": "a", "adjusted_solve_rate": 0.5})) + self.answer("GET", "/compare", {"columns": []}) + self.call("compare_jobs", {"job_ids": ["a", "b"], "matched": True}) + self.assertEqual(self.last()["query"], "job=a&job=b&matched=1") + self.answer("POST", "/runs/check", {"ready": True, "confirm": "Run all?"}) + self.call("check_run", {"recipe": "nightly", "where": "bench"}) + self.assertEqual(self.last()["body"], {"recipe": "nightly", "where": "bench"}) + + def test_start_run_says_yes_only_when_told(self): + self.answer("POST", "/runs", {"runs": []}) + self.call("start_run", {"recipe": "nightly"}) + self.assertEqual(self.last()["body"], {"recipe": "nightly"}) + self.call("start_run", {"recipe": "nightly", "confirm": True}) + self.assertEqual(self.last()["body"], {"recipe": "nightly", "confirm": True}) + asked = len(self.server.asked) + for yes in ("false", "true", 1, [0]): # only true is a yes + self.assertEqual(self.call("start_run", {"recipe": "nightly", "confirm": yes})["error"]["code"], -32602, yes) + self.assertEqual(len(self.server.asked), asked) + + def test_a_malformed_message_is_answered_and_the_next_one_too(self): + lines = ["not json", "[]", '{"jsonrpc":"2.0","id":1,"result":{}}'] + lines += [json.dumps({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": p}) + for p in ([1], {"name": []}, {"name": "get_job", "arguments": "a"}, {"name": "get_job", "arguments": [1]}, + {"name": "compare_jobs", "arguments": {"job_ids": 7}}, {"name": "compare_jobs", "arguments": {"job_ids": "ab"}})] + lines.append(json.dumps({"jsonrpc": "2.0", "id": 3, "method": "ping"})) + lines.append(json.dumps({"jsonrpc": "2.0", "id": 4, "method": "initialize", "params": {"protocolVersion": {}}})) + out = io.StringIO() + with mock.patch.dict(os.environ, {"NULLIUS_SERVER": self.server.url, "NULLIUS_TOKEN": TOKEN}), \ + mock.patch("sys.stdin", io.StringIO("\n".join(lines))), contextlib.redirect_stdout(out): + self.assertEqual(mcp_server.main([]), 0) + got = [json.loads(x) for x in out.getvalue().splitlines()] + self.assertEqual([g.get("error", {}).get("code") for g in got], [-32700, -32600] + [-32602] * 6 + [None, None]) + self.assertEqual(got[-1]["result"]["protocolVersion"], mcp_server.PROTOCOLS[0]) + self.assertEqual(self.server.asked, []) + + def test_a_refusal_an_unknown_tool_and_a_missing_argument(self): + self.answer("POST", "/runs", {"error": "This token's scope is read: this needs run."}, 403) + got = self.call("start_run", {"recipe": "nightly"})["result"] + self.assertTrue(got["isError"]) + self.assertEqual(json.loads(got["content"][0]["text"])["error"], "This token's scope is read: this needs run.") + self.assertEqual(self.call("delete_everything")["error"]["code"], -32602) + asked = len(self.server.asked) + got = self.call("get_trial", {"job_id": "a"})["result"] + self.assertTrue(got["isError"]) + self.assertIn("get_trial needs trial", got["content"][0]["text"]) + self.assertEqual(len(self.server.asked), asked) # nothing was asked of the server + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_settings.py b/app/tests/test_settings.py index 65bece6f..33e177e1 100644 --- a/app/tests/test_settings.py +++ b/app/tests/test_settings.py @@ -35,6 +35,7 @@ def test_every_variable_the_application_reads_is_in_the_table(self): read -= {"DOCKER_CONFIG"} # docker's own: where it keeps a login (sandbox.py reads the username) read -= {"DOCKER_HOST", "DOCKER_CONTEXT"} # docker's own: when set, container.py leaves the current context to them read -= {"XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS"} # the user's session: where systemd-run finds its manager (constraints.session) + read -= {"NULLIUS_SERVER", "NULLIUS_TOKEN"} # the client's, on another machine: the server it asks and its token (client.py) missing = sorted(v for v in read if v not in settings.BY_NAME and v not in settings.STARTUP) self.assertEqual(missing, [], f"read by the application but neither on the page nor a named start-up option: {missing}") self.assertEqual(sorted(set(settings.BY_NAME) & set(settings.STARTUP)), []) diff --git a/app/ui_tests/test_api.py b/app/ui_tests/test_api.py new file mode 100644 index 00000000..7a9092c1 --- /dev/null +++ b/app/ui_tests/test_api.py @@ -0,0 +1,625 @@ +"""The HTTP API (``web/api.py``): the token every route takes and what each +scope may do, the guards a page takes that it does not, the reads as the +commands print them, a recipe checked and started as Review does it, a run +followed and stopped; then the client, the command and the MCP tools against +the application served on a socket. The execution's runners are fakes.""" +from __future__ import annotations + +import contextlib +import io +import json +import logging +import os +import re +import shutil +import tempfile +import threading +import time +import unittest +from contextlib import ExitStack +from pathlib import Path +from unittest.mock import patch + +from werkzeug.serving import make_server + +from nullius import access, cli, client, execution, mcp_server, workspace +from nullius.compare import cli as compare_cli, comparison +from nullius.judge import client as judge_client, questions as Q, store as judge_store +from nullius.recipes import store +from nullius.runs import cli as runs_cli +from nullius.standard.pages import recipe as standard_recipe +from .test_routes import web + +api = web.api +FIXTURES = Path(__file__).resolve().parents[1] / "tests" / "fixtures" +JOB = FIXTURES / "harbor-jobs" / "liveboard-oracle-x4" + + +def doc(value): + """A document as the API sends it: through JSON, timestamps as the commands print them.""" + return json.loads(json.dumps(value, default=runs_cli._stamp)) + + +def gsm8k(**kw): + return dict({"version": 1, "harness": "standard", "name": "g", "title": "GSM8K", "benchmark": "gsm8k", "datasets": ["test"], + "others": ["original"], "model": "openai/x", "provider": "openrouter", "where": "local"}, **kw) + + +class Case(unittest.TestCase): + def setUp(self): + self.stack = ExitStack(); self.addCleanup(self.stack.close) + self.tmp = Path(tempfile.mkdtemp(prefix="nullius-api-")); self.addCleanup(shutil.rmtree, self.tmp, True) + for name in ("oracle-a", "oracle-b"): + shutil.copytree(JOB, self.tmp / "jobs" / name) + self.stack.enter_context(patch.dict(os.environ, {"NULLIUS_HOME": str(self.tmp / "home"), "HOSTS": "bench", "RUNS_DIR": str(self.tmp / "runs"), + "OPENROUTER_API_KEY": "sk-testkey-0123456789"})) + self.stack.enter_context(patch.object(web.shared, "WS_HOME", str(self.tmp / "workspaces"))) + self.stack.enter_context(patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []}, clear=True)) + self.stack.enter_context(patch.dict(web.app.config, TESTING=True)) + self.stack.enter_context(patch.dict(execution.EXECUTIONS, clear=True)) + self.stack.enter_context(patch.object(execution, "SYNC_EVERY", 0.05)) + ws = workspace.create(web.shared.WS_HOME, [str(self.tmp / "jobs")], "api") + workspace.save(ws) + web.shared.open_workspace(ws) + self.reader, _ = access.create("reader", "read") + self.runner, self.runner_record = access.create("runner", "run") + self.client = web.app.test_client() + + def ask(self, method, path, token="runner", body=None, **kw): + headers = dict(kw.pop("headers", {})) + if token: + headers["Authorization"] = "Bearer " + {"runner": self.runner, "reader": self.reader}.get(token, token) + r = self.client.open("/api/v1" + path, method=method, headers=headers, + **({"data": json.dumps(body), "content_type": "application/json"} if body is not None else {}), **kw) + self.addCleanup(r.close) + return r + + def get(self, path, token="reader", **kw): + return self.ask("GET", path, token, **kw) + + def post(self, path, body=None, token="runner", **kw): + return self.ask("POST", path, token, body if body is not None else {}, **kw) + + +class Tokens(Case): + def test_every_route_takes_a_token_in_the_authorization_header(self): + rules = [r for r in web.app.url_map.iter_rules() if str(r).startswith("/api/v1")] + self.assertGreater(len(rules), 15) + for rule in rules: + url = str(rule).replace("", "oracle-a").replace("", "t").replace("", "result") \ + .replace("", "r").replace("", "x") + for method in sorted(rule.methods - {"HEAD", "OPTIONS"}): + r = self.client.open(url, method=method); self.addCleanup(r.close) + self.assertEqual((r.status_code, r.headers.get("WWW-Authenticate")), (401, "Bearer"), (method, url)) + self.assertIn("nullius access create", r.json["error"]) + for sent in ("nope", self.runner + "x", "Bearer", ""): + self.assertEqual(self.get("", token=None, headers={"Authorization": f"Bearer {sent}"}).status_code, 401, sent) + self.assertEqual(self.get("", token=None, headers={"Authorization": f"Basic {self.runner}"}).status_code, 401) + # a token is read from the header only: never the query, a form or a cookie, which a page can be made to send + self.assertEqual(self.get(f"?token={self.runner}&access_token={self.runner}", token=None).status_code, 401) + self.client.set_cookie("token", self.runner) + self.assertEqual(self.get("", token=None).status_code, 401) + self.assertEqual(self.get("").status_code, 200) + + def test_a_revoked_token_and_a_server_without_tokens_answer_nothing(self): + self.assertEqual(self.get("/jobs", token="runner").status_code, 200) + access.revoke(self.runner_record["id"]) + self.assertEqual(self.get("/jobs", token="runner").status_code, 401) + os.unlink(access.file()) + self.assertEqual(self.get("/jobs").status_code, 401) + + def test_read_reads_and_only_run_writes(self): + for path in ("/recipes", "/runs/check", "/runs", "/runs/r/stop", "/runs/r/continue"): + r = self.post(path, token="reader") + self.assertEqual((r.status_code, r.json), (403, {"error": "This token's scope is read: this needs run."}), path) + self.assertEqual(execution.EXECUTIONS, {}) + for path in ("", "/catalogue", "/workspaces", "/jobs", "/recipes", "/runs"): + self.assertEqual(self.get(path).status_code, 200, path) + info = self.get("", token="runner").json + self.assertEqual((info["api"], info["token"], info["where"], info["workspace"]), + (1, access.shown(self.runner_record), ["local", "bench"], web.shared.STATE["workspace"].name)) + + def test_no_route_reads_settings_or_sends_a_key(self): + """Nothing under the API names Settings, and no answer carries the provider's key.""" + self.assertEqual([str(r) for r in web.app.url_map.iter_rules() if str(r).startswith("/api/v1") and "setting" in str(r)], []) + for path in ("", "/catalogue", "/workspaces", "/jobs", "/recipes", "/runs"): + self.assertNotIn("sk-testkey-0123456789", self.get(path).get_data(as_text=True), path) + + def test_the_api_keeps_no_session_and_answers_in_json_with_no_store(self): + for r in (self.get("/jobs"), self.get("/jobs/nope"), self.get("", token=None), self.post("/runs/check", {"recipe": gsm8k()})): + self.assertIsNone(r.headers.get("Set-Cookie"), r.request.path) + self.assertEqual((r.mimetype, r.headers["Cache-Control"]), ("application/json", "no-store"), r.request.path) + + def test_a_token_stands_where_a_page_s_guards_would_refuse(self): + """A page's write takes the form token, the same origin and a loopback browser, and a page is served + under the server's own name only. A client on another machine has none of these: its token is the guard.""" + far = {"environ_base": {"REMOTE_ADDR": "10.0.0.7"}, "headers": {"Host": "bench.internal:5057"}} + self.assertEqual(self.client.get("/runs", headers={"Host": "bench.internal:5057"}).status_code, 421) # a page: refused + self.assertEqual(self.get("/jobs", **far).status_code, 200) + self.assertEqual(self.get("/jobs", token=None, **far).status_code, 401) + self.assertEqual(self.post("/runs/check", {"recipe": gsm8k()}, **far).status_code, 200) + self.assertEqual(self.client.post("/run", data="{}", content_type="application/json", headers={"Authorization": "Bearer " + self.runner}).status_code, 403) # the page's route keeps its own + + +class Reads(Case): + def setUp(self): + super().setUp() + with web.app.test_request_context("/"): + self.jobs = web.shared._load_jobs() + self.job = next(j for j in self.jobs if j.job_id == "oracle-a") + self.trial = next(t for t in self.job.trials if t.has_trajectory) if any(t.has_trajectory for t in self.job.trials) else self.job.trials[0] + + def test_jobs_and_a_job_are_what_the_command_prints(self): + self.assertEqual(self.get("/jobs").json, doc([runs_cli.job_row(j) for j in self.jobs])) + self.assertEqual(sorted(j["job_id"] for j in self.get("/jobs").json), ["oracle-a", "oracle-b"]) + got = self.get("/jobs/oracle-a").json + self.assertEqual(got, doc(runs_cli.job_detail(self.job))) + self.assertEqual(len(got["trials"]), len(self.job.trials)) + self.assertEqual((got["adjusted_solve_rate"], got["counts"]), (self.job.adjusted_solve_rate, doc(self.job.counts))) + r = self.get("/jobs/nope") + self.assertEqual((r.status_code, r.json), (404, {"error": "no job 'nope' in this workspace"})) + + def test_a_trial_its_records_and_its_conversation(self): + name = self.trial.trial_name + self.assertEqual(self.get(f"/jobs/oracle-a/trials/{name}").json, doc(runs_cli.trial_detail(self.job, self.trial))) + listed = self.get(f"/jobs/oracle-a/trials/{name}/artifacts").json + self.assertIn("result", [r["key"] for r in listed]) + self.assertTrue(all(sorted(r) == ["filename", "key", "label", "size"] and r["size"] is not None for r in listed)) + got = self.get(f"/jobs/oracle-a/trials/{name}/artifacts/result").json + self.assertEqual((got["key"], got["filename"], got["truncated"]), ("result", "result.json", False)) + self.assertEqual(json.loads(got["text"])["trial_name"], name) + page = self.client.get(f"/trial/oracle-a/{name}/conversation"); self.addCleanup(page.close) + self.assertEqual(self.get(f"/jobs/oracle-a/trials/{name}/conversation").json, page.json) # the page's own + for path in ("/jobs/oracle-a/trials/nope", f"/jobs/oracle-a/trials/{name}/artifacts/nope", f"/jobs/oracle-a/trials/{name}/artifacts/..%2Fconfig", + f"/jobs/oracle-a/trials/{name}/artifacts/..%2F..%2Fconfig.json", f"/jobs/nope/trials/{name}/conversation", "/no-such-route"): + r = self.get(path) + self.assertEqual((r.status_code, sorted(r.json)), (404, ["error"]), path) + + def test_a_trace_is_sent_redacted_and_a_trial_without_one_has_none(self): + name = self.trial.trial_name + r = self.get(f"/jobs/oracle-a/trials/{name}/trace") + self.assertEqual((r.status_code, r.json), (404, {"error": f"trial {name!r} has no trace that can be read"})) + shutil.copytree(JOB, self.tmp / "jobs" / "traced") + agent = self.tmp / "jobs" / "traced" / name / "agent"; agent.mkdir(exist_ok=True) + secret = "sk-or-v1-" + "a" * 64 + (agent / "trace.json").write_text(json.dumps({"schema_version": "harbor-trace-v1", "spans": [{"name": "call", "attributes": {"auth": "Bearer " + secret, "password": "hunter2hunter2", + "url": "http://relay:8080", "agent": "x@1.0", "token": 123456789}}]})) + web.shared.open_workspace(web.shared.STATE["workspace"], refresh=True) + r = self.get(f"/jobs/traced/trials/{name}/trace") + self.assertEqual((r.status_code, r.json["schema_version"], r.json["spans"][0]["name"]), (200, "harbor-trace-v1", "call")) + self.assertNotIn(secret, r.get_data(as_text=True)) + self.assertEqual(r.json["spans"][0]["attributes"], {"auth": "Bearer [REDACTED]", "password": "[REDACTED]", # each string alone: the JSON stays JSON + "url": "http://relay:8080", "agent": "x@1.0", "token": 123456789}) + + def test_a_trace_that_is_a_link_or_no_trace_is_not_read(self): + name = self.trial.trial_name + shutil.copytree(JOB, self.tmp / "jobs" / "linked") + agent = self.tmp / "jobs" / "linked" / name / "agent"; agent.mkdir(exist_ok=True) + (self.tmp / "outside.json").write_text('{"private": "file"}') + (agent / "trace.json").symlink_to(self.tmp / "outside.json") # the agent writes this folder + web.shared.open_workspace(web.shared.STATE["workspace"], refresh=True) + self.assertEqual(self.get(f"/jobs/linked/trials/{name}/trace").status_code, 404) + (agent / "trace.json").unlink() + for text in ("[]", "PRIVATE KEY", "[" * 20000): + (agent / "trace.json").write_text(text) + self.assertEqual(self.get(f"/jobs/linked/trials/{name}/trace").status_code, 404, text[:20]) + shutil.rmtree(agent) + (self.tmp / "elsewhere").mkdir(); (self.tmp / "elsewhere" / "trace.json").write_text("{}") + agent.symlink_to(self.tmp / "elsewhere") + self.assertEqual(self.get(f"/jobs/linked/trials/{name}/trace").status_code, 404) + + def test_the_live_board_is_the_page_s(self): + page = self.client.get("/job/oracle-a/live"); self.addCleanup(page.close) + r = self.get("/jobs/oracle-a/live") + self.assertEqual((r.status_code, r.json["state"], sorted(r.json)), (page.status_code, page.json["state"], sorted(page.json))) + self.assertEqual(len(r.json["trials"]), len(self.job.trials)) + r = self.get("/jobs/nope/live") + self.assertEqual((r.status_code, sorted(r.json)), (404, ["error"])) + + def test_a_comparison_is_what_the_command_prints(self): + selected = comparison.resolve([":oracle-a", ":oracle-b"], {"": self.jobs}) + for query, cohort in (("", "whole"), ("&matched=1", "matched")): + self.assertEqual(self.get("/compare?job=oracle-a&job=oracle-b" + query).json, doc(compare_cli.document(comparison.build(selected, cohort))), cohort) + self.assertEqual(self.get("/compare?job=oracle-a&job=oracle-a").status_code, 400) # one run twice is one run + r = self.get("/compare?job=oracle-a&job=nope") + self.assertEqual((r.status_code, r.json), (404, {"error": "Run nope is unavailable in the active source."})) + + def test_another_workspace_by_name_and_one_that_is_not_there(self): + other = workspace.create(web.shared.WS_HOME, [str(self.tmp / "jobs" / "oracle-b")], "only-b") + workspace.save(other) + self.assertEqual([j["job_id"] for j in self.get(f"/jobs?workspace={other.name}").json], ["oracle-b"]) + self.assertEqual(self.get(f"/jobs/oracle-a?workspace={other.name}").status_code, 404) + self.assertEqual(sorted(w["name"] for w in self.get("/workspaces").json), sorted([other.name, web.shared.STATE["workspace"].name])) + r = self.get("/jobs?workspace=nope") + self.assertEqual((r.status_code, sorted(r.json)), (404, ["error"])) + + def test_the_catalogue_names_what_a_recipe_names(self): + got = self.get("/catalogue").json + g = next(b for b in got["benchmarks"] if b["key"] == "gsm8k") + self.assertEqual((g["runners"], [d["id"] for d in g["datasets"]]), (["standard"], ["test", "platinum"])) + self.assertIn("reference", g["fits"]) + self.assertIn("reference", [a["ref"] for a in got["agents"]]) + self.assertTrue(all(sorted(c) == ["key", "label", "offers", "ref", "summary"] for c in got["agents"] + got["capabilities"])) + + +class Judgements(Case): + """A judge's answers read, and a judge asked: one trial by the request, several only with a yes. The judge is a fake.""" + + def setUp(self): + super().setUp() + self.asked = [] + judges = {"decision": judge_client.Judge("typesafe", "k", "m"), "llm": judge_client.Judge("openrouter", "k", "m", url="http://127.0.0.1:9/v1", lane="llm")} + self.stack.enter_context(patch.object(web.judge, "key", lambda lane="decision": judges[lane])) + + def judge_trial(job, trial, k, post=None, calibration=None): + self.asked.append((job.job_id, trial.trial_name, k.lane)) + if trial.trial_name in self.failing: + raise judge_client.JudgeError(self.failing[trial.trial_name], "the judge is busy") + record = {"questions": Q.VERSION, "judge": {"model": k.lane}, "answers": {"task_completed": {"choice": "yes", "confidence": 0.9}}} + judge_store.save(web.judge.ws_dir(), job.job_id, trial.trial_name, record, lane=k.lane, started=web.judge.started_of(trial)) + return record + self.failing = {} + self.stack.enter_context(patch.object(web.judge, "judge_trial", judge_trial)) + for trial in sorted((self.tmp / "jobs" / "oracle-a").glob("*__*"))[:3]: # a judge reads a trajectory: three trials kept one + (trial / "agent").mkdir(exist_ok=True) + (trial / "agent" / "trajectory.json").write_text("{}") + web.shared.open_workspace(web.shared.STATE["workspace"], refresh=True) + with web.app.test_request_context("/"): + self.job = next(j for j in web.shared._load_jobs() if j.job_id == "oracle-a") + self.judgeable = [t.trial_name for t in self.job.trials if t.has_trajectory] + self.assertGreater(len(self.judgeable), 1) + self.trial = self.judgeable[0] + + def test_a_trial_is_judged_by_the_request_and_its_record_read_back(self): + r = self.get(f"/jobs/oracle-a/trials/{self.trial}/judgement") + self.assertEqual((r.status_code, r.json), (404, {"error": f"trial {self.trial!r} has no decision judgement"})) + r = self.post(f"/jobs/oracle-a/trials/{self.trial}/judge") + self.assertEqual((r.status_code, r.json["answers"]["task_completed"]["choice"]), (200, "yes")) + self.assertEqual(self.asked, [("oracle-a", self.trial, "decision")]) + self.assertEqual(self.get(f"/jobs/oracle-a/trials/{self.trial}/judgement").json["answers"], r.json["answers"]) + # the LLM judge judges apart: its own records, asked by name + self.assertEqual(self.get(f"/jobs/oracle-a/trials/{self.trial}/judgement?lane=llm").status_code, 404) + self.assertEqual(self.post(f"/jobs/oracle-a/trials/{self.trial}/judge", {"lane": "llm"}).json["judge"], {"model": "llm"}) + self.assertEqual(self.get(f"/jobs/oracle-a/trials/{self.trial}/judgement?lane=llm").json["judge"], {"model": "llm"}) + got = self.get("/jobs/oracle-a/judgements").json + self.assertEqual((got["lane"], got["judged"], got["trials"], list(got["records"])), ("decision", 1, len(self.job.trials), [self.trial])) + self.assertEqual(self.get("/jobs/oracle-b/judgements").json["judged"], 0) # its twin was not asked about + + def test_a_job_is_judged_only_with_a_yes_and_only_where_unjudged(self): + self.post(f"/jobs/oracle-a/trials/{self.trial}/judge") + n = len(self.judgeable) - 1 + for body in ({}, {"confirm": "true"}, {"confirm": 1}): + r = self.post("/jobs/oracle-a/judge", body) + self.assertEqual((r.status_code, r.json["todo"]), (409, n), body) + self.assertEqual(r.json["error"], f'This asks the judge about {n} trial(s), a paid call each. Send "confirm": true to ask.') + self.assertEqual(len(self.asked), 1) # nothing asked meanwhile + r = self.post("/jobs/oracle-a/judge", {"confirm": True}) + self.assertEqual((r.status_code, r.json), (200, {"lane": "decision", "todo": n, "judged": n, "failed": []})) + self.assertEqual(sorted(t for _, t, _ in self.asked[1:]), sorted(self.judgeable[1:])) + self.assertEqual(self.get("/jobs/oracle-a/judgements").json["judged"], len(self.judgeable)) + again = self.post("/jobs/oracle-a/judge") # nothing left: nothing to confirm, nothing asked + self.assertEqual((again.status_code, again.json["todo"], len(self.asked)), (200, 0, 1 + n)) + + def test_a_request_that_names_no_judge_it_knows_asks_none(self): + path, headers = f"/api/v1/jobs/oracle-a/trials/{self.trial}/judge", {"Authorization": f"Bearer {self.runner}"} + for raw in ('{"lane":"llm"', '["llm"]', '"llm"', "lane=llm", '{"lane":[]}', '{"lane":""}', "[" * 20000): + self.assertEqual(self.client.post(path, data=raw, headers=headers).status_code, 400, raw[:20]) + self.assertEqual(self.asked, []) + for ask in ({"data": '{"lane":"llm"}'}, {"data": '{"lane":"llm"}', "content_type": "application/x-www-form-urlencoded"}, + {"query_string": "lane=llm"}): + self.assertEqual(self.client.post(path, headers=headers, **ask).status_code, 200, ask) + self.assertEqual({lane for *_, lane in self.asked}, {"llm"}) + + def test_an_attempt_s_earlier_try_is_read_and_never_judged(self): + with patch.object(web.traces, "_find_try", lambda job, name: self.job.trials[0] if name == "t.try-1" else None): + self.assertEqual(self.get("/jobs/oracle-a/trials/t.try-1").status_code, 200) + self.assertEqual(self.post("/jobs/oracle-a/trials/t.try-1/judge").status_code, 404) + self.assertEqual(self.asked, []) + + def test_a_job_of_another_workspace_is_judged_into_its_own(self): + web.shared.open_workspace(workspace.create(web.shared.WS_HOME, [str(self.tmp / "jobs")], "other")) + r = self.post("/jobs/oracle-a/judge?workspace=api", {"confirm": True}) + self.assertEqual((r.status_code, r.json["judged"]), (200, len(self.judgeable))) + self.assertEqual(self.get("/jobs/oracle-a/judgements?workspace=api").json["judged"], len(self.judgeable)) + self.assertEqual(self.get("/jobs/oracle-a/judgements").json["judged"], 0) + + def test_a_judge_that_fails_is_said_and_a_refused_key_is_the_request_s_fault(self): + self.failing = {self.trial: 500} + r = self.post(f"/jobs/oracle-a/trials/{self.trial}/judge") + self.assertEqual((r.status_code, r.json), (502, {"error": "the judge is busy"})) + self.failing = {self.trial: 401} + self.assertEqual(self.post(f"/jobs/oracle-a/trials/{self.trial}/judge").status_code, 400) + self.failing = {self.judgeable[1]: 500} + r = self.post("/jobs/oracle-a/judge", {"confirm": True}) + self.assertEqual((r.json["judged"], r.json["failed"]), (len(self.judgeable) - 1, [f"{self.judgeable[1]}: the judge is busy"])) + + def test_asking_takes_the_run_scope_and_reading_does_not(self): + for path in (f"/jobs/oracle-a/trials/{self.trial}/judge", "/jobs/oracle-a/judge"): + self.assertEqual(self.post(path, {"confirm": True}, token="reader").status_code, 403, path) + self.assertEqual(self.asked, []) + self.assertEqual(self.get("/jobs/oracle-a/judgements", token="reader").status_code, 200) + for path in ("/jobs/oracle-a/judgements?lane=other", f"/jobs/oracle-a/trials/{self.trial}/judgement?lane=other"): + self.assertEqual(self.get(path).json, {"error": "A judge is one of: decision, llm."}, path) + self.assertEqual(self.post("/jobs/nope/judge", {"confirm": True}).status_code, 404) + self.assertEqual(self.post("/jobs/oracle-a/trials/nope/judge").status_code, 404) + + def test_without_a_workspace_there_is_nowhere_to_keep_a_judgement(self): + with patch.object(web.judge, "ws_dir", lambda: None): + r = self.post(f"/jobs/oracle-a/trials/{self.trial}/judge") + self.assertEqual((r.status_code, r.json, self.asked), (400, {"error": "No workspace is open: judgements are kept in the workspace."}, [])) + + +class SettingsTokens(Case): + """Settings' API access section: a token made, shown once, listed without its value, revoked; a browser on this machine only.""" + + def setUp(self): + super().setUp() + page = self.client.get("/settings"); self.addCleanup(page.close) + self.html = page.get_data(as_text=True) + with self.client.session_transaction() as s: + self.headers = {"Origin": "http://localhost", "X-CSRF-Token": s["csrf"]} + + def form(self, path, data, **kw): + r = self.client.post(path, data=data, headers=kw.pop("headers", self.headers), **kw); self.addCleanup(r.close) + return r + + def test_the_section_lists_the_tokens_and_never_a_value_or_a_hash(self): + self.assertIn(']*data-state=\'([^\']*)\'', self.html).group(1).replace(""", '"')) + self.assertEqual([(t["name"], t["scope"], t["expired"]) for t in state], [("reader", "read", False), ("runner", "run", False)]) + self.assertEqual(sorted(state[0]), ["created", "expired", "expires", "id", "name", "scope"]) + for secret in (self.reader, self.runner, self.reader.split("_", 2)[2], self.runner_record["sha256"]): + self.assertNotIn(secret, self.html) + self.assertIn("data-api-add", self.html) + far = self.client.get("/settings", environ_base={"REMOTE_ADDR": "10.0.0.7"}); self.addCleanup(far.close) + self.assertNotIn("data-api-add", far.get_data(as_text=True)) # read-only from another machine: no form, no routes + self.assertNotIn("data-revoke", far.get_data(as_text=True)) + + def test_a_token_is_created_shown_once_and_opens_the_api(self): + r = self.form("/settings/api/create", {"name": "laptop", "scope": "run", "days": "30"}) + self.assertEqual((r.status_code, r.json["ok"], r.headers["Cache-Control"]), (200, True, "no-store")) + self.assertEqual((r.json["token"]["name"], r.json["token"]["scope"], r.json["token"]["expires"][:4].isdigit()), ("laptop", "run", True)) + self.assertEqual([t["name"] for t in r.json["tokens"]], ["reader", "runner", "laptop"]) + self.assertNotIn(r.json["value"], json.dumps(r.json["tokens"])) + self.assertEqual(self.get("", token=r.json["value"]).json["token"]["name"], "laptop") + page = self.client.get("/settings"); self.addCleanup(page.close) + self.assertNotIn(r.json["value"], page.get_data(as_text=True)) # the page after it holds the name only + never = self.form("/settings/api/create", {"name": "forever"}) + self.assertEqual((never.json["token"]["scope"], never.json["token"]["expires"]), ("read", None)) + + def test_what_is_refused_and_from_where(self): + for data, said in (({"name": "runner"}, "A token is named 'runner' already: revoke it first, or choose another name."), + ({"name": "a/b"}, "A token's name is 1 to 64 letters, digits, spaces, '.', '_' or '-'."), + ({"name": "x", "scope": "admin"}, "A token's scope is one of: read, run."), + ({"name": "x", "days": "soon"}, "A token expires after 1 to 3650 days, or never."), + ({"name": "x", "days": "0"}, "A token expires after 1 to 3650 days, or never.")): + r = self.form("/settings/api/create", data) + self.assertEqual((r.status_code, r.json), (400, {"ok": False, "error": said}), data) + for path, data in (("/settings/api/create", {"name": "x"}), ("/settings/api/revoke", {"id": self.runner_record["id"]})): + self.assertEqual(self.form(path, data, headers={"Origin": "http://localhost"}).status_code, 403, path) # no form token + self.assertEqual(self.form(path, data, environ_base={"REMOTE_ADDR": "10.0.0.7"}).status_code, 403, path) # not this machine + self.assertEqual(self.form(path, data, headers={**self.headers, "Authorization": "Bearer " + self.runner, "X-CSRF-Token": "x"}).status_code, 403, path) # a token makes no token + self.assertEqual([r["name"] for r in access.listing()], ["reader", "runner"]) + + def test_a_revoked_token_is_refused_at_once(self): + self.assertEqual(self.get("/jobs", token="runner").status_code, 200) + r = self.form("/settings/api/revoke", {"id": self.runner_record["id"]}) + self.assertEqual((r.status_code, [t["name"] for t in r.json["tokens"]]), (200, ["reader"])) + self.assertEqual(self.get("/jobs", token="runner").status_code, 401) + gone = self.form("/settings/api/revoke", {"id": self.runner_record["id"]}) + self.assertEqual((gone.status_code, gone.json), (404, {"ok": False, "error": "That token is gone already."})) + + +class Recipes(Case): + def test_a_recipe_is_saved_listed_and_read_by_id_or_name(self): + saved = self.post("/recipes", {"recipe": gsm8k(title="Nightly")}).json + self.assertEqual((saved["name"], saved["recipe"]["benchmark"]), ("Nightly", "gsm8k")) + self.assertEqual(self.get("/recipes").json, [saved]) + self.assertEqual(store.listing(), [saved]) # the builder's own store + for key in (saved["id"], "Nightly"): + self.assertEqual(self.get(f"/recipes/{key}").json, saved) + again = self.post("/recipes", {"recipe": gsm8k(title="Nightly", model="openai/y")}).json + self.assertEqual((again["id"], again["recipe"]["model"]), (saved["id"], "openai/y")) # the same name: updated + self.assertEqual(self.get("/recipes/nope").status_code, 404) + r = self.post("/recipes", {"recipe": {"version": 2}}) + self.assertEqual((r.status_code, r.json), (400, {"error": 'a recipe is a JSON object with "version": 1'})) + + +class Runs(Case): + def setUp(self): + super().setUp() + self.calls = [] + real = execution.subprocess_run + + def run(argv, timeout=600, stdin=None, stop=None): + if argv[0] == "bash": + return real(argv, timeout, stdin, stop=stop) + self.calls.append(argv) + return 0, "" + self.stack.enter_context(patch.object(execution, "subprocess_run", run)) + self.stack.enter_context(patch.object(execution, "docker_here", lambda sh, needs="", program="docker": None)) + self.adopted = [] + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: self.adopted.extend(ex.plan.name for ex in runs))) + + def scripted(self, script="echo started; echo \"key=${#OPENAI_API_KEY}\""): + """A recipe of the first two problems, whose run is this test's script in place of the standard's command.""" + real = standard_recipe.compile + + def compile_(recipe, *a, **kw): + out = real(recipe, *a, **kw) + for shard in out.get("shards") or []: + shard.update(script=script, parts=[]) + return out + self.stack.enter_context(patch.object(standard_recipe, "compile", compile_)) + return gsm8k(limit=2) + + def wait(self): + for ex in list(execution.EXECUTIONS.values()): + ex.thread.join(10) + + def test_a_check_is_review_s_and_starts_nothing(self): + got = self.post("/runs/check", {"recipe": gsm8k()}) + self.assertEqual(got.status_code, 200) + self.assertEqual(sorted(got.json), ["confirm", "errors", "jobs", "machines", "notes", "ready", "review"]) + self.assertEqual((got.json["errors"], got.json["ready"], got.json["confirm"]), ([], True, "Run all problems of GSM8K with GSM8K original?")) + self.assertEqual([(m["where"], m["label"]) for m in got.json["machines"]], [("local", "this machine")]) + self.assertIn([2, "Dataset", "GSM8K test · 1319 problems"], got.json["review"]) + self.assertEqual((execution.EXECUTIONS, os.path.exists(self.tmp / "runs")), ({}, False)) + # a recipe that does not compile says what Review says, and its machines are not asked + bad = self.post("/runs/check", {"recipe": gsm8k(model="")}).json + self.assertEqual((bad["errors"], bad["ready"], bad["machines"]), (["Choose a model."], False, [])) + # a saved recipe by its name, and the request's Where over the recipe's + store.save(gsm8k(title="Nightly")) + there = self.post("/runs/check", {"recipe": "Nightly", "where": ["nobody@10.9.9.9"]}).json + self.assertEqual(there["ready"], False) + self.assertEqual([r["detail"] for m in there["machines"] for r in m["rows"] if r["state"] == "missing"], ["nobody@10.9.9.9 is not one of the hosts in Settings"]) + for where in ("", None, []): # blank is no machine: the recipe's own stay + got = self.post("/runs/check", {"recipe": gsm8k(where=["nobody@10.9.9.9"]), "where": where}).json + self.assertEqual([m["where"] for m in got["machines"]], ["nobody@10.9.9.9"], where) + long = self.post("/runs/check", {"recipe": gsm8k(name="n" * 70)}).json # named as the run would be + self.assertEqual((long["ready"], len(long["errors"])), (False, 1)) + for body in ({}, {"recipe": 7}, {"recipe": "no-such-recipe"}): + self.assertIn(self.post("/runs/check", body).status_code, (400, 404), body) + + def test_a_start_is_refused_as_review_would_refuse_it(self): + r = self.post("/runs", {"recipe": gsm8k(model="")}) + self.assertEqual((r.status_code, r.json["error"], r.json["errors"]), (400, "Choose a model.", ["Choose a model."])) + r = self.post("/runs", {"recipe": gsm8k(where=["nobody@10.9.9.9"]), "confirm": True}) + self.assertEqual((r.status_code, r.json["error"], r.json["ready"]), (409, "A machine lacks what this recipe needs: see machines.", False)) + r = self.post("/runs", {"recipe": gsm8k()}) # the whole dataset is a decision: asked, never assumed + self.assertEqual((r.status_code, r.json["confirm"]), (409, "Run all problems of GSM8K with GSM8K original?")) + self.assertEqual(r.json["error"], 'Run all problems of GSM8K with GSM8K original? Send "confirm": true to start it.') + for yes in ("true", 1, "yes"): # only true is a yes + self.assertEqual(self.post("/runs", {"recipe": gsm8k(), "confirm": yes}).status_code, 409, yes) + with patch.dict(os.environ): + os.environ.pop("OPENROUTER_API_KEY") + r = self.post("/runs", {"recipe": gsm8k(), "confirm": True}) + check = self.post("/runs/check", {"recipe": gsm8k()}).json # and the check says so first + self.assertEqual((check["ready"], check["errors"]), (False, r.json["errors"])) + self.assertEqual(r.status_code, 400) + self.assertIn("OPENROUTER_API_KEY is not set in Settings", r.json["error"]) + self.assertEqual((execution.EXECUTIONS, os.path.exists(self.tmp / "runs"), self.adopted), ({}, False, [])) + + def test_a_standard_recipe_starts_as_the_page_starts_it(self): + """What reaches the execution is what the page's Run posts: the recipe, named by its name and the second, + compiled on the server from the definitions.""" + seen = [] + real = web.execute.start + self.stack.enter_context(patch.object(web.execute, "start", lambda body: seen.append(body) or real(body))) + self.stack.enter_context(patch.object(execution.Execution, "_main", lambda ex: None)) # followed elsewhere: the plan is what is read here + r = self.post("/runs", {"recipe": gsm8k(), "confirm": True}) + self.assertEqual(r.status_code, 200, r.json) + self.assertRegex(r.json["name"], r"^g-\d{4}-\d{6}$") + self.assertEqual(seen, [{"name": r.json["name"], "where": "local", "recipe": gsm8k(name=r.json["name"])}]) + self.assertEqual((r.json["ok"], [x["id"] for x in r.json["runs"]], "open" in r.json), (True, [r.json["id"]], False)) + plan = execution.EXECUTIONS[r.json["id"]].plan + self.assertEqual((plan.runner, plan.recipe["benchmark"], plan.key_var, plan.host), ("standard", "gsm8k", "OPENROUTER_API_KEY", None)) + self.assertIn("standard", plan.script); self.assertIn("gsm8k", plan.script) + self.assertEqual(self.adopted, [r.json["name"]]) + named = self.post("/runs", {"recipe": gsm8k(), "confirm": True, "name": "mine"}) + self.assertEqual((named.status_code, named.json["name"]), (200, "mine")) + again = self.post("/runs", {"recipe": gsm8k(), "confirm": True, "name": "mine"}) # a name is a run, once + self.assertEqual(again.status_code, 409, again.json) + + def test_a_run_is_followed_listed_and_stopped_by_its_id(self): + r = self.post("/runs", {"recipe": self.scripted()}) + self.assertEqual(r.status_code, 200, r.json) + run_id = r.json["id"]; self.wait() + got = self.get(f"/runs/{run_id}").json + self.assertEqual((got["state"], got["host"], got["exit_code"], got["job_ids"]), ("done", "this machine", 0, [r.json["name"]]), got["log"]) + self.assertIn("key=21", "\n".join(got["log"])) # the run had its provider's key + self.assertNotIn("sk-testkey-0123456789", json.dumps(got)) # and its log does not + self.assertEqual(self.get(f"/runs/{run_id}?since={got['lines']}").json["log"], []) + self.assertEqual([x["id"] for x in self.get("/runs").json], [run_id]) + self.assertEqual(self.get("/runs/nope").status_code, 404) + for verb in ("stop", "continue"): + self.assertEqual(self.post(f"/runs/nope/{verb}").status_code, 404) + + def test_a_running_run_is_stopped_from_another_machine(self): + r = self.post("/runs", {"recipe": self.scripted("echo started; sleep 60")}) + run_id = r.json["id"] + for _ in range(400): + if "started" in "\n".join(self.get(f"/runs/{run_id}").json["log"]): break + time.sleep(0.02) + s = self.post(f"/runs/{run_id}/stop", environ_base={"REMOTE_ADDR": "10.0.0.7"}) + self.assertEqual((s.status_code, s.json["id"]), (200, run_id)) + self.assertIn(s.json["state"], ("stopping", "stopped")) + self.wait() + self.assertEqual(self.get(f"/runs/{run_id}").json["state"], "stopped") + + def test_a_harbor_recipe_is_started_from_the_builder(self): + """Its compiler is the builder's page: over the API it is refused with where to start it, checked or started.""" + harbor = json.loads((FIXTURES / "recipes" / "harbor-swe-bench-release-pin.json").read_text()) + for recipe in (harbor, {"version": 1, "name": "h"}, {}): # a recipe naming no runner is Harbor's + for path in ("/runs/check", "/runs"): + r = self.post(path, {"recipe": recipe, "confirm": True}) + self.assertEqual((r.status_code, r.json), (400, {"error": api.STANDARD_ONLY}), (path, recipe.get("name"))) + self.assertEqual(execution.EXECUTIONS, {}) + + +class OverASocket(Case): + """The client, the command and the MCP tools against the application itself, served on the loopback.""" + + def setUp(self): + super().setUp() + log = logging.getLogger("werkzeug"); level = log.level + log.setLevel(logging.ERROR); self.addCleanup(log.setLevel, level) # one line a request otherwise + self.httpd = make_server("127.0.0.1", 0, web.app, threaded=True) + threading.Thread(target=self.httpd.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True).start() + self.addCleanup(self.httpd.server_close); self.addCleanup(self.httpd.shutdown) + self.url = f"http://127.0.0.1:{self.httpd.server_port}" + self.nx = client.Client(self.url, self.reader) + + def test_the_client_reads_what_the_routes_answer(self): + self.assertEqual(self.nx.info()["token"]["scope"], "read") + jobs = self.nx.jobs() + self.assertEqual(jobs, self.get("/jobs").json) + job = self.nx.job("oracle-a") + self.assertEqual(job, self.get("/jobs/oracle-a").json) + trial = job["trials"][0]["trial_name"] + self.assertEqual(self.nx.trial("oracle-a", trial)["trial"]["trial_name"], trial) + self.assertEqual(json.loads(self.nx.artifact("oracle-a", trial, "result")["text"])["trial_name"], trial) + self.assertEqual(self.nx.compare("oracle-a", "oracle-b", matched=True), self.get("/compare?job=oracle-a&job=oracle-b&matched=1").json) + self.assertEqual([b["key"] for b in self.nx.catalogue()["benchmarks"]], [b["key"] for b in self.get("/catalogue").json["benchmarks"]]) + + def test_the_client_s_refusals_are_the_server_s(self): + for call, status, said in ((lambda: self.nx.job("nope"), 404, "no job 'nope' in this workspace"), + (lambda: self.nx.check(gsm8k()), 403, "This token's scope is read: this needs run."), + (lambda: client.Client(self.url, "not-a-token").jobs(), 401, None)): + with self.assertRaises(client.ApiError) as c: + call() + self.assertEqual(c.exception.status, status) + if said: + self.assertEqual(str(c.exception), said) + + def test_a_recipe_is_checked_started_followed_and_read_back(self): + runs = Runs("test_a_run_is_followed_listed_and_stopped_by_its_id") + runs.stack, runs.adopted = self.stack, [] + recipe = Runs.scripted(runs, "echo one; echo two") + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda started: None)) + self.stack.enter_context(patch.object(execution, "docker_here", lambda sh, needs="", program="docker": None)) + nx = client.Client(self.url, self.runner) + nx.save_recipe(dict(recipe, title="Nightly")) + self.assertEqual((nx.check("Nightly")["ready"], nx.check("Nightly")["confirm"]), (True, "")) + run = nx.start("Nightly")["runs"][0] + lines = list(nx.follow(run["id"], every=0.05)) + self.assertEqual([l for l in lines if l in ("one", "two")], ["one", "two"]) + ended = nx.wait(run["id"], every=0.05, timeout=10) + self.assertEqual((ended["state"], ended["job_ids"]), ("done", [run["name"]])) + self.assertEqual([r["id"] for r in nx.runs()], [run["id"]]) + + def test_the_command_and_the_mcp_tools_ask_the_same_server(self): + out = io.StringIO() + with patch.dict(os.environ, {"NULLIUS_SERVER": self.url, "NULLIUS_TOKEN": self.reader}), contextlib.redirect_stdout(out): + self.assertEqual(cli.main(["remote", "job", "oracle-a"]), 0) + self.assertEqual(json.loads(out.getvalue()), self.get("/jobs/oracle-a").json) + call = lambda name, args: mcp_server.handle({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}}, self.nx)["result"] + got = call("get_job", {"job_id": "oracle-a"}) + self.assertEqual((got["isError"], json.loads(got["content"][0]["text"])), (False, self.get("/jobs/oracle-a").json)) + refused = call("start_run", {"recipe": gsm8k(), "confirm": True}) # a read token starts nothing, by any door + self.assertEqual((refused["isError"], json.loads(refused["content"][0]["text"])["error"]), (True, "This token's scope is read: this needs run.")) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/ui_tests/test_every_route.py b/app/ui_tests/test_every_route.py index 198a3c6c..86173a98 100644 --- a/app/ui_tests/test_every_route.py +++ b/app/ui_tests/test_every_route.py @@ -27,7 +27,7 @@ from pathlib import Path from unittest.mock import patch -from nullius import workspace +from nullius import access, workspace from nullius.catalogue import catalog, harbor_entry from nullius.traces import trace as trace_mod from nullius.traces.spans import all_spans @@ -50,8 +50,14 @@ "/job//live": "driven under the live-board workflow with a job carrying a feed", "/launch//ask": "driven under the Launches page workflow with a run record (test_run_routes.LaunchesPage)", "/launch//open": "driven under the Launches page workflow with a run record (test_run_routes.LaunchesPage)", + "/api/v1/jobs//trials//trace": "driven with a trial that kept a trace (test_api.Reads)", + "/api/v1/jobs//trials//judgement": "driven with a trial a judge was asked about (test_api.Judgements)", } +# The API's routes take a token (web/api.py): asked with one here, of the read scope. Without one, test_api.Tokens. +API = "/api/v1" +API_TOKEN = "the-every-route-token" + # Rules that answer 404 without a query argument by design - the argument names # a record inside the trial, not a page - so they are asked with a real one. NEEDS_SPAN = ("/trial///trace-span",) @@ -62,7 +68,8 @@ # builder's agent grid answers 404 without the benchmark it draws. HARBOR_QUERY = {"/new-run/harbor/refs": "repo=example/harbor", "/new-run/harbor/agents": "kind=release&version=0.24.0", - "/new-run/agents": "benchmark=gsm8k"} + "/new-run/agents": "benchmark=gsm8k", + "/api/v1/compare": "job=oracle-a&job=oracle-b"} NO_GIT = "/nonexistent/nullius-route-test/git" @@ -89,6 +96,7 @@ def setUpClass(cls): cls.stack.enter_context(patch.dict(os.environ)) os.environ.pop("TYPESAFE_API_KEY", None) cls.stack.enter_context(patch.object(urllib.request, "urlopen", offline)) + cls.stack.enter_context(patch.object(access, "verify", lambda token: {"id": "t", "name": "t", "scope": "read"} if token == API_TOKEN else None)) if gitrefs is not None: cls.stack.enter_context(patch.object(gitrefs, "GIT", NO_GIT)) roots = [str(cls.jobs_root)] @@ -131,7 +139,7 @@ def a_span_id(job) -> str: return "" def get(self, url): - resp = self.client.get(url) + resp = self.client.get(url, headers={"Authorization": f"Bearer {API_TOKEN}"} if url.startswith(API) else {}) self.addCleanup(resp.close) return resp diff --git a/app/web/api.py b/app/web/api.py new file mode 100644 index 00000000..9413401a --- /dev/null +++ b/app/web/api.py @@ -0,0 +1,481 @@ +"""The HTTP API, ``/api/v1``: what the pages read and the builder runs, for a +program on another machine (``nullius.client``, ``docs/api.md``). + +Every route takes a token (``nullius.access``) in ``Authorization: Bearer``, +never a cookie or a query argument: a page in a browser cannot send one, so +these routes take neither the form token nor the loopback rule, and the +served-name rule (``shared._served_name``) leaves them to their token. +``read`` reads; ``run`` also checks, starts, continues and stops runs, saves +recipes and asks a judge. Nothing here reads or writes Settings, a key or a licence. + +A read answers the document its command prints with ``--json`` +(``nullius.runs.cli``, ``nullius.compare.cli``, ``nullius.workspace_cli``). +A run is a recipe of the Nullius standard, started as Review starts it: +compiled on the server, its prerequisites asked first, the question Review +asks answered by ``confirm``. A Harbor recipe is started from the builder. +An error is ``{"error": "..."}`` with its status. +""" +from __future__ import annotations + +import contextvars +import functools +import importlib.metadata +import json +import os +import time + +from flask import Response, g, request +from werkzeug.exceptions import HTTPException + +from nullius import access, execution, providers +from nullius.catalogue import catalog +from nullius.compare import cli as compare_cli, comparison +from nullius.judge import client as judge_client, store as judge_store +from nullius.recipes import store as recipe_store +from nullius.redact import redact +from nullius.runs import artifacts, cli as runs_cli +from nullius.standard.contract import definitions, match +from nullius.standard.pages import recipe as standard_recipe +from nullius import workspace, workspace_cli + +from .core import app +from . import builder, execute, judge, runs, shared, traces + +PREFIX = "/api/v1" +STANDARD_ONLY = "Only a recipe of the Nullius standard runs over the API: start a Harbor recipe from the builder." + + +def _json(doc, status: int = 200) -> Response: + """One JSON document, timestamps in ISO 8601 as the commands print them.""" + response = Response(json.dumps(doc, ensure_ascii=False, default=runs_cli._stamp) + "\n", status=status, mimetype="application/json") + response.headers["Cache-Control"] = "no-store" + return response + + +def _error(status: int, message: str, **more) -> Response: + return _json({"error": message, **more}, status) + + +def api(scope: str): + """A route of the API: its token checked for ``scope``, its refusals in JSON.""" + def wrap(view): + @functools.wraps(view) + def guarded(*args, **kwargs): + kind, _, sent = request.headers.get("Authorization", "").partition(" ") + record = access.verify(sent.strip()) if kind.lower() == "bearer" else None + if record is None: + response = _error(401, "This API takes a token: Authorization: Bearer (nullius access create NAME, on the server).") + response.headers["WWW-Authenticate"] = "Bearer" + return response + if not access.allows(record, scope): + return _error(403, f"This token's scope is {record['scope']}: this needs {scope}.") + g.api_token = record + try: + return view(*args, **kwargs) + except HTTPException as e: + return _error(e.code or 500, e.description or e.name) + return guarded + return wrap + + +class _Refused(HTTPException): + """A refusal with its status, said in JSON by ``api``.""" + + def __init__(self, code: int, description: str): + super().__init__(description) + self.code = code + + +@app.errorhandler(405) +def _wrong_method(e): + """Refused in JSON under the API; a page's stays the page's. A 404 and a 500 are the error page's (web/filters.py).""" + return _error(405, e.description) if request.path.startswith(PREFIX) else e + + +def _body() -> dict: + """The request's JSON object, {} when nothing was sent. One that cannot be read is refused: a default read in its + place could ask another judge, or start another run, than the one it names.""" + if not request.get_data(): + return {} + try: + got = request.get_json(force=True, silent=True) + except RecursionError: + got = None + if not isinstance(got, dict): + raise _Refused(400, "The request's body is one JSON object.") + return got + + +@app.route(PREFIX) +@api("read") +def api_info(): + """Who is asking, and where a run can go.""" + try: + version = importlib.metadata.version("nullius-eval") + except importlib.metadata.PackageNotFoundError: + version = "source checkout" + ws = shared.STATE["workspace"] + return _json({"api": 1, "version": version, "token": access.shown(g.api_token), "workspace": ws.name if ws else None, + "where": ["local", *(h.entry for h in execute._hosts())]}) + + +@app.route(PREFIX + "/catalogue") +@api("read") +def api_catalogue(): + """The benchmarks with the runners that can run each, the agents and the capabilities; a standard benchmark with + its datasets and what fits it, by the reference a recipe names it with.""" + defs = {kind: definitions.load(kind)[0] for kind in definitions.KINDS} + fits = match.table(defs["benchmark"], defs["agent"], defs["capability"]) + standard = {b["key"]: b for b in defs["benchmark"]} + benchmarks = [] + for b in catalog.load().listed_benchmarks: + row = {"key": b.key, "title": b.title, "runners": [r.harness for r in b.usable_routes]} + s = standard.get(b.key) + if s: + row.update(family=s["family"], needs=s.get("needs") or [], + datasets=[{"id": d["id"], "label": d.get("label"), "units": d.get("units")} for d in s["datasets"]], + fits=[ref for ref, why in fits.get(b.key, {}).items() if not why]) + benchmarks.append(row) + others = {kind: [{"key": d["key"], "ref": d.get("_ref") or d["key"], "label": d.get("label"), "summary": d.get("summary"), + "offers": d.get("offers") or []} for d in defs[kind]] for kind in ("agent", "capability")} + return _json({"benchmarks": benchmarks, "agents": others["agent"], "capabilities": others["capability"]}) + + +@app.route(PREFIX + "/workspaces") +@api("read") +def api_workspaces(): + return _json([workspace_cli.row(ws) for ws in workspace.list_all(shared.WS_HOME)]) + + +# Jobs and trials are the open workspace's, or ?workspace='s, as on the pages. + +@app.route(PREFIX + "/jobs") +@api("read") +def api_jobs(): + return _json([runs_cli.job_row(j) for j in shared._jobs_for_request()]) + + +def _job(job_id): + job = shared._job_for_request(job_id) + if job is None: + raise _Refused(404, f"no job {job_id!r} in this workspace") + return job + + +@app.route(PREFIX + "/jobs/") +@api("read") +def api_job(job_id): + return _json(runs_cli.job_detail(_job(job_id))) + + +@app.route(PREFIX + "/jobs//live") +@api("read") +def api_job_live(job_id): + """The live board's snapshot, as the job page polls it.""" + return runs.job_live(job_id) + + +def _trial(job_id, trial_name, tries=True): + """``tries``: an attempt's earlier try too, evidence to read and never a trial to judge, as on the pages.""" + job = _job(job_id) + trial = traces._find_trial(job, trial_name) or (traces._find_try(job, trial_name) if tries else None) + if trial is None: + raise _Refused(404, f"no trial {trial_name!r} in job {job_id!r}") + return job, trial + + +@app.route(PREFIX + "/jobs//trials/") +@api("read") +def api_trial(job_id, trial_name): + return _json(runs_cli.trial_detail(*_trial(job_id, trial_name))) + + +@app.route(PREFIX + "/jobs//trials//conversation") +@api("read") +def api_conversation(job_id, trial_name): + """The trial page's conversation browser: paged, with its ``q``, ``kind``, ``page`` and ``step``.""" + return traces.conversation_data(job_id, trial_name) + + +@app.route(PREFIX + "/jobs//trials//trace") +@api("read") +def api_trace(job_id, trial_name): + """The trial's trace document, each of its strings redacted. Read as a declared record is, no link followed: a + trial's files are the agent's, and a link could lead anywhere on the server.""" + _, trial = _trial(job_id, trial_name) + try: + fd = artifacts._open_under(trial.dir, os.path.relpath(trial.trace_path, trial.dir), os.O_RDONLY | os.O_NONBLOCK) + with open(fd, encoding="utf-8", errors="replace") as fh: + raw = fh.read(artifacts.MAX_READ + 1) + if len(raw) > artifacts.MAX_READ: + return _error(413, "The trace is larger than the reader's limit: read it on the server.") + doc = json.loads(raw) + if not isinstance(doc, dict): + raise ValueError("not a trace") + return _json(_redacted(doc)) + except (OSError, ValueError, RecursionError): + raise _Refused(404, f"trial {trial_name!r} has no trace that can be read") from None + + +def _redacted(value, name: str = ""): + """A JSON value with its strings redacted, each as the value of the name it is under: the JSON stays JSON.""" + if isinstance(value, dict): + return {redact(k): _redacted(v, k) for k, v in value.items()} + if isinstance(value, list): + return [_redacted(v, name) for v in value] + if not isinstance(value, str): + return value + under = redact(f"{name}={value}") + return under[len(name) + 1:] if name and under.startswith(f"{name}=") else redact(value) + + +@app.route(PREFIX + "/jobs//trials//artifacts") +@api("read") +def api_artifacts(job_id, trial_name): + _, trial = _trial(job_id, trial_name) + return _json([{k: r[k] for k in ("key", "label", "filename", "size")} + for r in artifacts.listing(trial.dir, artifacts.declared(trial.source)) if r["exists"]]) + + +@app.route(PREFIX + "/jobs//trials//artifacts/") +@api("read") +def api_artifact(job_id, trial_name, key): + """One record whole, redacted, up to the reader's limit.""" + _, trial = _trial(job_id, trial_name) + try: + declared = artifacts.declared(trial.source) + text, truncated = artifacts.whole(trial.dir, key, declared) + except (LookupError, OSError): + raise _Refused(404, f"trial {trial_name!r} has no record {key!r}") + return _json({"key": key, "filename": artifacts.describe(key, declared)[1], "truncated": truncated, "text": text}) + + +@app.route(PREFIX + "/compare") +@api("read") +def api_compare(): + """``?job=a&job=b[&matched=1]``: the comparison ``nullius compare --json`` prints.""" + ids = list(dict.fromkeys(request.args.getlist("job"))) + if len(ids) < 2: + return _error(400, "Two different job ids are needed to compare: ?job=A&job=B.") + try: + selected = comparison.resolve([comparison.RunRef("", i).value for i in ids], {"": shared._jobs_for_request()}) + except ValueError as e: + return _error(404, str(e)) + return _json(compare_cli.document(comparison.build(selected, "matched" if request.args.get("matched") in ("1", "true") else "whole"))) + + +# Judgements: a judge model's answers about a trial, kept in the job's workspace (web/judge.py). Reading one is +# free; asking is a paid model call for each trial, so it takes the run scope, and several trials at once take a yes. + +def _lane(value) -> str: + lane = "decision" if value is None else value + if lane not in judge_client.LANES: + raise _Refused(400, f"A judge is one of: {', '.join(judge_client.LANES)}.") + return lane + + +def _judgements_dir() -> str: + d = judge.ws_dir() + if d is None: + raise _Refused(400, "No workspace is open: judgements are kept in the workspace.") + return d + + +def _judge_error(e: judge_client.JudgeError) -> Response: + return _error(400 if e.status in (401, 422) else 502, str(e)) + + +@app.route(PREFIX + "/jobs//judgements") +@api("read") +def api_judgements(job_id): + """``?lane=decision|llm``: {judged, trials, records: {trial: record}} for one job and one judge.""" + job, lane = _job(job_id), _lane(request.args.get("lane")) + judged = judge_store.for_job(_judgements_dir(), job.job_id, judge.started_by_name(job), lane=lane) + return _json({"lane": lane, "judged": len(judged), "trials": len(job.trials), "records": judged}) + + +@app.route(PREFIX + "/jobs//trials//judgement") +@api("read") +def api_judgement(job_id, trial_name): + job, trial = _trial(job_id, trial_name) + _judgements_dir() + lane = _lane(request.args.get("lane")) + record = judge.judgement_of(job, trial, lane) + if record is None: + raise _Refused(404, f"trial {trial_name!r} has no {lane} judgement") + return _json(record) + + +@app.route(PREFIX + "/jobs//trials//judge", methods=["POST"]) +@api("run") +def api_judge_trial(job_id, trial_name): + """Ask a judge about one trial, ``{"lane"?}``: the record as stored.""" + job, trial = _trial(job_id, trial_name, tries=False) + _judgements_dir() + try: + return _json(judge.judge_trial(job, trial, judge.key(_lane(_body().get("lane", request.args.get("lane")))))) + except judge_client.JudgeError as e: + return _judge_error(e) + + +@app.route(PREFIX + "/jobs//judge", methods=["POST"]) +@api("run") +def api_judge_job(job_id): + """Ask a judge about every trial of a job it has not judged, ``{"lane"?, "confirm"?}``: {todo, judged, failed}. + Each trial is a paid call: without ``confirm`` it answers how many it would ask, and asks none.""" + job, body = _job(job_id), _body() + lane = _lane(body.get("lane", request.args.get("lane"))) + judged = judge_store.for_job(_judgements_dir(), job.job_id, judge.started_by_name(job), lane=lane) + todo = [t for t in job.trials if t.has_trajectory and t.trial_name not in judged] + if todo and body.get("confirm") is not True: + return _error(409, f"This asks the judge about {len(todo)} trial(s), a paid call each. Send \"confirm\": true to ask.", todo=len(todo)) + k, cal = judge.key(lane), judge.batch_calibration() + here = {t.trial_name: contextvars.copy_context() for t in todo} # the batch's threads keep this request's ?workspace= + done, failed = judge.run_batch(todo, lambda t: here[t.trial_name].run(judge.judge_trial, job, t, k, calibration=cal), lambda t: t.trial_name) + return _json({"lane": lane, "todo": len(todo), "judged": done, "failed": failed}) + + +# Saved recipes, as the builder keeps them. + +@app.route(PREFIX + "/recipes") +@api("read") +def api_recipes(): + return _json(recipe_store.listing()) + + +def _saved(recipe_id: str) -> dict: + """A saved recipe by its id, or by its name.""" + item = next((x for x in recipe_store.listing() if recipe_id in (x["id"], x["name"])), None) + if item is None: + raise _Refused(404, f"no saved recipe {recipe_id!r}") + return item + + +@app.route(PREFIX + "/recipes/") +@api("read") +def api_recipe(recipe_id): + return _json(_saved(recipe_id)) + + +@app.route(PREFIX + "/recipes", methods=["POST"]) +@api("run") +def api_recipe_save(): + body = _body() + try: + return _json(recipe_store.save(body.get("recipe"), body.get("id") or None)) + except ValueError as e: + return _error(400, str(e)) + + +# Runs: checked and started as Review does it. + +def _recipe_of(body: dict) -> dict: + """The recipe a request names: inline, or a saved one by id or name; its *Where* replaced when the request says. + Named as its run is, so a check refuses what the start would.""" + recipe = body.get("recipe") + if isinstance(recipe, str): + recipe = _saved(recipe)["recipe"] + if not isinstance(recipe, dict): + raise _Refused(400, "A run takes a recipe: {\"recipe\": {...}}, or a saved recipe's id or name.") + if body.get("where"): # blank is not a machine: the recipe's own stay + recipe = {**recipe, "where": body["where"]} + name = str(body.get("name") or "").strip() or f"{recipe.get('name') or ''}-{time.strftime('%m%d-%H%M%S')}" + return {**recipe, "name": name} + + +def _compiled(recipe: dict) -> tuple: + """(what Run posts, the check's document without its machines) for one recipe of the standard. A Harbor + recipe is compiled by the builder's page, not here: it is started from the builder.""" + if recipe.get("harness") != standard_recipe.HARNESS: + raise _Refused(400, STANDARD_ONLY) + out = builder._standard_compile(recipe) + post = {"name": recipe.get("name"), "where": recipe.get("where"), "recipe": recipe} + return post, {"errors": [e["message"] for e in out["errors"]], "notes": out["notes"], "review": out["review"], + "jobs": out["jobs"], "confirm": out["confirm"] or ""} + + +def _checked(recipe: dict) -> tuple: + """(what Run posts, the whole check): the compile, then what each machine has when the recipe compiles.""" + post, doc = _compiled(recipe) + 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 + doc["errors"].append(missing) + if not doc["errors"]: + choice = providers.choice(str(provider or ""), str(endpoint or "")) + machines = builder.prerequisites_of({"recipe": recipe, "provider": choice}).get_json() + doc["errors"] += machines.get("errors") or [] + doc["notes"] += machines.get("notes") or [] + doc.update(machines=machines["machines"], ready=bool(machines.get("ready")) and not doc["errors"]) + return post, doc + + +@app.route(PREFIX + "/runs/check", methods=["POST"]) +@api("run") +def api_run_check(): + """What Review shows before Run: {ready, errors, notes, review, jobs, confirm, machines}. Starts nothing.""" + return _json(_checked(_recipe_of(_body()))[1]) + + +@app.route(PREFIX + "/runs", methods=["POST"]) +@api("run") +def api_run_start(): + """Start a recipe: ``{"recipe": {...} | "", "where"?, "name"?, "confirm"?}``. A new run each + time, named by the recipe's name and the second unless ``name`` says; refused with what Review would show + when the recipe does not compile, a machine lacks a prerequisite, or its question is not answered.""" + body = _body() + post, doc = _checked(_recipe_of(body)) + if doc["errors"]: + return _error(400, " ".join(doc["errors"]), **doc) + if not doc["ready"]: + return _error(409, "A machine lacks what this recipe needs: see machines.", **doc) + if doc["confirm"] and body.get("confirm") is not True: + return _error(409, doc["confirm"] + " Send \"confirm\": true to start it.", **doc) + started = execute.start(post) + out = started[0].get_json() if isinstance(started, tuple) else started.get_json() + status = started[1] if isinstance(started, tuple) else 200 + if not out.get("ok"): + return _error(status, out.get("error") or "The run did not start.") + out.pop("open", None) # a page's address + out.setdefault("runs", [{k: v for k, v in out.items() if k != "ok"}]) + return _json(out) + + +@app.route(PREFIX + "/runs") +@api("read") +def api_runs(): + """The runs this server follows or kept a record of, the latest started first.""" + return _json(sorted((ex.summary() for ex in list(execution.EXECUTIONS.values())), key=lambda s: s.get("started") or 0, reverse=True)) + + +def _run(run_id): + ex = execution.EXECUTIONS.get(run_id) + if ex is None: + raise _Refused(404, f"no run {run_id!r}") + return ex + + +@app.route(PREFIX + "/runs/") +@api("read") +def api_run(run_id): + """State, stages and the log lines from ``since`` on.""" + ex = _run(run_id) + return _json({**ex.summary(), "log": ex.tail(request.args.get("since", type=int) or 0)}) + + +@app.route(PREFIX + "/runs//stop", methods=["POST"]) +@api("run") +def api_run_stop(run_id): + ex = _run(run_id) + ex.stop() + return _json(ex.summary()) + + +@app.route(PREFIX + "/runs//continue", methods=["POST"]) +@api("run") +def api_run_continue(run_id): + ex = _run(run_id) + ex.continue_() + return _json(ex.summary()) diff --git a/app/web/builder.py b/app/web/builder.py index e1404d5f..953603b4 100644 --- a/app/web/builder.py +++ b/app/web/builder.py @@ -240,7 +240,11 @@ def new_run_prerequisites(): shared._require_csrf() if not shared._local_client(): abort(403, description="Machines are checked from a browser on the application host only.") - body = request.get_json(silent=True) or {} + return prerequisites_of(request.get_json(silent=True) or {}) + + +def prerequisites_of(body: dict): + """``new_run_prerequisites`` past its guards, for the page and the API (``web/api.py``).""" recipe = body.get("recipe") if isinstance(body.get("recipe"), dict) else {} if len(json.dumps(recipe)) > 200_000: abort(413) diff --git a/app/web/execute.py b/app/web/execute.py index 7cc557df..0ac77cb0 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -24,7 +24,12 @@ def run_start(): shared._require_csrf() if not shared._local_client(): abort(403, description="Runs are started from a browser on the application host only.") - body = request.get_json(silent=True) or {} + return start(request.get_json(silent=True) or {}) + + +def start(body: dict): + """``run_start`` past its guards: what the page posts, and what the API + posts once its token is checked (``web/api.py``).""" recipe = body.get("recipe") if isinstance(body.get("recipe"), dict) else {} if recipe.get("harness") == standard_recipe.HARNESS: return _start_standard(recipe) diff --git a/app/web/filters.py b/app/web/filters.py index 5e579e0c..6fd67f13 100644 --- a/app/web/filters.py +++ b/app/web/filters.py @@ -5,7 +5,7 @@ import re from pathlib import Path -from flask import g, render_template, url_for +from flask import g, jsonify, render_template, request, url_for from nullius import importers as harnesses, providers from nullius.judge import client as judge_client @@ -238,6 +238,8 @@ def _inject(): def _error_page(title, status): + if request.path.startswith("/api/v1"): # a program reads JSON (web/api.py) + return jsonify(error=title), status g.error_page = True # an unknown ?workspace= may be what failed: the page does not read it again return render_template("error.html", title=title), status diff --git a/app/web/settings.py b/app/web/settings.py index 656df7ce..4f3a9811 100644 --- a/app/web/settings.py +++ b/app/web/settings.py @@ -6,7 +6,7 @@ import shutil import socket from flask import abort, flash, jsonify, redirect, render_template, request, url_for -from nullius import constraints, execution, hosts, paths, prerequisites, prices, providers, sandbox, secrets, settings +from nullius import access, constraints, execution, hosts, paths, prerequisites, prices, providers, sandbox, secrets, settings from nullius.standard.backends import boat, container from nullius.standard.pages import recipe as standard_recipe from nullius.judge import client @@ -44,7 +44,7 @@ def settings_page(): ("Cache", paths.cache_dir())], unread=[dict(u, inherited=u["name"] not in withheld, startup=u["instead"] in settings.STARTUP) for u in settings.unread(shared.ENV_FILE)], - prices=prices.state(), + prices=prices.state(), api_tokens=_api_tokens(), machines=_machines(), constraint_table=constraints.TABLE, provider_cards=provider_cards({r["name"]: r for r in rows}), ssh_hosts=hosts.scan_ssh_config(), judges=(client.decision_judge(os.environ), client.llm_judge(os.environ)), llm_providers=client.llm_providers(os.environ), decision_providers=client.decision_judge_providers(os.environ), @@ -341,6 +341,39 @@ def settings_sandbox_logout(): return jsonify(got), (200 if got["ok"] else 502) +def _api_tokens() -> list: + return [access.shown(r) for r in access.listing()] + + +@app.route("/settings/api/create", methods=["POST"]) +def settings_api_create(): + """A new token of the HTTP API (``nullius.access``): its value is in this answer and nowhere after it. Same guards as Save.""" + _sandbox_guard("Tokens are created") + f = request.form + try: + days = f.get("days", "") + if days and not days.isdigit(): + raise ValueError(f"a token expires after 1 to {access.MAX_DAYS} days, or never") + value, record = access.create(f.get("name", "").strip(), f.get("scope", "read"), int(days) if days else None) + except ValueError as e: + return jsonify(ok=False, error=str(e)[:1].upper() + str(e)[1:] + "."), 400 + response = jsonify(ok=True, value=value, token=access.shown(record), tokens=_api_tokens()) + response.headers["Cache-Control"] = "no-store" + return response + + +@app.route("/settings/api/revoke", methods=["POST"]) +def settings_api_revoke(): + _sandbox_guard("Tokens are revoked") + try: + gone = access.revoke(request.form.get("id", "")) + except ValueError as e: + return jsonify(ok=False, error=str(e)[:1].upper() + str(e)[1:] + "."), 400 + if not gone: + return jsonify(ok=False, error="That token is gone already."), 404 + return jsonify(ok=True, tokens=_api_tokens()) + + @app.route("/settings/prices/update", methods=["POST"]) def settings_prices_update(): """The public price list fetched and kept (``nullius.prices``): the one diff --git a/app/web/shared.py b/app/web/shared.py index a47855ad..3bb306c0 100644 --- a/app/web/shared.py +++ b/app/web/shared.py @@ -56,7 +56,8 @@ def _served_name(name: str) -> bool: @app.before_request def _refuse_foreign_host(): - if not _served_name(_host_name(request.host)): + # the API's routes take a token no page can send (web/api.py): a client names the server as it reaches it + if not _served_name(_host_name(request.host)) and not request.path.startswith("/api/v1"): abort(421, description="This server answers on its own address only (localhost, an IP address or its --host name).") diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 00000000..091026ca --- /dev/null +++ b/docs/api.md @@ -0,0 +1,149 @@ +# From another machine + +Nullius serves on one machine; a script, a pipeline or an assistant on another reads its results and runs its recipes over HTTP. + +| Piece | For | +| --- | --- | +| [Token](#tokens) | What the server accepts | +| [Python client](#python) | Scripts, notebooks, pipelines | +| [`nullius remote`](#shell) | A shell | +| [`nullius mcp`](#assistants) | An assistant | +| [Routes](#routes) | Any other language | + +## Serve + +```bash title="On the server" +nullius serve --host 0.0.0.0 +``` + +Then create a token: **Settings → API access**, or `nullius access create`. + +!!! warning "The network" + The pages have no login: `--host` on a shared network shows them to it. Tokens travel in clear over `http`. Put the server behind a tunnel or a TLS proxy. + +## Tokens + +**Settings → API access**, from a browser on the server: a name, its access, when it expires. Or: + +```bash title="On the server" +nullius access create NAME [--scope read|run] [--days N] +nullius access list +nullius access revoke ID +``` + +| Access | Allows | +| --- | --- | +| Read, `read` (default) | Catalogue, jobs, trials, judgements, comparisons, saved recipes, runs | +| Read and run, `run` | Read, and check, start, continue and stop runs, ask a judge, save recipes | + +- Shown once, at creation. The server keeps its hash. +- Expires after its days, or never. Revoked or expired: refused at once. +- No token created: the API answers nothing. +- No scope reads or changes Settings, keys or licences. Model keys stay on the server. + +## Python + +One file, standard library only: installed with Nullius, or `nullius/client.py` copied alone. + +```python title="Run a saved recipe, read the result" +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's name or id, or a recipe 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"] +``` + +| Call | Gives | +| --- | --- | +| `info()`, `catalogue()`, `workspaces()` | The server, what it can run, its workspaces | +| `jobs()`, `job(id)`, `live(id)` | As `nullius runs list` and `show --json`; the live board | +| `trial(job, trial)`, `conversation(...)`, `trace(...)`, `artifacts(...)`, `artifact(..., key)` | One trial and its evidence, redacted as on the pages | +| `compare(a, b, ..., matched=False)` | As `nullius compare --json` | +| `judgements(job)`, `judgement(job, trial)` | A judge's stored answers; `lane="llm"` for the LLM judge | +| `judge(job, trial)`, `judge_job(job, confirm=False)` | Ask a judge: [below](#asking-a-judge) | +| `recipes()`, `recipe(id_or_name)`, `save_recipe(recipe)` | The builder's saved recipes | +| `check(recipe, where=None)` | What Review shows: `ready`, `errors`, `confirm`, `machines` | +| `start(recipe, where=None, name=None, confirm=False)` | `runs`: one per machine | +| `runs()`, `run(id, since=0)`, `follow(id)`, `wait(id)` | State, stages, log | +| `stop(id)`, `continue_(id)` | Stop; answer a paused run | + +A refusal raises `ApiError`: the server's sentence, `status`, `document`. A redirect is refused: give the final address. + +## Starting a run + +A run starts as Review starts it. + +| Refused | Until | +| --- | --- | +| The recipe has errors (400) | Fixed: `errors` names them | +| A machine lacks a prerequisite (409) | Met: `machines` lists each | +| The recipe asks a question (409), such as the whole dataset | `confirm=True` | + +- Build a recipe in the [run builder](builder.md), save it, start it by name. +- Each start is a new run: the recipe's name and the second, or `name`. +- `where` replaces the recipe's machines: `local`, or a host of Settings. +- Standard recipes only. A Harbor recipe starts from the builder. + +## Asking a judge + +Every trial asked is a paid model call, on the judge set in Settings. + +| Call | Asks | +| --- | --- | +| `judge(job, trial, lane="decision")` | That trial | +| `judge_job(job, lane="decision")` | Nothing: refused (409) with `todo`, how many it would ask; nothing left, it answers so | +| `judge_job(job, confirm=True)` | Every trial of the job with a trajectory that judge has not judged | + +Records are kept in the job's workspace, as the [pages](judgement.md) keep them. + +## Shell + +```bash title="On the other machine" +export NULLIUS_SERVER=http://bench.internal:5057 NULLIUS_TOKEN=... +nullius remote jobs +nullius remote job JOB [TRIAL] +nullius remote compare JOB JOB [--matched] +nullius remote judgements JOB [--lane llm] +nullius remote judge JOB [TRIAL] [--lane llm] [--yes] +nullius remote check RECIPE +nullius remote run RECIPE [--where W] [--name N] [--yes] [--follow] +nullius remote status RUN +nullius remote stop RUN +``` + +`RECIPE`: a recipe file, or a saved recipe's name or id. One JSON document on stdout. Exit 3 not found, 4 refused or unreachable; `run --follow` exits 4 unless the run ends `done`. + +## Assistants + +```bash title="An MCP server over stdio" +NULLIUS_SERVER=http://bench.internal:5057 NULLIUS_TOKEN=... nullius mcp +``` + +Tools: read jobs, trials, judgements and comparisons; check, start, follow and stop runs; ask a judge about one trial. A `read` token makes it read-only. `start_run` starts only with `confirm` when the recipe asks a question. + +## Routes + +`Authorization: Bearer ` on every request, under `/api/v1`. Errors are `{"error": "..."}`. + +| Route | Scope | +| --- | --- | +| `GET /api/v1` | read | +| `GET /catalogue`, `/workspaces` | read | +| `GET /jobs`, `/jobs/`, `/jobs//live` | read | +| `GET /jobs//trials/`, `…/conversation`, `…/trace`, `…/artifacts`, `…/artifacts/` | read | +| `GET /jobs//judgements`, `/jobs//trials//judgement` (`?lane=decision\|llm`) | read | +| `GET /compare?job=A&job=B[&matched=1]` | read | +| `GET /recipes`, `/recipes/` | read | +| `GET /runs`, `/runs/[?since=N]` | read | +| `POST /recipes` | run | +| `POST /runs/check`, `/runs` | run | +| `POST /runs//stop`, `/runs//continue` | run | +| `POST /jobs//trials//judge`, `/jobs//judge` | run | + +Jobs are the open workspace's; `?workspace=NAME` reads another. diff --git a/docs/cli/README.md b/docs/cli/README.md index 533fd34c..1771e3e9 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -23,6 +23,7 @@ From a source checkout, replace `nullius` with | [Model prices](../settings/model-prices.md) | `nullius prices [list\|update\|set\|remove]` | | [Migration](../getting-started.md#migrate-an-existing-checkout) | `nullius migrate --from CHECKOUT [--secrets PATH] [--apply]` | | [Provider records](../settings/model-providers.md#older-settings) | `nullius migrate --providers [--apply]` | +| [From another machine](../api.md) | `nullius access`, `nullius remote`, `nullius mcp` | | [Pages from a shell](pages.md) | | | [Exit codes and output](exit-codes.md) | | diff --git a/docs/cli/exit-codes.md b/docs/cli/exit-codes.md index c3762671..c7125aee 100644 --- a/docs/cli/exit-codes.md +++ b/docs/cli/exit-codes.md @@ -25,6 +25,7 @@ A refusal is one line on stderr, nothing partial written; the standard's command | Job id | The job directory's name, everywhere | | Secrets | Read commands make no model call and never print credentials. Job content is redacted | | Writes | Reads write nothing, open no socket; import under `-o`; the standard its jobs, and a user definition on `new`, `prove`, `conform`, `fidelity`; migration writes only with `--apply`; `flags` writes only the job's `failure-analysis.json` | +| Paid actions | `nullius remote judge JOB TRIAL` asks one trial; a whole job needs `--yes` |
diff --git a/docs/cli/pages.md b/docs/cli/pages.md index 7caed9c2..e9c9f7d6 100644 --- a/docs/cli/pages.md +++ b/docs/cli/pages.md @@ -15,6 +15,7 @@ Each page's command, or why there is none. | `/workspaces/open/` | `nullius serve ...`, `WORKSPACE=` | | `/workspaces` | `nullius workspace list [--home DIR] [--json]` | | `/settings` | User `settings.json`, or the environment; `nullius paths` locates the file | +| Settings, API access | `nullius access create`, `list`, `revoke` | | `/benchmarks` | `nullius standard list` for standard entries; Harbor entries on the page | | `/agents`, `/capabilities` | `nullius standard list` includes agents, capabilities and their proven ports | | A benchmark's *Prove it* | `nullius standard prove KEY` ([Prove](prove.md)) | @@ -32,15 +33,19 @@ Each page's command, or why there is none. | A picture the agent sent its model | `/trial/…/picture/` | | One task side by side | `/compare/task/` | +## From another machine + +`nullius remote` asks a served Nullius for the same reads, and checks, starts and stops its recipes: [From another machine](../api.md). + ## No command yet | Page | What it would be | | --- | --- | | `/trial/…/save-trace` | a `harbor-trace-v1` writer | -| `/judge/…` | `judge.cli job --confirm` | +| `/judge/…` | `judge.cli job --confirm`; today `nullius remote judge` against a served Nullius | | Rename or delete a workspace | `nullius workspace rename`, `nullius workspace delete --yes` | | Unlink a workspace's root, delete its folder | `workspace.forget`, `execution.delete`; today `POST /workspaces//roots/unlink` and `/roots/delete` | -| `/new-run` | `recipes.cli`; today `POST /new-run/runner` | +| `/new-run` | `recipes.cli`; today `POST /new-run/runner`, or `nullius remote check` and `run` against a served Nullius | | Delete a launch | `execution.delete`; today `POST /launch//delete` | | `/launches`, add a launch to a workspace | today `POST /launch//add` | diff --git a/docs/settings/README.md b/docs/settings/README.md index bbe948b3..e058ff54 100644 --- a/docs/settings/README.md +++ b/docs/settings/README.md @@ -13,6 +13,7 @@ Existing results open without credentials. | [Hosts](run-hosts.md) | SSH machines | | [Data providers](data-providers.md) | Hugging Face and Docker Hub connections | | [Sandbox](sandbox.md) | Docker on this machine, the Boat key | +| [API access](../api.md#tokens) | Tokens for scripts and assistants on other machines | | [General](other.md) | Tour and checklist | ## Variables