diff --git a/.agents/skills/find-flawed-tasks/SKILL.md b/.agents/skill-library/evaluation/find-flawed-tasks/SKILL.md similarity index 100% rename from .agents/skills/find-flawed-tasks/SKILL.md rename to .agents/skill-library/evaluation/find-flawed-tasks/SKILL.md diff --git a/.agents/skills/find-flawed-tasks/references/tau3-banking.md b/.agents/skill-library/evaluation/find-flawed-tasks/references/tau3-banking.md similarity index 100% rename from .agents/skills/find-flawed-tasks/references/tau3-banking.md rename to .agents/skill-library/evaluation/find-flawed-tasks/references/tau3-banking.md diff --git a/.agents/skills/find-flawed-tasks/references/where.md b/.agents/skill-library/evaluation/find-flawed-tasks/references/where.md similarity index 100% rename from .agents/skills/find-flawed-tasks/references/where.md rename to .agents/skill-library/evaluation/find-flawed-tasks/references/where.md diff --git a/.agents/skills/find-flawed-tasks/scripts/flags.py b/.agents/skill-library/evaluation/find-flawed-tasks/scripts/flags.py similarity index 99% rename from .agents/skills/find-flawed-tasks/scripts/flags.py rename to .agents/skill-library/evaluation/find-flawed-tasks/scripts/flags.py index e5cf6373e..670419c22 100644 --- a/.agents/skills/find-flawed-tasks/scripts/flags.py +++ b/.agents/skill-library/evaluation/find-flawed-tasks/scripts/flags.py @@ -11,8 +11,9 @@ import re import sys from collections import Counter +from pathlib import Path -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), *[".."] * 4, "app"))) +sys.path.insert(0, str(Path(__file__).resolve().parents[5] / "app")) KINDS = ("flawed", "ambiguous") VERDICTS = KINDS + ("fair", "cannot_tell") diff --git a/.agents/skills/fix-flawed-tasks/SKILL.md b/.agents/skill-library/evaluation/fix-flawed-tasks/SKILL.md similarity index 100% rename from .agents/skills/fix-flawed-tasks/SKILL.md rename to .agents/skill-library/evaluation/fix-flawed-tasks/SKILL.md diff --git a/.agents/skills/fix-flawed-tasks/references/patch.md b/.agents/skill-library/evaluation/fix-flawed-tasks/references/patch.md similarity index 100% rename from .agents/skills/fix-flawed-tasks/references/patch.md rename to .agents/skill-library/evaluation/fix-flawed-tasks/references/patch.md diff --git a/.agents/skills/fix-flawed-tasks/references/tau3-banking.md b/.agents/skill-library/evaluation/fix-flawed-tasks/references/tau3-banking.md similarity index 100% rename from .agents/skills/fix-flawed-tasks/references/tau3-banking.md rename to .agents/skill-library/evaluation/fix-flawed-tasks/references/tau3-banking.md diff --git a/.agents/skills/fix-flawed-tasks/scripts/fix.py b/.agents/skill-library/evaluation/fix-flawed-tasks/scripts/fix.py similarity index 100% rename from .agents/skills/fix-flawed-tasks/scripts/fix.py rename to .agents/skill-library/evaluation/fix-flawed-tasks/scripts/fix.py diff --git a/.agents/skills/label-benchmark/SKILL.md b/.agents/skill-library/evaluation/label-benchmark/SKILL.md similarity index 100% rename from .agents/skills/label-benchmark/SKILL.md rename to .agents/skill-library/evaluation/label-benchmark/SKILL.md diff --git a/.agents/skills/label-benchmark/scripts/decide.py b/.agents/skill-library/evaluation/label-benchmark/scripts/decide.py similarity index 99% rename from .agents/skills/label-benchmark/scripts/decide.py rename to .agents/skill-library/evaluation/label-benchmark/scripts/decide.py index 0097e5e25..7ead2b854 100644 --- a/.agents/skills/label-benchmark/scripts/decide.py +++ b/.agents/skill-library/evaluation/label-benchmark/scripts/decide.py @@ -48,13 +48,14 @@ import http.client import json import os +from pathlib import Path import re import sys import time import urllib.error import urllib.request -HERE = os.path.dirname(os.path.abspath(__file__)) +REPO = Path(__file__).resolve().parents[5] # Fixed: no option, argument or variable changes them. TypeSafe's models, and the others SYSTEMONE names, are asked # on `systemone`; another maker's on `decisions`. Both take the same request and give the same reply. URLS = {"systemone": "https://openrouter.ai/api/v1/systemone", "decisions": "https://openrouter.ai/api/alpha/decisions"} @@ -96,7 +97,7 @@ def redirect_request(self, *args, **kwargs): # a redirect would carry t def definitions(): - with open(os.path.join(HERE, "..", "..", "..", "..", "app", "nullius", "leaderboard", "definitions.json"), encoding="utf-8") as fh: + with open(REPO / "app" / "nullius" / "leaderboard" / "definitions.json", encoding="utf-8") as fh: return json.load(fh) diff --git a/.agents/skills/label-benchmark/scripts/public_ids.py b/.agents/skill-library/evaluation/label-benchmark/scripts/public_ids.py similarity index 100% rename from .agents/skills/label-benchmark/scripts/public_ids.py rename to .agents/skill-library/evaluation/label-benchmark/scripts/public_ids.py diff --git a/.agents/skills/run-analysis/SKILL.md b/.agents/skill-library/evaluation/run-analysis/SKILL.md similarity index 100% rename from .agents/skills/run-analysis/SKILL.md rename to .agents/skill-library/evaluation/run-analysis/SKILL.md diff --git a/.agents/skills/run-analysis/assets/template.html b/.agents/skill-library/evaluation/run-analysis/assets/template.html similarity index 100% rename from .agents/skills/run-analysis/assets/template.html rename to .agents/skill-library/evaluation/run-analysis/assets/template.html diff --git a/.agents/skills/run-analysis/references/files.md b/.agents/skill-library/evaluation/run-analysis/references/files.md similarity index 100% rename from .agents/skills/run-analysis/references/files.md rename to .agents/skill-library/evaluation/run-analysis/references/files.md diff --git a/.agents/skills/run-analysis/references/investigation.md b/.agents/skill-library/evaluation/run-analysis/references/investigation.md similarity index 100% rename from .agents/skills/run-analysis/references/investigation.md rename to .agents/skill-library/evaluation/run-analysis/references/investigation.md diff --git a/.agents/skills/run-analysis/scripts/runs.py b/.agents/skill-library/evaluation/run-analysis/scripts/runs.py similarity index 100% rename from .agents/skills/run-analysis/scripts/runs.py rename to .agents/skill-library/evaluation/run-analysis/scripts/runs.py diff --git a/.agents/skills/import-agent/SKILL.md b/.agents/skill-library/integrations/import-agent/SKILL.md similarity index 100% rename from .agents/skills/import-agent/SKILL.md rename to .agents/skill-library/integrations/import-agent/SKILL.md diff --git a/.agents/skills/import-benchmark/SKILL.md b/.agents/skill-library/integrations/import-benchmark/SKILL.md similarity index 100% rename from .agents/skills/import-benchmark/SKILL.md rename to .agents/skill-library/integrations/import-benchmark/SKILL.md diff --git a/.agents/skills/import-module/SKILL.md b/.agents/skill-library/integrations/import-module/SKILL.md similarity index 100% rename from .agents/skills/import-module/SKILL.md rename to .agents/skill-library/integrations/import-module/SKILL.md diff --git a/.agents/skills/import-standard/SKILL.md b/.agents/skill-library/integrations/import-standard/SKILL.md similarity index 99% rename from .agents/skills/import-standard/SKILL.md rename to .agents/skill-library/integrations/import-standard/SKILL.md index e224aa264..495e0de0d 100644 --- a/.agents/skills/import-standard/SKILL.md +++ b/.agents/skill-library/integrations/import-standard/SKILL.md @@ -12,8 +12,7 @@ description: >- benchmark meant for any agent or any Module - even if they never say "standard" or "port". An agent goes to import-agent, a Module to import-module (this skill still works for them). Not for Harbor benchmarks - run by Harbor agents (import-benchmark), nor for converting existing run - output (nullius.importers). + run by Harbor agents (import-benchmark). --- # Import into the Nullius standard diff --git a/.agents/skills/remove-integration/SKILL.md b/.agents/skill-library/integrations/remove-integration/SKILL.md similarity index 100% rename from .agents/skills/remove-integration/SKILL.md rename to .agents/skill-library/integrations/remove-integration/SKILL.md diff --git a/.agents/skills/docs-drift/SKILL.md b/.agents/skill-library/maintenance/docs-drift/SKILL.md similarity index 97% rename from .agents/skills/docs-drift/SKILL.md rename to .agents/skill-library/maintenance/docs-drift/SKILL.md index 5facb1baf..ee2e06025 100644 --- a/.agents/skills/docs-drift/SKILL.md +++ b/.agents/skill-library/maintenance/docs-drift/SKILL.md @@ -13,8 +13,7 @@ runs them: - repository paths named in backticks in a tracked `.md`, and files under `app/` or `docs/` named in a fenced command; - the `docs/` folder map in `docs/README.md`; -- AGENTS.md "Where code lives" against the packages of `app/nullius`, both ways; -- the importer registry against the README table. +- AGENTS.md "Where code lives" against the packages of `app/nullius`, both ways. A path is only checked when its first segment is a top-level entry of the repository, so a path under a wrong top-level directory passes silently. @@ -49,7 +48,6 @@ or name the merge commit and diff its first parent. | `app/nullius/catalogue/storage.py`, `app/nullius/standard/contract/definitions.py`, `app/nullius/standard/runner/payload.py` | `docs/standard.md`, `docs/builder.md`, `docs/how-it-works.md`; all import skills and manual-add guides: user overlays versus bundled contributions, whole-folder selection, and runtime snapshots sent to hosts; generated Supported pages use explicit bundled roots | | `app/nullius/runs/` | README "Reading a result"; `.claude/rules/running.md` "Reading a result"; `docs/field-guide.md`, what each field it names means; `docs/how-it-works.md` "Page by page"; `docs/cli/` when a CLI changed | | `app/nullius/traces/` | `.claude/rules/traces.md`; README "Reading a result" | - | `app/nullius/importers/` | README "Ways to run" and "Local by design"; `.claude/rules/running.md` "Running the app"; `docs/cli/import.md` | | `app/nullius/compare/` | `docs/cli/read-jobs.md`; `docs/field-guide.md`; `docs/how-it-works.md`, the `/compare` row | | `app/nullius/catalogue/`, `app/nullius/recipes/`, `app/nullius/harbor/` | README "What it does" and "Ways to run"; `docs/builder.md` "Stages"; `.claude/rules/running.md` "What this repository runs"; for `harbor/`, the `source.py` docstring and `docs/builder.md` "Which Harbor"; for `catalogue/`, `.agents/skills/import-benchmark/SKILL.md` (a Harbor entry, the listing rule) too; for `providers.py`, the provider rows of `docs/builder.md` "Which providers" | | `app/nullius/execution.py`, `app/nullius/hosts.py`, `app/nullius/settings.py` | `.claude/rules/running.md` "What this repository runs"; README "What it does"; `docs/builder.md` "Run"; `docs/settings/README.md`; `docs/how-it-works.md`, Paths 2 and 3 | diff --git a/.agents/skills/docs-drift/scripts/check_docs.py b/.agents/skill-library/maintenance/docs-drift/scripts/check_docs.py similarity index 83% rename from .agents/skills/docs-drift/scripts/check_docs.py rename to .agents/skill-library/maintenance/docs-drift/scripts/check_docs.py index 2fc6f44ae..bdb80a81f 100755 --- a/.agents/skills/docs-drift/scripts/check_docs.py +++ b/.agents/skill-library/maintenance/docs-drift/scripts/check_docs.py @@ -17,7 +17,7 @@ import sys from pathlib import Path -REPO = Path(__file__).resolve().parents[4] +REPO = Path(__file__).resolve().parents[5] # Paths intentionally absent from a checkout, with the reason for each. KNOWN_ABSENT = { @@ -150,29 +150,6 @@ def check_map() -> list[str]: for name in sorted(named - folders - entries) if not (REPO / name).is_dir()]) -def check_importers() -> list[str]: - """The README's ways-in table names every importer of the registry.""" - # The registry is read in a subprocess so this process's import path stays - # what it was: the test suite runs these checks over copies of the tree. - proc = subprocess.run([sys.executable, "-c", "import json, sys; from nullius import importers as r; " - "print(json.dumps(sorted(m.LABEL for m in r.available().values())))"], - cwd=REPO, capture_output=True, text=True, env={**os.environ, "PYTHONPATH": str(REPO / "app")}) - if proc.returncode != 0: - return [f"app/nullius/importers: the registry could not be read: {proc.stderr.strip()[-200:]}"] - labels = set(json.loads(proc.stdout)) - bad = [] - readme = (REPO / "README.md").read_text(encoding="utf-8") if (REPO / "README.md").exists() else "" - table = re.search(r"^\| Way in \| Runs \| Reads \|.*?(?=\n\n)", readme, re.M | re.S) - if not table: - bad.append("README.md: no ways-in table (`| Way in | Runs | Reads |`)") - else: - rows = table.group(0) - for label in sorted(labels): - if label not in rows: - bad.append(f"README.md: the ways-in table does not name the {label} importer") - return bad - - def check_folders() -> list[str]: """docs/README.md names the folders that are actually under docs/.""" readme = REPO / "docs/README.md" @@ -189,7 +166,7 @@ def check_folders() -> list[str]: def checks() -> list[str]: """Every finding, in one list.""" return (check_hrefs() + check_md_links() + check_md_paths() + check_fenced_paths() - + check_folders() + check_map() + check_importers()) + + check_folders() + check_map()) def main() -> int: diff --git a/.agents/skills/file-issue/SKILL.md b/.agents/skill-library/maintenance/file-issue/SKILL.md similarity index 100% rename from .agents/skills/file-issue/SKILL.md rename to .agents/skill-library/maintenance/file-issue/SKILL.md diff --git a/.agents/skills/ui-sweep/SKILL.md b/.agents/skill-library/maintenance/ui-sweep/SKILL.md similarity index 100% rename from .agents/skills/ui-sweep/SKILL.md rename to .agents/skill-library/maintenance/ui-sweep/SKILL.md diff --git a/.agents/skills/ui-sweep/scripts/sweep.py b/.agents/skill-library/maintenance/ui-sweep/scripts/sweep.py similarity index 100% rename from .agents/skills/ui-sweep/scripts/sweep.py rename to .agents/skill-library/maintenance/ui-sweep/scripts/sweep.py diff --git a/.agents/skills/docs-drift b/.agents/skills/docs-drift new file mode 120000 index 000000000..95f6c9782 --- /dev/null +++ b/.agents/skills/docs-drift @@ -0,0 +1 @@ +../skill-library/maintenance/docs-drift \ No newline at end of file diff --git a/.agents/skills/file-issue b/.agents/skills/file-issue new file mode 120000 index 000000000..a0bed80e7 --- /dev/null +++ b/.agents/skills/file-issue @@ -0,0 +1 @@ +../skill-library/maintenance/file-issue \ No newline at end of file diff --git a/.agents/skills/find-flawed-tasks b/.agents/skills/find-flawed-tasks new file mode 120000 index 000000000..a4e30e519 --- /dev/null +++ b/.agents/skills/find-flawed-tasks @@ -0,0 +1 @@ +../skill-library/evaluation/find-flawed-tasks \ No newline at end of file diff --git a/.agents/skills/fix-flawed-tasks b/.agents/skills/fix-flawed-tasks new file mode 120000 index 000000000..868742565 --- /dev/null +++ b/.agents/skills/fix-flawed-tasks @@ -0,0 +1 @@ +../skill-library/evaluation/fix-flawed-tasks \ No newline at end of file diff --git a/.agents/skills/import-agent b/.agents/skills/import-agent new file mode 120000 index 000000000..77be28b89 --- /dev/null +++ b/.agents/skills/import-agent @@ -0,0 +1 @@ +../skill-library/integrations/import-agent \ No newline at end of file diff --git a/.agents/skills/import-benchmark b/.agents/skills/import-benchmark new file mode 120000 index 000000000..15638ec6b --- /dev/null +++ b/.agents/skills/import-benchmark @@ -0,0 +1 @@ +../skill-library/integrations/import-benchmark \ No newline at end of file diff --git a/.agents/skills/import-capability/SKILL.md b/.agents/skills/import-capability/SKILL.md deleted file mode 100644 index e65650078..000000000 --- a/.agents/skills/import-capability/SKILL.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -name: import-capability -description: Compatibility alias for importing a Module into Nullius. ---- - -Read and follow [import-module](../import-module/SKILL.md). diff --git a/.agents/skills/import-feature/SKILL.md b/.agents/skills/import-feature/SKILL.md deleted file mode 100644 index 58c231219..000000000 --- a/.agents/skills/import-feature/SKILL.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -name: import-feature -description: Compatibility alias for importing a Module into Nullius. ---- - -Read and follow [import-module](../import-module/SKILL.md). diff --git a/.agents/skills/import-module b/.agents/skills/import-module new file mode 120000 index 000000000..79bd46423 --- /dev/null +++ b/.agents/skills/import-module @@ -0,0 +1 @@ +../skill-library/integrations/import-module \ No newline at end of file diff --git a/.agents/skills/import-standard b/.agents/skills/import-standard new file mode 120000 index 000000000..62836dc3c --- /dev/null +++ b/.agents/skills/import-standard @@ -0,0 +1 @@ +../skill-library/integrations/import-standard \ No newline at end of file diff --git a/.agents/skills/label-benchmark b/.agents/skills/label-benchmark new file mode 120000 index 000000000..cd32ebdbd --- /dev/null +++ b/.agents/skills/label-benchmark @@ -0,0 +1 @@ +../skill-library/evaluation/label-benchmark \ No newline at end of file diff --git a/.agents/skills/remove-integration b/.agents/skills/remove-integration new file mode 120000 index 000000000..4e19a39ff --- /dev/null +++ b/.agents/skills/remove-integration @@ -0,0 +1 @@ +../skill-library/integrations/remove-integration \ No newline at end of file diff --git a/.agents/skills/run-analysis b/.agents/skills/run-analysis new file mode 120000 index 000000000..7c5ca9ee3 --- /dev/null +++ b/.agents/skills/run-analysis @@ -0,0 +1 @@ +../skill-library/evaluation/run-analysis \ No newline at end of file diff --git a/.agents/skills/ui-sweep b/.agents/skills/ui-sweep new file mode 120000 index 000000000..c64ea0819 --- /dev/null +++ b/.agents/skills/ui-sweep @@ -0,0 +1 @@ +../skill-library/maintenance/ui-sweep \ No newline at end of file diff --git a/.claude/rules/running.md b/.claude/rules/running.md index 360305490..75d23d677 100644 --- a/.claude/rules/running.md +++ b/.claude/rules/running.md @@ -42,8 +42,7 @@ Conflicts stop migration before copying. Links within the copied contents are refused. Result roots open as a workspace under the user data directory's `workspaces/` -(`WORKSPACES_DIR` overrides it); ATIF and OpenTelemetry roots are converted into -its `imported/`. Review runs go under the user data directory's `runs/` +(`WORKSPACES_DIR` overrides it). Review runs go under the user data directory's `runs/` (`RUNS_DIR`). Direct standard CLI jobs default to `jobs_standard/` in the invoking directory. User catalogue entries overlay bundled entries by whole folder; editing a bundled definition first copies it into user storage. diff --git a/.gitignore b/.gitignore index 087579e91..c456c8975 100644 --- a/.gitignore +++ b/.gitignore @@ -64,3 +64,7 @@ workspaces/ /harbor-pins/ # This repository's app/ at a commit, unpacked to be sent to a host for a standard run. /standard-app/ + +# Application workspace UI is source, not a local run profile. +!app/templates/workspaces/ +!app/static/workspaces/ diff --git a/AGENTS.md b/AGENTS.md index 1b2957a35..b699db373 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ Nullius runs AI evaluations and opens every score into its evidence, to tell an agent's failure from a benchmark's. - Runs through the Nullius standard (`docs/standard.md`) or Harbor, only when - asked. Reads Harbor, ATIF and OpenTelemetry results. + asked. Reads Nullius and Harbor results. - `app/nullius/` is the backend: standard library only, except code that runs in an upstream's own environment. `app/web/` is Flask, the web framework and the only runtime dependency. @@ -62,13 +62,14 @@ is: `grep -m1 '"""' app/nullius/*.py app/nullius/runs/*.py`. | `app/nullius/leaderboard/` | Reading `labels.json`, scoring each axis over its labelled tasks, the board's selection | | `app/nullius/catalogue/` | A folder per entry under `benchmarks/`, `agents/`, `modules/`: its definition and code | | `app/nullius/recipes/`, `harbor/` | What the builder offers and saves; the Harbor a recipe pins | -| `app/nullius/importers/`, `judge/` | Foreign results in; questions to a judge model | +| `app/nullius/judge/` | Questions to a judge model | | `app/nullius/standard/` | The standard: `contract/`, `requirements/`, `protocols/`, `calls/`, `backends/`, `runner/`, `proofs/`, `pages/`, whose imports never loop, and the conformance `kits/` | | `app/web/` | One module per area; `core` is the application, `shared` what pages share. Write `shared.STATE`, so one patch reaches all | | `app/templates/`, `app/static/` | The interface, under the same names | | `app/tests/`, `app/ui_tests/` | Backend and route suites; fixtures are small and hand-made | | `app/site/`, `docs/` | The website; the documentation it publishes | -| `.agents/skills/` | Skills, `/name` here; `.claude/skills` links to it | +| `.agents/skill-library/` | Skill sources grouped into integrations, evaluation and maintenance | +| `.agents/skills/` | Flat skill symlinks for `/name` discovery; `.claude/skills` links to it | ## Commands diff --git a/README.md b/README.md index 965b10a86..764fb259b 100644 --- a/README.md +++ b/README.md @@ -99,8 +99,6 @@ The same benchmark before and after a change: the tasks both runs share, the one |---|---|---| | **Nullius standard** | Any agent (over ACP) or Module that proved the ports a benchmark needs; or the benchmark's own scripts as published, its *Original* setup. | Harbor-shaped job directories. | | **[Harbor](https://github.com/harbor-framework/harbor)** | Harbor's task folders in containers, with Harbor's agents. | Job directories from any Harbor agent. | -| **ATIF** trajectories | — | ATIF documents, converted into one job. | -| **OpenTelemetry** spans | — | OTLP/JSON span exports, converted into one job. | ## Reading a result diff --git a/app/nullius/__init__.py b/app/nullius/__init__.py index 609cbaea9..432c77922 100644 --- a/app/nullius/__init__.py +++ b/app/nullius/__init__.py @@ -16,8 +16,6 @@ - `recipes/` — `launch`, the vocabulary the run builder composes. - `providers` — where a run's model calls go, and the builder's steps. - `harbor/` — `source`: the Harbor a recipe pins, built here, kept, scanned. -- `importers/` — run trees other harnesses write: `atif`, `otel`, and the - `cli`. - `judge/` — judgement: `questions`, `state`, `client`, `store`, `batch`, `reconcile`, `lanes`. - `execution`, `hosts`, `gitrefs` — running a recipe here or on a host, the diff --git a/app/nullius/catalogue/agents/pi/agent.json b/app/nullius/catalogue/agents/pi/agent.json index 8d88d98c0..2a451afde 100644 --- a/app/nullius/catalogue/agents/pi/agent.json +++ b/app/nullius/catalogue/agents/pi/agent.json @@ -1,7 +1,7 @@ { "schema": "nullius.agent/v1", "key": "pi", - "label": "pi", + "label": "Pi", "company": "Earendil", "summary": "An extensible terminal coding agent; its ACP adapter does not forward session MCP servers.", "upstream": { diff --git a/app/nullius/catalogue/modules/keyword-memory/capability.json b/app/nullius/catalogue/modules/keyword-memory/capability.json deleted file mode 100644 index f0612bcd2..000000000 --- a/app/nullius/catalogue/modules/keyword-memory/capability.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "schema": "nullius.capability/v1", - "key": "keyword-memory", - "label": "Example memory", - "example": true, - "summary": "Nullius's example memory, to read or copy: BM25 over whole sessions.", - "upstream": { - "version": "1", - "license": "same as Nullius" - }, - "kind": "memory", - "start": { - "command": [ - "python3", - "{here}/capability.py" - ] - } -} diff --git a/app/nullius/catalogue/modules/keyword-memory/capability.py b/app/nullius/catalogue/modules/keyword-memory/capability.py deleted file mode 100644 index de06d8be8..000000000 --- a/app/nullius/catalogue/modules/keyword-memory/capability.py +++ /dev/null @@ -1,55 +0,0 @@ -"""The reference memory: BM25 over whole sessions, the top few recalled. - -cap.memory/v1 in JSON lines: ``add {session}`` keeps a session -(``{id, date, turns: [{role, text}], text}``), ``recall {question}`` answers -``{memory}`` - the best-matching sessions, each with its date, as text. -""" -import json -import math -import re -import sys - -TOP = 3 -WORD = re.compile(r"[a-z0-9]+") -kept = [] - - -def words(text): - return WORD.findall((text or "").lower()) - - -def recall(question): - q = set(words(question)) - if not kept or not q: - return "" - n = len(kept) - avg = sum(len(d["words"]) for d in kept) / n - df = {w: sum(1 for d in kept if w in d["set"]) for w in q} - def bm25(d): - s = 0.0 - for w in q: - if w in d["set"]: - tf = d["words"].count(w) - idf = math.log(1 + (n - df[w] + 0.5) / (df[w] + 0.5)) - s += idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * len(d["words"]) / avg)) - return s - best = sorted(kept, key=bm25, reverse=True)[:TOP] - return "\n\n".join(f"[{d['session'].get('date') or d['session'].get('id')}]\n{d['text']}" for d in best if bm25(d) > 0) - - -for line in sys.stdin: - try: - req = json.loads(line) - if req["op"] == "add": - s = req["session"] - text = s.get("text") or "\n".join(f"{t.get('role')}: {t.get('text')}" for t in s.get("turns") or []) - ws = words(text) - kept.append({"session": s, "text": text, "words": ws, "set": set(ws)}) - out = {} - elif req["op"] == "recall": - out = {"memory": recall(req["question"])} - else: - out = {"error": f"unknown op {req['op']!r}"} - except Exception as e: - out = {"error": f"{type(e).__name__}: {e}"} - print(json.dumps(out), flush=True) diff --git a/app/nullius/catalogue/modules/keyword-memory/proofs.json b/app/nullius/catalogue/modules/keyword-memory/proofs.json deleted file mode 100644 index fbc304016..000000000 --- a/app/nullius/catalogue/modules/keyword-memory/proofs.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "schema": "nullius.proofs/v1", - "kind": "capability", - "key": "keyword-memory", - "versions": { - "1": { - "offers": [ - "cap.memory/v1" - ], - "proven": { - "cap.memory/v1": { - "passed": "2/2", - "model": "openai/gpt-5-mini", - "provider": "openrouter", - "version": "1", - "kit_version": 1, - "backend": "docker" - } - } - } - } -} diff --git a/app/nullius/cli.py b/app/nullius/cli.py index 40da8638f..6640d961e 100644 --- a/app/nullius/cli.py +++ b/app/nullius/cli.py @@ -17,7 +17,6 @@ "compare": "compare runs", "leaderboard": "workspace agent scores over labelled tasks", "flags": "write a run's task flags", - "import": "import ATIF or OpenTelemetry output", "standard": "inspect and run standard definitions", "workspace": "manage workspaces", "paths": "show persistent storage locations", @@ -32,7 +31,6 @@ "compare": "nullius.compare.cli", "leaderboard": "nullius.leaderboard.cli", "flags": "nullius.runs.flags_cli", - "import": "nullius.importers.cli", "standard": "nullius.standard.cli", "workspace": "nullius.workspace_cli", "paths": "nullius.paths", diff --git a/app/nullius/importers/__init__.py b/app/nullius/importers/__init__.py deleted file mode 100644 index 57194e3e7..000000000 --- a/app/nullius/importers/__init__.py +++ /dev/null @@ -1,358 +0,0 @@ -"""Importers for run trees this app did not produce. - -The app walks one shape: a job directory whose subdirectories each carry a -``result.json``. Everything else — a run tree another harness wrote — is -converted into that shape rather than taught to the walker. That keeps `parse.py` a reader of one -format no matter how many harnesses there are. - -An importer knows how one harness lays out a whole run on disk; what a -dataset's verifier report means is `nullius.runs.verifier`'s. A new dataset -under a harness already read needs nothing here. - -**Adding one** is a module in this package exposing three names: - - NAME str what to pass to --harness - detect (path) -> bool does this directory look like ours? - convert (src, out_root, job_name="", command="") -> list[str] - -`convert` returns job directories, plural: one run tree is not always one -job. A directory that accumulates runs across sittings holds several, and -pooling them would report the idle time between as though it were work. - -and optionally ``LABEL``, how a person should see it named — -``check``, ``(path) -> None``, which reads the tree the way `convert` would -and raises ``SystemExit`` for what `convert` would refuse, writing -nothing (without it, :func:`problem` converts into a scratch directory to -learn the same thing) — and ``trees``, ``(root) -> list[str]``, which names -the directories under a root the app opened that are one `convert` each. -Without it a claimed root is one tree, which is how the CLI reads it. The -picker uses the same boundaries so both surfaces produce the same jobs. - -**One source, one job folder.** A tree is a source, known by its real -path. Its first conversion gives it an id of its own (:func:`place`), derived -from the format and that path so every workspace importing it agrees, written -in the job's ``config.json`` as ``nullius.source`` and read back on every -reconversion, so the folder and the identity stay its own: a second source of -one basename gets a folder of its own, and a job name that names a folder not -shown to be this source's is refused. A folder converted before the id is -kept as it is, without one, when its format and recorded source are this one's. - -**Refusing a tree** is `convert` raising ``SystemExit`` with a message -that names the file and what is wrong with it — never a job with no trials or a traceback. The message is what a person sees, on the picker or from -the CLI, so it is redacted at construction: a tree is arbitrary bytes from -wherever a run was made, and a credential in a bad file's path or content -must not travel into an error just because the file was bad. - -**Removing one is deleting its module**, plus its tests. Registration is by -discovery rather than a table here. Nothing outside a harness module mentions the harness. -""" -from __future__ import annotations - -import contextlib -import importlib -import json -import os -import pkgutil -import shutil -import tempfile -import uuid -from collections import Counter -from types import ModuleType - -from nullius import ondisk -from nullius.redact import redact - -# A module must expose all three to count. A half-written one is skipped -# rather than half-registered, so an editor's stray file cannot break `--list`. -_CONTRACT = ("NAME", "detect", "convert") - - -def available() -> dict[str, ModuleType]: - """Every importer in this package, keyed by its NAME.""" - found: dict[str, ModuleType] = {} - for info in pkgutil.iter_modules(__path__): - if info.name.startswith("_"): - continue - try: - module = importlib.import_module(f"{__name__}.{info.name}") - except ImportError: - continue - if all(hasattr(module, attr) for attr in _CONTRACT): - found[getattr(module, "NAME")] = module - return dict(sorted(found.items())) - - -def get(name: str) -> ModuleType | None: - """The importer called *name*, or None.""" - return available().get((name or "").strip().lower()) - - -def detect(path: str) -> ModuleType | None: - """The importer that recognises *path*, or None when nothing does. - - First match wins in name order. - """ - for module in available().values(): - try: - if module.detect(path): - return module - except OSError: - continue - return None - - -def trees(module: ModuleType, root: str) -> list[str]: - """The trees under *root* that *module* converts one job each. - - The importer's own ``trees`` when it has one; otherwise *root* itself - when the importer claims it, and nothing when it does not. A caller - converts each entry as it would the root a person named on the CLI, so - the two agree on what one job is. - """ - if hasattr(module, "trees"): - return list(module.trees(root)) - return [root] if module.detect(root) else [] - - -def problem(path: str) -> str | None: - """Why the importer that claims *path* cannot read it — or None. - - None also when nothing claims *path*: an unclaimed root is one for the - Harbor reader, and whether it holds a job is that reader's question. - The message is redacted whichever way it arrived, so a caller can show - it as it is. - """ - module = detect(path) - if module is None: - return None - try: - if hasattr(module, "check"): - module.check(path) - else: - scratch = tempfile.mkdtemp(prefix="nullius-check-") - try: - module.convert(path, scratch) - finally: - shutil.rmtree(scratch, ignore_errors=True) - except (OSError, SystemExit) as e: - return redact(str(e) or f"{module.NAME} could not read it") - return None - - -def write_if_changed(path: str, data: bytes) -> bool: - """Write *data* to *path* unless the file already holds it; True when - written, whole, renamed over the old file: a refresh cut short leaves the - old one. A conversion runs at each open of a workspace; an unchanged one - keeps its mtimes, and with them the parse cache that keys on them.""" - try: - with open(path, "rb") as fh: - if fh.read() == data: - return False - except OSError: - pass - ondisk.write_whole(path, data) - return True - - -def _reserved(job_dir: str) -> dict: - """Trial name -> the document it was given to, as the job's ``config.json`` - keeps it across conversions: a name stays its document's after its folder - is pruned.""" - try: - with open(os.path.join(job_dir, "config.json"), encoding="utf-8") as fh: - reserved = json.load(fh)["trial_documents"] - return {str(k): str(v) for k, v in reserved.items() if v} - except (OSError, ValueError, KeyError, TypeError, AttributeError): - return {} - - -def reservations(job_dir: str, written, existing: dict = None, merged: set = frozenset()) -> dict: - """The ``trial_documents`` to keep in *job_dir*'s ``config.json``: what - it kept, and the folders *existing* held before pruning (but a *merged* one or one whose document - could not be told), with *written* ((name, document) pairs) on top.""" - reserved = _reserved(job_dir) - reserved.update((name, identity) for name, identity in (existing or {}).items() - if identity and name not in merged and name not in reserved) - reserved.update((name, identity) for name, identity in written if identity) - return dict(sorted(reserved.items())) - - -def existing_trials(job_dir: str, identity_of) -> tuple[dict, set]: - """The trials a previous conversion left in *job_dir*: name -> the - document each holds, by ``identity_of(trial_dir)`` (None when the files - cannot tell), with the names reserved for documents whose folders are - gone, and the names of folders two documents were once written - into: a name its ``config.json`` lists twice among its tasks, or, without - that list, any name when the job counted more trials than it has folders.""" - trials, merged = _folders(job_dir, identity_of) - held = set(trials.values()) - for name, identity in _reserved(job_dir).items(): - if name not in trials and identity not in held: - trials[name] = identity - return trials, merged - - -def _folders(job_dir: str, identity_of) -> tuple[dict, set]: - trials = {} - if os.path.isdir(job_dir): - for name in sorted(os.listdir(job_dir)): - if os.path.isdir(os.path.join(job_dir, name)): - trials[name] = identity_of(os.path.join(job_dir, name)) - try: - with open(os.path.join(job_dir, "config.json"), encoding="utf-8") as fh: - tasks = json.load(fh)["tasks"] - listed = Counter(str(t["name"]).split("/", 1)[-1] for t in tasks) - return trials, {name for name, n in listed.items() if n > 1} - except (OSError, ValueError, KeyError, TypeError): - pass - try: - with open(os.path.join(job_dir, "result.json"), encoding="utf-8") as fh: - counted = json.load(fh)["n_total_trials"] - except (OSError, ValueError, KeyError, TypeError): - counted = len(trials) - # shortcut: a folder deleted by hand also counts, so any collision splits; only jobs without a tasks list - return trials, set(trials) if isinstance(counted, int) and counted > len(trials) else set() - - -def unique_names(documents: list[tuple], existing: dict | None = None, - merged: set = frozenset()) -> list[str]: - """One trial directory per document, decided before anything is written. - - Each document is (identity, name, longer name). A document whose trial - already exists keeps that trial's name: judgements are keyed by it. A - folder whose document is known stays that document's, even when it is - gone. A folder whose document cannot be told keeps its name for the first - document that would take it. Any other document takes its name unless - another holds it, else the longer one. A *merged* folder (two documents - written into one by an older conversion) is split: each of its documents - takes the longer name. Two documents still left with one name, or a - document left with a gone document's, are refused. - """ - existing = existing or {} - identities = {identity for identity, _, _ in documents} - held = {identity: name for name, identity in existing.items() if identity in identities} - unknown = {name for name, identity in existing.items() if identity is None} - gone = {name for name, identity in existing.items() if identity is not None and identity not in identities} - shorts = Counter(name for _, name, _ in documents) - split = {name for name, n in shorts.items() if n > 1 and name in existing and name in merged} - out = [held.get(identity) if held.get(identity) not in split else None - for identity, _, _ in documents] - taken = {name for name in out if name} | gone - for i, (_, name, longer) in enumerate(documents): - if out[i] is None: - free = name not in taken and name not in split - out[i] = name if free and (shorts[name] == 1 or name in unknown) else longer - taken.add(out[i]) - shared = sorted({name for name, n in Counter(out).items() if n > 1} | (set(out) & gone)) - if shared: - raise SystemExit(redact(f"two documents would share the trial {shared[0]!r}")) - return out - - -def mark_changed(job_dir: str, summaries: list) -> None: - """Move the job's own ``result.json`` when one of its trials was written: - an ended job's cached parse is checked by that file, not trial by trial.""" - if any(s["changed"] for s in summaries): - os.utime(os.path.join(job_dir, "result.json")) - - -def _config(job_dir: str) -> dict: - try: - with open(os.path.join(job_dir, "config.json"), encoding="utf-8") as fh: - cfg = json.load(fh) - except (OSError, ValueError): - return {} - return cfg if isinstance(cfg, dict) else {} - - -def _source(cfg: dict) -> tuple: - """``(id, path)`` a conversion recorded in ``nullius``, or ``(None, None)``.""" - own = cfg.get("nullius") if isinstance(cfg.get("nullius"), dict) else {} - try: - return str(uuid.UUID(str(own["source"]))), own.get("source_path") - except (KeyError, ValueError, TypeError): - return None, None - - -#: fixed for good: changing it changes every import's identity -NS_SOURCE = uuid.UUID("3b1d7e44-9a0c-4f62-8e15-2c7a9f4d6b08") - - -def source_id(fmt: str, root: str) -> str: - """A source's id: a ``uuid5`` over its format and real path, ``"v": 1``; a moved tree is a new source.""" - facts = {"v": 1, "format": fmt, "path": os.path.realpath(root)} - return str(uuid.uuid5(NS_SOURCE, json.dumps(facts, sort_keys=True, separators=(",", ":")))) - - -def place(out_root: str, root: str, default: str, job_name: str = "", fmt: str = "") -> tuple: - """``(job_name, source id)``: the folder under *out_root* the tree at *root* - is converted into, and its id, None for a folder converted before ids. - - The folder that already records this source's id is its own. Otherwise *default*, - then ``-2``, ``-3``…, skipping a folder that holds anything not - shown to be this source's: another id, or an older conversion :func:`_verified` - does not tie to it. A named *job_name* is used as it is, and refused when - it is not shown to be this source's. Call it under :func:`locked`, through - the write, so two conversions never pick one folder. - """ - src, new = os.path.realpath(root), source_id(fmt, root) - names = sorted(os.listdir(out_root)) if not job_name and os.path.isdir(out_root) else [] - for name in names: - if _source(_config(os.path.join(out_root, name)))[0] == new: - return name, new - n = 1 - while True: - name = job_name or (default if n == 1 else f"{default}-{n}") - job_dir = os.path.join(out_root, name) - if not os.path.isdir(job_dir) or not os.listdir(job_dir): - return name, new - cfg = _config(job_dir) - sid = _source(cfg)[0] - if sid == new: - return name, sid - if not sid and _verified(job_dir, cfg, fmt, src): - return name, None - if job_name: - raise SystemExit(redact(f"{job_dir} holds an import not shown to be this source's; " - "choose another job name")) - n += 1 - - -def _verified(job_dir: str, cfg: dict, fmt: str, src: str) -> bool: - """A folder converted before ids is the source at real path *src* only when it - stored the format *fmt* and names *src*: by the absolute path it recorded, - else as the one tree its trials are named from (where each says its document - was read) that ends with the relative path it recorded.""" - if not cfg or cfg.get("harness") != fmt: - return False - old = recorded(cfg) - if isinstance(old, str) and os.path.isabs(old): - return os.path.realpath(old) == src - module = get(fmt) - roots = module._trial_roots(job_dir) if hasattr(module, "_trial_roots") else [] - if isinstance(old, str): - roots = [r for r in roots if os.path.normpath(old) == "." or r.endswith(os.sep + os.path.normpath(old))] - return roots == [src] - - -@contextlib.contextmanager -def locked(out_root: str): - """One conversion at a time into *out_root*, from :func:`place` through the write.""" - os.makedirs(out_root, exist_ok=True) - with ondisk.locked(os.path.join(out_root, ".nullius-import.lock")): - yield - - -def recorded(cfg: dict): - """The source path an import from before ids recorded in its ``config.json``, or None.""" - module = get(str(cfg.get("harness") or "")) - return module._recorded(cfg) if module and hasattr(module, "_recorded") else None - - -def recorded_as(sid, root: str) -> dict: - """What a job's ``config.json`` carries of its source: nothing for a folder converted before ids.""" - return {"nullius": {"source": sid, "source_path": os.path.realpath(root)}} if sid else {} - - -def labels() -> str: - return ", ".join(getattr(m, "LABEL", name) for name, m in available().items()) diff --git a/app/nullius/importers/atif.py b/app/nullius/importers/atif.py deleted file mode 100644 index e858882a4..000000000 --- a/app/nullius/importers/atif.py +++ /dev/null @@ -1,439 +0,0 @@ -"""ATIF trajectories from any producer: standalone documents in, one job out. - - PYTHONPATH=app python3 -m nullius.importers.cli trajectories/ -o jobs_imported - PYTHONPATH=app python3 -m nullius.importers.cli agent/trajectory.json -o jobs_imported - -An ATIF document is the file Harbor's agents write as ``agent/trajectory.json`` -and the reader already opens inside a trial (``nullius.traces.trajectory``). -This recognises one on its own by content: a JSON -object whose ``schema_version`` reads ``ATIF-v1.x`` and which carries -``steps``. The producer's name, the file's name and the directory it sits in -are not consulted. - -**Supported schema versions**: ``ATIF-v1.0`` through ``ATIF-v1.7`` -(``SUPPORTED_VERSIONS``) — the versions Nullius already parses inside a job, -as written by Harbor's agents (``final_metrics``, per-step -``metrics``, the ``extra`` usage slot). A document of any other version is -refused by name rather than read as though it were one of these. - -The app walks Harbor's shape, so this converts: one directory (or one file) becomes one job, each document -a trial directory holding the document *copied byte for byte* as -``agent/trajectory.json``. Nothing is parsed twice — ``trajectory.load`` is -the one reader, here and on the trial page — and nothing is re-measured: - -- **No benchmark outcome is invented.** A trajectory records what an agent - did, not whether it was right. The trial carries no ``verifier_result``, - no reward and no ``verifier/`` marker, so it reads as ``unknown`` — never - a score, never a solve rate — and stays out of every rate. -- **Usage and timing are the document's own, or absent.** ``agent_result`` - copies ``final_metrics`` (prompt, completion, cached, cost) and is null - where the document is silent; the trial window is the span of the step - timestamps, and null when no step carries one. Nothing is zeroed to fill - a column: "unmeasured" and "zero" are different claims. -- **Provenance is the document's.** ``agent_info`` comes from the ATIF - ``agent`` block (name, version, model_name), falling back to the first - step's ``model_name`` for the model; the schema version, session id and - the source file's path and digest are kept on the trial record under - ``source_document``. -- **The recorded command is the import.** No harness ran here, so the line - the job page offers to copy is the one that reproduces this job - directory. - -A tree this claims but cannot read is refused before anything is written, -with a ``SystemExit`` whose message names the file (relative to the tree -given) and what is wrong — a document that is not JSON, one without -``steps``, one of an unsupported version — and is redacted. A ``.json`` -that is well-formed but not ATIF at all (a ``trace.json``, a -``spans.meta.json``) is simply not one of ours and is passed over. - -What this does *not* claim: a Harbor job or trial (a ``result.json`` on the -walk). Those trajectories belong to the record around them, whose accounting -is the reader's and must not be shadowed by a second, thinner reading of the same -file. - -Re-converting is idempotent: trial names are -deterministic (the document's path relative to the tree, a bare -``trajectory.json`` named after its directory), every file is rewritten in -place, and a trial the tree no longer holds is removed; its name stays -its document's, kept in the job's ``config.json`` under ``trial_documents``. -""" -from __future__ import annotations - -import hashlib -import json -import os -import re -import shlex -import shutil -from datetime import timezone - -from nullius import importers -from nullius.redact import redact -from nullius.traces.trajectory import parse_ts - -NAME = "atif" -LABEL = "ATIF" - -# The schema versions this reads. Anchoring on the list is what keeps detect() -# from claiming a future shape and reading it as one of these. -SUPPORTED_VERSIONS = tuple(f"ATIF-v1.{minor}" for minor in range(8)) - -# What makes a JSON object an ATIF document at all, whatever its version: -# the schema tag. Shape (steps present, a list) is checked when read, so a -# partial document is refused by name rather than passed over as foreign. -_VERSION_RE = re.compile(r"^ATIF-v\d+\.\d+$") - -# A file that is not JSON is only *ours* to refuse when it says it is an -# ATIF document; sniffed in the head of the file, since it cannot be parsed. -_MARKER = b'"ATIF-v' -_SNIFF_BYTES = 4096 - -# Files that mark a directory as part of a record another reader owns. -_OWNED_BY = ("result.json",) - - - -def _is_atif(doc) -> bool: - return (isinstance(doc, dict) - and isinstance(doc.get("schema_version"), str) - and bool(_VERSION_RE.match(doc["schema_version"]))) - - -def _mentions_atif(path: str) -> bool: - try: - with open(path, "rb") as fh: - return _MARKER in fh.read(_SNIFF_BYTES) - except OSError: - return False - - -def _read(path: str, shown: str) -> tuple: - """``(document, bytes)`` at *path*, or a SystemExit naming what is wrong with it. - - The message is redacted here. - """ - try: - with open(path, "rb") as fh: - data = fh.read() - doc = json.loads(data.decode("utf-8")) - except OSError as e: - raise SystemExit(redact(f"{shown}: cannot be read ({e.strerror})")) from None - except ValueError as e: - raise SystemExit(redact(f"{shown}: not JSON ({e})")) from None - if not _is_atif(doc): - raise SystemExit(redact(f"{shown}: not an ATIF document")) - version = doc["schema_version"] - if version not in SUPPORTED_VERSIONS: - raise SystemExit(redact( - f"{shown}: unsupported ATIF schema_version {version!r} " - f"(supported: {SUPPORTED_VERSIONS[0]} through {SUPPORTED_VERSIONS[-1]})")) - if "steps" not in doc: - raise SystemExit(redact(f"{shown}: no steps (a partial document)")) - if not isinstance(doc["steps"], list): - raise SystemExit(redact(f"{shown}: steps is not a list")) - return doc, data - - -def _claims(path: str) -> bool: - """Is this file ours — an ATIF document, or a broken file that says it is?""" - try: - with open(path, encoding="utf-8") as fh: - doc = json.load(fh) - except OSError: - return False - except ValueError: - return _mentions_atif(path) - return _is_atif(doc) - - -def find_documents(root: str) -> list[str]: - """Every file under *root* this importer claims, sorted; *root* itself - when it is one file. Empty when a ``result.json`` is - seen on the walk — that tree is a record another reader owns.""" - if os.path.isfile(root): - return [root] if _claims(root) else [] - found = [] - for dirpath, dirnames, filenames in os.walk(root): - dirnames.sort() - if any(name in filenames for name in _OWNED_BY): - return [] - for name in sorted(filenames): - path = os.path.join(dirpath, name) - if name.endswith(".json") and _claims(path): - found.append(path) - return found - - -def detect(path: str) -> bool: - """Does *path* hold standalone ATIF documents (or is it one)?""" - return bool(find_documents(path)) - - -def check(path: str) -> None: - """Read every document the way `convert` would, writing nothing; raises - ``SystemExit`` (redacted) for the first thing `convert` would refuse.""" - _read_all(path) - - -def trees(root: str) -> list[str]: - """One directory, one job, whatever its depth — the CLI's reading of - *root*, shared by the picker. The documents found under it are - that job's trials, named by their place in the tree (`_trial_name`), so - a nested directory of trajectories is one job of several trials rather - than a job per child.""" - return [root] if detect(root) else [] - - -def _shown(path: str, root: str) -> str: - """How a file is named in a message: relative to the tree given.""" - if os.path.isfile(root): - return os.path.basename(path) - return os.path.relpath(path, root) - - -def _read_all(root: str) -> list[tuple[str, dict, bytes]]: - paths = find_documents(root) - if not paths: - raise SystemExit(redact( - f"no ATIF trajectories (schema_version {SUPPORTED_VERSIONS[0]} through " - f"{SUPPORTED_VERSIONS[-1]}) found in {root}")) - return [(path, *_read(path, _shown(path, root))) for path in paths] - - - -def _trial_name(path: str, root: str) -> str: - """The document's place in the tree, flattened for a directory name. - - A bare ``trajectory.json`` is named after the directory holding it, so - ``claude-code/trajectory.json`` and ``claude-code.json`` are the same - trial under either layout. A single file, or a ``trajectory.json`` at - the root itself, takes the file's own stem. - """ - if os.path.isfile(root): - rel = os.path.basename(path) - else: - rel = os.path.relpath(path, root) - stem = rel[:-len(".json")] if rel.endswith(".json") else rel - parts = [p for p in stem.split(os.sep) if p and p != "."] - if len(parts) > 1 and parts[-1] == "trajectory": - parts.pop() - return "__".join(parts) or "trajectory" - - -def _instant(stamp: str) -> float: - """A stamp as seconds since the epoch, a naive one read as UTC: what the - job's first start and last end are chosen by.""" - when = parse_ts(stamp) - if when is None: - return float("inf") - return (when.replace(tzinfo=timezone.utc) if when.tzinfo is None else when).timestamp() - - -def _window(doc: dict) -> tuple[str | None, str | None]: - """The first and last step timestamps that parse, in step order and as - recorded; None when no step carries a clock — the trial then has no - duration, not a zero one. Step order rather than min/max: the document's - ordering is preserved, and two clocks of different kinds (one naive, one - zoned) are never compared.""" - stamps = [s.get("timestamp") for s in doc["steps"] - if isinstance(s, dict) and parse_ts(s.get("timestamp")) is not None] - if not stamps: - return None, None - return stamps[0], stamps[-1] - - -def _agent_info(doc: dict) -> dict: - agent = doc.get("agent") if isinstance(doc.get("agent"), dict) else {} - model = agent.get("model_name") or next( - (s.get("model_name") for s in doc["steps"] - if isinstance(s, dict) and s.get("model_name")), "") - return { - "name": str(agent.get("name") or ""), - "version": str(agent.get("version") or ""), - "model_info": {"name": str(model or "")}, - } - - -def _usage(doc: dict) -> dict: - """``final_metrics`` in the fields the reader sums — null where absent.""" - metrics = doc.get("final_metrics") if isinstance(doc.get("final_metrics"), dict) else {} - - def number(key): - value = metrics.get(key) - return value if isinstance(value, (int, float)) and not isinstance(value, bool) else None - - return { - "n_input_tokens": number("total_prompt_tokens"), - "n_output_tokens": number("total_completion_tokens"), - "n_cache_tokens": number("total_cached_tokens"), - "cost_usd": number("total_cost_usd"), - } - - -def _dump(path: str, data) -> bool: - return importers.write_if_changed(path, json.dumps(data, indent=2).encode()) - - - -# ── one document = one trial ──────────────────────────────────────────────── - -def convert_document(path: str, doc: dict, data: bytes, trial: str, job_dir: str) -> dict: - """Write one document, parsed from *data*, as a Harbor-shaped trial directory. Returns a summary.""" - trial_dir = os.path.join(job_dir, trial) - agent_dir = os.path.join(trial_dir, "agent") - os.makedirs(agent_dir, exist_ok=True) - - started, finished = _window(doc) - result = { - "trial_name": trial, - "task_name": f"{NAME}/{trial}", - # The harness, not a dataset: the benchmark readers stay unengaged, - # and with no report and no reward the outcome is `unknown`. - "source": NAME, - "agent_info": _agent_info(doc), - "exception_info": {}, - "verifier_result": {}, - "started_at": started, - "finished_at": finished, - "environment_setup": None, - "agent_setup": None, - # The document is the agent's own window; what surrounded it (image - # pull, setup, a verifier) was never recorded here. - "agent_execution": ( - {"started_at": started, "finished_at": finished} if started else None), - "verifier": None, - "agent_result": _usage(doc), - "source_document": { - "path": os.path.abspath(path), - "sha256": hashlib.sha256(data).hexdigest(), - "schema_version": doc["schema_version"], - "session_id": doc.get("session_id"), - }, - } - changed = _dump(os.path.join(trial_dir, "result.json"), result) - - # Byte for byte the bytes parsed: the trial page reads what the producer - # wrote, and a digest of the copy is a digest of the source. - changed |= importers.write_if_changed(os.path.join(agent_dir, "trajectory.json"), data) - - return {"trial_dir": trial, "started_at": started, "finished_at": finished, - "agent_info": result["agent_info"], "changed": changed} - - - -def _source_in(trial_dir: str): - """The source document a trial folder was made from, as recorded, by its real path: one tree - reached through a link is the same tree.""" - try: - with open(os.path.join(trial_dir, "result.json"), encoding="utf-8") as fh: - return os.path.realpath(str(json.load(fh)["source_document"]["path"])) - except (OSError, ValueError, KeyError, TypeError): - return None - - -def _write_job(docs: list, root: str, out_root: str, job_name: str, command: str, sid=None) -> str: - """The read documents, as one job directory of one trial each.""" - # Flattening can give two paths one name (a/b.json, a__b.json): those take - # a digest of their path, so each document keeps a trial of its own. - job_dir = os.path.join(out_root, job_name) - existing = importers.existing_trials(job_dir, _source_in) - names = importers.unique_names([ - (os.path.realpath(path), _trial_name(path, root), _trial_name(path, root) + "__" - + hashlib.sha256(_shown(path, root).encode()).hexdigest()[:8]) - for path, _doc, _data in docs], *existing) - os.makedirs(job_dir, exist_ok=True) - - summaries = [convert_document(path, doc, data, name, job_dir) - for (path, doc, data), name in zip(docs, names)] - - # ordered as instants, not as text: one stamp with a zone and one without sort apart as strings - starts = sorted((s["started_at"] for s in summaries if s["started_at"]), key=_instant) - ends = sorted((s["finished_at"] for s in summaries if s["finished_at"]), key=_instant) - _dump(os.path.join(job_dir, "result.json"), { - "started_at": starts[0] if starts else None, - "finished_at": ends[-1] if ends else None, - "n_total_trials": len(summaries), - "stats": {"n_errored_trials": 0, "n_running_trials": 0, - "n_pending_trials": 0, "n_retries": 0}, - }) - importers.mark_changed(job_dir, summaries) - - # The first document's producer names the job; a tree that mixes - # producers still shows each trial's own under agent_info. - agent = next((s["agent_info"] for s in summaries if s["agent_info"]["name"]), - summaries[0]["agent_info"]) - _dump(os.path.join(job_dir, "config.json"), { - "job_name": job_name, - "harness": NAME, # provenance; the walker ignores unknown keys - # a folder converted before ids keeps the command its identity was derived from - "command": importers._config(job_dir).get("command") if sid is None else command or ( - f"PYTHONPATH=app python3 -m nullius.importers.cli {shlex.quote(root)} " - f"-o {shlex.quote(out_root)} --job-name {shlex.quote(job_name)}"), - "agents": [{"name": agent["name"], - "model_name": agent["model_info"]["name"]}], - "tasks": [{"name": f"{NAME}/{s['trial_dir']}"} for s in summaries], - "trial_documents": importers.reservations( - job_dir, ((name, os.path.realpath(path)) for (path, _doc, _data), name in zip(docs, names)), *existing), - **importers.recorded_as(sid, root), - }) - # Derived output this importer wholly owns: a trial the tree no longer - # holds is stale and would keep being counted. Pruned once - # config.json reserves its name: a refresh cut short before then keeps the folder. - produced = {s["trial_dir"] for s in summaries} - for name in os.listdir(job_dir): - sub = os.path.join(job_dir, name) - if os.path.isdir(sub) and name not in produced: - shutil.rmtree(sub) - return job_dir - - -def convert(root: str, out_root: str, job_name: str = "", - command: str = "") -> list[str]: - """Convert the documents at *root* — a directory of them or one file — - into one job. Every document is read before anything is written, so a - refused tree leaves no half-written job behind.""" - base = os.path.basename(os.path.normpath(root)) - if os.path.isfile(root): - base = _trial_name(root, root) - root = os.path.realpath(root) # one spelling of the source, whatever the caller's cwd or links - _read_all(root) # a refused tree is refused before even the lock is written - with importers.locked(out_root): - docs = _read_all(root) # read under the lock: a newer conversion is never undone - job_name, sid = importers.place(out_root, root, f"{NAME}__{base}", job_name, NAME) - return [_write_job(docs, root, out_root, job_name, command, sid)] - - -def _recorded(cfg: dict): - """The tree a conversion from before ids was made from: the one its default command names.""" - try: - words = shlex.split(str(cfg.get("command") or "")) - return words[words.index("nullius.importers.cli") + 1] - except (ValueError, IndexError): - return None - - -def _trial_roots(job_dir: str) -> list: - """Every tree whose documents, named from there, give *job_dir*'s trials the - names they have, by where each trial records its document was read; - empty when one cannot tell.""" - found = [] - for name in sorted(os.listdir(job_dir)): - trial = os.path.join(job_dir, name) - if not os.path.isdir(trial): - continue - try: - with open(os.path.join(trial, "result.json"), encoding="utf-8") as fh: - found.append((name, os.path.realpath(str(json.load(fh)["source_document"]["path"])))) - except (OSError, ValueError, KeyError, TypeError): - return [] - if not found: - return [] - roots, root = [], os.path.commonpath([path for _, path in found]) - while True: - # a name another document's took is its own name with a digest of its path - if all(name in (_trial_name(path, root), _trial_name(path, root) + "__" - + hashlib.sha256(_shown(path, root).encode()).hexdigest()[:8]) for name, path in found): - roots.append(root) - if os.path.dirname(root) == root: - return roots - root = os.path.dirname(root) diff --git a/app/nullius/importers/cli.py b/app/nullius/importers/cli.py deleted file mode 100755 index ad2042a6d..000000000 --- a/app/nullius/importers/cli.py +++ /dev/null @@ -1,131 +0,0 @@ -"""Turn a foreign harness's run tree into a job directory this app can walk. - - PYTHONPATH=app python3 -m nullius.importers.cli -o - PYTHONPATH=app python3 -m nullius.importers.cli -o --json - PYTHONPATH=app python3 -m nullius.importers.cli --list - -The harness is detected from the directory's own shape; ``--harness NAME`` -names one outright when detection would be ambiguous or a tree is unusual. -Each importer lives in ``nullius/importers/`` and registers by being -there. With no importers, ``--list`` prints ``no importers registered`` and no tree is recognised. - -Every job written is named on stdout by its id — the directory's basename, -which is what ``nullius.runs.cli list`` prints and ``/job/`` opens — and -``--json`` gives the same as one document. The source tree is never edited; -the only writes land under ``-o``. The exit codes are the contract in -``docs/cli.md``, shared by every CLI here. -""" -from __future__ import annotations - -import argparse -import json -import os -import sys - -from nullius import importers as harnesses - -# See docs/cli.md for exit codes. 1 is left to Python itself: an uncaught exception is a bug. -EXIT_OK = 0 -EXIT_NOT_FOUND = 3 -EXIT_FAILED = 4 - -EPILOG = """\ -examples: - nullius import /path/to/logs -o jobs_imported - nullius import /path/to/logs -o jobs_imported --json - nullius import --list - -exit codes: - 0 done - 1 unexpected error (a traceback: report it) - 2 usage: a bad flag, a missing argument, an unknown --harness - 3 input not found: no such run tree, or no importer recognised it - 4 the importer refused the tree: nothing under it could be converted -With --json, stdout is exactly one JSON document; everything else goes to stderr. -""" - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser( - prog="nullius import", description=__doc__.splitlines()[0], - epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("run_dir", nargs="?", help="the harness's run tree") - ap.add_argument("-o", "--out", default="jobs_imported", - help="job root to write into (default: jobs_imported)") - ap.add_argument("--harness", default="", - help="name an importer instead of detecting one") - ap.add_argument("--job-name", default="", help="name for the job directory") - ap.add_argument("--command", default="", - help="the invocation that produced the run, shown verbatim " - "on the job page") - ap.add_argument("--list", action="store_true", help="list known harnesses") - ap.add_argument("--json", action="store_true", - help="one JSON document naming the harness and every job written") - args = ap.parse_args(argv) - - known = harnesses.available() - if args.list: - if args.json: - json.dump({name: (module.__doc__ or "").strip().splitlines()[0] - for name, module in known.items()}, sys.stdout, indent=1) - sys.stdout.write("\n") - return EXIT_OK - # An empty registry is a state, not a crash - but printing nothing - # would read exactly like a CLI that imported and did no work. - if not known: - print("no importers registered") - for name, module in known.items(): - summary = (module.__doc__ or "").strip().splitlines()[0] - print(f" {name:<10} {summary}") - return EXIT_OK - - if not args.run_dir: - ap.error("run_dir is required (or pass --list)") - - if args.harness: - module = harnesses.get(args.harness) - if module is None: - ap.error(f"unknown harness {args.harness!r}; known: {', '.join(known)}") - if not os.path.isdir(args.run_dir): - print(f"no such directory: {args.run_dir}", file=sys.stderr) - return EXIT_NOT_FOUND - if not args.harness: - module = harnesses.detect(args.run_dir) - if module is None: - print(f"no importer recognised {args.run_dir}; " - f"pass --harness (known: {', '.join(known) or 'none'})", file=sys.stderr) - return EXIT_NOT_FOUND - - # Use the importer's tree boundaries so a parent can yield several jobs. - # Report refusal messages on stderr with EXIT_FAILED; preserve numeric exits. - try: - job_dirs = [] - for tree in harnesses.trees(module, args.run_dir) or [args.run_dir]: - job_dirs += module.convert(tree, args.out, args.job_name if tree == args.run_dir else "", args.command) - except SystemExit as e: - if isinstance(e.code, int): - raise - print(e.code, file=sys.stderr) - return EXIT_FAILED - - jobs = [] - for job_dir in job_dirs: - trials = sum( - 1 for name in os.listdir(job_dir) - if os.path.isfile(os.path.join(job_dir, name, "result.json")) - ) - jobs.append({"job_id": os.path.basename(os.path.normpath(job_dir)), - "dir": job_dir, "trials": trials}) - if args.json: - json.dump({"harness": module.NAME, "out": args.out, "jobs": jobs}, - sys.stdout, ensure_ascii=False, indent=1) - sys.stdout.write("\n") - return EXIT_OK - for job in jobs: - print(f"{module.NAME}: wrote {job['trials']} trial(s) to {job['dir']} " - f"(job id {job['job_id']})") - return EXIT_OK - - -if __name__ == "__main__": # pragma: no cover - entry point - raise SystemExit(main()) diff --git a/app/nullius/importers/otel.py b/app/nullius/importers/otel.py deleted file mode 100644 index e044b32dd..000000000 --- a/app/nullius/importers/otel.py +++ /dev/null @@ -1,310 +0,0 @@ -"""OpenTelemetry span exports: a directory of OTLP/JSON files in, one job out. - - PYTHONPATH=app python3 -m nullius.importers.cli traces-export/ -o jobs_imported - -A production trace export is not a benchmark run — no task, no verifier, no -reward — but it is spans with clocks, which is what the trial page's waterfall -and ``/charts`` draw. So this lays the export out as the one shape the app -walks: a job directory holding **one trial per trace id**, each with the -``harbor-trace-v1`` document ``traces/otel.py`` builds under ``agent/``. The -format, the conventions read and the field mapping are that module's; this one -decides what a trial *is* and what its ``result.json`` may honestly say. - -What it says is little, on purpose: - -- **The outcome is unknown, and no reward exists.** A span in ERROR marks that - span in the trace; it is not an exception on the trial, because a failed - call is not a failed task and the app's outcome taxonomy is about tasks. - ``exception_info`` and ``verifier_result`` are therefore empty, which - ``classify`` reads as *unknown* — not resolved, not failed. -- **Tokens are the trace's own totals** — the sum over its LLM spans — written - only when at least one span reported usage; a trace with no usage attributes - records no ``agent_result`` at all rather than three zeros. -- **The model is the first LLM span's**, the agent the resource's - ``service.name``. An export that names neither shows neither. -- **The clock is the trace's window**, first span start to last span end, as - both the trial's ``started_at``/``finished_at`` and its ``agent_execution`` - phase — the only phase there is evidence for. - -Recognition is by content: a ``.json`` file whose top level is an -``ExportTraceServiceRequest`` (``resourceSpans``), or a JSON-lines file of them -— under the directory at any depth. What one job is under a root the app opened is this module's answer -(``trees``): an export directory is one job, and a parent that holds no -export of its own but several export directories is one job per directory — -each is one producer's export (the trial's agent is its ``service.name``), -and pooling them would put several agents under one heading. The CLI pools the supplied directory into one job. - -A file the reader refuses — bad JSON, no ``resourceSpans``, an unsupported -schema URL — is reported with its redacted message and skipped; only when -*nothing* converts is that fatal. The source directory is never written to: -everything lands under the output root, and a re-convert rewrites the same -names in place (a trace the export no longer holds is removed), so refreshing -a workspace updates rather than duplicates. -""" -from __future__ import annotations - -import json -import os -import re -import shutil -from datetime import datetime, timezone - -from nullius import importers -from nullius.redact import redact -from nullius.traces import otel as reader -from nullius.traces.spans import raw_spans_of - -NAME = "otel" -LABEL = "OpenTelemetry" - -# Directory-name characters for a trial: the root span's name can be anything -# a producer chose, and a slash in it would nest the trial. -_UNSAFE = re.compile(r"[^A-Za-z0-9._-]+") - - - -def find_exports(root: str) -> list[str]: - """Every OTLP/JSON file under *root*, sorted. A cheap head check first, - then the real read: the walk runs on every workspace open, over roots - that may hold thousands of Harbor files that are not this.""" - out = [] - for dirpath, _dirnames, filenames in os.walk(root): - for name in filenames: - path = os.path.join(dirpath, name) - if not (name.endswith(".json") or name.endswith(".jsonl")): - continue - if not reader.looks_like_export(path): - continue - try: - if reader.read_file(path): - out.append(path) - except reader.ReadError: - continue - return sorted(out) - - -def detect(path: str) -> bool: - """Does *path* hold at least one readable OTLP/JSON trace export?""" - return os.path.isdir(path) and bool(find_exports(path)) - - -def trees(root: str) -> list[str]: - """The directories under *root* that are one job each. - - *root* itself when an export file sits directly in it — an export - directory is one job however its files are arranged below. Otherwise - each child directory holding an export. Nothing when there is no - export under *root* at all. - """ - exports = find_exports(root) if os.path.isdir(root) else [] - if not exports: - return [] - if any(os.path.dirname(path) == root for path in exports): - return [root] - return [os.path.join(root, name) for name in sorted(os.listdir(root)) - if os.path.isdir(os.path.join(root, name)) and detect(os.path.join(root, name))] - - -def refused(root: str) -> list[str]: - """(path, redacted reason) for every candidate file the reader refuses.""" - out = [] - for dirpath, _dirnames, filenames in os.walk(root): - for name in sorted(filenames): - path = os.path.join(dirpath, name) - if not (name.endswith(".json") or name.endswith(".jsonl")): - continue - if not reader.looks_like_export(path): - continue - try: - reader.read_file(path) - except reader.ReadError as exc: - # The reader names the file by basename; this names it by its - # path under the root, once, in place of that. - reason = str(exc) - prefix = os.path.basename(path) + ": " - if reason.startswith(prefix): - reason = reason[len(prefix):] - out.append(f"{os.path.relpath(path, root)}: {reason}") - return out - - - -def _iso(ns: int) -> str: - return datetime.fromtimestamp(ns / 1e9, tz=timezone.utc).isoformat().replace("+00:00", "Z") - - -def _dump(path: str, data) -> bool: - return importers.write_if_changed(path, (json.dumps(data, ensure_ascii=False, indent=1) + "\n").encode()) - - -def _window(document: dict) -> tuple: - """(start_ns, end_ns) over every span, end None when no span ended.""" - starts, ends = [], [] - for raw in raw_spans_of(document.get("spans") or []): - starts.append(raw["start_ns"]) - if raw.get("end_ns") is not None: - ends.append(raw["end_ns"]) - return (min(starts) if starts else None, max(ends) if ends else None) - - -def trial_name_of(document: dict, full: bool = False) -> str: - """``__<7 hex of the trace id>``, readable; with *full*, - the whole trace id, for traces whose short names collide.""" - tid = str(document.get("session_id") or "") - stem = _UNSAFE.sub("_", str(document.get("trial_name") or "")).strip("._-") or "trace" - return f"{stem[:80]}__{(tid if full else tid[:7]) or 'unknown'}" - - -def write_trial(document: dict, job_dir: str, trial: str = "") -> dict: - """One trace document as a trial directory. Returns a summary.""" - trial = trial or trial_name_of(document) - trial_dir = os.path.join(job_dir, trial) - agent_dir = os.path.join(trial_dir, "agent") - os.makedirs(agent_dir, exist_ok=True) - - start_ns, end_ns = _window(document) - started = _iso(start_ns) if start_ns else None - finished = _iso(end_ns) if end_ns else None - tokens = (document.get("totals") or {}).get("tokens") or {} - model = reader.model_of(document) - agent = document.get("agent") or {} - - result = { - "trial_name": trial, - "task_name": f"{NAME}/{document.get('trial_name') or trial}", - "source": NAME, - "agent_info": { - "name": agent.get("name") or "", - "version": agent.get("version") or "", - "model_info": {"name": model}, - }, - # Deliberately empty: a span's status is not a task's outcome, and no - # verifier ran. The walker reads this pair as `unknown`. - "exception_info": {}, - "verifier_result": {}, - "started_at": started, - "finished_at": finished, - "environment_setup": None, - "agent_setup": None, - "agent_execution": ( - {"started_at": started, "finished_at": finished} if started and finished else None), - "verifier": None, - "config": {"environment": {"type": ""}}, - "source_document": {"trace_id": document.get("session_id")}, - } - if tokens: - result["agent_result"] = { - "n_input_tokens": tokens.get("input_tokens", 0), - "n_output_tokens": tokens.get("output_tokens", 0), - "n_cache_tokens": tokens.get("cache_read_tokens", 0), - "cost_usd": None, - } - changed = _dump(os.path.join(trial_dir, "result.json"), result) - changed |= _dump(os.path.join(agent_dir, "trace.json"), document) - return {"trial_dir": trial, "started_at": started, "finished_at": finished, - "model": model, "agent": agent.get("name") or "", "changed": changed} - - -def _trace_id_in(trial_dir: str): - """The trace a trial folder holds: its recorded id, or its trace's own.""" - for path, keys in ((("result.json"), ("source_document", "trace_id")), - (os.path.join("agent", "trace.json"), ("session_id",))): - try: - with open(os.path.join(trial_dir, path), encoding="utf-8") as fh: - value = json.load(fh) - for key in keys: - value = value[key] - except (OSError, ValueError, KeyError, TypeError): - continue - if value is not None: - return str(value) - return None - - -def _write_job(documents: list, out_root: str, job_name: str, command: str, - root: str, skipped: list, sid=None) -> str: - job_dir = os.path.join(out_root, job_name) - ids = [str(doc.get("session_id") or "") for doc in documents] - existing = importers.existing_trials(job_dir, _trace_id_in) - names = importers.unique_names( - [(tid, trial_name_of(doc), trial_name_of(doc, full=True)) for tid, doc in zip(ids, documents)], - *existing) - os.makedirs(job_dir, exist_ok=True) - summaries = [write_trial(doc, job_dir, name) for doc, name in zip(documents, names)] - - starts = sorted(s["started_at"] for s in summaries if s["started_at"]) - ends = sorted(s["finished_at"] for s in summaries if s["finished_at"]) - _dump(os.path.join(job_dir, "result.json"), { - "started_at": starts[0] if starts else None, - "finished_at": ends[-1] if ends else None, - "n_total_trials": len(summaries), - "stats": {"n_errored_trials": 0, "n_running_trials": 0, - "n_pending_trials": 0, "n_retries": 0}, - }) - importers.mark_changed(job_dir, summaries) - agents = sorted({s["agent"] for s in summaries if s["agent"]}) or [""] - models = sorted({s["model"] for s in summaries if s["model"]}) - _dump(os.path.join(job_dir, "config.json"), { - "job_name": job_name, - "harness": NAME, - "command": command, - "agents": [{"name": agents[0], "model_name": models[0] if len(models) == 1 else "", - "kwargs": {}}], - # a folder converted before ids keeps the path its identity was derived from - "datasets": [{"name": NAME, "path": _recorded(importers._config(job_dir)) if sid is None else root, - "n_tasks": len(summaries)}], - "import": {"format": reader.FORMAT, "conventions": reader.CONVENTIONS, - "skipped": skipped}, - "trial_documents": importers.reservations(job_dir, zip(names, ids), *existing), - **importers.recorded_as(sid, root), - }) - # Derived output this importer wholly owns: a trial the export no longer - # produces is stale and would keep being counted. Pruned once - # config.json reserves its name: a refresh cut short before then keeps the folder. - produced = {s["trial_dir"] for s in summaries} - for name in os.listdir(job_dir): - sub = os.path.join(job_dir, name) - if os.path.isdir(sub) and name not in produced: - shutil.rmtree(sub) - return job_dir - - -def convert(root: str, out_root: str, job_name: str = "", - command: str = "") -> list[str]: - """Convert every OTLP/JSON export under *root* into one job directory. - - Traces are grouped across files, one trial each. Files the reader refuses - are listed in the job's ``config.json`` under ``import.skipped`` with their - redacted reasons; when nothing reads, that list is the error. - """ - default = f"{NAME}__{os.path.basename(os.path.abspath(root)) or 'export'}" - root = os.path.realpath(root) # one spelling of the source, whatever the caller's cwd or links - _read(root) # a refused tree is refused before even the lock is written - with importers.locked(out_root): - documents, skipped = _read(root) # read under the lock: a newer conversion is never undone - name, sid = importers.place(out_root, root, default, job_name, NAME) - return [_write_job(documents, out_root, name, command, root, skipped, sid)] - - -def _read(root: str) -> tuple: - """``(documents, refused files)`` of the exports under *root*, or a SystemExit.""" - paths = find_exports(root) - skipped = refused(root) - if not paths: - raise SystemExit(redact( - f"no OTLP/JSON trace exports (resourceSpans) found in {root}" - + ("; refused: " + "; ".join(skipped) if skipped else ""))) - try: - documents = reader.read(paths) - except reader.ReadError as exc: # a file changed under us since find_exports - raise SystemExit(str(exc)) from None - if not documents: - raise SystemExit(redact(f"the OTLP/JSON exports in {root} carry no spans")) - return documents, skipped - - -def _recorded(cfg: dict): - """The export a conversion from before ids was made from.""" - datasets = cfg.get("datasets") - first = datasets[0] if isinstance(datasets, list) and datasets and isinstance(datasets[0], dict) else {} - return first.get("path") if isinstance(first.get("path"), str) else None diff --git a/app/nullius/providers.py b/app/nullius/providers.py index b53ff489f..4841a4998 100644 --- a/app/nullius/providers.py +++ b/app/nullius/providers.py @@ -555,7 +555,7 @@ def list_reasoning(provider: str, model: str, *, opener=None) -> Optional[dict]: return _levels(found) if found else None -# Settings' Test, for each run provider (TypeSafe has no free request): only requests that cost nothing. A +# Settings' Test: only requests that cost nothing. A # model list everywhere; OpenRouter's is public, so its key is asked at its own key-information endpoint. _TESTS_LOCK = threading.Lock() @@ -577,21 +577,27 @@ def test(choice: str, env=None, *, opener=None, clock=time.monotonic) -> dict: ValueError, before any request, when the provider has no test or its settings are incomplete.""" env = os.environ if env is None else env provider, endpoint = split(choice) - if provider not in PROVIDERS: + if provider not in (*PRESETS, "custom"): raise ValueError("This provider has no test.") rec = record(choice, env) if rec["preset"] and not env.get(rec["key"]): raise ValueError("Add the provider key in Settings.") base, key, headers = _where(provider, endpoint, env) + openrouter = base == PRESETS["openrouter"]["base"] models = base + "/models" + ("?limit=1000" if provider == "anthropic" else "") out = {"at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "reached": False, "key": "not tested", "models": None, "ms": 0, "error": ""} start = clock() try: # OpenRouter's model list is public: its key goes to its key endpoint only - out["models"] = len(_models(_get(models, {} if provider == "openrouter" else headers, opener))) + content = _get(models, {} if openrouter else headers, opener) + listing = json.loads(content) + if isinstance(listing, dict) and isinstance(listing.get("models"), list): + listing = {"data": [{"id": row.get("name", "")} for row in listing["models"] if isinstance(row, dict)]} + content = json.dumps(listing).encode() + out["models"] = len(_models(content)) out["reached"] = True - if provider == "openrouter": + if openrouter: _get(base + "/key", headers, opener) out["key"] = "accepted" elif provider != "custom": @@ -600,7 +606,7 @@ def test(choice: str, env=None, *, opener=None, clock=time.monotonic) -> dict: out["key"] = "not checked" else: try: - _get(models, auth("chat", "nullius-wrong-" + secrets.token_hex(8)), opener) + _get(models, {**headers, **auth("messages" if "x-api-key" in headers else "chat", "nullius-wrong-" + secrets.token_hex(8))}, opener) out["key"] = "not checked" except urllib.error.HTTPError as e: e.close() @@ -612,6 +618,8 @@ def test(choice: str, env=None, *, opener=None, clock=time.monotonic) -> dict: out["reached"] = True if e.code in (401, 403): out["key"] = "refused" + elif provider == "custom" and e.code in (404, 405): + out["note"] = "Model listing unavailable; key not verified" else: out["error"] = f"HTTP {e.code}" except urllib.error.URLError as e: @@ -659,7 +667,9 @@ def mark(result: dict) -> str: def said(result: dict) -> str: """A test in one line: what failed, or the key, the model count and the time it took; then when.""" when = str(result.get("at", "")).replace("T", " ")[:16] + " UTC" - if result.get("error"): + if result.get("note"): + head = result["note"] + elif result.get("error"): head = ("" if result.get("reached") else "Not reached: ") + result["error"] elif result.get("key") == "refused": head = "Key refused" diff --git a/app/nullius/runs/uid.py b/app/nullius/runs/uid.py index af56f9e71..53daf4c74 100644 --- a/app/nullius/runs/uid.py +++ b/app/nullius/runs/uid.py @@ -32,11 +32,26 @@ import os import uuid -from nullius import importers +import shlex #: fixed for good: changing one changes every derived identity NS_JOB = uuid.UUID("6f0f3a52-5c1e-4d39-9a2b-6a4c1f0e7d21") +def _recorded_source(cfg): + """Keep identities of previously converted jobs stable without a converter.""" + if cfg.get("harness") == "atif": + try: + words = shlex.split(str(cfg.get("command") or "")) + return words[words.index("nullius.importers.cli") + 1] + except (ValueError, IndexError): + return None + if cfg.get("harness") == "otel": + datasets = cfg.get("datasets") + first = datasets[0] if isinstance(datasets, list) and datasets and isinstance(datasets[0], dict) else {} + return first.get("path") if isinstance(first.get("path"), str) else None + return None + + def _declared(cfg: dict): std = cfg.get("standard") if isinstance(cfg.get("standard"), dict) else {} own = cfg.get("nullius") if isinstance(cfg.get("nullius"), dict) else {} @@ -63,7 +78,7 @@ def facts(job_dir: str, cfg: dict, res: dict): agents = [a for a in cfg.get("agents") or [] if isinstance(a, dict)] if isinstance(cfg.get("harness"), str): # an import from before nullius.source: its folder and recorded source return {"v": 1, "format": cfg["harness"], "folder": os.path.basename(job_dir), - "source": str(importers.recorded(cfg) or "")} + "source": str(_recorded_source(cfg) or "")} start = str(res["started_at"]) if res.get("started_at") else None if std and not res: return None diff --git a/app/nullius/standard/kits/agent-computer-v1/standard.json b/app/nullius/standard/kits/agent-computer-v1/standard.json index 680176615..8652ea270 100644 --- a/app/nullius/standard/kits/agent-computer-v1/standard.json +++ b/app/nullius/standard/kits/agent-computer-v1/standard.json @@ -1,7 +1,7 @@ { "schema": "nullius.benchmark/v1", "key": "agent-computer-v1", - "kit_version": 3, + "kit_version": 1, "label": "Kit: agent.computer/v1", "summary": "Nine checks on a small real desktop, reached through the computer port's MCP server, where the desktop is reached through steps alone once the task is given: four basic - read the screen, click, type, stop at the step budget - and five skills - drag, scroll, recover from an error, several actions in one step, and a button that appears late, seen by looking again with a step. The desktop's own records decide each one.", "family": "agent", diff --git a/app/nullius/standard/kits/agent-search-v1/standard.json b/app/nullius/standard/kits/agent-search-v1/standard.json index d768d40cc..ac08c1bf8 100644 --- a/app/nullius/standard/kits/agent-search-v1/standard.json +++ b/app/nullius/standard/kits/agent-search-v1/standard.json @@ -1,7 +1,7 @@ { "schema": "nullius.benchmark/v1", "key": "agent-search-v1", - "kit_version": 2, + "kit_version": 1, "label": "Kit: agent.search/v1", "summary": "Search a generated HTTP collection from the task environment, distinguish the current source and follow a reference; retrieve the supporting document and cite its exact evidence. Uses the agent\u2019s available tools, including a terminal, with no injected MCP tools.", "family": "agent", diff --git a/app/nullius/standard/kits/agent-tools-v1/standard.json b/app/nullius/standard/kits/agent-tools-v1/standard.json index 8ac7e3eca..216c9536c 100644 --- a/app/nullius/standard/kits/agent-tools-v1/standard.json +++ b/app/nullius/standard/kits/agent-tools-v1/standard.json @@ -1,7 +1,7 @@ { "schema": "nullius.benchmark/v1", "key": "agent-tools-v1", - "kit_version": 2, + "kit_version": 1, "label": "Kit: agent.tools/v1", "summary": "Five checks against one MCP server of twenty tools: two basic - a tool without arguments, one with typed arguments - and three skills - the right tool among decoys, a chain of three, a call refused and corrected.", "family": "agent", diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 87322c2d4..4ac057aab 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -363,7 +363,7 @@ def choices() -> dict: # one entry per benchmark, its default version, which lists the others (``versions``); the fits cover every version defaults = [b for b in d["benchmark"] if b.get("_version") == b.get("_default")] return {"benchmarks": [_with_versions(b) for b in defaults], - # an example (the example memory) is there to read or copy, never to choose + # Entries marked as examples are not offered for runs. "agents": [_other_page(o) for o in d["agent"] + definitions.benchmark_agents(d["benchmark"]) if not o.get("example")], "modules": [_other_page(o) for o in d["module"] if not o.get("example")], "fits": match.table(d["benchmark"], d["agent"], d["module"]), diff --git a/app/nullius/traces/calls.py b/app/nullius/traces/calls.py index aaee14a22..3a9fe783f 100644 --- a/app/nullius/traces/calls.py +++ b/app/nullius/traces/calls.py @@ -133,6 +133,30 @@ def recorded(trial_dir: str) -> int: return len(_record(trial_dir, route_tag(trial_dir, exchanges.tags(folder)))) +def prompt_series(trial_dir: str) -> list[dict]: + """Recorded input per successful agent model call, in start order, without loading message bodies. + + Relay input already includes cache reads and writes. Missing usage is omitted; + side calls and free requests are not steps of the agent's prompt growth. + """ + tag = route_tag(trial_dir, exchanges.tags(store_folder(trial_dir))) + records = sorted(_record(trial_dir, tag), key=lambda r: _number(r.get("t0")) or 0.0) + series, number = [], 0 + for rec in records: + if rec.get("status") != 200 or not rec.get("model") or rec.get("side") or relay._free(str(rec.get("path") or "")): + continue + number += 1 + reply = rec.get("reply") + usage = reply.get("usage") if isinstance(reply, dict) else None + if not isinstance(usage, dict) or type(usage.get("input")) is not int or usage["input"] < 0: + continue + sent = usage["input"] + cached = min(sent, max(0, usage.get("cached", 0))) if type(usage.get("cached")) is int else 0 + output = max(0, usage["output"]) if type(usage.get("output")) is int else 0 + series.append({"step_id": number, "sent": sent, "cached": cached, "new": sent - cached, "completion": output}) + return series + + def signature(trial_dir: str, trajectory_path: str = "") -> tuple: """What a view is read from, by size and time: a view kept for it holds while this is the same.""" folder = store_folder(trial_dir) diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 48c386df9..58e69b641 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -6,7 +6,7 @@ run tree — happens once per change rather than once per page. //workspace.json name, label, roots, created, opened, closed - //imported/ foreign run trees converted to job dirs + //imported/ previously converted job directories //jobs/.json a parsed Job, keyed by the job dir's signature //jobs/counts.json its runs and checks, while its jobs had all ended @@ -97,7 +97,7 @@ class Workspace: created: str opened: str dir: str - job_roots: list = field(default_factory=list) # after imports: what parse walks + job_roots: list = field(default_factory=list) # job directories the parser walks closed: bool = False # closed by the user: a restart leaves it closed @property diff --git a/app/packaging/verify.py b/app/packaging/verify.py index f802b66c6..5a58e79ae 100644 --- a/app/packaging/verify.py +++ b/app/packaging/verify.py @@ -183,11 +183,10 @@ def run(*command, expected=0): backend = json.loads(run(python, '-I', '-c', BACKEND, json.dumps(requirements))) for prefix in ((python, '-I', '-m', 'nullius'), (command,)): assert 'serve' in run(*prefix, '--help') - assert set(json.loads(run(*prefix, 'import', '--list', '--json'))) == {'atif', 'otel'} assert run(*prefix, '--version').strip() == 'nullius ' + backend['version'] for subcommand in ('runs', 'compare', 'standard', 'workspace', 'paths', 'prices', 'migrate'): assert 'usage:' in run(*prefix, subcommand, '--help') - run(*prefix, 'import', root / 'missing', expected=3) + run(*prefix, 'import', root / 'missing', expected=2) locations = json.loads(run(command, 'paths', '--json')) assert all(Path(path).is_relative_to(profile) for path in locations.values()), locations run(command, 'standard', 'new', 'agent', 'packaging-fixture') @@ -200,7 +199,7 @@ def run(*command, expected=0): tool_python = root / 'tools' / 'nullius-eval' / binaries.name / python.name assert run(tool, '--version').strip() == 'nullius ' + backend['version'] assert 'usage:' in run(tool, 'standard', '--help') - assert set(json.loads(run(tool, 'import', '--list', '--json'))) == {'atif', 'otel'} + run(tool, 'import', '--list', '--json', expected=2) package_before = run(tool_python, '-I', '-c', PACKAGE_DIGEST) run(tool_python, '-I', '-c', PROFILE_WRITE) installed_profile = run(tool_python, '-I', '-c', PROFILE_CHECK) diff --git a/app/site/diagrams.py b/app/site/diagrams.py index afbb03ce7..56ca15aa2 100644 --- a/app/site/diagrams.py +++ b/app/site/diagrams.py @@ -279,25 +279,19 @@ def pieces() -> Figure: def path_open() -> Figure: f = Figure('path-open', 640, 432, 'Path 1: open results that exist', - 'Roots given to the runs pages are recognised, converted when foreign, parsed into the ' - 'workspace cache, and the pages read that cache back.') - you, web, imp, par, ws = 80, 200, 320, 440, 560 - for cx in (you, web, imp, par, ws): + 'Job roots are parsed into the workspace cache, and the pages read that cache back.') + you, web, par, ws = 80, 240, 400, 560 + for cx in (you, web, par, ws): f.lifeline(cx, 72, 384) - f.activation(web, 104, 200) - f.activation(imp, 144, 200) - f.activation(par, 224, 280) - f.activation(web, 224, 360) - f.message(you, web - 4, 112, '/IMPORT · ROOTS') - f.message(web + 4, imp - 4, 152, 'RECOGNISED?') - f.message(imp + 4, ws, 192, 'INTO IMPORTED/', 'dashed', at=380) - f.message(web + 4, par - 4, 232, 'PARSE EACH JOB', at=260) - f.message(par + 4, ws, 272, 'PARSE CACHE', 'dashed') - f.message(you, web - 4, 312, '/RUNS /JOB /TRIAL') + f.activation(web, 104, 360) + f.activation(par, 144, 200) + f.message(you, web - 4, 112, 'OPEN WORKSPACE') + f.message(web + 4, par - 4, 152, 'PARSE EACH JOB') + f.message(par + 4, ws, 192, 'PARSE CACHE', 'dashed') + f.message(you, web - 4, 272, '/RUNS /JOB /TRIAL') f.message(web + 4, ws, 352, 'READ · RE-PARSE') f.actor(you, 24, 'You', kind='input') f.actor(web, 24, 'Runs pages', 'web/runs') - f.actor(imp, 24, 'Importers', 'nullius/importers') f.actor(par, 24, 'Parser', 'parse, classify') f.actor(ws, 24, 'Workspace', 'workspaces//', kind='store') f.legend(408, [('arrow', 'Call'), ('dashed', 'Write')]) diff --git a/app/site/mkdocs.yml b/app/site/mkdocs.yml index da2e3e848..fdc9daff3 100644 --- a/app/site/mkdocs.yml +++ b/app/site/mkdocs.yml @@ -101,7 +101,6 @@ nav: - CLI: - cli/README.md - Read jobs: cli/read-jobs.md - - Import a run: cli/import.md - Task flags: cli/flags.md - Definitions: cli/definitions.md - Run a benchmark: cli/run.md diff --git a/app/static/builder/command-builder.css b/app/static/builder/command-builder.css index 79b60858c..349cd4a00 100644 --- a/app/static/builder/command-builder.css +++ b/app/static/builder/command-builder.css @@ -198,8 +198,8 @@ /* Dataset counts and proof badges occupy separate, consistent rows. */ #nullius-builder .std-optgrid:has(> [data-std-dataset]) { grid-template-columns: repeat(auto-fill, minmax(min(100%, 300px), 1fr)); } -#nullius-builder [data-std-dataset] .nb-tile-foot { display: grid; grid-template-columns: max-content max-content; align-items: start; gap: 8px; } -#nullius-builder [data-std-dataset] .nb-tile-foot > span:first-child:not([class]) { grid-column: 1 / -1; margin: 0 0 2px; } +#nullius-builder [data-std-dataset] .nb-tile-foot { display: flex; flex-wrap: wrap; align-items: start; gap: 8px; } +#nullius-builder [data-std-dataset] .nb-tile-foot > span:first-child:not([class]) { flex-basis: 100%; margin: 0 0 2px; } #nullius-builder [data-std-dataset] .std-ctl { justify-self: start; flex-wrap: nowrap; white-space: nowrap; } #nullius-builder .std-ctls { display: grid; justify-items: start; gap: 5px; min-width: 0; } diff --git a/app/static/catalogue/agent-versions.js b/app/static/catalogue/agent-versions.js new file mode 100644 index 000000000..bd3e55f97 --- /dev/null +++ b/app/static/catalogue/agent-versions.js @@ -0,0 +1,8 @@ +/* Each card's version picks the same definition and proofs as its detail page. */ +document.addEventListener('change', (event) => { + const select = event.target.closest('[data-agent-version]'); + if (!select) return; + const url = new URL(location.href); + url.searchParams.set('v:' + select.dataset.agentVersion, select.value); + location.assign(url); +}); diff --git a/app/static/catalogue/agents/README.md b/app/static/catalogue/agents/README.md index 5787f07d5..1d0ae8fc3 100644 --- a/app/static/catalogue/agents/README.md +++ b/app/static/catalogue/agents/README.md @@ -1,8 +1,8 @@ # Agent marks The catalogue, entry pages, sidebar, Nullius run builder and a trial's head share `marks.json`. -Keys are agent catalogue keys; versions use the same mark. Unknown agents and -Modules retain their initial as a fallback. Files are bundled locally; +Keys are agent catalogue keys; versions use the same mark. Unknown agents retain their initial as a fallback. Module marks live beside this +folder in `../modules/`. Files are bundled locally; rendering a logo makes no request to its upstream website. | Agent | Asset source | @@ -16,6 +16,10 @@ rendering a logo makes no request to its upstream website. | mini-swe-agent | [Official square mascot](https://github.com/SWE-agent/mini-swe-agent/blob/04d809ceab9df28f9adaed044884180159172930/docs/assets/mini_square.svg) | | OpenCode | [Official favicon](https://github.com/anomalyco/opencode/blob/66f1fa816d583fdfa0f52eff1c7d56c8458b1c4e/packages/ui/src/assets/favicon/favicon.svg) | | Terminus 2 | Harbor's mark in `../../brand/marks.svg`, identifying its maker | +| hermes | [Official favicon](https://github.com/NousResearch/hermes-agent/blob/d3fc37d081d254498a46226bdd2670f04fd082ad/website/static/img/favicon.svg) | +| kilo-code | [Official favicon](https://github.com/Kilo-Org/kilocode/blob/79951cd6e27bb3b978b46a3955ec1bb297b798ef/packages/kilo-docs/public/favicon/favicon.svg) | +| openclaw | [Official favicon](https://github.com/openclaw/openclaw/blob/8023e739d66efbb75bfdfd70c11a89de7511e812/ui/public/favicon.svg) | +| pi | [Official favicon](https://github.com/badlogic/pi-mono/blob/d5f8a9727909a021e414f64e6030048cbf3b53de/apps/p2/public/icons/favicon.svg) | Upstream assets are copied unchanged from these pinned sources. These marks belong to their respective owners; inclusion does not imply endorsement. diff --git a/app/static/catalogue/agents/hermes.svg b/app/static/catalogue/agents/hermes.svg new file mode 100644 index 000000000..0f7f871e8 --- /dev/null +++ b/app/static/catalogue/agents/hermes.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/app/static/catalogue/agents/kilo-code.svg b/app/static/catalogue/agents/kilo-code.svg new file mode 100644 index 000000000..038ae57b6 --- /dev/null +++ b/app/static/catalogue/agents/kilo-code.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/static/catalogue/agents/marks.json b/app/static/catalogue/agents/marks.json index 14ec5c860..c57d969ed 100644 --- a/app/static/catalogue/agents/marks.json +++ b/app/static/catalogue/agents/marks.json @@ -7,5 +7,9 @@ "claude-code": "brand/marks.svg#anthropic", "terminus-2": "brand/marks.svg#harbor", "digitalmate": "catalogue/agents/digitalmate.svg", - "swe-agent": "catalogue/agents/swe-agent.ico" + "swe-agent": "catalogue/agents/swe-agent.ico", + "hermes": "catalogue/agents/hermes.svg", + "kilo-code": "catalogue/agents/kilo-code.svg", + "openclaw": "catalogue/agents/openclaw.svg", + "pi": "catalogue/agents/pi.svg" } diff --git a/app/static/catalogue/agents/openclaw.svg b/app/static/catalogue/agents/openclaw.svg new file mode 100644 index 000000000..dfa44629a --- /dev/null +++ b/app/static/catalogue/agents/openclaw.svg @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/static/catalogue/agents/pi.svg b/app/static/catalogue/agents/pi.svg new file mode 100644 index 000000000..03e351806 --- /dev/null +++ b/app/static/catalogue/agents/pi.svg @@ -0,0 +1 @@ + diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index 489f4fa40..b31279998 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -67,9 +67,9 @@ tr:has([data-pick]:not(:disabled)) { cursor: pointer; } @container (max-width: 391.9px) { .bench-stats:has(> :nth-child(5)) { --cols: 3; } } @container (max-width: 471.9px) { .bench-stats:has(> :nth-child(6)) { --cols: 3; } } .bench-stats > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; } -.bench-stats dd { margin: 0; font-size: 18px; font-weight: 500; font-variant-numeric: tabular-nums; } +.bench-stats dd { margin: 0; font-size: 16px; font-weight: 500; font-variant-numeric: tabular-nums; } .bench-stats dd.word { font-size: 14px; line-height: 1.35; padding-top: 3px; } -.bench-stats dt { font-size: 12px; color: var(--text-faint); } /* a long label wraps between words; its longest word sizes its column */ +.bench-stats dt { font-size: 12px; color: var(--text-dim); white-space: nowrap; } /* labels stay on one line */ .bench-card-blocker { font-size: 13px; line-height: 1.5; color: var(--text-dim); } .bench-none { color: var(--text-dim); font-size: 14px; } @@ -118,7 +118,7 @@ tr:has([data-pick]:not(:disabled)) { cursor: pointer; } @media (max-width: 640px) { .bench-sources .src-by { padding-left: 0; } } .bench-cols { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 30px; } .bench-cols.one { grid-template-columns: minmax(0, 1fr); } -.bench-list { list-style: none; margin: 0; padding: 0; border-top: 1px solid var(--border-soft); } +.bench-list { list-style: none; margin: 0; padding: 0; border-top: 1px solid var(--border-soft); overflow-wrap: anywhere; } .bench-list li { padding: 12px 0; border-bottom: 1px solid var(--border-soft); font-size: 14px; line-height: 1.55; } .bench-bibtex { margin: 0; white-space: pre; overflow-x: auto; font: 12.5px/1.6 var(--mono); color: var(--text-dim); background: var(--surface); border: 1px solid var(--border-soft); border-radius: 10px; padding: 16px 18px; } .bench-glance { margin: 0; display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 12px 16px; padding: 18px; border-radius: 12px; background: var(--surface); border: 1px solid var(--border-soft); font-size: 13px; } @@ -132,20 +132,6 @@ tr:has([data-pick]:not(:disabled)) { cursor: pointer; } .bench-cols { grid-template-columns: minmax(0, 1fr); } } -/* Import paths and folders. */ -.setup-wrap.import-setup { max-width: 820px; margin: 0; text-align: left; } -.import-setup .subtitle { font-size: 14px; line-height: 1.8; color: var(--text-dim); justify-content: flex-start; max-width: 70ch; } -.import-setup .setup-card { border-radius: 9px; padding: 28px 30px; margin-top: 27px; background: var(--surface); } -.import-setup .field-label { color: var(--text); font-size: 13px; text-transform: none; letter-spacing: 0; font-weight: 500; display: block; margin-bottom: 10px; } -.import-setup .divider { color: var(--text-dim); font-size: 11px; margin: 26px 0; } -.import-setup .drop { background: var(--bg); border: 1px dashed var(--border); border-radius: 8px; padding: 32px 23px; line-height: 1.8; } -.import-setup .drop strong { color: var(--text); font-weight: 500; }.import-setup .drop .hint { color: var(--text-dim); font-size: 12px; margin-top: 6px; } -.import-setup .drop.over { background: var(--accent-soft); border-color: var(--accent); } -.import-setup .submit-row { margin-top: 23px; }.import-setup .submit-row .primary { padding: 11px 25px; } -.import-next { display: flex; gap: 15px; flex-wrap: wrap; color: var(--text-dim); font-size: 13px; border-top: 1px solid var(--border-soft); padding-top: 23px; margin-top: 25px; } -@media(max-width:640px){.setup-wrap.import-setup{margin:0}.import-setup .setup-card{padding:22px 18px}.import-setup .drop{padding:26px 17px}.import-setup .field-label{font-size:12px}.import-setup .path-row input{font-size:16px}} -@media(pointer:coarse){.import-setup .add-btn,.import-setup .row-x{min-width:44px;min-height:44px}} - /* Settings: what testing a host said. */ .settings-page .settings-test { font-size: 12px; color: var(--text-dim); } .settings-page .settings-test:empty { display: none; } @@ -233,8 +219,8 @@ tr:has([data-pick]:not(:disabled)) { cursor: pointer; } .std-problems strong { color: var(--bad); } .std-card { padding: 22px; border-radius: 12px; background: var(--surface); border: 1px solid var(--border-soft); margin: 0 0 18px; } .std-mark { width: 40px; height: 40px; border-radius: 10px; display: grid; place-items: center; background: var(--accent-soft); color: var(--accent); font: 500 18px/1 var(--mono); flex: none; } -.std-tag { padding: 2px 9px; border: 1px solid var(--border); border-radius: 5px; font: 11px/1.5 var(--mono); color: var(--text-dim); } -.std-versions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 4px 0 14px; } +.std-tag { padding: 2px 9px; border: 1px solid var(--border); border-radius: 5px; font: 11px/1.5 var(--mono); color: var(--text); background: var(--surface-2); } +.std-versions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 16px 0 14px; } .std-versions > span { font-size: 12px; color: var(--text-dim); margin-right: 4px; } .std-versions a { display: flex; flex-direction: column; padding: 6px 12px; border: 1px solid var(--border); border-radius: 8px; color: inherit; text-decoration: none; } .std-versions a b { font: 500 13px/1.3 var(--mono); } @@ -373,7 +359,7 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli /* Check details sit in their own card below the kit definition. */ .kit-checks h2 { font-size: 16px; } :is(.kit-check, .kit-shared-source) { padding: 14px 0; border-top: 1px solid var(--border); } -.kit-check-heading { display: grid; grid-template-columns: 16px minmax(0, 1fr) 10ch 8ch; align-items: center; gap: 8px; } +.kit-check-heading { display: grid; grid-template-columns: 16px minmax(max-content, 1fr) max-content max-content; align-items: center; gap: 8px; white-space: nowrap; overflow-x: auto; } .kit-check-name { margin: 0; font-size: 15px; text-transform: none; letter-spacing: normal; } .kit-check-heading code { color: var(--muted); font-size: 12px; } .kit-check p { margin: 6px 0 0; overflow-wrap: anywhere; } @@ -384,11 +370,6 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli .kit-shared-source { margin-top: 0; } .kit-check-heading .std-tag { justify-self: start; } -@media (max-width: 560px) { - .kit-check-heading { grid-template-columns: 16px minmax(0, 1fr) max-content; } - .kit-check-name { grid-column: 2 / -1; } - .kit-check-heading code { grid-column: 2; } -} .kit-check-source h3, .kit-check-source h4 { margin: 12px 0 6px; font-size: 13px; text-transform: none; letter-spacing: normal; } .kit-check-source small { font-weight: normal; color: var(--text-dim); } .kit-check-source pre { max-height: 420px; overflow: auto; padding: 12px; border: 1px solid var(--border); border-radius: 8px; font-size: 12px; white-space: pre-wrap; overflow-wrap: anywhere; } @@ -510,3 +491,15 @@ a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underli .tasks-question-list { max-height: 20rem; overflow-y: auto; } .tasks-table tr:has(.tasks-questions) > .tasks-tick { vertical-align: top; } + +.bench-stats .scorer { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; } +.std-skills-list { margin: .75rem 0 0; } +.std-skills-list ul { padding-left: 1.25rem; } +.std-fidelity-fields { display: flex; flex-wrap: wrap; gap: .35rem .75rem; padding: 0; list-style: none; } + +.agent-card-version { display: flex; min-width: 0; } +.agent-card-version .ui-select-trigger { width: max-content; max-width: 100%; white-space: nowrap; } +@container (max-width: 320px) { + :is(#agents, #capabilities) .bench-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } + :is(#agents, #capabilities) .bench-stats > div:nth-child(3) { grid-column: 1 / -1; margin-top: 6px; } +} diff --git a/app/static/catalogue/modules/README.md b/app/static/catalogue/modules/README.md new file mode 100644 index 000000000..c9a380411 --- /dev/null +++ b/app/static/catalogue/modules/README.md @@ -0,0 +1,5 @@ +# Module marks + +Mem0: official organization avatar from https://github.com/mem0ai +(downloaded from https://avatars.githubusercontent.com/u/137054526?s=200&v=4). +Used to identify the upstream Module. diff --git a/app/static/catalogue/modules/mem0.png b/app/static/catalogue/modules/mem0.png new file mode 100644 index 000000000..48e642b05 Binary files /dev/null and b/app/static/catalogue/modules/mem0.png differ diff --git a/app/static/controls.js b/app/static/controls.js index 9c372beda..be889ae0a 100644 --- a/app/static/controls.js +++ b/app/static/controls.js @@ -1,8 +1,8 @@ // Keep real selects as form/state owners; render a consistent, keyboard-accessible menu. (() => { const controls = new Map(); let active = null, serial = 0, scheduled = false; - function optionLabel(target, option) { - target.textContent = option?.dataset.label || option?.textContent || 'Select…'; + function optionLabel(target, option, compact = false) { + target.textContent = (compact && option?.dataset.shortLabel) || option?.dataset.label || option?.textContent || 'Select…'; const origin = option?.dataset.origin; if (!['official', 'experiment'].includes(origin)) return; const label = document.createElement('span'); @@ -106,9 +106,9 @@ select.addEventListener('change', () => { button.removeAttribute('aria-invalid'); scan(); }); } const option = select.selectedOptions[0]; - const signature = JSON.stringify([option?.textContent, option?.dataset.label, option?.dataset.origin]); + const signature = JSON.stringify([option?.textContent, option?.dataset.label, option?.dataset.origin, option?.dataset.shortLabel]); if (button.dataset.optionLabel !== signature) { - optionLabel(button, option); + optionLabel(button, option, true); button.dataset.optionLabel = signature; } if ('placeholder' in (option?.dataset || {})) button.setAttribute('data-placeholder', ''); else button.removeAttribute('data-placeholder'); // nothing chosen: a default, shown as a placeholder is diff --git a/app/static/runs/board.css b/app/static/runs/board.css index 357670203..33add1638 100644 --- a/app/static/runs/board.css +++ b/app/static/runs/board.css @@ -236,6 +236,12 @@ .rp .board:not(.no-judge) .b-tot .kv > .k { grid-column: 1; } } @container board (max-width: 760px) { + .rp .board:not(.no-judge) .b-tot { grid-template-columns: max-content minmax(0, 1fr); } + .rp .board:not(.no-judge) .b-tot .token-split { grid-column: 1 / -1; height: auto; } + .rp .b-tot .token-split { min-width: 0; max-width: 100%; margin-left: 0; } + .rp .token-split .pop > summary { white-space: normal; } + .rp .token-split .popm { max-width: calc(100vw - 64px); box-sizing: border-box; white-space: normal; } + .rp .board, .rp .board.no-judge, .rp .board:not(.no-judge) { grid-template-columns: minmax(0, 1fr); grid-template-areas: "rate" "out" "judge" "tot"; grid-template-rows: none; } .rp .lab .aside { gap: 10px; } .rp .b-judge .lab { flex-wrap: wrap; height: auto; min-height: 44px; padding-block: 8px; } @@ -352,7 +358,7 @@ .rp .pick, .rp .pick-why { margin-left: auto; } .rp .pick { display: inline-flex; align-items: center; gap: 8px; flex-wrap: wrap; } .rp .pick-n { white-space: nowrap; } -.rp .pick-row { float: left; margin: 4px 8px 0 0; accent-color: var(--accent); } +.rp :is(.pick-row, .pick-group) { float: left; margin: 4px 8px 0 0; accent-color: var(--accent); } .rp .pick-row + .task { display: block; overflow: hidden; } /* a name that wraps stays beside its tick */ .rp .tt:has(.pick-row) td:first-child { min-width: 172px; } /* the tick's room, beside the name's */ /* a task with no result: a hollow mark, no outcome's colour */ @@ -383,10 +389,10 @@ dialog.std-how.rerun-ask { width: min(520px, calc(100vw - 32px)); } .rp .more > details > summary:hover { color: var(--text); } .rp .more summary .end { margin-left: auto; display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 4px 12px; font-size: 12px; color: var(--text-faint); } .rp .more summary .end .off { font: 11.5px var(--mono); color: var(--text); } -.rp .more > details[open] { grid-column: 1 / -1; } +.rp .more > details { grid-column: 1 / -1; } .rp .rcmd { display: flex; align-items: flex-start; gap: 10px; margin: 10px 0 6px; } .rp .rcmd code { flex: 1; min-width: 0; white-space: pre-wrap; padding: 7px 10px; border-radius: 6px; background: var(--rail); border: 1px solid var(--hair); font: 11.5px/1.5 var(--mono); color: var(--text-dim); overflow-wrap: anywhere; } -.rp dl.gl { margin: 12px 0 4px; display: grid; grid-template-columns: 13rem minmax(0, 54rem); gap: 10px 20px; font-size: 12.5px; } +.rp dl.gl { margin: 12px 0 4px; display: grid; grid-template-columns: 13rem minmax(0, 54rem); gap: 12px 20px; } .rp dl.gl dt { color: var(--text); display: flex; gap: 8px; align-items: baseline; align-self: start; } .rp dl.gl dt .sw { align-self: center; flex: none; } .rp dl.gl dd { margin: 0; color: var(--text-dim); } diff --git a/app/static/runs/board.js b/app/static/runs/board.js index 3c3767c5f..13315eecd 100644 --- a/app/static/runs/board.js +++ b/app/static/runs/board.js @@ -39,7 +39,7 @@ groups.forEach(g => { g.head.hidden = !g.rows.some(r => r.matched); g.btn.setAttribute('aria-expanded', String(g.open)); }); } groups.forEach(g => g.head.addEventListener('click', e => { - if (e.target.closest('a')) return; + if (e.target.closest('a, input')) return; g.open = g.chosen = !g.open; reveal(); if (g.open && !matchMedia('(prefers-reduced-motion: reduce)').matches) g.rows.forEach(r => { if (!r.hidden) r.animate([{ opacity: 0, transform: 'translateY(-4px)' }, { opacity: 1, transform: 'none' }], { duration: 240, easing: 'cubic-bezier(.2, 0, 0, 1)' }); }); @@ -181,7 +181,20 @@ const tasks = n => n + (n === 1 ? ' task' : ' tasks'); const where = $('p.muted', ask), again = where.textContent; const recount = () => { const c = chosen(), n = c.length; pickN.textContent = n + ' chosen'; go.disabled = !n; - go.textContent = n && c.every(first) ? 'Run selected' : 'Run selected again'; }; + go.textContent = n && c.every(first) ? 'Run selected' : 'Run selected again'; + groups.forEach(g => { + const box = $('.pick-group', g.head), children = g.rows.map(r => $('.pick-row', r)).filter(Boolean); + if (!box) return; + const selected = children.filter(x => x.checked).length; + box.checked = children.length > 0 && selected === children.length; + box.indeterminate = selected > 0 && selected < children.length; + }); + }; + groups.forEach(g => $('.pick-group', g.head)?.addEventListener('change', event => { + g.rows.forEach(r => { const box = $('.pick-row', r); if (box) box.checked = event.target.checked; }); + recount(); + })); + recount(); ticks.forEach(x => x.addEventListener('change', recount)); $('#pick-shown').addEventListener('click', () => { rows.forEach(r => { const x = $('.pick-row', r); if (x && r.matched) x.checked = true; }); recount(); }); // the rest, or a set's tasks not yet run: those rows ticked alone, then the same question diff --git a/app/static/runs/launches.css b/app/static/runs/launches.css index 86d14d407..9091f1774 100644 --- a/app/static/runs/launches.css +++ b/app/static/runs/launches.css @@ -1,9 +1,5 @@ /* The Runs page: runs grouped by the launch that made them. A launch is one block - its task checks, its agents on one 0-100% scale, raw as a tick on the adjusted bar - and the flat table is the second view. */ -.runs-glance { display: flex; flex-wrap: wrap; gap: 4px 16px; margin: 0 0 1rem; font-size: 13px; color: var(--text-dim); } -.runs-glance b { color: var(--text); font-weight: 500; } -.runs-glance .st-paused b, .runs-glance .st-stopping b { color: var(--patch_failed_tests); } -.runs-glance .st-stopped b, .runs-glance .st-failed b, .runs-glance .st-not b { color: var(--bad); } /* The view toggle leads the outcome chips' row; the chips wrap beside it, so it never moves as they change. */ .runs-filters { display: flex; align-items: flex-start; gap: .45rem .9rem; margin-bottom: 1.5rem; } @@ -80,6 +76,7 @@ dialog.std-how.launch-delete { width: min(520px, calc(100vw - 32px)); } @media (max-width: 900px) { .launch-agents .lh-more { display: none; } } @media (max-width: 640px) { .launch-agents .lh-state, .launch-agents .lh-mix { display: none; } + .launch-agents .la-who { min-width: 170px; } .launch-when, .lc-verdict { margin-left: 0; } .la-rate { min-width: 120px; grid-template-columns: 2.8em minmax(50px, 1fr); } } diff --git a/app/static/runs/path-suggestions.js b/app/static/runs/path-suggestions.js deleted file mode 100644 index dd608247b..000000000 --- a/app/static/runs/path-suggestions.js +++ /dev/null @@ -1,119 +0,0 @@ -(() => { - const list = document.getElementById('path-list'); - const menu = document.getElementById('path-suggestions'); - const csrf = document.querySelector('#pathform [name=csrf]').value; - let field = null, timer, request, index = -1; - - function close() { - clearTimeout(timer); - request?.abort(); - request = null; - menu.hidden = true; - menu.replaceChildren(); - index = -1; - if (field) { - field.setAttribute('aria-expanded', 'false'); - field.removeAttribute('aria-activedescendant'); - } - } - - function prepare(input) { - input.setAttribute('role', 'combobox'); - input.setAttribute('aria-autocomplete', 'list'); - input.setAttribute('aria-controls', menu.id); - input.setAttribute('aria-expanded', 'false'); - input.removeAttribute('aria-activedescendant'); - } - list.querySelectorAll('input').forEach(prepare); - - function highlight(next) { - index = next; - [...menu.children].forEach((row, i) => { - row.classList.toggle('is-active', i === index); - row.setAttribute('aria-selected', String(i === index)); - }); - const row = menu.children[index]; - field.setAttribute('aria-activedescendant', row.id); - // Scroll the menu only, keeping the page and the input still. - if (row.offsetTop < menu.scrollTop) menu.scrollTop = row.offsetTop; - if (row.offsetTop + row.offsetHeight > menu.scrollTop + menu.clientHeight) - menu.scrollTop = row.offsetTop + row.offsetHeight - menu.clientHeight; - } - - function choose(row) { - field.value = row.dataset.path; - field.dispatchEvent(new Event('input', {bubbles: true})); - } - - function suggest(input, delay = 180, edge = 0) { - close(); - field = input; - prepare(input); - const value = input.value; - if (!value.trim()) return; - timer = setTimeout(async () => { - const controller = new AbortController(); - request = controller; - try { - const response = await nulliusFetch(list.dataset.suggestionsUrl, { - method: 'POST', signal: controller.signal, - headers: {'X-CSRF-Token': csrf}, body: new URLSearchParams({path: value}) - }); - if (!response.ok) return; - const data = await response.json(); - if (controller.signal.aborted || field !== input || input.value !== value || document.activeElement !== input) return; - if (!data.paths.length) return; - menu.replaceChildren(...data.paths.map((path, i) => { - const row = document.createElement('div'); - row.className = 'ui-select-option'; - row.id = `${menu.id}-${i}`; - row.setAttribute('role', 'option'); - row.setAttribute('aria-selected', 'false'); - row.setAttribute('aria-label', path); - row.dataset.path = path; - row.title = path; - const separator = path.slice(-1); - row.textContent = path.slice(0, -1).split(separator).pop() + separator; - return row; - })); - const rect = input.getBoundingClientRect(); - const below = window.innerHeight - rect.bottom - 12; - const above = rect.top - 12; - const up = below < 150 && above > below; - menu.style.left = `${rect.left}px`; - menu.style.width = `${rect.width}px`; - menu.style.maxHeight = `${Math.min(260, Math.max(0, up ? above : below))}px`; - menu.style.top = up ? 'auto' : `${rect.bottom + 4}px`; - menu.style.bottom = up ? `${window.innerHeight - rect.top + 4}px` : 'auto'; - menu.hidden = false; - field.setAttribute('aria-expanded', 'true'); - if (edge) highlight(edge < 0 ? menu.children.length - 1 : 0); - } catch (_) { /* Typing can cancel a pending lookup; the path remains editable. */ } - }, delay); - } - - list.addEventListener('input', e => { if (e.target.matches('input')) suggest(e.target); }); - list.addEventListener('focusin', e => { if (e.target.matches('input')) suggest(e.target); }); - list.addEventListener('focusout', close); - list.addEventListener('keydown', e => { - if (!e.target.matches('input')) return; - if (e.key === 'Escape') { close(); e.stopPropagation(); return; } - if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { - e.preventDefault(); - const direction = e.key === 'ArrowDown' ? 1 : -1; - if (menu.hidden) { suggest(e.target, 0, direction); return; } - highlight(index < 0 ? (direction < 0 ? menu.children.length - 1 : 0) - : (index + direction + menu.children.length) % menu.children.length); - } else if (e.key === 'Enter' && !menu.hidden && index >= 0) { - e.preventDefault(); - choose(menu.children[index]); - } - }); - menu.addEventListener('pointerdown', e => e.preventDefault()); - menu.addEventListener('click', e => { - const row = e.target.closest('[role=option]'); - if (row) choose(row); - }); - window.addEventListener('resize', () => { if (!menu.hidden) close(); }); - document.addEventListener('scroll', e => { if (!menu.hidden && !menu.contains(e.target)) close(); }, true); -})(); diff --git a/app/static/runs/start.css b/app/static/runs/start.css index e8692b4ec..75d1307df 100644 --- a/app/static/runs/start.css +++ b/app/static/runs/start.css @@ -1,5 +1,4 @@ -/* Runs with no workspace open: build a run, or bring the ones made elsewhere, - or open a workspace already here. */ +/* Build a run or open an existing workspace. */ .start { width: 100%; max-width: 1440px; margin: 0 auto; display: flex; flex-direction: column; gap: 28px; } .start > .page-head { margin-bottom: calc(var(--head-gap) - 28px); } /* the column's gap is part of the head's */ .start-ways { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 18px; } diff --git a/app/static/settings/autosave.js b/app/static/settings/autosave.js index 7cd43b8f1..7133433a9 100644 --- a/app/static/settings/autosave.js +++ b/app/static/settings/autosave.js @@ -8,6 +8,11 @@ const snapshot = () => new Map(new FormData(form)); let saved = snapshot(), pending = null; const changes = current => [...current].filter(([key, value]) => !['csrf', 'embedded'].includes(key) && value !== (saved.get(key) ?? '')); + // Editors with Done/Add controls keep their drafts out of unrelated saves. + const savable = (current, editor) => changes(current).filter(([key]) => { + const card = form.elements.namedItem(key)?.closest?.('[data-provider-card], [data-key-new], [data-key-card][data-key-kind=agent]'); + return !card || card === editor; + }); function say(message, error = false, retryable = false) { status.textContent = message; retry.hidden = !retryable; @@ -17,9 +22,9 @@ function notify(message) { window.nulliusNotify(message, {key: 'settings'}); } - async function write() { + async function write(editor) { const current = snapshot(); - const changed = changes(current); + const changed = savable(current, editor); if (!changed.length) return true; const body = new FormData(); body.set('csrf', current.get('csrf')); @@ -130,16 +135,16 @@ form.removeAttribute('aria-busy'); } } - async function flush() { - if (pending) { const ok = await pending; return ok ? flush() : false; } - if (!changes(snapshot()).length) { say(''); return true; } - pending = write(); + async function flush(editor = null) { + if (pending) { const ok = await pending; return ok ? flush(editor) : false; } + if (!savable(snapshot(), editor).length) { say(''); return true; } + pending = write(editor); let ok; try { ok = await pending; } finally { pending = null; } - return ok && changes(snapshot()).length ? flush() : ok; + return ok && savable(snapshot(), editor).length ? flush(editor) : ok; } - // rebase: the form as it is now is what the file holds (a part of the page replaced from a save of its own) - window.nulliusSettings = {flush, dirty: () => changes(snapshot()).length > 0, rebase: () => { saved = snapshot(); }}; + // Rebase fields saved separately, preserving drafts in explicit-save editors. + window.nulliusSettings = {flush, dirty: () => changes(snapshot()).length > 0, rebase: () => { for (const [key, value] of savable(snapshot(), null)) saved.set(key, value); }}; // Replace, type, then Keep: moving to Keep blurs the input, whose change // would save the text Keep is about to throw away. A change whose focus // stays in the field (Keep, or Remove on the way to it) waits until focus @@ -147,7 +152,7 @@ const replacing = input => input.name?.startsWith('value:') && !input.hidden && input.closest('.st-field')?.querySelector('[data-replace]') ? input.closest('.st-field') : null; form.addEventListener('change', event => { - if (event.target.closest('[data-key-new]')) return; // Add/Cancel or leaving the key editor owns this draft. + if (event.target.closest('[data-key-new]')) return; // Add/Cancel owns this draft. const field = replacing(event.target); if (!field) { void flush(); return; } setTimeout(() => { diff --git a/app/static/settings/custom-keys.js b/app/static/settings/custom-keys.js index 5d532d7f6..e07b79b13 100644 --- a/app/static/settings/custom-keys.js +++ b/app/static/settings/custom-keys.js @@ -56,7 +56,7 @@ if (toggle) { const card = toggle.closest('[data-key-card]'); const open = toggle.getAttribute('aria-expanded') !== 'true'; - if (!open && card.dataset.keyKind === 'agent' && window.nulliusSettings && !await window.nulliusSettings.flush()) return; + if (!open && card.dataset.keyKind === 'agent' && window.nulliusSettings && !await window.nulliusSettings.flush(card)) return; // A save may replace the agent card while flush resolves. if (!card.isConnected) { add?.focus({preventScroll: true}); return; } if (!open && card.dataset.keyKind === 'benchmark') card.querySelectorAll('input').forEach(input => { input.value = ''; }); @@ -70,17 +70,9 @@ } if (event.target.closest('[data-key-new-cancel]')) closeNew(); if (event.target.closest('[data-key-new-save]')) { - if (window.nulliusSettings && await window.nulliusSettings.flush()) add.focus({preventScroll: true}); + if (window.nulliusSettings && await window.nulliusSettings.flush(newCard())) add.focus({preventScroll: true}); } }); - // Add and Cancel control this draft. Moving within it must not save before Cancel runs. - section.addEventListener('focusout', event => { - const panel = event.target.closest('[data-key-new]'); - if (!panel || panel.contains(event.relatedTarget)) return; - setTimeout(() => { - if (panel.isConnected && !panel.hidden && !panel.contains(document.activeElement)) void window.nulliusSettings?.flush(); - }, 0); - }); document.addEventListener('nullius-settings-saved', () => { // Autosave replaces AGENT_KEYS, so initialise new nodes rather than retaining old cards. section.querySelectorAll('#AGENT_KEYS [data-key-card]:not([data-key-ready])').forEach(card => editor(card, false, false)); @@ -88,12 +80,33 @@ const empty = section.querySelector('[data-keys-empty]'); if (empty) empty.hidden = cards().length > 0; }); + const search = section.querySelector('[data-key-search]'); + function filterKeys() { + const query = search.value.trim().toLowerCase(); + cards().forEach(card => { + const group = card.closest('.st-key-group'); + const label = (group?.querySelector('summary').textContent || '') + ' ' + card.querySelector('h3').textContent; + card.hidden = !label.toLowerCase().includes(query); + }); + section.querySelectorAll('.st-key-group').forEach(group => { + group.hidden = ![...group.querySelectorAll('[data-key-card]')].some(card => !card.hidden); + if (query && !group.hidden) group.open = true; + }); + section.querySelector('[data-key-no-results]').hidden = !query || cards().some(card => !card.hidden); + } + search.addEventListener('input', filterKeys); + document.addEventListener('nullius-settings-saved', filterKeys); function fromHash() { let id; try { id = decodeURIComponent(location.hash.slice(1)); } catch { return; } const target = document.getElementById(id); + if (target?.matches('details.st-key-group')) target.open = true; const card = target?.closest('[data-key-card]'); - if (card && section.contains(card)) editor(card, true, false); + if (card && section.contains(card)) { + const group = card.closest("details.st-key-group"); + if (group) group.open = true; + editor(card, true, false); + } } window.addEventListener('hashchange', fromHash); initialise(); fromHash(); diff --git a/app/static/settings/modal.css b/app/static/settings/modal.css index 959be92a8..905a0f459 100644 --- a/app/static/settings/modal.css +++ b/app/static/settings/modal.css @@ -23,6 +23,7 @@ body:has(.settings-modal[open]) { overflow: hidden; } .settings-embedded main { padding: 16px; } .settings-embedded .st-layout { flex-direction: column; } .settings-embedded .st-index { flex: 0 1 auto; max-height: 38%; width: 100%; box-sizing: border-box; } + .settings-embedded .st-index-ready { flex: none; max-height: none; overflow: visible; } .settings-embedded .st-main { width: 100%; flex: 1 1 0; } } diff --git a/app/static/settings/modal.js b/app/static/settings/modal.js index 3b22b97fd..1cd084c30 100644 --- a/app/static/settings/modal.js +++ b/app/static/settings/modal.js @@ -88,6 +88,15 @@ return true; } window.nulliusOpenSettings = open; + const entry = new URL(location.href); + if (entry.searchParams.get('settings') === '1') { + const target = '/settings' + entry.hash; + entry.searchParams.delete('settings'); + entry.hash = ''; + history.replaceState(null, '', entry); + open(target, document.querySelector('a[href="/settings"]')); + } + document.addEventListener('click', event => { const link = event.target.closest('a[href]'); if (!link || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || link.target || link.download) return; diff --git a/app/static/settings/navigation.js b/app/static/settings/navigation.js index cd9a118d6..1d3eba77e 100644 --- a/app/static/settings/navigation.js +++ b/app/static/settings/navigation.js @@ -4,9 +4,30 @@ const links = [...document.querySelectorAll('.st-index [data-section]')]; const index = document.querySelector('.st-index'); const search = document.getElementById('settings-search'); + const picker = document.getElementById('settings-section'); + const placeholder = new Option('Choose a section', ''); + placeholder.disabled = placeholder.hidden = true; + picker.append(placeholder); + const options = new Map(links.map(link => { + const option = new Option(link.textContent.trim(), link.dataset.section); + picker.append(option); + return [link.dataset.section, option]; + })); + picker.parentElement.hidden = false; + index.classList.add('st-index-ready'); + let current = ''; + function syncPicker() { + const selected = options.get(current)?.hidden ? '' : current; + [...picker.options].forEach(option => option.toggleAttribute('selected', option.value === selected)); + picker.value = selected; + picker.disabled = links.every(link => link.hidden); + } + picker.addEventListener('change', () => { if (picker.value) location.hash = picker.value; }); function show(id) { + current = id; sections.forEach(section => { section.hidden = section.id !== id; }); links.forEach(link => link.setAttribute('aria-current', link.dataset.section === id ? 'page' : 'false')); + syncPicker(); } function fromHash(event) { let id; @@ -25,18 +46,21 @@ links.forEach(link => { const haystack = (link.textContent + ' ' + link.dataset.search).toLowerCase(); link.hidden = !words.every(word => haystack.includes(word)); + options.get(link.dataset.section).hidden = link.hidden; }); document.querySelectorAll('.st-nav-group').forEach(group => { group.hidden = [...group.querySelectorAll('[data-section]')].every(link => link.hidden); }); document.querySelector('.st-search-empty').hidden = links.some(link => !link.hidden); + syncPicker(); }); search.addEventListener('keydown', event => { if (event.key === 'Enter') { event.preventDefault(); const first = links.find(link => !link.hidden); first?.click(); - first?.focus(); + const compact = picker.parentElement.getClientRects().length; + (compact ? picker.parentElement.querySelector('.ui-select-trigger') : first)?.focus(); } }); window.addEventListener('hashchange', fromHash); diff --git a/app/static/settings/providers.js b/app/static/settings/providers.js index 85410d314..76ecb1ada 100644 --- a/app/static/settings/providers.js +++ b/app/static/settings/providers.js @@ -29,8 +29,8 @@ if (ask && mode !== 'list') { ask.hidden = true; remove.setAttribute('aria-expanded', 'false'); } }); } - async function leave() { - if (window.nulliusSettings && !await window.nulliusSettings.flush()) return; + async function leave(done = false) { + if (window.nulliusSettings && !await window.nulliusSettings.flush(done ? selected : null)) return; mode = 'list'; render(); (selected && !selected.hidden ? selected.querySelector('[data-provider-edit]') : add).focus({preventScroll: true}); @@ -67,7 +67,7 @@ add.addEventListener('click', () => { mode = 'catalogue'; render(); search.value = ''; search.dispatchEvent(new Event('input')); search.focus(); }); - back.addEventListener('click', leave); + back.addEventListener('click', () => void leave()); // Remove asks first, in place: Yes saves the removal, Keep it or Escape closes the question. const setAsk = (card, open) => { const button = card.querySelector('[data-provider-remove-ask]'); @@ -95,7 +95,7 @@ if (tester) { void test(tester); return; } const pick = event.target.closest('[data-provider-select], [data-provider-edit]'); if (pick) edit(pick.dataset.providerSelect || pick.dataset.providerEdit); - if (event.target.closest('[data-provider-done]')) void leave(); + if (event.target.closest('[data-provider-done]')) void leave(true); }); search.addEventListener('input', () => { const choices = [...catalogue.querySelectorAll('[data-provider-select]')]; diff --git a/app/static/settings/settings.css b/app/static/settings/settings.css index 88c519de8..f32da6b76 100644 --- a/app/static/settings/settings.css +++ b/app/static/settings/settings.css @@ -28,8 +28,9 @@ /* a card's rows: a label, then what it holds - an endpoint, a key, a field */ .st-row { display: grid; grid-template-columns: 120px minmax(0, 1fr); gap: 6px 16px; align-items: center; } .st-row-label { font-size: 14px; font-weight: 500; color: var(--text); } -#AGENT_KEYS, .st-key-group { display: grid; gap: 12px; } -.st-key-group-title { margin: 8px 0 0; font-size: 13px; font-weight: 500; letter-spacing: 0; text-transform: none; color: var(--text-dim); overflow-wrap: anywhere; } +#AGENT_KEYS { display: grid; gap: 12px; } +.st-key-group > summary { margin: 8px 0 12px; } +.st-key-group .st-key-card + .st-key-card { margin-top: 12px; } .st-row-value { min-width: 0; display: flex; flex-direction: column; gap: 6px; overflow-wrap: anywhere; } .st-row-value.mono { display: block; font-size: 13px; } .st-about { margin: 0; font-size: 12px; line-height: 1.5; color: var(--text-faint); } @@ -231,10 +232,16 @@ .st-search-empty { padding: 8px 12px; font-size: 13px; color: var(--text-dim); } .st-theme-options { display: flex; flex-wrap: wrap; gap: 8px; } .st-theme-options .btn[aria-pressed="true"] { border-color: transparent; background: var(--accent-soft); color: var(--text); } +.st-section-picker { display: none; } @media (max-width: 760px) { .st-index .st-nav-group { flex: 1 1 130px; } .st-index .st-search { flex: 1 0 calc(100% - 16px); } .st-nav-label { margin: 8px 10px 6px; } + .st-index-ready { flex-direction: column; flex-wrap: nowrap; gap: 12px; } + .st-index-ready .st-search { flex: none; margin: 0; } + .st-index-ready .st-nav-group { display: none; } + .st-index-ready .st-section-picker { display: block; min-width: 0; } + .st-section-picker > select, .st-section-picker > .ui-select-trigger { width: 100%; } } /* Palette previews use the same surface and accent colors as the app. */ @@ -287,8 +294,6 @@ .st-provider-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 220px), 1fr)); gap: 12px; } .st-provider-choice { display: flex; align-items: center; gap: 12px; padding: 18px 16px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); color: var(--text); font: 500 14px/1.5 var(--sans); text-align: left; cursor: pointer; } .st-provider-choice:hover { background: var(--nav-hover); border-color: var(--text-faint); } -/* A custom provider's logo: the first two letters of its name, on the workspace badge. */ -.ws-avatar.st-logo { width: var(--ic-lg); height: var(--ic-lg); font-size: .56rem; border-radius: 5px; color: var(--accent); letter-spacing: 0; } .st-provider-summary { display: flex; align-items: center; gap: 14px; min-width: 0; } .st-provider-summary > div { flex: 1; min-width: 0; } .st-provider-summary h3 { overflow-wrap: anywhere; } diff --git a/app/static/style.css b/app/static/style.css index 2ded4c998..c55fa8546 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -8,7 +8,7 @@ --ic-lg: 24px; /* an interface icon standing as a tile; a logo in a card, a row or a tile */ --ic-xl: 32px; /* an interface icon at its largest drawn size */ --tool-h: 2.1rem; /* a page's buttons and a table's controls: as tall as a small button with its icon */ - --h1-size: clamp(1.75rem, 2.5vw, 2.15rem); + --h1-size: clamp(1.35rem, 2vw, 1.65rem); --head-gap: 1.5rem; /* under a page's head, on every page */ --nav-hover: #32363d; --nav-text: #d6d9df; @@ -272,7 +272,7 @@ h1 { font-size: var(--h1-size); font-weight: 500; line-height: 1.22; letter-spac /* the page head (templates/_page.html): the title flush left, one line under it, the page's buttons right of the title's first line and centred on it; on a narrow screen the buttons go under, flush left. One gap under it. */ -.page-head { --h1-line: calc(var(--h1-size) * 1.22); display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: .5rem 1.5rem; margin: 0 0 var(--head-gap); } +.page-head { --h1-line: calc(var(--h1-size) * 1.22); display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 1rem 1.5rem; margin: 0 0 var(--head-gap); } .page-head > h1 { grid-column: 1; grid-row: 1; overflow-wrap: anywhere; } .page-head-mark { display: inline-flex; align-items: center; height: var(--h1-line); margin-right: .45em; vertical-align: top; } .page-head .page-head-mark > * { width: calc(var(--h1-size) * .9); height: calc(var(--h1-size) * .9); } @@ -325,7 +325,7 @@ h3 .total { margin-left: .15rem; color: var(--text); font-weight: 600; text-tran /* the behaviour flags as a table */ .jflags-head { display: flex; align-items: baseline; justify-content: space-between; gap: 1rem; margin: .4rem 0 .5rem; } .jflags-head h3 { margin: 0; } -.jflags { width: 100%; border-collapse: separate; border-spacing: 0; border: 1px solid var(--border-soft); border-radius: var(--radius); overflow: hidden; background: var(--surface); } +.jflags { width: 100%; min-width: 36rem; border-collapse: separate; border-spacing: 0; border: 1px solid var(--border-soft); border-radius: var(--radius); overflow: hidden; background: var(--surface); } .jflags th { text-align: left; font-weight: 500; color: var(--text-dim); font-size: .8rem; padding: .7rem 1rem; border-bottom: 1px solid var(--border-soft); } .jflags td { padding: .9rem 1rem; border-bottom: 1px solid var(--border-soft); vertical-align: middle; } .jflags tr:last-child td, .jflags tr.jflag-detail td { border-bottom: none; } @@ -1028,20 +1028,6 @@ tr.control-row td { color: var(--text-dim); } .glossary dl > div { grid-template-columns: 1fr; gap: .2rem; } } -.datasets { display: flex; flex-direction: column; gap: .85rem; } -.dataset { - background: var(--surface); border: 1px solid var(--border); - border-radius: var(--radius); padding: 1.1rem 1.25rem; -} -.dataset-head { display: flex; align-items: baseline; gap: .6rem; flex-wrap: wrap; margin-bottom: .55rem; } -.dataset-name { - font-size: 1rem; margin: 0; color: var(--text); - text-transform: none; letter-spacing: -0.01em; -} -.dataset-count { color: var(--text-faint); font-size: .8rem; white-space: nowrap; } -.dataset p { margin: .5rem 0 0; color: var(--text-dim); font-size: .9rem; max-width: 78ch; } -.dataset .lede { color: var(--text); font-weight: 500; } - .legend { display: flex; flex-wrap: wrap; gap: .45rem; margin-bottom: 1.5rem; } .chip { font: inherit; font-size: .77rem; line-height: 1; @@ -1182,42 +1168,6 @@ pre.msg { color: var(--text); max-height: 220px; } .cat-plan .cat-dot, .chip.cat-plan::before { background: var(--cat-plan); } .cat-other .cat-dot, .chip.cat-other::before { background: var(--text-faint); } -.setup-wrap { max-width: 720px; margin: 7vh auto 0; text-align: center; } -.setup-wrap .subtitle { justify-content: center; font-size: .95rem; } -.setup-card { background: var(--surface); border: 1px solid var(--border); border-radius: 14px; padding: 2.25rem 2.5rem; margin-top: 1.75rem; text-align: left; } -.field-label { font-size: .74rem; text-transform: uppercase; letter-spacing: .09em; color: var(--text-dim); font-weight: 500; margin-bottom: .55rem; } -/* + sits at the end of the row so it lines up with the input, not the label */ -.add-btn { - font: inherit; font-size: 1.15rem; line-height: 1; cursor: pointer; flex: none; - width: 2.6rem; height: 2.6rem; display: inline-flex; - align-items: center; justify-content: center; - background: var(--surface-2); color: var(--text-dim); - border: 1px solid var(--border); border-radius: 8px; -} -.add-btn:hover { color: var(--text); border-color: var(--accent); background: var(--accent-soft); } -.add-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; box-shadow: none; } - -.path-row { display: flex; gap: .6rem; margin-bottom: .5rem; align-items: center; } -.row-x { - font: inherit; font-size: .9rem; cursor: pointer; flex: none; - display: inline-grid; place-items: center; padding: 0; - width: 2.6rem; height: 2.6rem; border-radius: 8px; - background: none; color: var(--text-faint); - border: 1px solid transparent; -} -.row-x:hover { color: var(--bad); border-color: var(--border); } -.path-actions { display: flex; align-items: center; gap: .6rem; margin-top: .9rem; } -.submit-row { margin-top: 1.4rem; padding-top: 1.2rem; border-top: 1px solid var(--border-soft); } -.submit-row .footnote { margin: 0; } - -.staged { list-style: none; margin: .9rem 0 0; padding: 0; display: flex; flex-direction: column; gap: .35rem; } -.staged li { - display: flex; align-items: center; gap: .6rem; - background: var(--surface-2); border: 1px solid var(--border-soft); - border-radius: 8px; padding: .45rem .5rem .45rem .7rem; font-size: .86rem; -} -.staged-name { flex: 1; min-width: 0; color: var(--text); overflow-wrap: anywhere; } -.staged-count { font-size: .78rem; white-space: nowrap; } input[type=text] { flex: 1; min-width: 0; background: var(--bg); border: 1px solid var(--border); border-radius: 8px; color: var(--text); font: .95rem var(--mono); padding: .8rem .95rem; outline: none; @@ -1263,22 +1213,6 @@ input[type=text].invalid:focus { box-shadow: inset 0 0 0 1px var(--bad); } @media (prefers-reduced-motion: reduce) { .btn, .btn:hover, .btn:active { transition: none; transform: none; } } -.divider { display: flex; align-items: center; gap: .9rem; color: var(--text-faint); font-size: .74rem; text-transform: uppercase; letter-spacing: .1em; margin: 1.5rem 0; } -.divider::before, .divider::after { content: ""; height: 1px; background: var(--border-soft); flex: 1; } -.drop { - display: block; - border: 1.5px dashed var(--border); border-radius: 10px; padding: 2.5rem 1.25rem; - text-align: center; color: var(--text-dim); font-size: .95rem; - transition: border-color .12s, background .12s, color .12s; - cursor: pointer; -} -/* Children must not receive pointer/drag events: dragleave bubbling up from them - is what made the highlight flicker while dragging across the zone. */ -.drop > * { pointer-events: none; } -.drop:hover { border-color: var(--text-faint); background: var(--surface-2); color: var(--text); } -.drop.over { border-color: var(--accent); background: var(--accent-soft); color: var(--text); } -.drop strong { color: var(--text); font-weight: 500; } -.drop .hint { font-size: .82rem; color: var(--text-faint); margin-top: .4rem; } /* Neutral by default — only .error earns the red treatment, so a hint never reads as a failure. */ .alert { @@ -1391,13 +1325,10 @@ a.chip { text-decoration: none; } .ch-x-title { margin: .15rem 0 0; font-size: .7rem; line-height: 1.3; text-align: center; color: var(--text-faint); } .chart-legend { margin: 0; gap: .3rem; } -.chart-legend .chip { font-size: .68rem; } +.chart-legend .chip { border-color: var(--text-faint); background: var(--surface); color: var(--text); } .chart-legend a.chip:hover { border-color: var(--accent); } .chart-note { margin: 0; font-size: .72rem; } .chart-foot { margin: .8rem 0 0; } -.chart-values { margin-top: .6rem; } -.chart-values table { margin-top: .6rem; } -.chart-values caption { caption-side: top; text-align: left; font-size: .78rem; color: var(--text-dim); padding-bottom: .25rem; } /* Same hue-by-kind mapping as the waterfall, so a colour means one thing on the page. The default keeps a single-series chart — and an unknown enum value — @@ -1780,8 +1711,6 @@ pre.instruction { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 32 .std-fidelity.ok { color: var(--ok) !important; } .std-fidelity.no { color: var(--bad) !important; } /* A port's skills under it, shown or not (an agent's page, the builder's agent step): the skill's id in small type. */ -.std-skills { display: block; } -.std-skills code { font-size: 11px; color: var(--text-faint); } .std-options { margin-top: 18px; } .std-options h3 { font-size: 13px; margin: 0 0 2px; } .std-options > small { display: block; color: var(--text-dim); font-size: 12px; margin-bottom: 10px; } @@ -1815,7 +1744,6 @@ select.ui-select-native { display: none !important; } .ui-select-trigger[data-placeholder] { color: var(--text-faint); } .ui-select-trigger[hidden] { display: none; } .ui-select-menu { position: fixed; inset: auto; margin: 0; padding: 5px; box-sizing: border-box; border: 1px solid var(--border); border-radius: 9px; background: var(--surface-2); color: var(--text); box-shadow: 0 12px 30px #0005; overflow-y: auto; overscroll-behavior: contain; font: 13px/1.5 var(--sans); z-index: 100; } -.path-suggestions { font-family: var(--mono); } .ui-option-label { display: inline-flex; align-items: center; flex-wrap: wrap; gap: 8px; } .ui-select-option { padding: 6px 9px; border-radius: 5px; cursor: pointer; overflow-wrap: anywhere; } .ui-select-option:hover, .ui-select-option.is-active { background: var(--nav-hover); } diff --git a/app/static/tables.js b/app/static/tables.js index c18bbeccb..66064aa85 100644 --- a/app/static/tables.js +++ b/app/static/tables.js @@ -147,6 +147,11 @@ window.NulliusTable = { // only that flip is undone, so a position its caller set is kept if (flipped) { menu.style.left = menu.style.right = ''; flipped = false; } if (open && menu.getBoundingClientRect().left < 0) { Object.assign(menu.style, {left: '0', right: 'auto'}); flipped = true; } + // A flipped menu can still cross the other edge when its button sits near the middle. + if (open) { + const excess = menu.getBoundingClientRect().right - (window.innerWidth - 8); + if (excess > 0) { Object.assign(menu.style, {left: `${menu.offsetLeft - excess}px`, right: 'auto'}); flipped = true; } + } if (open) menu.querySelector('input:not(:disabled), button, a[href]')?.focus(); }); document.addEventListener('click', e => { if (!menu.hidden && away(e.target)) close(); }); diff --git a/app/static/workspaces/create.css b/app/static/workspaces/create.css new file mode 100644 index 000000000..ca2fdc0d3 --- /dev/null +++ b/app/static/workspaces/create.css @@ -0,0 +1,3 @@ +dialog.std-how.workspace-create { width: min(360px, calc(100vw - 32px)); } +.workspace-create form { display: grid; gap: 12px; } +.workspace-create-actions { display: grid; grid-template-columns: repeat(2, 1fr); justify-self: end; gap: 8px; margin-top: 8px; } diff --git a/app/static/workspaces/create.js b/app/static/workspaces/create.js new file mode 100644 index 000000000..80eb2df35 --- /dev/null +++ b/app/static/workspaces/create.js @@ -0,0 +1,26 @@ +/* Create an empty workspace from either workspace entry point. */ +(() => { + const dialog = document.getElementById('workspace-create'); + let opener; + document.querySelectorAll('[data-workspace-new]').forEach(button => { + button.addEventListener('click', () => { + const pop = document.getElementById('ws-pop'); + const switcher = document.getElementById('ws-btn'); + opener = pop?.contains(button) ? switcher : button; + if (pop) pop.hidden = true; + switcher?.setAttribute('aria-expanded', 'false'); + dialog.querySelector('form').reset(); + dialog.showModal(); + }); + }); + dialog.querySelectorAll('[data-workspace-cancel]').forEach(button => { + button.addEventListener('click', () => dialog.close()); + }); + dialog.addEventListener('click', event => { + if (event.target !== dialog) return; + const rect = dialog.getBoundingClientRect(); + if (event.clientX < rect.left || event.clientX > rect.right + || event.clientY < rect.top || event.clientY > rect.bottom) dialog.close(); + }); + dialog.addEventListener('close', () => opener?.focus()); +})(); diff --git a/app/templates/_cards.html b/app/templates/_cards.html index db70d0640..0cd9006cd 100644 --- a/app/templates/_cards.html +++ b/app/templates/_cards.html @@ -44,7 +44,7 @@ {#- An item's icon: `src` an image URL or a sprite symbol, else the initials of `name`. #} {% macro mark(icon, src, name) %} {%- if not src %} - {%- elif '#' in src %} + {%- elif '#' in src %} {%- else %}{% endif %}{% endmacro %} {#- A row's attributes, written once per item by rows. #} @@ -105,7 +105,7 @@
{% if f.icon %}{% endif %}{{ v.text }}
{% endcall %} {%- set stats = by.stat|rejectattr('key', 'in', item.get('hide', []))|list %}{% if stats %}
{% for f in stats %}{% set v = item.get(f.key) %}{% set v = v if v is mapping else {'text': v} -%} -
{{ v.label or f.card_label or f.label }}
{{ '—' if v.text is none or v.text == '' else v.text }}
{% endfor %}
{% endif %} +
{{ v.label or f.card_label or f.label }}
{{ '—' if v.text is none or v.text == '' else v.text }}
{% endfor %}{% endif %} {%- call(f, v) each(item, by.alert) %}
{{ v.text }}
{% endcall %} {%- set actions %}{% call(f, v) each(item, by.action) %}{% if v.href %}{{ v.text }}{% else %}{% endif %}{% endcall %}{% endset %}{% if actions %} diff --git a/app/templates/_icons.svg b/app/templates/_icons.svg index 90b07421f..07a057675 100644 --- a/app/templates/_icons.svg +++ b/app/templates/_icons.svg @@ -9,6 +9,8 @@ + + +{% elif d._version %}{{ 'v' if d._version[:1].isdigit() else '' }}{{ d._version }}{% endif %} diff --git a/app/templates/agents/entry.html b/app/templates/agents/entry.html index fd8b2fafe..83a706bc0 100644 --- a/app/templates/agents/entry.html +++ b/app/templates/agents/entry.html @@ -64,9 +64,9 @@

Source

{% for r in e.ports %} {% if r.kit %}{{ r.label }}{% else %}{{ r.label }}{% endif %} {{ r.port }}{{ r.summary }} - {% if r.skills %}Skills: {% for s in r.skills %}{{ s.says }} {% if s.shown %}{% else %}{% endif %}{{ ' · ' if not loop.last }}{% endfor %}{% endif %} + {% if r.skills %}
Skills {{ r.skills|selectattr('shown')|list|length }}/{{ r.skills|length }}
    {% for s in r.skills %}
  • {{ s.says }}
  • {% endfor %}
{% endif %} {% if not r.kit %}No kit yet: nothing can prove it until a benchmark needs it.{% endif %} - {% if r.record %}{{ r.record.passed }}{% if r.older_kit %}newer kit: worth running again{% endif %} + {% if r.record %}{{ r.record.passed }}{% if r.older_kit %}Recheck port{% endif %} {%- else %}{{ r.state }}{% endif %} {% endfor %} @@ -76,7 +76,8 @@

Source

{# cli fidelity: the same tasks driven over ACP and through the agent's own command, the model's requests compared #}

Fidelity

ACP {% if e.fidelity.verdict == 'same' %}= its own CLI {% else %}≠ its own CLI: {{ e.fidelity.verdict }}{% endif %} - Its model gets the same requests over ACP as from its own command line{% if e.fidelity.differs %}; differs in {{ e.fidelity.differs|map(attribute='field')|join(', ') }}{% endif %}.

+ {% if e.fidelity.passes %}{{ e.fidelity.passes }} passes each way{% endif %}

+ {% if e.fidelity.differs %}
Changed fields {{ e.fidelity.differs|length }}
    {% for diff in e.fidelity.differs %}
  • {{ diff.field }}
  • {% endfor %}
{% endif %} {% endif %} {% if e.options %}

Options

diff --git a/app/templates/agents/kits.html b/app/templates/agents/kits.html index e7d13a9d3..1e91f5c21 100644 --- a/app/templates/agents/kits.html +++ b/app/templates/agents/kits.html @@ -10,7 +10,8 @@ {% set d = entry.d %}
{% set tags %}{{ entry.port }}v{{ entry.version }}{{ d.datasets|sum(attribute='units') }} checks{% endset %} - {{ page_head(entry.label ~ ' kit', sub=tags) }} + {% set mark %}{% endset %} + {{ page_head(entry.label ~ ' kit', sub=tags, mark=mark) }}

{{ d.summary }}

Pass criteria

{{ d.score.says }}.

Every basic check must pass to prove this port.

@@ -41,10 +42,10 @@

Checks

{% else %}
{{ page_head('Kits', sub=items|length ~ ' conformance kits') }} - {#- A card's fields (web/agents.py `_kit_card`); the family's pills filter them. #} - {% set cols = [dict(key='title', label='Name', card='title'), dict(key='family', label='Family', card='tag', class='std-tag', filter='pills'), + {#- A card's fields (web/agents.py `_kit_card`); the family dropdown filters them. #} + {% set cols = [dict(key='icon', label='Icon', card='icon', table=false, class='std-mark small'), dict(key='title', label='Name', card='title'), dict(key='family', label='Family', filter='dropdown'), dict(key='port', label='Port', card='text', style='code'), dict(key='checks', label='Checks', card='stat', type='num'), - dict(key='version', label='Version', card='meta')] %} + dict(key='version', label='Version', card='stat', class='mono small')] %} {{ cards('kits', cols, items, search='Name, port, check', choices={'family': [('agent', 'Agents'), ('capability', 'Modules')]}, sort=['title', 'port', 'checks'], empty='No kits match.', noun='kits', layout='table' if request.args.get('view') == 'table' else 'cards', default='cards') }}
{% endif %} diff --git a/app/templates/agents/standard.html b/app/templates/agents/standard.html index 168edc47c..fc91dd358 100644 --- a/app/templates/agents/standard.html +++ b/app/templates/agents/standard.html @@ -29,7 +29,7 @@ {% endfor %} -

The whole contract: docs/standard.md in the source checkout.{% if example_dir %} A bundled example to read: {{ example_dir }}.{% endif %}

+

The whole contract: docs/standard.md in the source checkout.

{% endcall %} {% if problems %}
Not offered: a definition with problems
    {% for p in problems %}
  • {{ p }}
  • {% endfor %}
{% endif %} @@ -42,9 +42,9 @@ dict(key='uses', label='Uses', card='badge', class='std-tag', off=true), dict(key='from', label='From'), dict(key='benchmark', label='Benchmark', card='meta', table=false), dict(key='runs_on', label='Runs on', class='cat-tag', off=true), dict(key='models', label='Models', card='note', width='expand', off=true), dict(key='proves', label='Proves', class='std-tag', off=true), dict(key='example', label='Example', card='badge', class='std-tag', off=true), dict(key='summary', label='Summary', card='text', class='std-clamp', width='expand', off=true), dict(key='ports', label='Ports proven', card='stat', type='num'), - dict(key='runs', label='Benchmarks it runs', card='stat', type='num'), dict(key='installs', label='Installs', card='stat', class='word'), - dict(key='version', label='Version')] %} + dict(key='runs', label='Benchmarks', card='stat', type='num'), + dict(key='version_control', label='Version', card='stat')] %} {% if items %}{{ cards('agents' if kind == 'agent' else 'capabilities', cols, items, search='Name, protocol, summary', choices=choices, only=only, sort=['title', 'ports', 'runs'], empty='No ' ~ one ~ ' matches.', noun=many, layout='table' if request.args.get('view') == 'table' else 'cards', default='cards') }}{% endif %}
{% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/templates/base.html b/app/templates/base.html index cbf89847d..6d2d8f45a 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -1,5 +1,5 @@ {% macro agent_mark(kind, key, label, css='agent-logo') -%} - {% set source = agent_mark_url(key) if kind == 'agent' else none %} + {% set source = agent_mark_url(key) if kind == 'agent' else module_mark_url(key) %} {% if source and '#' in source %} {% elif source %} {% else %}{{ label[:1] }}{% endif %} @@ -32,6 +32,8 @@ + + {% block head %}{% endblock %} @@ -89,7 +91,7 @@
{% if workspace %}No other workspace yet.{% else %}No workspace yet.{% endif %}
{% endfor %}
- New workspace + All workspaces @@ -122,7 +124,7 @@
{% for b in (nav_catalog.listed_benchmarks if nav_catalog else []) %} - {{ b.title }} + {{ b.title }} {% endfor %}
@@ -137,7 +139,7 @@ @@ -150,7 +152,7 @@
- {% for item in nav_kits %}{{ item.label }}{% endfor %} + {% for item in nav_kits %}{{ item.label }}{% endfor %}
@@ -421,6 +423,8 @@ {% if judgements_unmoved() %}{% endif %} {% if not embedded %} +{% include "workspaces/_create.html" %} +

Settings

diff --git a/app/templates/builder/benchmarks.html b/app/templates/builder/benchmarks.html index 4b62454b6..7e84a600e 100644 --- a/app/templates/builder/benchmarks.html +++ b/app/templates/builder/benchmarks.html @@ -2,10 +2,10 @@ (web/catalogue.py, benchmark_cards) as single-choice pick cards of the card toolkit (_cards.html), or its rows (`layout` 'table'), loaded by command-builder.js. -#} {% from '_cards.html' import cards %} -{#- the category a row of pills; what it evaluates (agents or Modules) and the origin menus of their own, beside Filter (runner) -#} +{#- Category, what it evaluates and origin use the catalogue's filter menus. -#} {% set cols = [dict(key='icon', label='Mark', card='icon', table=false, class='bench-mark'), dict(key='title', label='Name', card='title', width='expand'), dict(key='evaluates', label='Evaluates', card='badge', class='std-tag', filter='dropdown', filter_icon='target'), dict(key='tasks', label='Tasks', card='stat', type='num'), - dict(key='category', label='Category', card='tag', class='cat-tag', filter='pills'), dict(key='origin', label='Origin', class='origin-tag', filter='dropdown', filter_icon='origin'), + dict(key='category', label='Category', card='tag', class='cat-tag', filter='dropdown'), dict(key='origin', label='Origin', class='origin-tag', filter='dropdown', filter_icon='origin'), dict(key='runs', label='Runner', class='run-tag'), dict(key='domain', label='Domain', off=true)] %} {{ cards('nb-benchmarks', cols, items, search='Search benchmarks', choices=choices, sort=['title', 'tasks'], empty='No benchmark matches.', noun='benchmarks', layout=layout, default='cards') }} diff --git a/app/templates/catalogue/benchmarks.html b/app/templates/catalogue/benchmarks.html index 3ecf3694b..a42576555 100644 --- a/app/templates/catalogue/benchmarks.html +++ b/app/templates/catalogue/benchmarks.html @@ -26,12 +26,12 @@ {% endcall %} - {#- A card's fields (web/catalogue.py `_card`); the filters are the category's pills, the origin, what runs it and what it needs dropdowns and columns, never on the card. #} + {#- A card's fields (web/catalogue.py `_card`); category, origin, what runs it and what it needs use dropdowns and columns, never on the card. #} {% set cols = [dict(key='icon', label='Mark', card='icon', table=false, class='bench-mark'), dict(key='title', label='Name', card='title'), - dict(key='category', label='Category', card='badge', class='cat-tag', filter='pills'), dict(key='origin', label='Origin', class='origin-tag', filter='dropdown', filter_icon='origin'), + dict(key='category', label='Category', card='badge', class='cat-tag', filter='dropdown'), dict(key='origin', label='Origin', class='origin-tag', filter='dropdown', filter_icon='origin'), dict(key='domain', label='Domain', card='text', class='std-clamp', off=true), dict(key='runs', label='Runs with', class='run-tag', filter='dropdown', filter_icon='runner'), dict(key='tasks', label='Tasks', card='stat', type='num'), dict(key='datasets', label='Datasets', card='stat', type='num'), - dict(key='scoring', label='Scored by', card='stat', class='word'), dict(key='needs', label='Needs', filter='dropdown', filter_icon='wrench', off=true), + dict(key='scoring', label='Scored by', card='stat', class='word scorer'), dict(key='needs', label='Needs', filter='dropdown', filter_icon='wrench', off=true), dict(key='blocker', label='Blocker', card='alert')] %} {% set sort = ['title', 'tasks', 'datasets'] %} {% call cards('benchmarks', cols, items, search='Name, category, dataset', choices=choices, sort=sort, empty='No benchmark matches.', noun='benchmarks', layout='table' if request.args.get('view') == 'table' else 'cards', default='cards') %} diff --git a/app/templates/runs/index.html b/app/templates/runs/index.html index 889bd8447..7de894acd 100644 --- a/app/templates/runs/index.html +++ b/app/templates/runs/index.html @@ -83,21 +83,8 @@ {% set counts %} {{- launches|length }} launch{{ '' if launches|length == 1 else 'es' }}·{{ n_agent_runs }} run{{ '' if n_agent_runs == 1 else 's' }}·{{ n_trials }} trial{{ '' if n_trials == 1 else 's' }} {%- if n_checks %}·{{ n_checks }} check{{ '' if n_checks == 1 else 's' }}{% endif %}{% endset %} -{% set actions %}Import - New run{% endset %} +{% set actions %}New run{% endset %} {{ page_head('Runs', sub=counts, actions=actions) }} -

- {%- if workspace %}in {{ workspace.label }}{% endif -%} - {%- for s, n in states|dictsort %}{{ n }} {{ s }}{% endfor -%} - task checks {{ n_checked }} of {{ launches|length }} -

- -
- {% for k in ORDER %}{% if totals[k] %} - - {% endif %}{% endfor %} -
By launch @@ -279,25 +266,6 @@

{{ g.dataset_title if L.dataset else (L.name or g.dataset_title) }}{% if g.n

-{% if datasets %} -

Datasets in these runs

-
- {% for d in datasets %} -
-
-

{{ d.info.title }}

- {{ d.name }} - - {{ d.runs }} run{{ '' if d.runs == 1 else 's' }}·{{ d.trials }} trial{{ '' if d.trials == 1 else 's' }} -
-

{{ d.info.what }}

- {% if d.info.scored %}

How it's scored {{ d.info.scored }}

{% endif %} - {% if d.info.note %}

{{ d.info.note }}

{% endif %} -
- {% endfor %} -
-{% endif %} - - -{% endblock %} diff --git a/app/templates/runs/start.html b/app/templates/runs/start.html index d15abd93d..9fdf46b5b 100644 --- a/app/templates/runs/start.html +++ b/app/templates/runs/start.html @@ -4,8 +4,7 @@ {% block crumb %}/ runs{% endblock %} {% block head %}{% endblock %} {% block body %} -{# No workspace open: the two ways to have runs - start one, or bring the ones - made elsewhere - then the workspaces already here, and the mark last. #} +{# Build a run or open an existing workspace. #}
{{ page_head('Runs', sub='0 runs') }} @@ -16,12 +15,6 @@

Build a run

Choose a benchmark, an agent and a model. Follow the results here.

Open run builder -
- -

Import results

-

Bring in ATIF trajectories or OpenTelemetry exports.

- Choose files or folder -
{% if workspaces %} diff --git a/app/templates/settings/custom_keys.html b/app/templates/settings/custom_keys.html index 653f177a7..0ec151b2e 100644 --- a/app/templates/settings/custom_keys.html +++ b/app/templates/settings/custom_keys.html @@ -11,9 +11,11 @@

Custom keys

{% if writable %}{% endif %}

Credentials for your agents and benchmarks.

+ + {% for b in benchmark_access %} -
-

{{ b.title }}

+
+ {{ b.title }} {{ b.needs|length }} {% for s in b.needs %} {% set field_id = 'access-' ~ b.key ~ '-' ~ s.name %}
@@ -45,7 +47,7 @@

{{ b.title }}

{% endfor %} - + {% endfor %}

No custom keys yet.

{% for name in reserved_agent_keys or [] %}

AGENT_KEYS lists {{ name }}, which is now the name of a Nullius setting. Add this key again with a different name.

{% endfor %} diff --git a/app/templates/settings/settings.html b/app/templates/settings/settings.html index e9339cf34..6fbdde50a 100644 --- a/app/templates/settings/settings.html +++ b/app/templates/settings/settings.html @@ -54,6 +54,7 @@
- {% macro provider_logo(key, title='Custom') %}{% if key == 'typesafe' %}{% elif key.startswith('custom') %}{% else %}{% endif %}{% endmacro %} + {% macro provider_logo(key, title='Custom') %}{% if key == 'typesafe' %}{% elif key.startswith('custom') %}{% else %}{% endif %}{% endmacro %}