diff --git a/AGENTS.md b/AGENTS.md index 92a31444..b0a7c618 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,12 +39,12 @@ and its resources. workspace and its jobs, path resolution, the catalogue cache, the query helpers, the form-token guard), `filters` (template filters, page context), then `runs`, `traces`, `compare`, `builder`, `catalogue`, `agents`, - `settings`, `workspaces`, `execute`, `judge`, `feasibility`, `reconcile`, `judge_tasks`, `onboarding` (`agents` is the Agents + `settings`, `workspaces`, `execute`, `judge`, `feasibility`, `reconcile`, `judge_tasks`, `onboarding`, `failure` (`agents` is the Agents and Capabilities tabs and conformance Kits catalogue). Cross-module names are reached as attributes (`shared.STATE`, `traces._trial_evidence`): patch one, patched for all. - `app/nullius/` — its backend, one package per purpose: `runs/` (reading one - Harbor job tree: `parse`, `classify`, `live`, `artifacts`, - `feasibility`, `launches`, `verifier` - a verifier's report read by its + Harbor job tree: `parse`, `classify`, `live`, `artifacts`, `evidence`, + `feasibility`, `failure_analysis` - a job's failure labels and task flags, beside its result.json, written by `flags_cli` too -, `launches`, `verifier` - a verifier's report read by its benchmark's report block - `attempts`, a task's attempts in one job with their pass count and pass@k, and the `cli`), `traces/` (`trace`, the reader, with its span tree `spans`, `fold`, time accounting `breakdown` and layout `waterfall`; `trajectory`, diff --git a/app/.env.example b/app/.env.example index feda3fbc..599ab73d 100644 --- a/app/.env.example +++ b/app/.env.example @@ -48,13 +48,13 @@ LLM_JUDGE_PROVIDER= LLM_JUDGE_PROTOCOL= # The model of the LLM judgement, as its provider names it (on OpenRouter, vendor/model). It is asked the same questions as Decision and answers them as JSON; its numbers are what it states, so a choice or a score carries no confidence. LLM_JUDGE_MODEL= -# Additions to the OpenRouter provider, as a JSON object without the key: endpoints of protocols the preset does not list, {"endpoints": {"": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one. +# Unsupported overrides for OpenRouter. Use a Custom provider to configure endpoints. OPENROUTER= -# Additions to the OpenAI provider, as a JSON object without the key: endpoints of protocols the preset does not list, {"endpoints": {"": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one. +# Unsupported overrides for OpenAI. Use a Custom provider to configure endpoints. OPENAI= -# Additions to the Anthropic provider, as a JSON object without the key: endpoints of protocols the preset does not list, {"endpoints": {"": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one. +# Unsupported overrides for Anthropic. Use a Custom provider to configure endpoints. ANTHROPIC= -# Additions to the TypeSafe provider, as a JSON object without the key: endpoints of protocols the preset does not list, {"endpoints": {"": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one. +# Unsupported overrides for TypeSafe. Use a Custom provider to configure endpoints. TYPESAFE= # --- Run hosts --- diff --git a/app/app.py b/app/app.py index cca07559..101100cb 100644 --- a/app/app.py +++ b/app/app.py @@ -28,11 +28,11 @@ if __package__: # the wheel's private web namespace from .web.core import app from .web import shared - from .web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding + from .web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure else: # python app/app.py, and the source route suite from web.core import app from web import shared - from web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding + from web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure from nullius import execution, workspace # noqa: E402 - recorded runs, picked up again at start; the workspace left open diff --git a/app/nullius/catalogue/agents/jiuwenswarm/agent.json b/app/nullius/catalogue/agents/jiuwenswarm/agent.json index d090e995..42a257bd 100644 --- a/app/nullius/catalogue/agents/jiuwenswarm/agent.json +++ b/app/nullius/catalogue/agents/jiuwenswarm/agent.json @@ -2,7 +2,7 @@ "schema": "nullius.agent/v1", "key": "jiuwenswarm", "label": "JiuwenSwarm", - "summary": "openJiuwen's agent.", + "summary": "openJiuwen's WorkSwarm agent.", "start": { "acp": [ "{install}/.venv/bin/python", @@ -70,6 +70,54 @@ "openjiuwen @ git+https://github.com/openJiuwen-ai/agent-core.git@79f6ec656f513dadc412aaafa13f60ecf7f0fc04" ] } + }, + "0.2.9": { + "upstream": { + "repository": "https://github.com/openJiuwen-ai/jiuwenswarm", + "tag": "v0.2.9", + "tested": "453dce3054babf7f3a7000c8e57e068de01d8d2e", + "package": "workswarm", + "license": "Apache-2.0", + "core": "openjiuwen 0.1.21 and openjiuwen-agent-gateway 0.1.0, pinned by upstream" + }, + "install": { + "python": "3.12", + "wheels": [ + { + "url": "https://github.com/openJiuwen-ai/jiuwenswarm/releases/download/v0.2.9/workswarm-0.2.9-py3-none-any.whl", + "sha256": "241ed07f9a23f989984b68474e2b5147ad6907323c92fb8d139be8da6705130f" + } + ] + }, + "options": { + "web_max_fetches": { + "label": "Page fetch limit", + "summary": "Pages fetched per invocation.", + "pattern": "(?:[1-9]|[1-9][0-9]|100)", + "example": "6", + "default": "3" + } + }, + "model": { + "apis": [ + "chat" + ], + "env": { + "NULLIUS_BASE_URL": "{base_url}", + "NULLIUS_KEY": "{key}", + "NULLIUS_MODEL": "{model}", + "NULLIUS_REASONING": "{opt_reasoning_effort}", + "WEB_RESEARCH_MAX_FETCHES": "{opt_web_max_fetches}" + } + }, + "fidelity": { + "command": [ + "{install}/.venv/bin/python", + "{here}/agent.py", + "--cli", + "{prompt}" + ] + } } } } diff --git a/app/nullius/catalogue/agents/jiuwenswarm/agent.py b/app/nullius/catalogue/agents/jiuwenswarm/agent.py index ee9baeba..7f806e36 100644 --- a/app/nullius/catalogue/agents/jiuwenswarm/agent.py +++ b/app/nullius/catalogue/agents/jiuwenswarm/agent.py @@ -32,6 +32,8 @@ Requests for the unit's own JiuwenSwarm home are served by this wrapper on both backends, so its config and todo files remain accessible. +``--cli PROMPT`` runs the vendor's own CLI in place of the ACP bridge (fidelity). + The resident worker uses a short, private socket path. When the bridge ends, the servers and worker are stopped. """ @@ -132,10 +134,9 @@ def reasoning_level(): def mcp_into_config(servers): """ACP's stdio MCP servers as JiuwenSwarm's ``mcp.servers`` entries.""" + import portalocker import yaml path = os.path.join(CONFIG, "config.yaml") - with open(path) as f: - data = yaml.safe_load(f) or {} entries = [] for s in servers or []: if not s.get("command"): @@ -145,13 +146,17 @@ def mcp_into_config(servers): env = {e["name"]: e["value"] for e in env} entries.append({"name": s["name"], "enabled": True, "transport": "stdio", "command": s["command"], "args": list(s.get("args") or []), "env": env}) - data.setdefault("mcp", {}) - if not isinstance(data["mcp"], dict): - data["mcp"] = {} - data["mcp"]["servers"] = entries - with open(path + ".part", "w") as f: - yaml.safe_dump(data, f, allow_unicode=True, sort_keys=False) - os.replace(path + ".part", path) + # Upstream's own lock: its startup can still write config.yaml here. + with portalocker.Lock(os.path.join(CONFIG, "config.lock"), timeout=10): + with open(path) as f: + data = yaml.safe_load(f) or {} + data.setdefault("mcp", {}) + if not isinstance(data["mcp"], dict): + data["mcp"] = {} + data["mcp"]["servers"] = entries + with open(path + ".part", "w") as f: + yaml.safe_dump(data, f, allow_unicode=True, sort_keys=False) + os.replace(path + ".part", path) say("mcp servers:", [e["name"] for e in entries]) @@ -285,7 +290,7 @@ def stop_worker(env): say("runtime worker shutdown failed:", e) -def run(runtime_socket): +def run(runtime_socket, cli_prompt=None): os.makedirs(HOME, exist_ok=True) if not os.path.isfile(os.path.join(CONFIG, "config.yaml")): r = subprocess.run([PY, "-c", "from jiuwenswarm.common.utils import prepare_workspace\n" @@ -327,7 +332,14 @@ def stop(*_): return 1 time.sleep(0.25) say(f"ready in {time.time() - t0:.1f} s: agent server :{ports[0]}, gateway :{ports[1]}") - bridge = subprocess.Popen([PY, "-m", "jiuwenswarm.gateway.channel_manager.protocol.acp.acp_connect", + if cli_prompt is not None: + # The vendor CLI uses /tui; select the same agent mode as ACP. + bridge = subprocess.Popen([os.path.join(os.path.dirname(PY), "jiuwenswarm"), + "chat", "--mode", "agent", "--gateway-url", + f"ws://127.0.0.1:{ports[1]}/tui", "--cwd", os.getcwd(), + "--", cli_prompt], stdin=subprocess.DEVNULL, env=env) + return bridge.wait() + bridge = subprocess.Popen([os.path.join(os.path.dirname(PY), "jiuwenswarm-acp"), "--gateway-url", f"ws://127.0.0.1:{ports[1]}/acp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=sys.stderr, env=env, bufsize=0) ses = Sessions() @@ -343,12 +355,17 @@ def stop(*_): stop_worker(env) -def main(): +def main(cli_prompt=None): # A long job path exceeds the Unix socket limit. Each unit owns a short, # private directory, including on the local backend where /tmp is shared. with tempfile.TemporaryDirectory(prefix="nj-", dir="/tmp") as runtime: + if cli_prompt is not None: + return run(os.path.join(runtime, "worker.sock"), cli_prompt=cli_prompt) return run(os.path.join(runtime, "worker.sock")) if __name__ == "__main__": - sys.exit(main()) + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--cli", metavar="PROMPT", help="run the vendor CLI for fidelity") + sys.exit(main(parser.parse_args().cli)) diff --git a/app/nullius/catalogue/agents/jiuwenswarm/proofs.json b/app/nullius/catalogue/agents/jiuwenswarm/proofs.json index 73b76987..31ff379f 100644 --- a/app/nullius/catalogue/agents/jiuwenswarm/proofs.json +++ b/app/nullius/catalogue/agents/jiuwenswarm/proofs.json @@ -110,6 +110,186 @@ "backend": "docker" } } + }, + "0.2.9": { + "proven": { + "agent.task/v1": { + "passed": "3/3", + "model": "openai/gpt-5-mini", + "provider": "openrouter", + "version": "0.2.9", + "kit_version": 1, + "backend": "container" + }, + "agent.workspace/v1": { + "passed": "2/2", + "model": "openai/gpt-5-mini", + "provider": "openrouter", + "version": "0.2.9", + "kit_version": 1, + "backend": "container" + }, + "agent.tools/v1": { + "passed": "2/2", + "model": "openai/gpt-5-mini", + "provider": "openrouter", + "version": "0.2.9", + "kit_version": 2, + "backend": "container", + "repeat": 3, + "checks": { + "one-tool": "3/3", + "arguments": "3/3" + }, + "skills": { + "decoys": { + "passed": "3/3", + "ok": true + }, + "chain": { + "passed": "3/3", + "ok": true + }, + "retry": { + "passed": "3/3", + "ok": true + } + } + }, + "agent.conversation/v1": { + "passed": "2/2", + "model": "openai/gpt-5-mini", + "provider": "openrouter", + "version": "0.2.9", + "kit_version": 1, + "backend": "container" + }, + "fidelity": { + "verdict": "differs", + "model": "openai/gpt-5-mini", + "provider": "openrouter", + "version": "0.2.9", + "passes": 2, + "differs": [ + { + "field": "tools", + "acp": [ + "[\"fetch_webpage\", \"glob\", \"grep\", \"skill_tool\", \"subagent_spawn\", \"subagent_wait\", \"subagent_list\", \"subagent_send_input\", \"subagent_close\", \"subagent_resume\", \"tool_search\", \"tool_call\", \"todo_create\", \"todo_list\", \"todo_get\", \"todo_modify\", \"ask_user\"]", + "\u2014" + ], + "cli": [ + "[\"fetch_webpage\", \"read_file\", \"write_file\", \"edit_file\", \"glob\", \"grep\", \"bash\", \"subagent_spawn\", \"subagent_wait\", \"subagent_list\", \"subagent_send_input\", \"subagent_close\", \"subagent_resume\", \"skill_tool\", \"tool_search\", \"tool_call\", \"todo_create\", \"todo_list\", \"todo_get\", \"todo_modify\"]", + "\u2014" + ] + }, + { + "field": "tools[ask_user]", + "acp": [ + "sha256:b9b6b54f1f4fe625", + "\u2014" + ], + "cli": [ + "\u2014" + ] + }, + { + "field": "tools[bash]", + "acp": [ + "\u2014" + ], + "cli": [ + "sha256:9b5ef025b334ca8e", + "\u2014" + ] + }, + { + "field": "tools[edit_file]", + "acp": [ + "\u2014" + ], + "cli": [ + "sha256:41761b2c2ba6f0c7", + "\u2014" + ] + }, + { + "field": "tools[read_file]", + "acp": [ + "\u2014" + ], + "cli": [ + "sha256:e29b1ed9e6495ec3", + "\u2014" + ] + }, + { + "field": "tools[subagent_spawn]", + "acp": [ + "sha256:beaac04f5542bda5", + "\u2014" + ], + "cli": [ + "sha256:7bbb49b31256390b", + "\u2014" + ] + }, + { + "field": "tools[todo_create]", + "acp": [ + "sha256:5e7b55e5694bdfe6", + "\u2014" + ], + "cli": [ + "sha256:af5750590cd95e75", + "\u2014" + ] + }, + { + "field": "tools[todo_get]", + "acp": [ + "sha256:ebcca129352595fc", + "\u2014" + ], + "cli": [ + "sha256:c99d336992aa6228", + "\u2014" + ] + }, + { + "field": "tools[todo_list]", + "acp": [ + "sha256:faf553fb35d71dfe", + "\u2014" + ], + "cli": [ + "sha256:afaf3ad08441f12b", + "\u2014" + ] + }, + { + "field": "tools[todo_modify]", + "acp": [ + "sha256:6661c6391a3e744a", + "\u2014" + ], + "cli": [ + "sha256:774dc52d3a1d43f1", + "\u2014" + ] + }, + { + "field": "tools[write_file]", + "acp": [ + "\u2014" + ], + "cli": [ + "sha256:a5b46ab6c208ac80", + "\u2014" + ] + } + ] + } + } } } } diff --git a/app/nullius/catalogue/benchmarks/gaia/benchmark.json b/app/nullius/catalogue/benchmarks/gaia/benchmark.json index a89a7011..66b1b625 100644 --- a/app/nullius/catalogue/benchmarks/gaia/benchmark.json +++ b/app/nullius/catalogue/benchmarks/gaia/benchmark.json @@ -68,5 +68,11 @@ ], "citation": "@misc{mialon2023gaia,\n title={GAIA: a benchmark for General AI Assistants},\n author={Grégoire Mialon and Clémentine Fourrier and Craig Swift and Thomas Wolf and Yann LeCun and Thomas Scialom},\n year={2023},\n eprint={2311.12983},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}", "citation_source": "https://huggingface.co/spaces/gaia-benchmark/leaderboard/blob/9f133d71362e77b3539f1514f31b9c101a545fec/content.py", - "task_count": 165 + "task_count": 165, + "evidence": [ + { + "label": "Answer", + "path": "model_answer" + } + ] } diff --git a/app/nullius/catalogue/benchmarks/gsm8k/benchmark.json b/app/nullius/catalogue/benchmarks/gsm8k/benchmark.json index d85fd3e3..f6ee2806 100644 --- a/app/nullius/catalogue/benchmarks/gsm8k/benchmark.json +++ b/app/nullius/catalogue/benchmarks/gsm8k/benchmark.json @@ -43,5 +43,19 @@ "Answers must end with a line '#### '. The number is compared as text, so 18.00 does not match 18.", "The test split is run. The Socratic variant has the same questions and answers, with different worked explanations.", "GSM8K-Platinum is the test split with its errors cleaned. A problem has the same number in both, so the two runs compare problem by problem." + ], + "evidence": [ + { + "label": "Extracted answer", + "path": "extracted" + }, + { + "label": "Expected answer", + "path": "expected" + }, + { + "label": "Reply", + "path": "answer" + } ] } diff --git a/app/nullius/catalogue/benchmarks/humaneval/benchmark.json b/app/nullius/catalogue/benchmarks/humaneval/benchmark.json index 95ab2185..4cd92694 100644 --- a/app/nullius/catalogue/benchmarks/humaneval/benchmark.json +++ b/app/nullius/catalogue/benchmarks/humaneval/benchmark.json @@ -32,5 +32,23 @@ "citation_source": "https://github.com/openai/human-eval", "good_to_know": [ "One attempt per problem gives pass@1. With n attempts per problem, the run reports pass@1 to pass@n. The paper sampled 200." + ], + "evidence": [ + { + "label": "Why", + "path": "why" + }, + { + "label": "Result", + "path": "result" + }, + { + "label": "Not tested", + "path": "not_tested" + }, + { + "label": "solution.py", + "path": "solution.py" + } ] } diff --git a/app/nullius/catalogue/benchmarks/locomo/benchmark.json b/app/nullius/catalogue/benchmarks/locomo/benchmark.json index eaf8a1e0..3460beb4 100644 --- a/app/nullius/catalogue/benchmarks/locomo/benchmark.json +++ b/app/nullius/catalogue/benchmarks/locomo/benchmark.json @@ -39,5 +39,19 @@ } ], "citation": "@article{maharana2024evaluating,\n title={Evaluating very long-term conversational memory of llm agents},\n author={Maharana, Adyasha and Lee, Dong-Ho and Tulyakov, Sergey and Bansal, Mohit and Barbieri, Francesco and Fang, Yuwei},\n journal={arXiv preprint arXiv:2402.17753},\n year={2024}\n}", - "citation_source": "https://github.com/snap-research/locomo" + "citation_source": "https://github.com/snap-research/locomo", + "evidence": [ + { + "label": "Question", + "path": "question" + }, + { + "label": "Answer", + "path": "answer" + }, + { + "label": "Expected answer", + "path": "reference" + } + ] } diff --git a/app/nullius/catalogue/benchmarks/longmemeval/benchmark.json b/app/nullius/catalogue/benchmarks/longmemeval/benchmark.json index 2775d622..d23a9ac7 100644 --- a/app/nullius/catalogue/benchmarks/longmemeval/benchmark.json +++ b/app/nullius/catalogue/benchmarks/longmemeval/benchmark.json @@ -63,5 +63,20 @@ } ], "citation": "@article{wu2024longmemeval,\n title={LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory},\n author={Di Wu and Hongwei Wang and Wenhao Yu and Yuwei Zhang and Kai-Wei Chang and Dong Yu},\n year={2024},\n eprint={2410.10813},\n archivePrefix={arXiv},\n primaryClass={cs.CL},\n url={https://arxiv.org/abs/2410.10813},\n}", - "citation_source": "https://github.com/xiaowu0162/LongMemEval" + "citation_source": "https://github.com/xiaowu0162/LongMemEval", + "evidence": [ + { + "label": "Answer", + "path": "answer", + "reply": true + }, + { + "label": "Expected answer", + "path": "reference" + }, + { + "label": "Judge said", + "path": "judge_said" + } + ] } diff --git a/app/nullius/catalogue/benchmarks/open-telco/benchmark.json b/app/nullius/catalogue/benchmarks/open-telco/benchmark.json index 829563e6..57890e5a 100644 --- a/app/nullius/catalogue/benchmarks/open-telco/benchmark.json +++ b/app/nullius/catalogue/benchmarks/open-telco/benchmark.json @@ -202,5 +202,19 @@ ], "task_count": 20588, "citation": "@misc{maatouk2023teleqna,\n title={TeleQnA: A Benchmark Dataset to Assess Large Language Models Telecommunications Knowledge},\n author={Maatouk, Ali and Ayed, Fadhel and Piovesan, Nicola and De Domenico, Antonio and Debbah, Merouane and Luo, Zhi-Quan},\n year={2023}, eprint={2310.15051}, archivePrefix={arXiv}\n}\n\n@misc{ezzakri2025teletables,\n title={TeleTables: A Benchmark for Large Language Models in Telecom Table Interpretation},\n author={Ezzakri, Anas and Piovesan, Nicola and Sana, Mohamed and De Domenico, Antonio and Ayed, Fadhel and Zhang, Haozhe},\n year={2025}, eprint={2601.04202}, archivePrefix={arXiv}\n}\n\n@misc{colle2025telemath,\n title={TeleMath: A Benchmark for Large Language Models in Telecom Mathematical Problem Solving},\n author={Colle, Vincenzo and Sana, Mohamed and Piovesan, Nicola and De Domenico, Antonio and Ayed, Fadhel and Debbah, Merouane},\n year={2025}, eprint={2506.10674}, archivePrefix={arXiv}\n}\n\n@misc{sana2025telelogs,\n title={Reasoning Language Models for Root Cause Analysis in 5G Wireless Networks},\n author={Sana, Mohamed and Piovesan, Nicola and De Domenico, Antonio and Kang, Yibin and Zhang, Haozhe and Debbah, Merouane and Ayed, Fadhel},\n year={2025}, eprint={2507.21974}, archivePrefix={arXiv}\n}\n\n@misc{zou2024telecomgpt,\n title={TelecomGPT: A Framework to Build Telecom-Specific Large Language Models},\n author={Zou, Hang and Zhao, Qiyang and Tian, Yu and Bariah, Lina and Bader, Faouzi and Lestable, Thierry and Debbah, Merouane},\n year={2024}, eprint={2407.09424}, archivePrefix={arXiv}\n}\n\n@misc{gajjar2024oranbench,\n title={ORAN-Bench-13K: An Open Source Benchmark for Assessing LLMs in Open Radio Access Networks},\n author={Gajjar, Pranshav and Shah, Vijay K.},\n year={2024}, eprint={2407.06245}, archivePrefix={arXiv}\n}\n\n@misc{gajjar2025oransight2,\n title={ORANSight-2.0: Foundational LLMs for O-RAN},\n author={Gajjar, Pranshav and Shah, Vijay K.},\n year={2025}, eprint={2503.05200}, archivePrefix={arXiv}\n}\n\n@misc{ferrag2026sixgbench,\n title={6G-Bench: An Open Benchmark for Semantic Communication and Network-Level Reasoning with Foundation Models in AI-Native 6G Networks},\n author={Ferrag, Mohamed Amine and Lakas, Abderrahmane and Debbah, Merouane},\n year={2026}, eprint={2602.08675}, archivePrefix={arXiv}\n}", - "citation_source": "https://huggingface.co/datasets/GSMA/ot-full" + "citation_source": "https://huggingface.co/datasets/GSMA/ot-full", + "evidence": [ + { + "label": "Extracted answer", + "path": "extracted" + }, + { + "label": "Expected answer", + "path": "target" + }, + { + "label": "Reply", + "path": "answer" + } + ] } diff --git a/app/nullius/catalogue/benchmarks/osworld1/benchmark.json b/app/nullius/catalogue/benchmarks/osworld1/benchmark.json index c334a8d8..29f7c24d 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/benchmark.json +++ b/app/nullius/catalogue/benchmarks/osworld1/benchmark.json @@ -9,7 +9,6 @@ ], "origin": "official", "good_to_know": [ - "An agent runs it through the computer port: the agent's tool calls drive OSWorld's own loop, one step for each acting call. A step's observation is the screenshot that loop hands its agent for the next decision, with no capture added; the files a step names are read once its actions and their pauses have run. Steps (100) and Pause (3.0 seconds) set that loop.", "Original runs one of OSWorld's own agents, chosen by the Agent option (M3 by default), with a model it is published with.", "Providers: OpenAI for OpenAI CUA; OpenAI-compatible for Muse Spark (Meta's API) and for EvoCUA, AutoGLM-OS and Mano (your model server); OpenRouter for the others.", "At this version only the null control has run through Nullius. OSWorld's agents are the same code as in main (044bc33), where M3, PromptAgent and Qwen-CUA completed tasks.", @@ -58,7 +57,6 @@ "versions": { "044bc33": { "good_to_know": [ - "An agent runs it through the computer port: the agent's tool calls drive OSWorld's own loop, one step for each acting call. A step's observation is the screenshot that loop hands its agent for the next decision, with no capture added; the files a step names are read once its actions and their pauses have run. Steps (100) and Pause (3.0 seconds) set that loop.", "Original runs one of OSWorld's own agents, chosen by the Agent option (M3 by default), with a model it is published with.", "Providers: OpenAI for OpenAI CUA; OpenAI-compatible for Muse Spark (Meta's API) and for EvoCUA, AutoGLM-OS and Mano (your model server); OpenRouter for the others.", "Only M3, PromptAgent and Qwen-CUA have completed tasks through Nullius. The other agents were checked up to their first model call.", @@ -88,5 +86,6 @@ } } } - } + }, + "evidence": [] } diff --git a/app/nullius/catalogue/benchmarks/osworld1/standard.json b/app/nullius/catalogue/benchmarks/osworld1/standard.json index 00096f8b..70fae6c7 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/standard.json +++ b/app/nullius/catalogue/benchmarks/osworld1/standard.json @@ -170,6 +170,7 @@ "yours" ], "default": "default", + "yours": "100", "pattern": "default|[1-9][0-9]{0,3}", "example": "50", "limit": true, @@ -218,8 +219,8 @@ } }, "pause": { - "label": "Pause", - "summary": "run_single_example's sleep_after_execution for an agent: the seconds env.step waits after each action, 3.0 as in run_multienv_m3.py's default.", + "label": "Pause after each action (seconds)", + "summary": "Seconds to wait after each action before taking the next screenshot.", "pattern": "[0-9]{1,2}(\\.[0-9]{1,2})?", "example": "5.0", "default": "3.0", @@ -230,7 +231,8 @@ }, "host": { "docker": { - "summary": "Docker on the machine the driver runs on, usable without sudo, for the upstream's docker provider; /dev/kvm makes the VMs fast, and the upstream runs them without it, slowly.", + "label": "Docker for the tasks' VMs", + "summary": "Docker on the machine, usable without sudo: OSWorld starts each task's VM in it. /dev/kvm makes the VMs fast; without it they run slowly.", "check": [ "docker" ] diff --git a/app/nullius/catalogue/benchmarks/osworld2/benchmark.json b/app/nullius/catalogue/benchmarks/osworld2/benchmark.json index 5ad19c7c..b6b1f26d 100644 --- a/app/nullius/catalogue/benchmarks/osworld2/benchmark.json +++ b/app/nullius/catalogue/benchmarks/osworld2/benchmark.json @@ -62,5 +62,19 @@ } ], "citation": "@misc{yuan26osworld2,\n title={OSWorld 2.0: Benchmarking Computer Use Agents on Long-Horizon Real-World Tasks}, \n author={Mengqi Yuan and Zilong Zhou and Xinzhuang Xiong and Weiming Wu and Jiayang Sun and Jiamin Song and Kaiqian Cui and Bowen Wang and Haoyuan Wu and Yitong Li and Dunjie Lu and Haikong Lu and Qi Zhen and Xinyuan Wang and Jiaqi Deng and Yuhao Yang and Cheng Chen and Boyuan Zheng and Alex Su and Xiao Yu and Hao Zou and Saaket Agashe and Xing Han Lu and Manpreet Kaur and Zhengyang Qi and Vincent Sunn Chen and Frederic Sala and Dayiheng Liu and Junyang Lin and Zhou Yu and Yu Su and Siva Reddy and Xin Eric Wang and Peng Qi and Tianbao Xie and Tao Yu},\n year={2026},\n eprint={2606.29537},\n archivePrefix={arXiv},\n primaryClass={cs.AI},\n url={https://arxiv.org/abs/2606.29537}, \n}", - "citation_source": "https://github.com/xlang-ai/OSWorld-V2" + "citation_source": "https://github.com/xlang-ai/OSWorld-V2", + "evidence": [ + { + "label": "Safety checks failed", + "path": "safety.failed" + }, + { + "label": "Safety checks", + "path": "safety.checks" + }, + { + "label": "Penalty", + "path": "safety.total_penalty" + } + ] } diff --git a/app/nullius/catalogue/benchmarks/swe-bench-verified/benchmark.json b/app/nullius/catalogue/benchmarks/swe-bench-verified/benchmark.json index 789b156c..980b8712 100644 --- a/app/nullius/catalogue/benchmarks/swe-bench-verified/benchmark.json +++ b/app/nullius/catalogue/benchmarks/swe-bench-verified/benchmark.json @@ -83,5 +83,22 @@ } }, "citation": "@inproceedings{\n jimenez2024swebench,\n title={{SWE}-bench: Can Language Models Resolve Real-world Github Issues?},\n author={Carlos E Jimenez and John Yang and Alexander Wettig and Shunyu Yao and Kexin Pei and Ofir Press and Karthik R Narasimhan},\n booktitle={The Twelfth International Conference on Learning Representations},\n year={2024},\n url={https://openreview.net/forum?id=VTF8yNQM66}\n}", - "citation_source": "https://github.com/SWE-bench/SWE-bench" + "citation_source": "https://github.com/SWE-bench/SWE-bench", + "evidence": [ + { + "label": "Why", + "path": "why" + }, + { + "label": "Infrastructure failure", + "path": "infra_failure" + }, + { + "label": "Timed out", + "path": "timed_out", + "unless": [ + "no" + ] + } + ] } diff --git a/app/nullius/catalogue/benchmarks/tau3-bench/benchmark.json b/app/nullius/catalogue/benchmarks/tau3-bench/benchmark.json index 72871ecc..ca621f81 100644 --- a/app/nullius/catalogue/benchmarks/tau3-bench/benchmark.json +++ b/app/nullius/catalogue/benchmarks/tau3-bench/benchmark.json @@ -45,5 +45,44 @@ "verify": 300 }, "citation": "@misc{barres2025tau2,\n title={$\\tau^2$-Bench: Evaluating Conversational Agents in a Dual-Control Environment},\n author={Victor Barres and Honghua Dong and Soham Ray and Xujie Si and Karthik Narasimhan},\n year={2025},\n eprint={2506.07982},\n archivePrefix={arXiv},\n primaryClass={cs.AI},\n url={https://arxiv.org/abs/2506.07982},\n}\n\n@misc{yao2024tau,\n title={$\\tau$-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains},\n author={Shunyu Yao and Noah Shinn and Pedram Razavi and Karthik Narasimhan},\n year={2024},\n eprint={2406.12045},\n archivePrefix={arXiv},\n primaryClass={cs.AI},\n url={https://arxiv.org/abs/2406.12045},\n}\n\n@article{shi2026tau,\n title={$\\tau$-Knowledge: Evaluating Conversational Agents over Unstructured Knowledge},\n author={Shi, Quan and Zytek, Alexandra and Razavi, Pedram and Narasimhan, Karthik and Barres, Victor},\n journal={arXiv preprint arXiv:2603.04370},\n year={2026}\n}", - "citation_source": "https://github.com/sierra-research/tau2-bench" + "citation_source": "https://github.com/sierra-research/tau2-bench", + "evidence": [ + { + "label": "Checks", + "path": "reward_info.reward_breakdown", + "names": { + "DB": "Database", + "COMMUNICATE": "Communication", + "ACTION": "Actions", + "ENV_ASSERTION": "Environment", + "NL_ASSERTION": "Assertions" + }, + "values": { + "1.0": "Pass", + "0.0": "Fail" + } + }, + { + "label": "Ended by", + "path": "termination", + "values": { + "user_stop": "User", + "agent_stop": "Agent", + "max_steps": "Step limit", + "timeout": "Timeout", + "too_many_errors": "Too many errors", + "agent_error": "Agent error", + "user_error": "User error", + "context_window_exceeded": "Context window exceeded", + "unexpected_error": "Unexpected error" + } + }, + { + "label": "Tool errors", + "path": "tool_errors", + "unless": [ + "0" + ] + } + ] } diff --git a/app/nullius/catalogue/benchmarks/terminal-bench/benchmark.json b/app/nullius/catalogue/benchmarks/terminal-bench/benchmark.json index 6b51590c..e213beb9 100644 --- a/app/nullius/catalogue/benchmarks/terminal-bench/benchmark.json +++ b/app/nullius/catalogue/benchmarks/terminal-bench/benchmark.json @@ -68,5 +68,30 @@ } }, "citation": "@inproceedings{merrill2026terminalbench,\n title={Terminal-Bench: Benchmarking Agents on Hard, Realistic Tasks in Command Line Interfaces},\n author={Mike A Merrill and Alexander Glenn Shaw and Nicholas Carlini and Boxuan Li and Harsh Raj and Ivan Bercovich and Lin Shi and Jeong Yeon Shin and Thomas Walshe and E. Kelly Buchanan and Junhong Shen and Guanghao Ye and Haowei Lin and Jason Poulos and Maoyu Wang and Jenia Jitsev and Marianna Nezhurina and Di Lu and Orfeas Menis Mastromichalakis and Zhiwei Xu and Zizhao Chen and Yue Liu and Robert Zhang and Leon Liangyu Chen and Anurag Kashyap and Jan-Lucas Uslu and Jeffrey Li and Jianbo Wu and Minghao Yan and Song Bian and Vedang Sharma and Ke Sun and Steven Dillmann and Akshay Anand and Andrew Lanpouthakoun and Bardia Koopah and Changran Hu and Etash Kumar Guha and Gabriel H. S. Dreiman and Jiacheng Zhu and Karl Krauth and Li Zhong and Niklas Muennighoff and Robert Kwesi Amanfu and Shangyin Tan and Shreyas Pimpalgaonkar and Tushar Aggarwal and Xiangning Lin and Xin Lan and Xuandong Zhao and Yiqing Liang and Yuanli Wang and Zilong Wang and Changzhi Zhou and David Heineman and Hange Liu and Harsh Trivedi and John Yang and Junhong Lin and Manish Shetty and Michael Yang and Nabil Omi and Negin Raoof and Shanda Li and Terry Yue Zhuo and Wuwei Lin and Yiwei Dai and Yuxin Wang and Wenhao Chai and Shang Zhou and Dariush Wahdany and Ziyu She and Jiaming Hu and Zhikang Dong and Yuxuan Zhu and Sasha Cui and Ahson Saiyed and Arinbj{\\\"o}rn Kolbeinsson and Christopher Michael Rytting and Ryan Marten and Yixin Wang and Alex Dimakis and Andy Konwinski and Ludwig Schmidt},\n booktitle={The Fourteenth International Conference on Learning Representations},\n year={2026},\n url={https://openreview.net/forum?id=a7Qa4CcHak}\n}", - "citation_source": "https://github.com/laude-institute/terminal-bench" + "citation_source": "https://github.com/laude-institute/terminal-bench", + "evidence": [ + { + "label": "Why", + "path": "why" + }, + { + "label": "Tests failed", + "path": "tests.failed" + }, + { + "label": "Tests passed", + "path": "tests.passed" + }, + { + "label": "Timed out", + "path": "timed_out", + "unless": [ + "no" + ] + }, + { + "label": "Test output", + "path": "output" + } + ] } diff --git a/app/nullius/catalogue/catalog.py b/app/nullius/catalogue/catalog.py index c8f45593..1222ce61 100644 --- a/app/nullius/catalogue/catalog.py +++ b/app/nullius/catalogue/catalog.py @@ -16,6 +16,10 @@ order is the folders', and nothing depends on it. ``layout`` is the check on the tree itself - a folder named after its key - and ``validate`` runs it. +An optional ``records`` lists what the benchmark's verifier leaves in a +trial beside Nullius's own records, each a label and a path under the trial's +``verifier/``: a trial's Artifacts tab lists and serves those that exist. + An optional ``task_count`` gives the number of distinct tasks when datasets overlap, such as a full split beside difficulty subsets. It controls the benchmark headline only; every dataset keeps its own count. @@ -98,6 +102,13 @@ class Benchmark: #: the file, the fields that say pass or fail, the words the pages use; empty #: when the reward is all there is report: dict = field(default_factory=dict) + #: records its verifier leaves in a trial, each a ``label`` and a ``path`` under + #: the trial's ``verifier/`` (a file, or a folder whose files are listed): the + #: trial's Artifacts tab lists those that exist (``nullius.runs.artifacts``) + records: list = field(default_factory=list) + #: what of its score's detail a trial that fell short shows, in order + #: (``nullius.runs.evidence``); None shows the whole detail + evidence: list | None = None #: how to cite it: the BibTeX its official repository gives, else its paper's citation: str = "" citation_source: str = "" @@ -177,6 +188,28 @@ class Dataset: notes: str = "" +def valid_record(record) -> bool: + """A declared record's shape (``Benchmark.records``): a label, and a path + under ``verifier/`` with no empty, ``.`` or ``..`` part and no backslash.""" + if not isinstance(record, dict) or not isinstance(record.get("label"), str) or not record["label"].strip(): + return False + path = record.get("path") + if not isinstance(path, str) or "\\" in path or "\0" in path: + return False + parts = path.split("/") + return len(parts) > 1 and parts[0] == "verifier" and all(p not in ("", ".", "..") for p in parts[1:]) + + +def valid_evidence(entry) -> bool: + """A declared evidence row's shape (``nullius.runs.evidence``).""" + words = lambda x: isinstance(x, dict) and all(isinstance(v, str) for v in x.values()) + return (isinstance(entry, dict) and set(entry) <= {"label", "path", "values", "names", "unless", "reply"} + and all(isinstance(entry.get(k), str) and entry[k].strip() for k in ("label", "path")) + and words(entry.get("values", {})) and words(entry.get("names", {})) + and isinstance(entry.get("unless", []), list) and all(isinstance(x, str) for x in entry.get("unless", [])) + and isinstance(entry.get("reply", False), bool)) + + def sort_key(title: str) -> str: """Alphabetical as a reader expects: a title starting with τ files under T.""" return title.replace("τ", "t").replace("³", "3").lower() @@ -404,6 +437,10 @@ def validate(cat: Catalog) -> list: bad.append(f"{b.key}: published is {{agent: a Harbor agent's name, says: why it is the published one}}") if not b.category: bad.append(f"{b.key}: no category") + if not isinstance(b.records, list) or not all(valid_record(r) for r in b.records): + bad.append(f"{b.key}: records are each {{label, path under verifier/}}") + if b.evidence is not None and not (isinstance(b.evidence, list) and all(valid_evidence(e) for e in b.evidence)): + bad.append(f"{b.key}: evidence rows are each {{label, path}}, with values, names, unless or reply") for h in b.harness: if h not in dict(HARNESSES): bad.append(f"{b.key}: harness {h!r} is not one of {[k for k, _ in HARNESSES]}") diff --git a/app/nullius/charts.py b/app/nullius/charts.py index b6caf277..849d270b 100644 --- a/app/nullius/charts.py +++ b/app/nullius/charts.py @@ -3,7 +3,7 @@ The split: this module computes the geometry, in SVG user units, and ``templates/_charts.html`` draws it without arithmetic. -A caller passes :class:`Metric` objects, each a label, a tick formatter and one :class:`Value` per item, already +A caller passes :class:`Metric` objects, each a label, an axis formatter and one :class:`Value` per item, already computed and formatted as the caller shows them elsewhere: nothing here recomputes a value. A value of ``None`` is a gap, never a zero. A ``check`` item is drawn hollow and named so; nothing here ranks items. An item's ``series`` gives its marks one colour in every chart, the class ``s1`` to ``s8`` (cycling), which the stylesheet maps to @@ -63,11 +63,32 @@ def reading(self) -> str: return " ".join(filter(None, (self.text or "—", self.note))) +def places(step: float, least: int = 0) -> int: + """The fewest decimals, ``least`` at fewest, that write every multiple of ``step`` exactly.""" + p = least + while p < 12 and round(step, p) != round(step, 12): + p += 1 + return p + + +def number(v: float, step: float, top: float) -> str: + """A plain axis's tick: the decimals its step needs, the same for every tick; none at the origin.""" + return f"{v:.{0 if v == 0 else places(step)}f}" + + @dataclass(frozen=True) class Metric: + """``fmt(v, step, top)`` writes the tick ``v`` of an axis whose ticks are ``step`` apart and reach ``top`` at most + in size: one unit and one precision for the whole axis, so that every label is its own; the origin may drop its + decimals. ``bounds`` (low, high), either None, is the range the metric cannot leave (a rate's 0 and 1); the axis + keeps to it. ``size(top)``, when given, is the unit ``fmt`` writes such an axis in: a step that needs a decimal + more in it than twice the step does is doubled, so the axis shows the fewest decimals (95%, not 92.5%).""" + label: str values: tuple - fmt: Callable = str # a tick's label + fmt: Callable = number + bounds: tuple = (None, None) + size: Callable | None = None @dataclass(frozen=True) @@ -112,13 +133,15 @@ def viewbox(self) -> str: return f"0 0 {self.width:g} {self.height:g}" -def nice_ticks(lo: float, hi: float, count: int = 4, step_min: float = 0.0) -> tuple: - """Round ticks enclosing ``[lo, hi]``, about ``count`` steps, none finer than ``step_min``; ints where whole.""" +def nice_ticks(lo: float, hi: float, count: int = 4, step_min: float = 0.0, bounds: tuple = (None, None)) -> tuple: + """Round ticks enclosing ``[lo, hi]``, about ``count`` steps, none finer than ``step_min``; ints where whole. One + value gets a range around it, inwards only from a bound, and none below zero when it is zero.""" if hi < lo: lo, hi = hi, lo if hi == lo: - pad = abs(lo) * 0.1 or 1.0 - lo, hi = lo - pad, hi + pad + pad = abs(lo) * 0.1 + low, high = bounds + lo, hi = (max(lo - pad, low if low is not None else -math.inf), min(hi + pad, high if high is not None else math.inf)) if pad else (0, 1) raw = (hi - lo) / count mag = 10 ** math.floor(math.log10(raw)) step = max(next(m * mag for m in (1, 2, 2.5, 5, 10) if m * mag >= raw), step_min) @@ -131,8 +154,10 @@ def _clean(v: float): return int(v) if v == int(v) else v -def _tick(fmt: Callable, v) -> str: - return "0" if v == 0 else str(fmt(v)) +def _tick_labels(fmt: Callable, ticks: tuple) -> list: + """An axis's tick labels, in the one format ``fmt`` gives its step and its largest tick.""" + step, top = (ticks[1] - ticks[0]) if len(ticks) > 1 else 1, max(abs(t) for t in ticks) + return [str(fmt(t, step, top)) for t in ticks] class _Scale: @@ -145,15 +170,18 @@ def __call__(self, v: float) -> float: return round(self.a + (v - self.lo) / (self.hi - self.lo) * (self.b - self.a), 2) -def _ticks_for(values: list, with_zero: bool) -> tuple: +def _ticks_for(values: list, with_zero: bool, metric: Metric) -> tuple: """A metric's ticks: around its present values, from zero when its marks grow from zero.""" if with_zero: values = values + [0] lo, hi = (min(values), max(values)) if values else (0, 1) - if with_zero and lo == hi == 0: - hi = 1 whole = values and all(isinstance(v, int) for v in values) - return nice_ticks(lo, hi, step_min=1 if whole else 0) + ticks = nice_ticks(lo, hi, step_min=1 if whole else 0, bounds=metric.bounds) + if metric.size and len(ticks) > 1: + step, unit = ticks[1] - ticks[0], metric.size(max(abs(t) for t in ticks)) + if places(2 * step / unit) < places(step / unit): + ticks = nice_ticks(lo, hi, step_min=2 * step, bounds=metric.bounds) + return ticks def _x_labels(scale: _Scale, fmt: Callable, y: float) -> list: @@ -161,8 +189,7 @@ def _x_labels(scale: _Scale, fmt: Callable, y: float) -> list: before it is left out, the last one never: the gridlines still mark every tick.""" last = len(scale.ticks) - 1 kept = [] - for i, t in enumerate(scale.ticks): - text = _tick(fmt, t) + for i, (t, text) in enumerate(zip(scale.ticks, _tick_labels(fmt, scale.ticks))): anchor = "start" if i == 0 else "end" if i == last else "middle" x, w = scale(t), len(text) * _CHAR_W x0 = {"start": x, "end": x - w, "middle": x - w / 2}[anchor] @@ -178,7 +205,7 @@ def _rows(metric: Metric, with_zero: bool, mark: Callable) -> Panel: gives the marks of ``v`` at the row's centre ``y``, none for a gap, and the x its reading starts at. The gridlines and the baseline's reference cross each row's band only, never a name.""" present = [v.value for v in metric.values if v.value is not None] - scale = _Scale(_ticks_for(present, with_zero), _LEFT, WIDTH - _RIGHT) + scale = _Scale(_ticks_for(present, with_zero, metric), _LEFT, WIDTH - _RIGHT) base = next((v for v in metric.values if v.baseline and v.value is not None), None) base = base if len(present) > 1 else None marks, texts, y = [], [], 4.0 @@ -252,12 +279,12 @@ def scatter(x: Metric, y: Metric) -> Panel: shown = [(t, a, b) for t, (a, b) in zip(tags, pairs) if a.value is not None and b.value is not None] left, right, top, bottom = _S_LEFT, WIDTH - 8, _S_TOP, _S_HEIGHT - _S_BOTTOM # the scales inset from the frame, so a dot on the last tick is whole - sx = _Scale(_ticks_for([a.value for _, a, _ in shown], False), left + 12, right - 12) - sy = _Scale(_ticks_for([b.value for _, _, b in shown], False), bottom - 12, top + 12) + sx = _Scale(_ticks_for([a.value for _, a, _ in shown], False, x), left + 12, right - 12) + sy = _Scale(_ticks_for([b.value for _, _, b in shown], False, y), bottom - 12, top + 12) marks = [Mark("line", sx(t), top, x2=sx(t), y2=bottom, cls="grid") for t in sx.ticks] marks += [Mark("line", left, sy(t), x2=right, y2=sy(t), cls="grid") for t in sy.ticks] texts = _x_labels(sx, x.fmt, bottom + 14) - texts += [Text(left - 4, sy(t) + 4, (_tick(y.fmt, t),), "end", "tick") for t in sy.ticks] + texts += [Text(left - 4, sy(t) + 4, (text,), "end", "tick") for t, text in zip(sy.ticks, _tick_labels(y.fmt, sy.ticks))] texts += [Text(left, 12, (y.label,), cls="axis-title"), Text(right, bottom + 30, (x.label,), "end", "axis-title")] places: dict = {} for item in shown: diff --git a/app/nullius/cli.py b/app/nullius/cli.py index 0ac5fae3..aa960909 100644 --- a/app/nullius/cli.py +++ b/app/nullius/cli.py @@ -15,6 +15,7 @@ "serve": "open the web application", "runs": "inspect run output", "compare": "compare runs", + "flags": "write a run's task flags", "import": "import ATIF or OpenTelemetry output", "standard": "inspect and run standard definitions", "workspace": "manage workspaces", @@ -25,6 +26,7 @@ MODULES = { "runs": "nullius.runs.cli", "compare": "nullius.compare.cli", + "flags": "nullius.runs.flags_cli", "import": "nullius.importers.cli", "standard": "nullius.standard.cli", "workspace": "nullius.workspace_cli", diff --git a/app/nullius/compare/comparison.py b/app/nullius/compare/comparison.py index be28aba3..8bb5902a 100644 --- a/app/nullius/compare/comparison.py +++ b/app/nullius/compare/comparison.py @@ -137,6 +137,7 @@ class Comparison: datasets_match: bool datasets_known: bool pass_k: tuple[dict | None, ...] = () + set_aside_trials: tuple[int, ...] = () # trials of flagged tasks left out of each column @property def references(self) -> list[str]: @@ -147,7 +148,13 @@ def n_differing(self) -> int: return sum(row.differs for row in self.tasks) -def build(selected: Sequence[SelectedRun], cohort: str = "whole") -> Comparison: +def task_key(selection: SelectedRun, task_base: str) -> tuple[str, str]: + """A task's identity across columns: its recorded dataset and its name. Missing dataset identities cannot + prove that identical short names refer to the same task; a per-column sentinel keeps their rows apart.""" + return selection.job.dataset or f"[unidentified:{selection.value}]", task_base + + +def build(selected: Sequence[SelectedRun], cohort: str = "whole", set_aside: frozenset = frozenset()) -> Comparison: """Build a whole-run or exact shared-task view without changing any Job. Matching uses the dataset string as recorded, without alias/path guessing. @@ -158,6 +165,8 @@ def build(selected: Sequence[SelectedRun], cohort: str = "whole") -> Comparison: differ. Unknown outcomes remain in the adjusted-rate denominator because Job owns the arithmetic. A cohort cannot manufacture a new wall-clock run interval. + *set_aside*: ``(dataset, task_base)`` keys whose trials leave every column, after + the cohort: the flagged tasks of the page's filters, the same for all runs. """ if cohort not in {"whole", "matched"}: raise ValueError("Choose whole runs or matched tasks as the comparison cohort.") @@ -166,25 +175,24 @@ def build(selected: Sequence[SelectedRun], cohort: str = "whole") -> Comparison: datasets_match = len({selection.job.dataset for selection in selected}) <= 1 def key(selection, trial): - # Missing dataset identities cannot prove that identical short names - # refer to the same task. A per-column sentinel keeps their rows apart. - dataset = selection.job.dataset or f"[unidentified:{selection.value}]" - return dataset, trial.task_base + return task_key(selection, trial.task_base) sets = [{key(selection, trial) for trial in selection.job.trials} for selection in selected] common = set.intersection(*sets) if sets else set() # each task's attempts, one list per run, the tasks in the order they appear - jobs, excluded, repeated, by_task = [], [], [], {} + jobs, excluded, repeated, aside, by_task = [], [], [], [], {} for column, selection in enumerate(selected): original = selection.job - trials = [trial for trial in original.trials - if cohort == "whole" or key(selection, trial) in common] + cohort_trials = [trial for trial in original.trials + if cohort == "whole" or key(selection, trial) in common] + trials = [trial for trial in cohort_trials if key(selection, trial) not in set_aside] + aside.append(len(cohort_trials) - len(trials)) # Aggregate properties derive from trials; copied clocks are suppressed # for matched views because their interval still belongs to the full run. view = replace(original, trials=trials, - **({"started_at": None, "finished_at": None} if cohort == "matched" else {})) + **({"started_at": None, "finished_at": None} if cohort == "matched" or set_aside else {})) jobs.append(view) - excluded.append(len(original.trials) - len(trials)) + excluded.append(len(original.trials) - len(cohort_trials)) repeated.append(len(trials) - len({key(selection, trial) for trial in trials})) for trial in trials: by_task.setdefault(key(selection, trial), [[] for _ in selected])[column].append(trial) @@ -198,8 +206,8 @@ def task_row(task_key, columns): # pass@k from the rows' own tasks, so the summary and the table count alike pass_k = tuple(task_attempts.for_tasks(row.tried[column].trials for row in rows if row.tried[column]) for column in range(len(selected))) - return Comparison(selected, cohort, tuple(jobs), tuple(rows), len(common), - tuple(excluded), tuple(repeated), datasets_match, known, pass_k) + return Comparison(selected, cohort, tuple(jobs), tuple(rows), len(common - set_aside), + tuple(excluded), tuple(repeated), datasets_match, known, pass_k, tuple(aside)) diff --git a/app/nullius/constraints.py b/app/nullius/constraints.py index 832ead05..a4392d6f 100644 --- a/app/nullius/constraints.py +++ b/app/nullius/constraints.py @@ -40,6 +40,8 @@ """ from __future__ import annotations +import calendar +import contextlib import functools import json import math @@ -49,7 +51,6 @@ import stat import subprocess import textwrap -import threading import time from dataclasses import dataclass, field from typing import Callable, Dict, List, Optional, Sequence, Tuple @@ -559,7 +560,7 @@ def samples(cap: Optional[dict] = None) -> dict: # -- what the last test found, per machine ---------------------------------------- -_STORE = threading.Lock() # one load-modify-write at a time: Test all tests every machine at once +VERSION = 1 # the store's shape: {"version", "machines"}; a bare object of machines before it def store_path(env=None) -> str: @@ -567,34 +568,59 @@ def store_path(env=None) -> str: def load(env=None) -> Dict[str, dict]: - """Every machine's last test: ``{machine: {capacity, enforced, refused, applied, at}}``; empty when unread.""" + """Every machine's last test: ``{machine: {capacity, enforced, refused, applied, at}}``; empty when unread. + A file of before ``version`` is the bare object of machines.""" try: with open(store_path(env), encoding="utf-8") as f: doc = json.load(f) except (OSError, ValueError): return {} + if not isinstance(doc, dict): + return {} + if "version" in doc: + doc = doc.get("machines") return doc if isinstance(doc, dict) else {} +def tested_at(at: Optional[str]) -> str: + """A test's ``at`` in this machine's local time, as Settings shows it: UTC with ``Z`` + since ``version`` 1, local with no zone before it, shown as it was.""" + if not at or not at.endswith("Z"): + return (at or "").replace("T", " ") + try: + t = calendar.timegm(time.strptime(at, "%Y-%m-%dT%H:%M:%SZ")) + except ValueError: + return at.replace("T", " ") + return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t)) + + +@contextlib.contextmanager +def _changing(env=None): + """The store as it is now, for one change, written when the change is done; + one change at a time across processes, so none loses another's machine.""" + out = store_path(env) + os.makedirs(os.path.dirname(out), exist_ok=True) + with ondisk.locked(out + ".lock"): + doc = load(env) + yield doc + ondisk.write_whole(out, json.dumps({"version": VERSION, "machines": doc}, indent=1, sort_keys=True), mode=0o600) + + def save(machine: str, found: dict, env=None) -> None: """One machine's test over what it found before (a test that did not reach the engine keeps the last capacity), kept beside the others.""" - with _STORE: - doc = load(env) - doc[machine] = {**(doc.get(machine) or {}), **found, "at": time.strftime("%Y-%m-%dT%H:%M:%S")} + with _changing(env) as doc: + doc[machine] = {**(doc.get(machine) or {}), **found, "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} doc[machine].pop("stale", None) - _write(doc, env) def move(old: str, new: Optional[str], stale: bool = False, env=None) -> None: """A machine's last test under its new entry (``stale`` when it now names another machine), or forgotten when ``new`` is None.""" - with _STORE: - doc = load(env) + with _changing(env) as doc: found = doc.pop(old, None) if found is not None and new is not None: doc[new] = dict(found, stale=True) if stale else found - _write(doc, env) def rekey(text: str, old: str, new: Optional[str]) -> Optional[str]: @@ -611,13 +637,6 @@ def rekey(text: str, old: str, new: Optional[str]) -> Optional[str]: return json.dumps(doc) if doc else None -def _write(doc: dict, env=None) -> None: - """The store, written whole to a file of its own, then renamed.""" - out = store_path(env) - os.makedirs(os.path.dirname(out), exist_ok=True) - ondisk.write_whole(out, json.dumps(doc, indent=1, sort_keys=True), mode=0o600) - - def engine_less(found: Optional[dict]) -> bool: """Whether a machine's last test found no engine answering there, so no container constraint can hold.""" return bool((found or {}).get("capacity")) and not (found.get("engine") or found.get("enforced") or found.get("refused")) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index aa4d58d3..bcb809a1 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -133,7 +133,7 @@ # The line the launcher's stdin ends with, after the key and the endpoint: # either may be empty, so only this line says the two arrived whole. STDIN_END = "@end" -SYNC_EVERY = 10.0 # seconds between looks at a running part (mirror, log, exit) +SYNC_EVERY = 1.0 # seconds between looks at a running part (mirror, log, exit) STOP_POLL = 0.5 # how often a running command looks for a Stop STOP_WAIT = 20.0 # seconds a Stop's own commands on the target take at most: the kill and the last copy back, together LAUNCH_GRACE = 5.0 # seconds a restart waits for a part a launcher claimed to start (_settle) @@ -633,13 +633,13 @@ def summary(self) -> dict: def stages(self) -> dict: """The stages said so far, folded for the page (``progress.fold``). - Once the run has failed or been stopped, a stage still running was - cut short by it, and nothing is waiting any more.""" + Once the run has ended, no stage is running or waiting any more. + Counts remain exactly what the progress events reported.""" with self._lock: events = list(self.events) got = progress.fold(events) - if self.state in ("failed", "stopped"): - got["stages"] = [dict(r, state="failed") if r["state"] == "running" else r for r in got["stages"] if r["state"] != "waiting"] + if self.state in ("done", "failed", "stopped"): + got["stages"] = [dict(r, state="done" if self.state == "done" else "failed") if r["state"] == "running" else r for r in got["stages"] if r["state"] != "waiting"] got["current"] = None return got @@ -1479,8 +1479,8 @@ def _launch(self, part: dict) -> Optional[bool]: return False prices_on_target = "" if self.plan.runner == STANDARD and self.on_host: - # the price list is this machine's user's, so the run takes it along (nullius.prices) - an empty one - # too: a host's own list, if it has one, never prices a run started here + # the price list and the user's own rows are this machine's user's, so the run takes both along, in the one + # file of before (nullius.prices) - empty too: a host's own list, if it has one, never prices a run started here prices_on_target = run_dir + "/prices.json" rc, out = self._sh(f"cat > {self._q(prices_on_target)}", 60, stdin=json.dumps(price_list.load()) + "\n") if rc != 0: diff --git a/app/nullius/hosts.py b/app/nullius/hosts.py index f5d6af38..1093d8c5 100644 --- a/app/nullius/hosts.py +++ b/app/nullius/hosts.py @@ -294,20 +294,22 @@ def _reason(rc: int, last: str) -> str: _KEY_HEADER = re.compile(rb"^-----BEGIN (?:OPENSSH |RSA |EC |DSA |ENCRYPTED )?PRIVATE KEY-----") -def _key_name(user: str, host: str) -> str: - return re.sub(r"[^A-Za-z0-9._@-]+", "_", f"{user}@{host}") +def _key_name(user: str, host: str, port: Optional[int] = None) -> str: + """, then _ when the entry has one: no address holds a ``_``, + so two ports of one address, or an address and a port, never share a file.""" + return re.sub(r"[^A-Za-z0-9._@-]+", "_", f"{user}@{host}") + (f"_{port}" if port else "") -def save_key(user: str, host: str, data: bytes, key_dir: Optional[str] = None) -> str: +def save_key(user: str, host: str, data: bytes, key_dir: Optional[str] = None, port: Optional[int] = None) -> str: """A private key handed to the page, written where ssh can read it and - nobody else: /ssh/, mode 0600. The path it is at.""" + nobody else: /ssh/[_], mode 0600. The path it is at.""" if not _KEY_HEADER.match(data.lstrip()) or len(data) > 20000: raise ValueError("not a private key file (expected -----BEGIN … PRIVATE KEY-----)") if b"ENCRYPTED" in data[:200]: raise ValueError("the key has a passphrase; ssh could not use it without a prompt") key_dir = key_dir or KEY_DIR or os.path.join(paths.config_dir(), "ssh") os.makedirs(key_dir, mode=0o700, exist_ok=True) - path = os.path.join(key_dir, _key_name(user, host)) + path = os.path.join(key_dir, _key_name(user, host, port)) fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "wb") as fh: fh.write(data if data.endswith(b"\n") else data + b"\n") @@ -317,7 +319,8 @@ def save_key(user: str, host: str, data: bytes, key_dir: Optional[str] = None) - def forget_keys(old: str, new: str, key_dir: Optional[str] = None) -> List[tuple]: """Delete each key file that ``save_key`` wrote for an entry of the host list ``old`` when no entry of the list ``new`` names it. Only the file - /ssh/ of that entry goes: Nullius's own key and a key + /ssh/[_] of that entry goes, or , the name + an entry with a port was given before: Nullius's own key and a key the user named by path stay. The files not deleted, each as (path, reason).""" key_dir = os.path.realpath(key_dir or KEY_DIR or os.path.join(paths.config_dir(), "ssh")) try: @@ -328,7 +331,7 @@ def forget_keys(old: str, new: str, key_dir: Optional[str] = None) -> List[tuple failed = [] for h in before: path = h.key and os.path.realpath(os.path.expanduser(h.key)) - if not path or path in kept or path != os.path.join(key_dir, _key_name(h.user, h.host)): + if not path or path in kept or path not in {os.path.join(key_dir, _key_name(h.user, h.host, p)) for p in (h.port, None)}: continue try: os.unlink(path) diff --git a/app/nullius/judge/questions.py b/app/nullius/judge/questions.py index d24d9fa3..9271dd3f 100644 --- a/app/nullius/judge/questions.py +++ b/app/nullius/judge/questions.py @@ -171,6 +171,35 @@ def state_of(qid: str) -> str: }, }) +# --- the trial page: the same two questions a person answers on the User judge tab ----- +# A failed trial's cause in the tab's four labels, and whether its task is fair. Both models answer them beside the +# person, for comparison only: the Filtered score reads the person's flags alone (`runs.failure_analysis`). +register("trial", { + "failure_label": { + "label": 'Why it failed', "blurb": "The cause, in the User judge's four labels or other", + "type": "choice", "state": "failure", "when": "unresolved", + "instructions": "Why did this trial not resolve? Here `agent` means the program around the model, not the model's own steps. Pick the one layer the transcript, the recorded error and the verifier output blame most; pick `other` when they do not show which.", + "criteria": { + "agent": "The program around the model failed it: a step, turn or time limit it set was hit, a tool it provides returned an error or wrong data, or it lost or cut text the model needed", + "model": "The model's own mistake: a rule, document or tool result in view was not applied, a reasoning slip, a wrong or invented fact, a wrong or missing action", + "environment": "Something outside the agent broke the trial: the simulated user, an external service, the infrastructure, a model rate limit or an API error", + "evaluator": "The grading is at fault: the verifier or the expected outcome is wrong, or it rejects a defensible answer", + "other": "A cause outside this list, or the text shown does not say which layer is at fault", + }, + }, + "task_flag": { + "label": 'Task flag', "blurb": "Whether the task itself is sound, in the User judge's flags", + "type": "choice", "state": "failure", "when": "unresolved", + "instructions": "Is this task itself sound, judged from the instruction and the verifier output shown, not from the agent's work? Pick `cannot_tell` unless the text shown supports another option.", + "criteria": { + "flawed": "The verifier output shows an expected outcome that is wrong, or that the instruction gives no way to reach", + "ambiguous": "The instruction allows more than one defensible reading, and the verifier output accepts only one", + "fair": "The instruction has one defensible reading and the verifier output shows nothing wrong with the expected outcome", + "cannot_tell": "The text shown is not enough to judge the task: the expected outcome or the rules are not in view", + }, + }, +}) + # --- the compare page: a matched pair ------------------------------------------------- # Each side is scored on its own, over its own `trial` state, against one # rubric; the pick is made in code (`compare.comparison.better_of`), never by diff --git a/app/nullius/paths.py b/app/nullius/paths.py index 2f3ddb0b..349efdbd 100644 --- a/app/nullius/paths.py +++ b/app/nullius/paths.py @@ -51,6 +51,12 @@ def prices_file(env=None) -> str: return env.get("NULLIUS_PRICES") or os.path.join(config_dir(env), "prices.json") +def own_prices_file(env=None) -> str: + """The user's own price rows, beside the list: ``prices-own.json`` for ``prices.json``.""" + root, ext = os.path.splitext(prices_file(env)) + return f"{root}-own{ext}" + + def catalogue_dir(env=None) -> str: env = os.environ if env is None else env return env.get("NULLIUS_CATALOGUE") or os.path.join(data_dir(env), "catalogue") @@ -79,7 +85,7 @@ def main(argv=None) -> int: parser = argparse.ArgumentParser(description="Show Nullius's persistent user directories (no secret values).") parser.add_argument("--json", action="store_true") args = parser.parse_args(argv) - values = {"settings": settings_file(), "secrets": secrets_dir(), "prices": prices_file(), "catalogue": catalogue_dir(), + values = {"settings": settings_file(), "secrets": secrets_dir(), "prices": prices_file(), "own prices": own_prices_file(), "catalogue": catalogue_dir(), "workspaces": workspaces_dir(), "runs": runs_dir(), "recipes": recipes_dir(), "cache": cache_dir()} if args.json: print(json.dumps(values, indent=2)) diff --git a/app/nullius/prices.py b/app/nullius/prices.py index efecae2d..934d3e93 100644 --- a/app/nullius/prices.py +++ b/app/nullius/prices.py @@ -1,16 +1,20 @@ """Model prices, the user's own: what a call's cost is estimated from when the provider's reply does not carry one. -Nullius ships no price. The list lives in one file of the user's -configuration, ``prices.json`` (``NULLIUS_PRICES`` names another: the file a -host is sent), in two parts: +Nullius ships no price. The prices live in two files of the user's +configuration (``NULLIUS_PRICES`` names another list, the file a host is sent; +the user's rows then sit beside it): -``models`` a public list, fetched on request and before a capped run (``update``) and kept whole - with where it came from and when: LiteLLM's - ``model_prices_and_context_window.json``, keyed by the model - names the providers themselves use -``own`` the user's rows, which win over the list: a price it lacks, a - negotiated one, a model served under a name of one's own +``prices.json`` ``models``, a public list, fetched on request and before a capped run (``update``) and + replaced whole, with where it came from and when: LiteLLM's + ``model_prices_and_context_window.json``, keyed by the model names the providers themselves use +``prices-own.json`` ``own``, the user's rows, which win over the list: a price it lacks, a + negotiated one, a model served under a name of one's own. Written only when + the user sets or removes one; a row that cannot price is kept and said (``problems``) + +A ``prices.json`` of before held ``own`` too: while there is no ``prices-own.json``, its +``own`` is the user's rows, and a refetch keeps it; the first change of a row moves them. +A host is sent the list and the user's rows as such a file. A row is USD per million tokens: ``input`` and ``output``, optionally ``cached`` (input a cache served), ``cache_write``, ``cache_write_1h``, and ``max_output``, @@ -28,6 +32,7 @@ from __future__ import annotations import argparse +import contextlib import json import os import time @@ -48,25 +53,57 @@ def path(env=None) -> str: return paths.prices_file(env) -def load(env=None) -> dict: - """The file as ``{from, on, models, own}``; missing or unreadable, empty: - no price is better than a run that cannot start for its price list.""" - doc = {"from": "", "on": "", "models": {}, "own": {}} +def own_path(env=None) -> str: + return paths.own_prices_file(env) + + +def _read(file: str): + """``file``'s JSON object; None when it is missing, ``False`` when it does not read as one.""" try: - with open(path(env), encoding="utf-8") as f: + with open(file, encoding="utf-8") as f: got = json.load(f) + except FileNotFoundError: + return None except (OSError, ValueError): - return doc - if isinstance(got, dict): - for k in ("from", "on"): - if isinstance(got.get(k), str): - doc[k] = got[k] - for k in ("models", "own"): - if isinstance(got.get(k), dict): - doc[k] = {n: r for n, r in got[k].items() if _usable(r)} + return False + return got if isinstance(got, dict) else False + + +def _own(env=None): + """The user's rows as written, a row that cannot price too, and what is wrong with + their file (None when nothing). Before ``prices-own.json``: the ``own`` of ``prices.json``.""" + got = _read(own_path(env)) + if got is None: + got = _read(path(env)) or {} + rows = got.get("own", {}) + return (rows, None) if isinstance(rows, dict) else ({}, None) # a list of before that does not read: nothing of the user's to keep + rows = got.get("own", {}) if got is not False else None + if not isinstance(rows, dict): + return {}, f"{own_path(env)} does not read as your prices: fix it or remove it" + return rows, None + + +def load(env=None) -> dict: + """The prices as ``{from, on, models, own}``, each row one that can price; a file + missing or unreadable, empty: no price is better than a run that cannot start for its price list.""" + doc = {"from": "", "on": "", "models": {}, "own": {}} + got = _read(path(env)) or {} + for k in ("from", "on"): + if isinstance(got.get(k), str): + doc[k] = got[k] + if isinstance(got.get("models"), dict): + doc["models"] = {n: r for n, r in got["models"].items() if _usable(r)} + doc["own"] = {n: r for n, r in _own(env)[0].items() if _usable(r)} return doc +def problems(env=None) -> list: + """What keeps one of the user's rows from pricing, one line each: kept as written, never dropped.""" + rows, why = _own(env) + return ([why] if why else []) + [f"{n} prices nothing: set its input and output prices again" + for n, r in sorted(rows.items()) if not _usable(r)] + + def _usable(r) -> bool: return isinstance(r, dict) and all(_number(r.get(k)) for k in ("input", "output")) @@ -75,9 +112,8 @@ def _number(v) -> bool: return isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0 -def save(doc: dict, env=None) -> None: +def _save(out: str, doc: dict) -> None: """Written whole beside the file, then renamed: a reader never finds half a list.""" - out = path(env) os.makedirs(os.path.dirname(out) or ".", exist_ok=True) ondisk.write_whole(out, json.dumps(doc, indent=1, sort_keys=True) + "\n") @@ -184,26 +220,43 @@ def update(source: Optional[str] = None, env=None, fetch: Optional[Callable[[str models = convert(json.loads(raw)) except ValueError as e: raise ValueError(f"{source}: {e}") - doc = load(env) - doc.update({"from": source, "on": today or time.strftime("%Y-%m-%d"), "models": models}) - save(doc, env) + doc = {"from": source, "on": today or time.strftime("%Y-%m-%d"), "models": models} + before = _read(path(env)) + if before and "own" in before and not os.path.exists(own_path(env)): + doc["own"] = before["own"] # a list of before holds the user's rows until their first change moves them + _save(path(env), doc) return {"n": len(models), "from": doc["from"], "on": doc["on"]} +@contextlib.contextmanager +def _changing_own(env=None): + """The user's rows as written, for one change, then written to their own file; + one change at a time across processes. Refused when their file does not read: + writing over it would lose every row in it.""" + out = own_path(env) + os.makedirs(os.path.dirname(out) or ".", exist_ok=True) + with ondisk.locked(out + ".lock"): + rows, why = _own(env) + if why: + raise ValueError(why) + rows = dict(rows) + yield rows + _save(out, {"own": rows}) + + def set_own(name: str, r: dict, env=None) -> None: name = str(name).strip() if not name or not _usable(r): raise ValueError("a model's name, and its input and output prices") - doc = load(env) - doc["own"][name] = r - save(doc, env) + with _changing_own(env) as rows: + rows[name] = r def remove_own(name: str, env=None) -> bool: - doc = load(env) - if doc["own"].pop(str(name).strip(), None) is None: + if str(name).strip() not in _own(env)[0]: return False - save(doc, env) + with _changing_own(env) as rows: + rows.pop(str(name).strip(), None) return True @@ -211,7 +264,7 @@ def state(env=None) -> dict: """What Settings shows: how many models the list prices, where it came from and when, and the user's own rows.""" doc = load(env) - return {"n": len(doc["models"]), "from": doc["from"], "on": doc["on"], "own": doc["own"]} + return {"n": len(doc["models"]), "from": doc["from"], "on": doc["on"], "own": doc["own"], "problems": problems(env)} def said(name: str, r: dict) -> str: @@ -262,14 +315,18 @@ def main(argv=None) -> int: doc, names = load(), list(getattr(a, "models", None) or []) both = {**doc["models"], **doc["own"]} if getattr(a, "json", False): - print(json.dumps({"file": path(), "from": doc["from"], "on": doc["on"], "n": len(doc["models"]), "own": doc["own"], + print(json.dumps({"file": path(), "own_file": own_path(), "from": doc["from"], "on": doc["on"], "n": len(doc["models"]), "own": doc["own"], + "problems": problems(), "models": {n: both.get(n) for n in names}}, indent=2)) return 0 print(f"file: {path()}") + print(f"own: {own_path()}") print(f"list: {len(doc['models'])} models, from {doc['from']} on {doc['on']}" if doc["models"] else "list: none yet - nullius prices update") for n, r in sorted(doc["own"].items()): print("own " + said(n, r)) + for line in problems(): + print("bad " + line) for n in names: print(said(n, both[n]) if n in both else f"{n}: no price") return 0 diff --git a/app/nullius/progress.py b/app/nullius/progress.py index bdfcb477..0f940157 100644 --- a/app/nullius/progress.py +++ b/app/nullius/progress.py @@ -47,11 +47,13 @@ # What the page calls each stage. One not here is shown by its own name. LABELS = {"connect": "Connect", "uv": "uv", "tasks": "Send the tasks", "app": "Send app/", "harbor": "Harbor", - "image": "Base image", "environment": "Environment", "upstream": "Benchmark source", "dataset": "Dataset", + "models": "Check models", "requirements": "Check requirements", "image": "Base image", "environment": "Environment", "upstream": "Benchmark source", "dataset": "Dataset", "driver": "Driver environment", "install": "Install", "runtime": "Agent runtime", "units": "Units"} _WORD = re.compile(r'([A-Za-z_][A-Za-z0-9_]*)=("(?:[^"\\]|\\.)*"|\S*)') _BARE = re.compile(r'^[^\s"=]+$') +# an image digest, shown short as ``docker images`` does: its first 12 hex +_DIGEST = re.compile(r"(sha256:[0-9a-f]{12})[0-9a-f]{52}") def _value(v) -> str: @@ -269,9 +271,16 @@ def fold(events: Iterable[dict]) -> dict: if key != st and st in stages and stages[st]["state"] == "waiting": stages = {(key if k == st else k): v for k, v in stages.items()} stages[key]["key"] = key - stages.setdefault(key, {"key": key, "stage": st, "label": label(ev), "state": "waiting"}) + stages.setdefault(key, {"key": key, "stage": st, "state": "waiting"}) row = stages[key] - row["label"] = label(ev) + if state == "start": + # A later part or retry starts this stage afresh. + for field in ("seconds", "bytes", "total", "detail"): + row.pop(field, None) + full = label(ev) + row["label"] = _DIGEST.sub(r"\1", full) + if row["label"] != full: + row["full"] = full if ev.get("detail") is not None: row["detail"] = ev["detail"] if state == "start": @@ -295,7 +304,7 @@ def fold(events: Iterable[dict]) -> dict: last = seen[-1] if seen else -1 rows = [r for i, r in enumerate(rows) if r["state"] != "waiting" or i > last] if ended: # a run that ended has nothing running, nor anything still to come - rows = [dict(r, state="failed") if r["state"] == "running" and ended == "refused" else r + rows = [dict(r, state="failed" if ended == "refused" else "done") if r["state"] == "running" else r for r in rows if r["state"] != "waiting"] current = next((r for r in rows if r["state"] == "running"), None) return {"stages": rows, "units": units, "current": current["key"] if current else None, "ended": ended, "detail": detail} diff --git a/app/nullius/providers.py b/app/nullius/providers.py index 0bffdbdd..37bd1662 100644 --- a/app/nullius/providers.py +++ b/app/nullius/providers.py @@ -42,9 +42,8 @@ "decisions": {"label": "OpenRouter Decisions", "path": "/decisions", "auth": "authorization"}, "openai-decisions": {"label": "OpenAI Decisions", "path": "/decisions", "auth": "authorization"}, } -# A preset is a provider record whose name, base, key and known endpoints are fixed here. The user adds -# only endpoints of other protocols, in the setting ``setting`` (``settings.is_record``); its key is -# the secret setting ``key``. Its ``endpoints`` are also the protocols it serves. +# A preset has fixed name, base, key setting and endpoints. Custom providers configure their own +# endpoints. A preset's endpoints are also the protocols it serves. PRESETS = { "openrouter": {"name": "OpenRouter", "base": "https://openrouter.ai/api/v1", "key": "OPENROUTER_API_KEY", "endpoints": {"chat": "/chat/completions", "responses": "/responses", "systemone": "/systemone", @@ -72,14 +71,12 @@ def key_setting(choice: str) -> str: return PRESETS[p]["key"] if p in PRESETS else endpoint_vars(e)[1] -def _entry_problem(entry, host: str = "") -> Optional[str]: +def _entry_problem(entry) -> Optional[str]: """Why ``entry`` cannot be an endpoint: a path starting with one slash, without a ``..`` segment, or a - full URL that passes the checks a base gets; on ``host`` only, when one is given (a preset's own).""" + full URL that passes the checks a base gets.""" if not isinstance(entry, str): return "a path or a URL" if entry.startswith(("http://", "https://")): - if host and urllib.parse.urlsplit(entry).hostname != host: - return f"a path, or a URL on {host}: the preset's key is sent there" return settings.endpoint_url_problem(entry) if not entry.startswith("/") or entry.startswith("//") or any(c.isspace() or ord(c) < 32 for c in entry): return "a path that starts with / or an http(s) URL" @@ -91,17 +88,15 @@ def _entry_problem(entry, host: str = "") -> Optional[str]: def record_problem(name: str, value: str) -> Optional[str]: """Why ``value`` cannot be the record setting ``name``, or None. A JSON object of ``FIELDS``: a name, a base the checks of an endpoint's URL pass, the key's setting name (only its own: never a key), and - endpoints by protocol, each a path, a full URL or null. A preset's fields and known endpoints are fixed; - a full URL it adds is on its own host, the one its key is for.""" + endpoints by protocol, each a path, a full URL or null. Presets accept no overrides.""" rec = settings.json_object(value) if rec is None: return 'a JSON object, such as {"base": "https://…/v1"}' preset = next((p for p in PRESETS if p.upper() == name), "") if set(rec) - set(FIELDS): return "an object of " + ", ".join(FIELDS) - fixed = [k for k in ("name", "base", "key") if preset and k in rec] - if fixed: - return f"a record without {', '.join(fixed)}: they are fixed for {PRESETS[preset]['name']}" + if preset and rec: + return f"a custom provider instead: endpoints and fields are fixed for {PRESETS[preset]['name']}" if rec.get("name") is not None and (not isinstance(rec["name"], str) or not 0 < len(rec["name"]) <= 400 or any(ord(c) < 32 for c in rec["name"])): return "a record whose name is one line of 400 characters at most" @@ -117,9 +112,7 @@ def record_problem(name: str, value: str) -> Optional[str]: for proto, entry in ends.items(): if proto not in PROTOCOLS: return f"a record whose endpoints are some of {', '.join(PROTOCOLS)}" - if preset and proto in PRESETS[preset]["endpoints"]: - return f"a record without the {proto} endpoint: it is fixed for {PRESETS[preset]['name']}" - why = entry is not None and _entry_problem(entry, urllib.parse.urlsplit(PRESETS[preset]["base"]).hostname if preset else "") + why = entry is not None and _entry_problem(entry) if why: return f"a record whose {proto} endpoint is {why}" return None @@ -134,8 +127,8 @@ def join(base: str, entry: str) -> str: def record(choice: str, env=None) -> dict: - """A provider's record, the three layers merged field by field (the later wins): the preset in code, - the file's and then the environment's record setting (``settings.load`` merged those two). A custom + """A preset's fixed record, or a custom record from file and environment (``settings.load`` merges + those two field by field, the environment winning). A custom provider reads its old settings where its record says nothing (a null says: none): MODEL__NAME as ``name``, MODEL__API_URL (MODEL_API_URL, unnamed) as ``base``; ``ignored`` names an old setting the record overrides. ``{id, name, base, key, endpoints, preset, ignored}``, where ``key`` is a setting name only.""" @@ -145,10 +138,7 @@ def record(choice: str, env=None) -> dict: own = settings.json_object(env.get(setting_of(choice))) if setting_of(choice) else None if own is not None and record_problem(setting_of(choice), json.dumps(own)): own = None # a record that does not validate is no record - rec = settings.merge_patch({k: v for k, v in (preset or {}).items()}, own or {}) - if preset: - rec.update({k: preset[k] for k in ("name", "base", "key")}, - endpoints={**(rec.get("endpoints") or {}), **preset["endpoints"]}) + rec = dict(preset) if preset else dict(own or {}) ignored = [] if not preset: old_name, old_url = (f"MODEL_{e}_NAME" if e else ""), endpoint_vars(e)[0] diff --git a/app/nullius/runs/artifacts.py b/app/nullius/runs/artifacts.py index 99557c16..ddc13138 100644 --- a/app/nullius/runs/artifacts.py +++ b/app/nullius/runs/artifacts.py @@ -1,7 +1,18 @@ -"""Bounded, redacted views of named trial records. No writes or arbitrary paths.""" +"""Bounded, redacted views of named trial records. No writes or arbitrary paths. + +Nullius's own records are ``FILES``. A benchmark may declare its own in its +``benchmark.json`` (``records``: each a ``label`` and a ``path`` under the +trial's ``verifier/``, a file or a folder whose files are listed, one level; +text files alone): +``declared`` finds them by the trial's source, and each is addressed by its +place in that list (``r0``, or ``r0-NAME`` for a file of a folder). A declared +record is opened one folder at a time from the trial's own, no link followed: +it never leads outside the trial.""" from __future__ import annotations import os +import re +import stat from nullius.redact import redact @@ -27,6 +38,96 @@ } CHUNK_SIZE = 8_000 MAX_READ = 16 * 1024 * 1024 +FOLDER_FILES = 200 # the most files a declared folder lists +SNIFF = 8192 # a declared file with a NUL byte this far in is not text: not a record +DECLARED_KEY = re.compile(r"r(?P0|[1-9][0-9]{0,2})(?:-(?P.+))?", re.S) +_DIR = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + + +_CACHE: dict = {} + + +def declared(source) -> list: + """The records the benchmark of a trial's *source* declares, in its order: + found by the benchmark's key, a dataset's or a source its report block + names. Empty when it declares none.""" + from nullius.catalogue import catalog + sig = catalog.signature() + if _CACHE.get("sig") != sig: + table = {} + for b in catalog.load().benchmarks: + records = [dict(label=r["label"].strip(), path=r["path"]) for r in b.records or [] + if catalog.valid_record(r)] if isinstance(b.records, list) else [] + if records: + for name in [b.key, *b.datasets, *((b.report or {}).get("sources") or [])]: + table.setdefault(str(name).strip().lower(), records) + _CACHE.update(sig=sig, table=table) + return list(_CACHE["table"].get((source or "").strip().lower(), ())) + + +def _declared(key, records): + """(label, the path in the trial, the record's own path) of a declared record's key: a file of a declared folder + is labelled by the folder's label and its own name.""" + m = DECLARED_KEY.fullmatch(key or "") + if not m or int(m["n"]) >= len(records): + raise LookupError(key) + record = records[int(m["n"])] + name = m["name"] + if name is not None and (name in (".", "..") or "/" in name or not _plain_name(name)): + raise LookupError(key) + label = record["label"] if name is None else f"{record['label']}: {name}" + return label, record["path"] + ("/" + name if name is not None else ""), record["path"] + + +def _plain_name(name) -> bool: + """Whether a file's name in a declared folder can be listed and served: printable text alone. A name that is not + valid UTF-8 comes back from the system with a surrogate in it, which is not printable, as no control character is; + such a file is neither listed nor read.""" + return name.isprintable() + + +def _open_under(trial_dir, path, flags): + """A descriptor of *path* under the trial's folder, each part opened from the one before it, no link followed.""" + *folders, last = path.split("/") + fd = os.open(trial_dir, os.O_RDONLY | os.O_DIRECTORY) + try: + for part in folders: + child = os.open(part, _DIR, dir_fd=fd) + os.close(fd) + fd = child + return os.open(last, flags | os.O_NOFOLLOW, dir_fd=fd) + finally: + os.close(fd) + + +def _open_record(trial_dir, key, records): + """An open regular file of a key, fixed or declared.""" + if key in FILES: + path = path_for(trial_dir, key) + fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK) + else: + fd = _open_under(trial_dir, _declared(key, records)[1], os.O_RDONLY | os.O_NONBLOCK) + if not stat.S_ISREG(os.fstat(fd).st_mode) or (key not in FILES and not _text(fd)): + os.close(fd) + raise LookupError(key) + return fd + + +def _text(fd) -> bool: + """Whether an open file reads as text: no NUL byte in its first ``SNIFF`` bytes. It is read from its start + again after.""" + try: + return b"\0" not in os.pread(fd, SNIFF, 0) + except OSError: + return False + + +def describe(key, records=()): + """(label, filename) of a key: a fixed record's, or a declared one's, its path in the trial.""" + if key in FILES: + return FILES[key] + label, path, _ = _declared(key, records) + return label, path def path_for(trial_dir, key): @@ -39,8 +140,58 @@ def path_for(trial_dir, key): return path -def listing(trial_dir): - records = [] +def _declared_rows(trial_dir, records): + """The declared records that exist: a file, or each file of a folder, by name, one level, no link; each row + says it is ``declared``.""" + rows = [] + for n, record in enumerate(records): + try: + fd = _open_under(trial_dir, record["path"], os.O_RDONLY | os.O_NONBLOCK) + except OSError: + continue + entries = None + try: + info = os.fstat(fd) + if stat.S_ISREG(info.st_mode): + if _text(fd): + rows.append(dict(key=f"r{n}", label=record["label"], filename=record["path"], part="", + exists=True, size=info.st_size, declared=True)) + elif stat.S_ISDIR(info.st_mode): + entries = os.scandir(fd) + names = (e.name for e in entries if e.is_file(follow_symlinks=False)) + first, more = len(rows), False + count = 0 + for name in names: + if not _plain_name(name): + continue + try: + one = os.open(name, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW, dir_fd=fd) + except OSError: + continue + try: + info = os.fstat(one) + if stat.S_ISREG(info.st_mode) and _text(one): + if count == FOLDER_FILES: + more = True + break + rows.append(dict(key=f"r{n}-{name}", label=record["label"], part=name, exists=True, + filename=f"{record['path']}/{name}", size=info.st_size, declared=True)) + count += 1 + finally: + os.close(one) + rows[first:] = sorted(rows[first:], key=lambda row: row["part"]) + if more: + rows[-1]["more"] = True + finally: + if entries is not None: + entries.close() + os.close(fd) + return rows + + +def listing(trial_dir, records=()): + """Every fixed record, said whether it exists, then the declared ones that exist.""" + out = [] for key, (label, filename) in FILES.items(): try: path = path_for(trial_dir, key) @@ -48,22 +199,22 @@ def listing(trial_dir): size = os.path.getsize(path) if exists else None except (OSError, LookupError): exists, size = False, None - records.append(dict(key=key, label=label, filename=filename, exists=exists, size=size)) - return records + out.append(dict(key=key, label=label, filename=filename, part="", exists=exists, size=size)) + return out + _declared_rows(trial_dir, records) -def whole(trial_dir, key): +def whole(trial_dir, key, records=()): """The record redacted, up to ``MAX_READ``, and whether it was cut there: what a download or a copy carries, never more than the reader shows.""" - path = path_for(trial_dir, key) - with open(path, encoding="utf-8", errors="replace") as handle: + fd = _open_record(trial_dir, key, records) + with open(fd, encoding="utf-8", errors="replace") as handle: raw = handle.read(MAX_READ + 1) return redact(raw[:MAX_READ]), len(raw) > MAX_READ -def read(trial_dir, key, page=1): +def read(trial_dir, key, page=1, records=()): # Redact before slicing so credentials cannot straddle visible chunks. - text, truncated = whole(trial_dir, key) + text, truncated = whole(trial_dir, key, records) pages = max(1, (len(text) + CHUNK_SIZE - 1) // CHUNK_SIZE) try: page = int(page) @@ -71,7 +222,8 @@ def read(trial_dir, key, page=1): page = 1 page = min(pages, max(1, page)) start = (page - 1) * CHUNK_SIZE - return dict(key=key, label=FILES[key][0], filename=FILES[key][1], page=page, + label, filename = describe(key, records) + return dict(key=key, label=label, filename=filename, page=page, pages=pages, text=text[start:start + CHUNK_SIZE], empty=not text, truncated=truncated, characters=len(text), start=start, end=min(start + CHUNK_SIZE, len(text))) diff --git a/app/nullius/runs/cli.py b/app/nullius/runs/cli.py index ec5fe06a..d82549a9 100644 --- a/app/nullius/runs/cli.py +++ b/app/nullius/runs/cli.py @@ -89,6 +89,8 @@ def job_detail(job: parse.Job) -> dict: data = asdict(job) data.update(job_row(job)) data["harbor_label"] = job.harbor_label + data["mean_score"] = job.mean_score + data["mean_score_planned"] = job.mean_score_planned for trial, raw in zip(job.trials, data["trials"]): raw["outcome_label"] = trial.outcome_label raw["is_infra"] = trial.is_infra @@ -269,6 +271,10 @@ def _show(args) -> int: mix = " · ".join(f"{k} {v}" for k, v in row["counts"].items() if v) if mix: print(f" outcomes: {mix}") + if job.mean_score is not None: + planned = job.mean_score_planned + print(f" mean score {job.mean_score:.2f} over the trials scored" + + ("" if planned is None else f" · {planned:.2f} over the {max(job.n_planned, len(job.trials))} planned")) width = max((len(t.trial_name) for t in job.trials), default=0) for t in job.trials: line = f" {t.trial_name:<{width}} {t.outcome}" diff --git a/app/nullius/runs/evidence.py b/app/nullius/runs/evidence.py new file mode 100644 index 00000000..a6a91f1b --- /dev/null +++ b/app/nullius/runs/evidence.py @@ -0,0 +1,74 @@ +"""What a benchmark recorded about a trial that fell short: the Failure analysis tab's rows. + +A benchmark's ``benchmark.json`` may name them (``evidence``), in order:: + + {"label": "Expected answer", + "path": "reward_info.reward", a dotted path in the score's detail; an object gives a row per plain value + "values": {"1.0": "Pass"}, a value as the page says it + "names": {"DB": "Database"}, an object's keys as the page says them + "unless": ["no"], values that say nothing: no row + "reply": true} the trial's last reply when the detail holds no such value + +An empty list shows nothing. A benchmark without the block shows its whole +detail (``parse.score_detail``).""" +from __future__ import annotations + +from nullius.redact import redact + +from . import parse + +_CACHE: dict = {} + + +def declared(source) -> list | None: + """The rows the benchmark of a trial's *source* names, or None when it names none.""" + from nullius.catalogue import catalog + sig = catalog.signature() + if _CACHE.get("sig") != sig: + table = {} + for b in catalog.load().benchmarks: + if isinstance(b.evidence, list): + rows = [r for r in b.evidence if catalog.valid_evidence(r)] + for name in [b.key, *b.datasets, *((b.report or {}).get("sources") or [])]: + table.setdefault(str(name).strip().lower(), rows) + _CACHE.update(sig=sig, table=table) + return _CACHE["table"].get((source or "").strip().lower()) + + +def _at(detail, path): + """(found, value) at a dotted path; a key may hold dots itself.""" + if not isinstance(detail, dict): + return False, None + if path in detail: + return True, detail[path] + for i, c in enumerate(path): + if c == "." and path[:i] in detail: + found, value = _at(detail[path[:i]], path[i + 1:]) + if found: + return True, value + return False, None + + +def rows(trial_dir: str, spec: list, reply: str = "") -> list: + """``{label, text}`` per row *spec* names that the trial's score has, redacted.""" + detail = parse.read_detail(trial_dir) or {} + out = [] + + def add(label, value, entry): + text = parse._shown(value) + if text not in entry.get("unless", ()): + out.append({"label": redact(str(label)), "text": redact(entry.get("values", {}).get(text, text))}) + + for entry in spec: + found, value = _at(detail, entry["path"]) + if not found and entry.get("reply") and reply: + found, value = True, reply + if not found: + continue + if isinstance(value, dict): + for key, v in value.items(): + if parse._plain(v): + add(entry.get("names", {}).get(key, key), v, entry) + else: + add(entry["label"], value, entry) + return out diff --git a/app/nullius/runs/failure_analysis.py b/app/nullius/runs/failure_analysis.py new file mode 100644 index 00000000..e43641e9 --- /dev/null +++ b/app/nullius/runs/failure_analysis.py @@ -0,0 +1,327 @@ +"""A run's failure analysis: why each failed trial failed, and which tasks a person found flawed or ambiguous. + +One file per job, ``failure-analysis.json`` beside the job's ``result.json``. A person writes it from the trial +page's User judge tab or the ``nullius flags`` command; nothing here calls a model. Every writer goes through +:func:`update`, which holds a lock for the whole read, change and write, so the tab and the command never drop each +other's changes. + +- A *label* belongs to one trial (its ``trial_name``, a retry's ``.try-N`` included): the cause of its failure, one + of ``LABELS``. +- A *flag* belongs to one task of the job's dataset (its ``task_base``, the key Compare uses within a dataset): + ``flawed`` (its expected outcome is wrong) or ``ambiguous`` (more than one reading is defensible). A task has at + most one flag. A flag can name the task's version; when the task changes, that flag no longer applies. A flag + with no version applies to any version. + +A flag a person sets is accepted at once. A flag that comes from elsewhere (an import, a copy from another run, a +proposal such as an agent's) starts ``pending``, counts only once a person accepts it, and never replaces a flag a person accepted. +""" + +from __future__ import annotations + +import getpass +import json +import os +import subprocess +from functools import lru_cache +from dataclasses import asdict, dataclass, field, replace +from datetime import datetime, timezone +from typing import Any, Callable, Dict, Iterable, Optional, Set, Tuple + +from nullius import ondisk + +FILE = "failure-analysis.json" +SCHEMA = "nullius.failure-analysis/v1" + +LABELS = ("agent", "model", "environment", "evaluator") +KINDS = ("flawed", "ambiguous") +STATUSES = ("pending", "accepted") + +# The judge's failure_cause answer (judge/questions.py), read as a suggestion for a label. agent_error covers both +# the agent and the model, so it suggests both and the person picks. +JUDGE_CAUSE = { + "agent_error": ("agent", "model"), + "environment_error": ("environment",), + "rate_limit_or_timeout": ("environment",), + "task_ambiguous": ("evaluator",), + "verifier_disagrees": ("evaluator",), +} + + +class FailureAnalysisError(ValueError): + """A label, a flag or a file that does not follow the rules above.""" + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="seconds") + + +def _source_ok(source: str) -> bool: + prefixes = ("import:", "copy:", "proposed:") + return source == "person" or (source.startswith(prefixes) and len(source.split(":", 1)[1]) > 0) + + +@dataclass +class Label: + label: str + note: str = "" + by: str = "" + at: str = "" + judge_cause: Optional[str] = None # the judge's failure_cause when the label was set, if any + + +@dataclass +class Flag: + kind: str + category: str + evidence: str = "" # a pointer (a document, a tool), never the expected outcome + task_version: Optional[str] = None # the task_checksum its trial recorded when the flag was set + status: str = "accepted" + source: str = "person" # person | import: | copy: | proposed:, e.g. an agent + by: str = "" # who set or proposed it + at: str = "" + accepted_by: str = "" + accepted_at: str = "" + + +@dataclass +class Analysis: + labels: Dict[str, Label] = field(default_factory=dict) # by trial name + flags: Dict[str, Flag] = field(default_factory=dict) # by task_base + + def set_label(self, trial: str, label: str, *, by: str, note: str = "", judge_cause: Optional[str] = None) -> Label: + if not trial: + raise FailureAnalysisError("a label needs a trial name") + if label not in LABELS: + raise FailureAnalysisError(f"label {label!r} is not one of {', '.join(LABELS)}") + self.labels[trial] = Label(label, note, by, _now(), judge_cause) + return self.labels[trial] + + def clear_label(self, trial: str) -> None: + self.labels.pop(trial, None) + + def set_flag(self, task: str, kind: str, category: str, *, by: str, evidence: str = "", + task_version: Optional[str] = None, source: str = "person") -> Optional[Flag]: + """Set the task's flag. A flag from elsewhere never replaces one a person accepted for the same task version: it + returns None. An accepted flag on another version is inert, so a flag for the current one replaces it.""" + if not task: + raise FailureAnalysisError("a flag needs a task") + if kind not in KINDS: + raise FailureAnalysisError(f"kind {kind!r} is not one of {', '.join(KINDS)}") + if not category: + raise FailureAnalysisError("a flag needs a category") + if not _source_ok(source): + raise FailureAnalysisError(f"source {source!r} is not person, import:, copy: or proposed:") + old = self.flags.get(task) + stale = (old is not None and old.task_version is not None and task_version is not None + and old.task_version != task_version) + if source != "person" and old is not None and old.status == "accepted" and not stale: + return None + now = _now() + person = source == "person" + self.flags[task] = Flag(kind, category, evidence, task_version, "accepted" if person else "pending", source, + by, now, by if person else "", now if person else "") + return self.flags[task] + + def accept(self, task: str, *, by: str) -> Flag: + flag = self.flags.get(task) + if flag is None: + raise FailureAnalysisError(f"no flag on task {task!r}") + flag.status, flag.accepted_by, flag.accepted_at = "accepted", by, _now() + return flag + + def remove_flag(self, task: str) -> None: + """Remove the task's flag: how a person rejects a pending flag or withdraws an accepted one.""" + self.flags.pop(task, None) + + def set_aside(self, kinds: Iterable[str], versions: Optional[Dict[str, str]] = None) -> Set[str]: + """The tasks the filtered score leaves out: accepted flags of the chosen kinds. With *versions* (task to its current + digest), a flag that names another version does not count; a flag that names none still does.""" + chosen = set(kinds) + out = set() + for task, flag in self.flags.items(): + if flag.status != "accepted" or flag.kind not in chosen: + continue + if versions is not None and flag.task_version is not None and versions.get(task) != flag.task_version: + continue + out.add(task) + return out + + +@lru_cache(maxsize=1) +def who() -> str: + """The name a label or a flag is recorded under: git's global user.name on this machine, else the login name. + Read once per process.""" + try: + name = subprocess.run(["git", "config", "--global", "--get", "user.name"], capture_output=True, text=True, + timeout=5).stdout.strip() + except (OSError, subprocess.SubprocessError): + name = "" + if name: + return name + try: + return getpass.getuser() + except (OSError, KeyError): + return "unknown" + + +def suggestion(judge_cause: Optional[str]) -> Tuple[str, ...]: + """The labels a judge's failure_cause points to: none, one, or two for the person to pick from.""" + return JUDGE_CAUSE.get(judge_cause or "", ()) + + +def path(job_dir: str) -> str: + return os.path.join(job_dir, FILE) + + +def _records(raw: dict, name: str, cls): + block = raw.get(name) or {} + if not isinstance(block, dict): + raise FailureAnalysisError(f"{FILE}: {name} is not an object") + out = {} + for key, value in block.items(): + if not isinstance(value, dict): + raise FailureAnalysisError(f"{FILE}: {name} {key!r} is not an object") + try: + out[key] = cls(**value) + except TypeError as e: + raise FailureAnalysisError(f"{FILE}: {name} {key!r}: {e}") from e + return out + + +def load(job_dir: str) -> Analysis: + """The job's analysis; an empty one when the job has none yet.""" + try: + with open(path(job_dir), encoding="utf-8") as fh: + raw = json.load(fh) + except FileNotFoundError: + return Analysis() + except (OSError, json.JSONDecodeError) as e: + raise FailureAnalysisError(f"{FILE} cannot be read: {e}") from e + if not isinstance(raw, dict) or raw.get("schema") != SCHEMA: + raise FailureAnalysisError(f"{FILE} is not a {SCHEMA} file") + labels = _records(raw, "labels", Label) + flags = _records(raw, "flags", Flag) + for key, lab in labels.items(): + if lab.label not in LABELS: + raise FailureAnalysisError(f"trial {key!r}: label {lab.label!r} is not one of {', '.join(LABELS)}") + for key, fl in flags.items(): + if fl.kind not in KINDS or fl.status not in STATUSES or not fl.category or not _source_ok(fl.source): + raise FailureAnalysisError(f"task {key!r}: kind, status, category or source is not allowed") + return Analysis(labels, flags) + + +def _save(job_dir: str, analysis: Analysis) -> None: + body = {"schema": SCHEMA, + "labels": {k: asdict(v) for k, v in sorted(analysis.labels.items())}, + "flags": {k: asdict(v) for k, v in sorted(analysis.flags.items())}} + ondisk.write_whole(path(job_dir), lambda fh: (json.dump(body, fh, indent=1, ensure_ascii=False), fh.write("\n"))) + + +def update(job_dir: str, change: Callable[[Analysis], object]) -> object: + """Read the job's analysis, apply *change*, write it back, all under one lock. Returns what *change* returns.""" + # the lock is a file of its own: the analysis file is replaced on every write, so a lock on it would be lost + with ondisk.locked(path(job_dir) + ".lock"): + analysis = load(job_dir) + result = change(analysis) + _save(job_dir, analysis) + return result + + +@dataclass(frozen=True) +class Filtered: + """What the job page needs for its Filtered score.""" + flagged: Dict[str, int] # accepted flags on this job's tasks, by kind: what the switches offer + other_version: int # accepted flags that name another version of their task: they do not count + kinds: Tuple[str, ...] # the switches that are on + set_aside: Dict[str, int] # tasks left out, by kind + filtered_score: Optional[float] = None # the adjusted rate without those tasks; None if no switch is on or none left + solved: int = 0 + ran: int = 0 # trials left that ran (infra left out, as in the adjusted rate) + + +def filtered(job, analysis: Analysis, kinds: Iterable[str], versions: Optional[Dict[str, str]] = None) -> Filtered: + """The job's adjusted rate with the chosen filters on. It is computed by the job's own code on a copy that keeps + every trial except those of set-aside tasks; only the rate and its counts are read from that copy. With + *versions* (`task_versions`), a flag on another version of its task does not count.""" + tasks = {t.task_base for t in job.trials} + on = tuple(k for k in KINDS if k in set(kinds)) + flagged = {k: len(analysis.set_aside([k], versions) & tasks) for k in KINDS} + stale = len(analysis.set_aside(KINDS) & tasks) - len(analysis.set_aside(KINDS, versions) & tasks) + if not on: + return Filtered(flagged, stale, on, {}) + out = analysis.set_aside(on, versions) & tasks + by_kind = {k: sum(1 for t in out if analysis.flags[t].kind == k) for k in on} + rest = replace(job, trials=[t for t in job.trials if t.task_base not in out]) + return Filtered(flagged, stale, on, by_kind, rest.adjusted_solve_rate, rest.n_resolved, + len(rest.trials) - rest.n_infra) + + +def task_versions(job, tasks: Optional[Iterable[str]] = None) -> Dict[str, str]: + """Each task's version: the ``task_checksum`` Harbor records in a trial's ``result.json``. Only *tasks* when + given; a task whose trials record none is left out.""" + wanted = None if tasks is None else set(tasks) + out: Dict[str, str] = {} + for t in job.trials: + if t.task_base in out or (wanted is not None and t.task_base not in wanted): + continue + try: + with open(os.path.join(t.dir, "result.json"), encoding="utf-8") as fh: + checksum = (json.load(fh) or {}).get("task_checksum") + except (OSError, ValueError, AttributeError): + continue + if isinstance(checksum, str) and checksum: + out[t.task_base] = checksum + return out + + +def copy_flags(source: Analysis, target: Analysis, source_job: str, tasks: Iterable[str], *, + by: str) -> Tuple[list, list, list]: + """Copy *source*'s accepted flags on the target job's *tasks* into *target* as pending flags, keeping each flag's + task version. Returns the tasks copied, the tasks the target job does not hold, and the tasks skipped because + *target* already holds an accepted flag.""" + known = set(tasks) + copied, unknown, skipped = [], [], [] + for task, flag in sorted(source.flags.items()): + if flag.status != "accepted": + continue + if task not in known: + unknown.append(task) + continue + got = target.set_flag(task, flag.kind, flag.category, by=by, evidence=flag.evidence, + task_version=flag.task_version, source=f"copy:{source_job}") + (copied if got is not None else skipped).append(task) + return copied, unknown, skipped + + +def import_flags(target: Analysis, records: Iterable[dict], tasks: Iterable[str], *, source: str, by: str, + prefix: str = "", versions: Optional[Dict[str, str]] = None) -> Tuple[list, list, list]: + """Add flags from *records* (each with ``task``, ``kind``, ``category`` and an optional ``evidence``) as pending + flags. A task name is *prefix* plus the record's ``task``; a name the job does not hold is not guessed. Returns + the tasks added, the names not found, and the tasks skipped because they hold an accepted flag.""" + known = set(tasks) + added, unknown, skipped = [], [], [] + for rec in records: + if not isinstance(rec, dict): + raise FailureAnalysisError("each flag to import is an object") + if not rec.get("task"): + raise FailureAnalysisError("each flag to import names a task") + task = prefix + str(rec["task"]) + if task not in known: + unknown.append(task) + continue + got = target.set_flag(task, str(rec.get("kind", "")), str(rec.get("category", "")), by=by, + evidence=str(rec.get("evidence", "") or ""), source=source, + task_version=(versions or {}).get(task)) + (added if got is not None else skipped).append(task) + return added, unknown, skipped + + +def categories(analyses: Iterable[Analysis]) -> list: + """The categories of the accepted flags in *analyses*, most used first: what the tab suggests next to its + defaults. A pending flag does not count, so an unreviewed proposal never promotes its own category.""" + counts: Dict[str, int] = {} + for a in analyses: + for f in a.flags.values(): + if f.status == "accepted": + counts[f.category] = counts.get(f.category, 0) + 1 + return sorted(counts, key=lambda c: (-counts[c], c)) diff --git a/app/nullius/runs/flags_cli.py b/app/nullius/runs/flags_cli.py new file mode 100644 index 00000000..407fd159 --- /dev/null +++ b/app/nullius/runs/flags_cli.py @@ -0,0 +1,241 @@ +"""Write a run's failure analysis from a shell: the task flags the trial page's User judge tab writes, and +their import, copy and acceptance. + + nullius flags list [--json] + nullius flags set --kind flawed|ambiguous --category C [--evidence E] [--pending [--by NAME]] + nullius flags accept ( | --all-pending) + nullius flags remove + nullius flags copy + nullius flags import --from FILE [--prefix P] + nullius flags feasibility + +```` is anything ``nullius runs`` reads. A task is named as the job names it (its ``task_base``, the name +``nullius runs show`` prints). A flag set here is accepted at once, unless ``--pending`` (a flag an agent proposes); a flag copied, imported +or read from the feasibility controls is pending until a person accepts it, and never replaces an accepted one. Each change writes +only the job's ``failure-analysis.json``. Exit codes are those of ``docs/cli/exit-codes.md``. +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +from dataclasses import asdict + +from nullius.runs import failure_analysis as fa, feasibility, parse + +EXIT_OK = 0 +EXIT_USAGE = 2 +EXIT_NOT_FOUND = 3 +EXIT_INVALID = 4 + +# the feasibility verdicts that say the task, not the agent, is at fault +FEASIBILITY = {feasibility.TASK_BROKEN: "task broken", feasibility.REFERENCE_REJECTED: "reference rejected", + feasibility.UNEXPECTED_REWARD: "unexpected reward"} + + +def _jobs(root): + if not os.path.isdir(root): + print(f"no such directory: {root}", file=sys.stderr) + return None + return parse.load_all([root]) + + +def _job(jobs, job_id, root): + """The job of that id, or its exit code: not found, or ambiguous when two jobs under *root* share it.""" + found = [j for j in jobs if j.job_id == job_id] + if not found: + known = ", ".join(j.job_id for j in jobs) or "none" + print(f"no job named {job_id!r} under {root} (jobs there: {known})", file=sys.stderr) + return EXIT_NOT_FOUND + if len(found) > 1: + print(f"ambiguous job id {job_id!r}: {', '.join(j.dir for j in found)}", file=sys.stderr) + return EXIT_INVALID + return found[0] + + +def _task(job, task): + if task in {t.task_base for t in job.trials}: + return True + print(f"no task named {task!r} in {job.job_id}", file=sys.stderr) + return False + + +def _list(job, args) -> int: + a = fa.load(job.dir) + if args.json: + print(json.dumps({"job": job.job_id, "labels": {k: asdict(v) for k, v in sorted(a.labels.items())}, + "flags": {k: asdict(v) for k, v in sorted(a.flags.items())}}, indent=1, ensure_ascii=False)) + return EXIT_OK + versions = fa.task_versions(job, a.flags) + rows = [] + for task, f in sorted(a.flags.items()): + inert = f.task_version is not None and versions.get(task) != f.task_version + rows.append((task, f.kind, f.category, f.status + (" (another version)" if inert else ""), f.by)) + for trial, lab in sorted(a.labels.items()): + rows.append((trial, "label", lab.label, lab.note, lab.by)) + # columns padded to their widest cell, the last one left as it is + widths = [max((len(r[i]) for r in rows), default=0) for i in range(4)] + for r in rows: + print((" ".join(cell.ljust(w) for cell, w in zip(r, widths)) + " " + r[4]).rstrip()) + return EXIT_OK + + +def _report(verb, done, unknown=(), skipped=()): + print(f"{verb} {len(done)}") + for name in unknown: + print(f"not in the job: {name}", file=sys.stderr) + for name in skipped: + print(f"kept, already accepted: {name}", file=sys.stderr) + + +def run(args) -> int: + jobs = _jobs(args.root) + if jobs is None: + return EXIT_NOT_FOUND + job = _job(jobs, args.job_id, args.root) + if isinstance(job, int): + return job + if args.action == "list": + return _list(job, args) + by = fa.who() + tasks = {t.task_base for t in job.trials} + + if args.action == "accept" and args.task and args.all_pending: + print("accept takes a task or --all-pending, not both", file=sys.stderr) + return EXIT_USAGE + if args.action in ("set", "remove") or (args.action == "accept" and not args.all_pending): + if not args.task: + print(f"{args.action} needs a task" + (" or --all-pending" if args.action == "accept" else ""), + file=sys.stderr) + return EXIT_USAGE + if not _task(job, args.task): + return EXIT_NOT_FOUND + + if args.action == "set": + version = fa.task_versions(job, [args.task]).get(args.task) + if args.by and not args.pending: + print("--by names who proposes a flag: it goes with --pending", file=sys.stderr) + return EXIT_USAGE + proposer = args.by or by + source = f"proposed:{proposer}" if args.pending else "person" + before = fa.load(job.dir).flags.get(args.task) + got = fa.update(job.dir, lambda a: a.set_flag(args.task, args.kind, args.category, by=proposer, + evidence=args.evidence or "", task_version=version, + source=source)) + if got is None: + print(f"kept, already accepted: {args.task}", file=sys.stderr) + else: + if before is not None and before.status == "pending": + print(f"replaced the pending flag from {before.source}: {args.task}", file=sys.stderr) + print(f"flagged {args.task} {args.kind}" + (", pending" if args.pending else "")) + elif args.action == "accept": + if not args.all_pending and args.task not in fa.load(job.dir).flags: + print(f"no flag on {args.task}", file=sys.stderr) + return EXIT_NOT_FOUND + + def accept(a): + names = sorted(t for t, f in a.flags.items() if f.status == "pending") if args.all_pending else [args.task] + for name in names: + a.accept(name, by=by) + return names + _report("accepted", fa.update(job.dir, accept)) + elif args.action == "remove": + fa.update(job.dir, lambda a: a.remove_flag(args.task)) + print(f"removed {args.task}") + elif args.action == "copy": + target = _job(jobs, args.to_job_id, args.root) + if isinstance(target, int): + return target + if target is job: + print("copy needs two different jobs", file=sys.stderr) + return EXIT_USAGE + if job.dataset and target.dataset and job.dataset != target.dataset: + print(f"{job.job_id} ran {job.dataset}, {target.job_id} ran {target.dataset}: not copied", file=sys.stderr) + return EXIT_INVALID + source = fa.load(job.dir) + target_tasks = {t.task_base for t in target.trials} + copied, unknown, skipped = fa.update(target.dir, lambda a: fa.copy_flags(source, a, job.job_id, target_tasks, + by=by)) + _report(f"copied to {target.job_id}, pending:", copied, unknown, skipped) + elif args.action == "import": + try: + with open(args.from_file, encoding="utf-8") as fh: + raw = json.load(fh) + except OSError as e: + print(f"cannot read {args.from_file}: {e}", file=sys.stderr) + return EXIT_NOT_FOUND + except ValueError as e: + print(f"{args.from_file} is not JSON: {e}", file=sys.stderr) + return EXIT_INVALID + records = raw.get("flags") if isinstance(raw, dict) else raw + if not isinstance(records, list): + print(f"{args.from_file} holds no list of flags", file=sys.stderr) + return EXIT_INVALID + versions = fa.task_versions(job, {args.prefix + str(r.get("task", "")) for r in records if isinstance(r, dict)}) + source = "import:" + os.path.basename(args.from_file) + added, unknown, skipped = fa.update(job.dir, lambda a: fa.import_flags( + a, records, tasks, source=source, by=by, prefix=args.prefix, versions=versions)) + _report("imported, pending:", added, unknown, skipped) + elif args.action == "feasibility": + report = feasibility.report(job, jobs) + if not report.executed: + print(f"no nop or oracle control found for {job.job_id}", file=sys.stderr) + return EXIT_NOT_FOUND + versions = fa.task_versions(job) + controls = [j for c in report.executed for j in jobs if j.job_id == c.job_id and j is not job] + other = {t for cj in controls for t, v in fa.task_versions(cj).items() if versions.get(t) not in (None, v)} + for t in sorted(other): + print(f"control ran another version: {t}", file=sys.stderr) + records = [{"task": r.task_base, "kind": "flawed", "category": FEASIBILITY[r.verdict], "evidence": r.why} + for r in report.rows if r.verdict in FEASIBILITY and r.task_base not in other] + added, unknown, skipped = fa.update(job.dir, lambda a: fa.import_flags( + a, records, tasks, source="import:feasibility", by=by, versions=versions)) + _report("imported, pending:", added, unknown, skipped) + return EXIT_OK + + +def parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser(prog="nullius flags", description="Write a run's task flags.", + epilog="exit codes: 0 done, 2 usage, 3 not found, 4 invalid input") + sub = p.add_subparsers(dest="action", required=True) + for name, helptext in (("list", "show the run's flags and labels"), ("set", "flag a task: accepted at once, or pending with --pending"), + ("accept", "accept a pending flag"), ("remove", "remove a task's flag"), + ("copy", "copy accepted flags to another run of the same dataset, as pending"), + ("import", "import flags from a file, as pending"), + ("feasibility", "import the feasibility controls' task verdicts, as pending")): + s = sub.add_parser(name, help=helptext) + s.add_argument("root") + s.add_argument("job_id") + if name in ("set", "accept", "remove"): + s.add_argument("task", nargs="?" if name == "accept" else None) + if name == "list": + s.add_argument("--json", action="store_true") + if name == "set": + s.add_argument("--kind", required=True, choices=fa.KINDS) + s.add_argument("--category", required=True) + s.add_argument("--evidence") + s.add_argument("--pending", action="store_true", + help="wait for a person to accept it: for a flag an agent proposes") + s.add_argument("--by", help="who proposes it, e.g. the agent's name (with --pending)") + if name == "accept": + s.add_argument("--all-pending", action="store_true") + if name == "copy": + s.add_argument("to_job_id") + if name == "import": + s.add_argument("--from", dest="from_file", required=True) + s.add_argument("--prefix", default="") + return p + + +def main(argv=None) -> int: + args = parser().parse_args(argv) + try: + return run(args) + except fa.FailureAnalysisError as e: + print(str(e), file=sys.stderr) + return EXIT_INVALID + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index bd6e21c1..1597a461 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -8,9 +8,12 @@ from __future__ import annotations import functools +import json import os import re import shlex +import stat +from contextlib import ExitStack from dataclasses import dataclass, field, replace from datetime import datetime, timezone @@ -28,7 +31,7 @@ # The shape this module produces. A workspace caches parsed Jobs keyed on it, # so bump it when a Trial or Job field is added, renamed or means something # new — otherwise a cache written by the old parse is read back as current. -SCHEMA = "17" +SCHEMA = "18" # What a rate-limit record in `agent/gateway.log` looks like. The agent's SDK # retries a 429 below the harness, so a limit the run survived leaves nothing in result.json — @@ -72,6 +75,102 @@ def _retries_of(res: dict) -> int: return n if isinstance(n, int) and not isinstance(n, bool) and n > 0 else 0 +SCORE_BYTES = 1024 * 1024 + + +def _read_score(trial_dir: str): + """Read at most SCORE_BYTES from a regular score file without following links inside the trial.""" + try: + with ExitStack() as opened: + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + trial = os.open(trial_dir, flags) + opened.callback(os.close, trial) + folder = os.open("verifier", flags, dir_fd=trial) + opened.callback(os.close, folder) + fd = os.open("score.json", os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder) + opened.callback(os.close, fd) + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_size > SCORE_BYTES: + return None + raw = os.read(fd, SCORE_BYTES + 1) + return json.loads(raw) if 0 < len(raw) <= SCORE_BYTES else None + except (OSError, ValueError): + return None + + +# A value of a score's detail longer than this is cut on the trial's page, its whole text a click away +DETAIL_CELL = 200 + + +def _plain(value) -> bool: + return value is None or isinstance(value, (str, int, float, bool)) + + +def _shown(value) -> str: + """A value of a score's detail as the page writes it: text as written, a boolean as yes or no, none for null or + empty text, a list of plain values joined, anything deeper as its JSON.""" + if isinstance(value, bool): + return "yes" if value else "no" + if value is None or value == "": + return "none" + if isinstance(value, (str, int, float)): + return str(value) + if isinstance(value, list) and all(_plain(x) for x in value): + return ", ".join(_shown(x) for x in value) if value else "none" + return json.dumps(value, ensure_ascii=False) + + +def read_detail(trial_dir: str) -> dict | None: + """The detail beside a score's reward, redacted, or None.""" + said = _read_score(trial_dir) + detail = said.get("detail") if isinstance(said, dict) else None + return _options(detail) if isinstance(detail, dict) else None + + +def score_detail(trial_dir: str, leave_out=(), shown=None) -> dict | None: + """Redacted score evidence for display. Nested objects become named groups, + structured lists become numbered groups; no object is rendered as raw JSON. + ``leave_out`` excludes top-level metadata; ``shown`` suppresses duplicate numbers + by their full path. Long text keeps a preview and its full value.""" + detail = read_detail(trial_dir) + if detail is None: + return None + fields, groups = [], [] + + def cell(name, value): + text = redact(_shown(value)) + return {"name": redact(str(name)), "text": text, + "cut": text[:DETAIL_CELL] if len(text) > DETAIL_CELL else ""} + + def visit(values, path=""): + flags = [] + for name, value in values.items(): + full = f"{path}.{name}" if path else str(name) + if (not path and name in leave_out) or ( + isinstance(value, (int, float)) and not isinstance(value, bool) + and value in (shown or {}).get(full, ())): + continue + if isinstance(value, dict): + visit(value, full) + elif isinstance(value, list) and not all(_plain(x) for x in value): + visit({str(i + 1): x for i, x in enumerate(value)}, full) + elif path: + item = cell(name, value) + if not item["cut"]: + item.pop("cut") + item["held"] = value if isinstance(value, bool) else None + if isinstance(value, bool): + item["text"] = "" + flags.append(item) + else: + fields.append(cell(name, value)) + if flags: + groups.append({"name": redact(path), "flags": flags}) + + visit(detail) + return {"fields": fields, "groups": groups} if fields or groups else None + + def count_rate_limits(path: str) -> int | None: """Rate-limit records in a gateway log, or None when there is no log. @@ -317,6 +416,11 @@ class Job: # listing several): each one's {name, model, effort}, which split_agents # turns into one view per agent. [] for a job of one agent. agents: list = field(default_factory=list) + # What tells a Nullius standard run from another, as its records say it (identity_of): the benchmark, its + # version and options, the agent, its version and options, the model, the provider, the serving providers + # pinned and who served, the limits and the caps. A fact the job does not record is not a key. {} for + # every other job. + identity: dict = field(default_factory=dict) @property def agent_label(self) -> str: @@ -426,6 +530,17 @@ def mean_score(self): scored = [(t.score, t.n_parts or 1) for t in self.trials if t.score is not None] return sum(s * n for s, n in scored) / sum(n for _, n in scored) if scored else None + @property + def mean_score_planned(self): + """The mean score over every trial the run planned (``n_planned``), a + trial with no score - one that ended on an error, one never run - + counting 0; each trial contributes its own score regardless of part + counts. ``mean_score`` keeps its part weighting. None when no trial + was scored.""" + if self.mean_score is None: + return None + return sum(t.score for t in self.trials if t.score is not None) / max(self.n_planned, len(self.trials)) + @property def score_by_group(self) -> list: """The mean score by the field the benchmark breaks it down by - a @@ -786,6 +901,7 @@ def harbor_command(cfg: dict, env_type: str = "") -> str: # A launch carries only the name of a value filed under a name like these: it # is a credential, and the record is embedded in the builder's page. _SECRET_KEY = re.compile(r"(?:api[-_]?key|token|password|authorization|credential|secret)", re.I) +_TOKEN_COUNT_KEY = re.compile(r"^(?:(?:(?:max|min|num|n|total|input|output|prompt|completion|new)[-_])+tokens|token[-_](?:count|limit|budget))$", re.I) # What a recipe can say; any other key a config recorded is named, not dropped. _LAUNCH_TOP = {"job_name", "jobs_dir", "quiet", "debug", "agents", "datasets", "tasks", "retry", "n_concurrent_trials", "n_attempts", "timeout_multiplier", "environment", *_PHASE_MULTIPLIERS} @@ -800,7 +916,7 @@ def _scrub(values, at: str = "") -> tuple: kept, secret = {}, [] for key, value in (values if isinstance(values, dict) else {}).items(): name = f"{at}{key}" - if _SECRET_KEY.search(str(key)): + if _SECRET_KEY.search(str(key)) and not _TOKEN_COUNT_KEY.fullmatch(str(key)): secret.append(name) else: kept[str(key)], inner = _scrub_value(value, name) @@ -885,6 +1001,76 @@ def _budget(b) -> dict: "shards": num(b.get("shards")) or 0, "shards_stopped": num(b.get("shards_stopped")) or 0} +def _options(values) -> dict: + """A run's options as a page may show them: strings redacted at any depth + (``_scrub``), and an option filed under a credential's name kept by its + name with its value replaced. Token counts are not credentials.""" + out = {} + for key, value in (values if isinstance(values, dict) else {}).items(): + hidden = _SECRET_KEY.search(str(key)) and not _TOKEN_COUNT_KEY.fullmatch(str(key)) + out[str(key)] = "[REDACTED]" if hidden else _scrub_value(value, str(key))[0] + return out + + +def _served(v) -> dict: + """Who served a job's calls (``result.json``'s ``served``): the calls by + serving provider, those that named none, and for each pinned model + whether the pin ``held`` (true, ``unknown``, or null with no call); {} + when the job records none.""" + if not isinstance(v, dict): + return {} + count = lambda n: n if isinstance(n, int) and not isinstance(n, bool) and n >= 0 else None + calls = {redact(str(k)): count(n) for k, n in v["calls"].items() if count(n) is not None} if isinstance(v.get("calls"), dict) else {} + held = {redact(str(m)): h for m, h in v["held"].items() if h is True or h is None or h == "unknown"} if isinstance(v.get("held"), dict) else {} + unnamed = count(v.get("unnamed")) or 0 + if not calls and not unnamed and not held: + return {} + return {"calls": calls, "unnamed": unnamed, **({"held": held} if held else {})} + + +def identity_of(cfg: dict, res: dict, agent_version: str = "") -> dict: + """What tells a Nullius standard run from another, from its ``config.json`` + (``cfg``) and its ``result.json`` (``res``): the benchmark, its version and + options; the agent as the run named it, the version its trials report + (``agent_version``) and its options, defaults included; the model; the + provider; the serving providers pinned by model (``served_by``) and who + served (``served``); and the limits in force: time limits by phase, turns, + model calls, attempts of each unit, retries, units at a time, and the + spending caps and resource constraints. A fact the job does not record is not a key, never an + empty value, and a control that calls no model has no provider. {} for a + job not of the standard. Every string is redacted.""" + std = cfg.get("standard") if isinstance(cfg, dict) and isinstance(cfg.get("standard"), dict) else {} + if not std: + return {} + word = lambda v: redact(v) if isinstance(v, str) else "" + number = lambda v: isinstance(v, (int, float)) and not isinstance(v, bool) and v > 0 + agents = cfg.get("agents") if isinstance(cfg.get("agents"), list) else [] + first = agents[0] if agents and isinstance(agents[0], dict) else {} + out = {"benchmark": word(std.get("benchmark")), "benchmark_version": word(std.get("benchmark_version")), + "benchmark_options": _options(std.get("benchmark_options")), + "agent": word(std.get("plugged")), "agent_version": word(agent_version), + "agent_options": _options(std.get("options")), "model": word(first.get("model_name"))} + # a control asks no model unless it has a judge or a simulated user; the provider it records is then a default + asks = out["model"] or std.get("judge") or std.get("simulator") or std.get("kind") != "control" + out["provider"] = word(std.get("provider")) if asks else "" + pins = std.get("served_by") if isinstance(std.get("served_by"), dict) else {} + out["served_by"] = {redact(str(m)): [word(s) for s in slugs if isinstance(s, str)] + for m, slugs in pins.items() if isinstance(slugs, list) and slugs} + out["served"] = _served(res.get("served") if isinstance(res, dict) else None) + timeouts = std.get("timeouts") if isinstance(std.get("timeouts"), dict) else {} + budget = _budget(res.get("budget") if isinstance(res, dict) else None) + whole = lambda v: v if number(v) and isinstance(v, int) else None + retries = std.get("retries") + limits = {"timeouts": {str(k): v for k, v in timeouts.items() if number(v)}, + "constraints": _options(std.get("constraints")), + "max_turns": whole(std.get("max_turns")), "max_calls": whole(std.get("max_calls")), + "repeat": whole(std.get("repeat")) if (whole(std.get("repeat")) or 0) > 1 else None, + "retries": retries if type(retries) is int and retries >= 0 else None, "concurrency": whole(cfg.get("n_concurrent_trials")), + "max_usd": budget.get("max_usd"), "unit_max_usd": budget.get("unit_max_usd")} + out["limits"] = {k: v for k, v in limits.items() if v is not None and v != {}} + return {k: v for k, v in out.items() if v not in ("", {})} + + def parse_job(job_dir: str, reuse=None, trials: bool = True) -> Job: """One job directory. ``reuse(trial_dir)``: a Trial already parsed from files that have not changed since (a workspace's cache, for a running @@ -965,6 +1151,7 @@ def parse_job(job_dir: str, reuse=None, trials: bool = True) -> Job: merged = std.get("merged_from") job.merged_from = [s["job"] for s in merged if isinstance(s, dict) and isinstance(s.get("job"), str) and s["job"]] if isinstance(merged, list) else [] job.budget = _budget(res.get("budget")) + job.identity = identity_of(cfg, res, job.agent_version) job.standard = bool(std) setup = std.get("setup") if isinstance(std.get("setup"), dict) else {} was = (std.get("benchmark_options") or {}).get("agent") if isinstance(std.get("benchmark_options"), dict) else None diff --git a/app/nullius/settings.py b/app/nullius/settings.py index 9c964a97..290b93cf 100644 --- a/app/nullius/settings.py +++ b/app/nullius/settings.py @@ -217,8 +217,7 @@ def validate(self, value: str) -> Optional[str]: Variable("LLM_JUDGE_PROVIDER", GROUPS[0], "The provider of the LLM judgement, the second judgement beside Decision: openrouter, openai, anthropic, custom (the endpoint at MODEL_API_URL) or custom: (a custom provider), asked with that provider's own key and base from the model providers above. local and local: are read as custom. Unset: the first of them that is set, Anthropic last.", "llmprovider"), Variable("LLM_JUDGE_PROTOCOL", GROUPS[0], "The protocol the LLM judge is asked in, on a provider that serves both: chat (OpenAI Chat Completions) or messages (Anthropic Messages). Unset, or one the provider does not serve: the first the provider serves, chat before messages.", "llmprotocol"), Variable("LLM_JUDGE_MODEL", GROUPS[0], "The model of the LLM judgement, as its provider names it (on OpenRouter, vendor/model). It is asked the same questions as Decision and answers them as JSON; its numbers are what it states, so a choice or a score carries no confidence.", "model"), - *(Variable(name, GROUPS[0], f"Additions to the {title} provider, as a JSON object without the key: endpoints of protocols the preset does not list, " - '{"endpoints": {"": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one.', "provider") + *(Variable(name, GROUPS[0], f"Unsupported overrides for {title}. Use a Custom provider to configure endpoints.", "provider") for name, title in (("OPENROUTER", "OpenRouter"), ("OPENAI", "OpenAI"), ("ANTHROPIC", "Anthropic"), ("TYPESAFE", "TypeSafe"))), Variable("AGENT_KEYS", GROUPS[2], "The names of the agent keys this file holds, comma-separated: the keys an agent needs of its own vendor, beside the model's (Cursor's CLI agent a CURSOR_API_KEY, Copilot's a GH_TOKEN). Each is a line of its own in this file. A Harbor run gets every one of them in its environment - over stdin to a host - and a Nullius standard run's never; none is ever written into a recipe or a log.", "envnames"), Variable("HOSTS", GROUPS[1], "Machines a recipe can run on, over ssh: an alias from ~/.ssh/config, or user@host[:port][:/path/to/key]. Only the name is stored; keys stay where they are.", "hosts", "user@host[:port][:/path/to/key]"), diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index 5b890c7c..ad1d9642 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -523,7 +523,8 @@ def _bench_options(d: dict) -> List[str]: ``embeddings`` model called through the run's relay, ``host`` requirements or ``files`` by name - and ``when`` it applies: another option's values (a retriever's, only with a retrieval). ``limit``: a bound the upstream has of its own (its steps, its errors), offered with the run's limits; ``by``: - its default under each value of another option (an agent's own steps), for a default of ``default``. ``names``: a name for some of its values, shown in their place. ``step``: ``where`` for a choice of where the work runs, ``dataset`` for one its datasets need, the builder step that asks it.""" + its default under each value of another option (an agent's own steps), for a default of ``default``; ``yours``: the value + an agent's or a capability's run gets for it (the steps of a port's loop). ``names``: a name for some of its values, shown in their place. ``step``: ``where`` for a choice of where the work runs, ``dataset`` for one its datasets need, the builder step that asks it.""" opts = d.get("options") if opts is None: return [] @@ -548,6 +549,8 @@ def _bench_options(d: dict) -> List[str]: k != name and k in opts and isinstance(m, dict) and set(m) == set(opts[k].get("values") or [None]) and all(option_problem(o, v) is None for v in m.values()) for k, m in by.items())): bad.append(f"{w}.by: another option -> its every value -> this one's default under it") + if "yours" in o and (by is None or o["yours"] == o.get("default") or option_problem(o, o["yours"])): + bad.append(f"{w}.yours: beside by, the value an agent's or a capability's run gets for a default of default") # agent: an agent's run alone, on a benchmark agents run, and never beside another scope if on is not None and (not isinstance(on, list) or not on or any(x not in SETUPS + ("yours", "agent") for x in on) or "agent" in on and (on != ["agent"] or d.get("family") != "agent")): diff --git a/app/nullius/standard/kits/agent-computer-v1/fixture.py b/app/nullius/standard/kits/agent-computer-v1/fixture.py index 96920d4a..42c226aa 100644 --- a/app/nullius/standard/kits/agent-computer-v1/fixture.py +++ b/app/nullius/standard/kits/agent-computer-v1/fixture.py @@ -17,6 +17,8 @@ Words and labels are drawn as bitmaps from the glyphs below: no widget holds their text, and Tk's ``send`` is removed, so no other program can read them but from the screen. The window fills the screen, so every press lands on it. +Like an application's window, it names its machine and its process +(``WM_CLIENT_MACHINE`` and ``_NET_WM_PID``). Each press, release, scroll and key goes to ``events.jsonl`` in the fixture's home, a folder only ``fixture`` reads, one JSON object a line: ``kind``, the @@ -35,6 +37,7 @@ """ import json import os +import socket import struct import sys import time @@ -207,6 +210,7 @@ def __init__(self, values, log): self.root = tk.Tk() self.root.tk.call("rename", "send", "") # no other X client may run Tcl in this one self.root.title(TITLE) + self.root.wm_client(socket.gethostname()) # with it Tk sets _NET_WM_PID as the window maps self.root.configure(background=BACKGROUND) self.root.attributes("-fullscreen", True) self.images, self.names, self.field, self.texts = [], {}, None, [] diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 4e9230e0..5cf5ecf9 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -105,9 +105,11 @@ def _all() -> Dict[str, List[dict]]: def _shown(o: dict, v: str, values: dict) -> str: - """An option's value as Review shows it: its name, or for ``default`` under ``by`` the value it stands for.""" + """An option's value as Review shows it: its name, or for ``default`` under ``by`` the value it stands for (an + agent's or a capability's run, which takes no value of that other option, gets ``yours``).""" by = next(iter((o.get("by") or {}).items()), None) - v = by[1].get(values.get(by[0]), v) if v == "default" and by else v + if v == "default" and by: + v = by[1].get(values.get(by[0]), v) if by[0] in values else o.get("yours") or v return (o.get("names") or {}).get(v) or v @@ -185,7 +187,7 @@ def _bench_page(b: dict) -> dict: "options": {n: {"label": o.get("label") or n.replace("_", " ").capitalize(), "summary": o["summary"], "datasets": o.get("datasets") or [], "setups": o.get("setups") or ["yours"], **({"values": o["values"]} if "values" in o else {"pattern": o["pattern"], "example": o.get("example")}), "default": o.get("default"), "about": o.get("about") or {}, "names": o.get("names") or {}, "needs": o.get("needs") or {}, "when": o.get("when") or {}, - "limit": bool(o.get("limit")), "step": o.get("step") or "", "by": o.get("by") or {}} + "limit": bool(o.get("limit")), "step": o.get("step") or "", "by": o.get("by") or {}, "yours": o.get("yours") or ""} for n, o in (b.get("options") or {}).items()}, "host": {n: {"label": r.get("label") or n, "summary": r["summary"], "check": r["check"], "install": hostreq.install_lines(b, [n]), "needed_by": r["needed_by"]} for n, r in hostreq.all_of(b).items()}, @@ -424,10 +426,11 @@ def compile(recipe: dict, defs: Optional[Dict[str, List[dict]]] = None, *, the run sends it as.""" d = defs or _all() errors, notes = [], [] - # each problem once; shown: the step already says it elsewhere, so only Review lists it; field: the input it is about - def add(step, message, shown=False, field=None): + # each problem once; shown: the step already says it elsewhere, so only Review lists it; field: the input it is about; unset: nothing is + # chosen yet, which the Model step does not say before its field is used + def add(step, message, shown=False, field=None, unset=False): if not any(e["step"] == STEP[step] and e["message"] == message for e in errors): - errors.append({"step": STEP[step], "message": message, **({"shown": True} if shown else {}), **({"field": field} if field else {})}) + errors.append({"step": STEP[step], "message": message, **({"shown": True} if shown else {}), **({"field": field} if field else {}), **({"unset": True} if unset else {})}) out = {"errors": errors, "notes": notes, "review": [], "jobs": [], "confirm": "", "script": "", "parts": [], "model": "", "served_models": {}} name = str(recipe.get("name") or "") @@ -480,7 +483,7 @@ def add(step, message, shown=False, field=None): orig = (b.get("setups") or {}).get("original") or {} picked = str(recipe.get("model") or "").strip() if not picked: - add("model", "Choose a model.") + add("model", "Choose a model.", unset=True) continue method = "model" if recipe.get("model_choice", "any") != "paper" and "model" in (b.get("setups") or {}) else "original" if method == "original": @@ -558,7 +561,8 @@ def add(step, message, shown=False, field=None): add("model", why) agents_local = [p["o"]["label"] for p in picks if side == "agent" and not p["control"] and not p.get("setup") and backend == "local"] if agents_local and recipe.get("unsandboxed") is not True: - add("where", f"{', '.join(agents_local)} would run as you, not sandboxed: tick Run it as me, or choose Docker.") + add("where", f"{', '.join(agents_local)} would run as you, not sandboxed: tick Run it as me" + + ("; a container cannot start its VMs." if definitions.boots_vms(b) else ", or choose Docker."), field="unsandboxed") only_controls = bool(picks) and all(p["control"] for p in picks) needs_model = any(not p["control"] for p in picks) model_choice = recipe.get("model_choice", "any") @@ -589,7 +593,7 @@ def add(step, message, shown=False, field=None): add("model", f"{providers.label(provider)} does not serve what {b['label']}'s judge speaks: choose another provider.") model = str(recipe.get("model") or "").strip() if not _MODEL.match(model) and (needs_model or model): - add("model", "Choose a model or enter its ID.") + add("model", "Choose a model or enter its ID.", unset=not model) if model_choice == "paper" and model in orig.get("models", []) and provider_ in orig.get("providers", {}): model = orig["providers"][provider_] + (orig.get("served_as") or {}).get(model, model) # each unit tried K times (the upstream's --num-trials: pass^k); the user simulator's and the judge's models @@ -602,7 +606,7 @@ def add(step, message, shown=False, field=None): # each attempt run again up to N times when it ends in a failure a further try may mend (runner.retries) retries = 0 if recipe.get("retries") in (None, "") else _int(recipe.get("retries"), 0, MAX_RETRIES) if retries is None: - add("limits", f"Retries per attempt: a whole number from 0 to {MAX_RETRIES}.") + add("limits", f"Retries after an error: a whole number from 0 to {MAX_RETRIES}.") retries = 0 sim_model = str(recipe.get("simulator_model") or "").strip() judge_model = str(recipe.get("judge_model") or "").strip() @@ -764,7 +768,7 @@ def called_of(p: dict) -> List[str]: add("model", f"Served by pins {m} twice, with different providers: give its fields the same ones.") by_model[m] = list(slugs) # each field's model as the run sends it, for the builder to ask its providers under that name - out["served_models"] = {role: next((sent_of(p)[role] for p in sorted(picks, key=lambda q: q["control"]) if sent_of(p)[role]), None) + out["served_models"] = {role: next((sent_of(p)[role] for p in sorted(picks, key=lambda q: q["control"]) if _MODEL.match(sent_of(p)[role] or "")), None) for role in roles} def pinned(p: dict) -> Dict[str, List[str]]: @@ -900,15 +904,16 @@ def row(p: dict) -> list: [STEP["dataset"], "Datasets" if many else "Dataset", ", ".join(f"{x.get('label') or x['id']}" + (f" · {x['units']} {nouns}" if x.get("units") else "") for x in dss)], *[[STEP["limits" if (b.get("options") or {})[k].get("limit") else "dataset" if (b.get("options") or {})[k].get("step") else "agent"], (b.get("options") or {})[k].get("label") or k.replace("_", " ").capitalize(), - _shown((b.get("options") or {})[k], v, per_ds[next(x["id"] for x in dss if per_ds[x["id"]].get(k) == v)]) + ("" if k in chosen_opts else " (its default)") + f" · {', '.join(x['id'] for x in dss if per_ds[x['id']].get(k) == v)}"] - for k, v in {k: v for vals in per_ds.values() for k, v in vals.items()}.items() + _shown((b.get("options") or {})[k], v, per_ds[next(x["id"] for x in dss if per_ds[x["id"]].get(k) == v)]) + ("" if k in chosen_opts else " (its default)") + + ("" if all(per_ds[x["id"]].get(k) == v for x in dss) else f" · {', '.join(x.get('label') or x['id'] for x in dss if per_ds[x['id']].get(k) == v)}")] + for k, v in dict.fromkeys((k, v) for vals in per_ds.values() for k, v in vals.items()) # a row per value: datasets may differ if (b.get("options") or {})[k].get("step") != "where" and not (k == "agent" and definitions.own_agents(b)) and not ((b.get("options") or {})[k].get("when") or {}).get("agent") or "agent" in ((b.get("options") or {})[k].get("when") or {}) and any( # one of its own agents' settings: that agent's p.get("agent") and p["agent"]["start"]["driver"]["agent"] in b["options"][k]["when"]["agent"] for p in picks)], *[row(p) for p in picks], *[[STEP["agent"], "Options" + (f" of {p['o']['label']}" if several else ""), - ", ".join(f"{k} {v}" + ("" if k in p["given"] else " (its default)") for k, v in p["opts"].items())] + ", ".join(f"{(p['o'].get('options') or {}).get(k, {}).get('label') or k.replace('_', ' ').capitalize()} {v}" + ("" if k in p["given"] else " (its default)") for k, v in p["opts"].items())] for p in picks if p["opts"]], [STEP["model"], "Model", "none: a control calls no model" if out["keyless"] else f"{providers.label(providers.choice(provider, str(recipe.get('endpoint') or '')))} · " + (model if needs_model else ", ".join(p["o"]["sent"] for p in picks if p.get("setup")) or "the judge only") diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index 802433fc..eacf6226 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -848,7 +848,7 @@ def _start(self, lck, mine) -> str: HELD[lck] = held self.say(f"job {self.job_dir}") p, control = self.progress, self.other["_kind"] == "control" - p.emit("plan", stages=",".join((["image"] if self.backend == "container" or self.relay_container or self.container_check else []) + p.emit("plan", stages=",".join((["models"] if self.base else []) + ["requirements"] + (["image"] if self.backend == "container" or self.relay_container or self.container_check else []) + (["upstream"] if install.upstream_dir(self.bench) else []) + (["dataset"] if self.ds.get("url") else []) + (["driver"] if install.driver_dir(self.bench) else []) @@ -859,7 +859,9 @@ def _start(self, lck, mine) -> str: if self.cap_dropped: self.say(f"warning: {self.cap_dropped} ({self.cap_why})") try: - self.known_models() + if self.base: + with p.stage("models", start="checking the provider’s model list"): + self.known_models() self.ready() except Refused as e: # said in the job, which holds nothing else: the runs list reads why there (progress.refusal) @@ -1177,11 +1179,12 @@ def ready(self) -> None: when it declares one (``driver.install``), the agent's or capability's packages. Refused when one cannot be had.""" from ..requirements import network_requirements - why = network_requirements.check(self.bench, self.other) - if why: - raise BenchmarkRefused("; ".join(why)) p = self.progress - self.scope_limits = self.scope_ready(limits.scoped(self.constraints), refuse=self.backend == "local") + with p.stage("requirements", start="checking network access and machine limits"): + why = network_requirements.check(self.bench, self.other) + if why: + raise BenchmarkRefused("; ".join(why)) + self.scope_limits = self.scope_ready(limits.scoped(self.constraints), refuse=self.backend == "local") owns = any(definitions.own_image(e) for e in (self.bench.get("environments") or {}).values()) if self.backend == "container" or self.relay_container or self.container_check: try: diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 002abc0a..1a59d3d8 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -29,7 +29,8 @@ carries the run's end, so the last copy is checked trial by trial once more. An ended job's head is noted in ``jobs/index.json`` beside the signature it was seen with: a head that moves while the signature holds rewrites that index, not -the job's cache. +the job's cache. A job folder gone from disk, or no longer found under the roots +read, leaves the index with its cache, and the stored counts go. """ from __future__ import annotations @@ -249,18 +250,32 @@ def forget(ws: Workspace, roots, job_dirs) -> None: ws.job_roots = [r for r in ws.job_roots if r not in roots] save(ws) index = job_index(ws) - for d in job_dirs: - path = _cache_file(ws, d) - with _DECODED_LOCK: - _DECODED.pop(path, None) - try: - os.remove(path) - except OSError: - pass - index.pop(d, None) + # a root already gone from disk finds no job dirs: its entries go by where they were + for d in set(job_dirs) | {d for d in index if _under(d, roots)}: + _drop(ws, index, d) _write_index(ws, index) +def _under(job_dir: str, roots) -> bool: + """*job_dir* is one of *roots* or one level in it, as ``parse.find_job_dirs`` finds them.""" + roots = {os.path.normpath(r) for r in roots} + return os.path.normpath(job_dir) in roots or os.path.dirname(os.path.normpath(job_dir)) in roots + + +def _drop(ws: Workspace, index: dict, job_dir: str, keep=()) -> None: + """*job_dir*'s entry in *index* and its parsed job, unless its cache file is one of *keep*.""" + index.pop(job_dir, None) + path = _cache_file(ws, job_dir) + if path in keep: + return + with _DECODED_LOCK: + _DECODED.pop(path, None) + try: + os.remove(path) + except OSError: + pass + + def signature(job_dir: str) -> str: """What the parse of *job_dir* depends on: the files it reads, by size and mtime.""" @@ -562,8 +577,17 @@ def load_jobs(ws: Workspace, roots, runs: dict | None = None) -> list: # the rail's index read once and written once, not once per job index = job_index(ws) before = dict(index) + dirs = parse.find_job_dirs(roots) with verifier.held(): - jobs = [load_job(ws, d, index, runs)[0] for d in parse.find_job_dirs(roots)] + jobs = [load_job(ws, d, index, runs)[0] for d in dirs] + # a job folder gone from disk, or no longer found under these roots, leaves the index + found = set(dirs) + gone = [d for d in index if d not in found and (_under(d, roots) or not os.path.isdir(d))] + if gone: + keep = {_cache_file(ws, d) for d in dirs} # the same folder found by another path + for d in gone: + _drop(ws, index, d, keep) + store_counts(ws, None, None) if index != before: _write_index(ws, index) return parse.split_agents(jobs) diff --git a/app/site/diagrams.py b/app/site/diagrams.py index 7126545f..afbb03ce 100644 --- a/app/site/diagrams.py +++ b/app/site/diagrams.py @@ -321,7 +321,7 @@ def path_run_here() -> Figure: f.self_message(exe, 224, 'RUN.JSON · KEY', room=84) f.message(exe + 4, hbr - 4, 320, 'RUN-PART.SH') f.message(hbr + 4, llm, 360, 'MODEL CALLS') - f.message(hbr - 4, exe + 4, 400, 'JOBS/, EVERY 10 S', 'dashed') + f.message(hbr - 4, exe + 4, 400, 'JOBS/, 1 S PAUSE', 'dashed') f.message(exe - 4, you, 464, 'JOB PAGE · LIVE', 'accent', at=260) f.actor(you, 24, 'You', kind='input') f.actor(bld, 24, 'Builder', 'page, recipe core') @@ -335,13 +335,13 @@ def path_run_here() -> Figure: def path_run_host() -> Figure: f = Figure('path-run-host', 640, 416, 'Path 3: the same on an SSH host', 'Execution probes the host, sends the part and the key, starts it detached, then tails ' - 'the log and pulls the jobs back every ten seconds.') + 'the log and pulls the jobs back, pausing one second between looks.') exe, host = 160, 480 for cx in (exe, host): f.lifeline(cx, 72, 368) f.activation(exe, 104, 344) f.activation(host, 184, 344) - f.fragment(136, 224, 368, 120, 'LOOP', '[every 10 s]') + f.fragment(136, 224, 368, 120, 'LOOP', '[1 s pause]') f.message(exe + 4, host - 4, 112, 'PROBE: DOCKER, UV (INSTALLED IF MISSING)') f.message(exe + 4, host - 4, 152, 'SEND WHEELS, TASKS, RUN-PART.SH · KEY OVER STDIN') f.message(exe + 4, host - 4, 192, 'START RUN-PART.SH, DETACHED') @@ -423,7 +423,7 @@ def builder_run() -> Figure: f.self_message(nul, 176, 'RUNNER PREPARED ONCE', room=200) f.message(nul + 4, tgt - 4, 232, 'SSH: DOCKER, UV · THE RUNNER SENT') f.message(nul + 4, tgt - 4, 320, 'RUN-.SH DETACHED · PID, EXIT FILE') - f.self_message(nul, 344, 'EVERY 10 S: LOG TAIL, RSYNC JOBS/', 'dashed', room=200) + f.self_message(nul, 344, '1 S PAUSE: LOG TAIL, RSYNC JOBS/', 'dashed', room=200) f.message(nul - 4, page, 456, 'PAUSE: CONTINUE OR STOP') f.message(nul - 4, page, 536, 'JOB PAGE: RUN LOG, THEN LIVE', 'accent') f.actor(page, 24, 'Page', 'the builder', kind='input') diff --git a/app/site/mkdocs.yml b/app/site/mkdocs.yml index a0a396b4..2e465487 100644 --- a/app/site/mkdocs.yml +++ b/app/site/mkdocs.yml @@ -101,6 +101,7 @@ nav: - 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 - Prove a benchmark: cli/prove.md diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index dd54a9a8..8b838d58 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -219,7 +219,7 @@ keepEndpoint(r, raw); if ((Number.isInteger(raw.limit) && raw.limit >= 1) || raw.limit === '') r.limit = raw.limit; if ((Number.isInteger(raw.concurrency) && raw.concurrency >= 1) || raw.concurrency === '') r.concurrency = raw.concurrency; - // attempts per unit, retries per attempt, and the judge's and user simulator's models: a reopened recipe runs as it was saved + // attempts per unit, retries after an error, and the judge's and user simulator's models: a reopened recipe runs as it was saved if (Number.isInteger(raw.repeat) && raw.repeat >= 1 && raw.repeat <= 32) r.repeat = raw.repeat; if (Number.isInteger(raw.retries) && raw.retries >= 0 && raw.retries <= 9) r.retries = raw.retries; // the run's spending cap in USD, shared by its jobs (recipe.py): an amount above zero, or none @@ -509,7 +509,7 @@ const RESERVED = ['agent','a','model','m','dataset','d','path','p','n-tasks','l','n-concurrent','n','max-retries','r','env','e','job-name','jobs-dir','o','agent-timeout-multiplier','include-task-name','i','ak','agent-kwarg','ek','environment-kwarg','verifier-kwarg','agent-env','ae']; function validate(r) { const errors = [], notes = []; - const add = (step, message, group) => errors.push({step, message, ...(group ? {group} : {})}); + const add = (step, message, group, unset) => errors.push({step, message, ...(group ? {group} : {}), ...(unset ? {unset} : {})}); if (isStandard(r)) return {errors, notes}; // compiled and checked by the server, from its definition files if (r.harness !== 'harbor') { add(STEP.runner, RUNNER_GONE); return {errors, notes}; } const blocker = routeBlocker(r.benchmark); @@ -533,9 +533,9 @@ const named = r.model.trim() || (benchmarkCallsModel(r) && r.agents.every(id => agentById(id, r)?.control) ? (r.userModel || '').trim() : ''); if (callsModel && r.model_choice === 'paper') { const allowed = Object.values(paperModels(r).sent?.[r.provider] || {}); - if (!allowed.includes(r.model)) add(STEP.model, 'Choose one of the paper models on this provider.'); + if (!allowed.includes(r.model)) add(STEP.model, 'Choose one of the paper models on this provider.', '', !r.model); } - if (callsModel && !named) add(STEP.model, benchmarkCallsModel(r) ? 'Enter a model for the agent and/or simulated user and evaluator.' : 'Enter a model.'); + if (callsModel && !named) add(STEP.model, benchmarkCallsModel(r) ? 'Enter a model for the agent and/or simulated user and evaluator.' : 'Enter a model.', '', true); if (callsModel && !PROVIDERS.includes(r.provider)) add(STEP.model, 'Choose a provider: OpenRouter, OpenAI, Anthropic or a custom provider.'); for (const [key,label] of [['keyEnv','API key source variable'],['urlEnv','Endpoint source variable']]) { if (callsModel && (key !== 'urlEnv' || r[key]) && !/^[A-Z_][A-Z0-9_]*$/.test(r[key])) add(STEP.model, label + ' must be an environment variable name.'); @@ -548,7 +548,7 @@ if (!Number.isInteger(Number(r[key])) || Number(r[key]) < 1) add(STEP.limits, key + ' must be an integer of at least 1, or empty for every task.'); } // empty: none, as the standard's field reads it - if (r.retries !== '' && r.retries != null && (!Number.isInteger(Number(r.retries)) || Number(r.retries) < 0)) add(STEP.limits, 'Retries per attempt must be a whole number of at least 0, or empty.'); + if (r.retries !== '' && r.retries != null && (!Number.isInteger(Number(r.retries)) || Number(r.retries) < 0)) add(STEP.limits, 'Retries after an error must be a whole number of at least 0, or empty.'); if (!Number.isFinite(Number(r.timeoutMultiplier)) || !(Number(r.timeoutMultiplier) > 0)) add(STEP.agent, 'Timeout multiplier must be positive.', 'Common'); // Common trial settings (Harbor's own per-trial flags): empty means the flag is not written. for (const [key, label] of COMMON) if (r[key] !== '' && (!Number.isFinite(Number(r[key])) || !(Number(r[key]) > 0))) add(STEP.agent, label + ' must be a positive number, or empty.', 'Common'); diff --git a/app/static/builder/command-builder.css b/app/static/builder/command-builder.css index 98f86f05..9186496d 100644 --- a/app/static/builder/command-builder.css +++ b/app/static/builder/command-builder.css @@ -1,6 +1,5 @@ #nullius-builder { --nb-bg: var(--bg); --nb-surface: var(--surface); --nb-soft: var(--surface-2); --nb-text: var(--text); --nb-muted: var(--text-dim); --nb-line: var(--border); --nb-blue: var(--accent); --nb-tint: var(--accent-soft); --nb-ok: var(--ok); --nb-warn: var(--warn); --nb-red: var(--bad); color: var(--text); font: 14px/1.5 var(--sans); text-align: left; } -#nullius-builder *{box-sizing:border-box}#nullius-builder button,#nullius-builder input,#nullius-builder select{font:inherit}#nullius-builder button{cursor:pointer}#nullius-builder button:disabled{cursor:default;opacity:.55}#nullius-builder button:focus-visible,#nullius-builder input:focus-visible,#nullius-builder select:focus-visible,#nullius-builder summary:focus-visible{outline:2px solid var(--nb-blue);outline-offset:3px}#nullius-builder [hidden]{display:none!important}#nullius-builder h1,#nullius-builder h2,#nullius-builder h3,#nullius-builder p{margin:0}#nullius-builder h2{font-size:19px;font-weight:500;letter-spacing:-.35px}#nullius-builder h3{font-size:14px;font-weight:500}#nullius-builder small{font-size:12px;color:var(--nb-muted)}#nullius-builder strong{font-weight:500}#nullius-builder .nb-mono{font:12px/1.65 var(--mono);overflow-wrap:anywhere}#nullius-builder .nb-kicker{font:11px/1.5 var(--mono);letter-spacing:1.2px;color:var(--nb-muted);text-transform:uppercase;margin-bottom:9px}#nullius-builder .nb-button{display:inline-flex;align-items:center;justify-content:center;gap:7px;border:1px solid var(--nb-line);color:var(--nb-text);background:var(--nb-surface);border-radius:7px;padding:8px 12px;white-space:nowrap;font-size:12px}#nullius-builder .nb-button:hover{border-color:var(--nb-blue)}#nullius-builder .nb-primary{background:var(--nb-blue);color:var(--nb-bg);border-color:var(--nb-blue)}#nullius-builder .nb-steps{display:flex;gap:4px;border-bottom:1px solid var(--nb-line);margin-bottom:24px}#nullius-builder .nb-step{flex:1;display:flex;align-items:center;justify-content:center;gap:7px;padding:12px 3px;background:none;border:0;border-bottom:2px solid transparent;color:var(--nb-muted);font-size:12px}#nullius-builder .nb-step[aria-pressed=true]{color:var(--nb-blue);border-bottom-color:var(--nb-blue)}#nullius-builder .nb-step em{font:11px var(--mono);font-style:normal;color:inherit}#nullius-builder .nb-layout{display:grid;grid-template-columns:minmax(0,1fr) minmax(265px,.68fr);gap:26px;align-items:start}#nullius-builder .nb-editor{min-width:0}#nullius-builder .nb-sectionhead{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:17px}#nullius-builder .nb-state{font:11px/1.4 var(--mono);color:var(--nb-ok);margin-top:4px;display:block}#nullius-builder .nb-state.warn{color:var(--nb-warn)}#nullius-builder .nb-note{padding:12px 0;color:var(--nb-muted);font-size:12px;line-height:1.7}#nullius-builder .nb-notice{padding:12px 14px;background:var(--nb-soft);border-left:2px solid var(--nb-warn);border-radius:0 6px 6px 0;font-size:12px;color:var(--nb-muted);margin:15px 0}#nullius-builder .nb-notice strong{display:block;color:var(--nb-warn);margin-bottom:3px}#nullius-builder .nb-field{display:grid;gap:7px;color:var(--nb-muted);font-size:12px;margin-bottom:16px}#nullius-builder .nb-field input,#nullius-builder .nb-field select{width:100%;min-width:0;color:var(--nb-text);border:1px solid var(--nb-line);border-radius:7px;background:var(--nb-surface);padding:10px 11px;font-size:13px}#nullius-builder select option{color:var(--nb-text);background:var(--nb-surface)}#nullius-builder .nb-field input[type=checkbox]{width:17px;height:17px;accent-color:var(--nb-blue)}#nullius-builder .nb-two{display:grid;grid-template-columns:1fr 1fr;gap:14px}#nullius-builder input[type=checkbox]{accent-color:var(--nb-blue);width:17px;height:17px;flex-shrink:0}#nullius-builder .nb-subtabs{display:flex;flex-wrap:wrap;gap:4px;margin-bottom:17px}#nullius-builder .nb-subtab{border:0;background:none;color:var(--nb-muted);border-radius:6px;padding:7px 10px;font-size:12px}#nullius-builder .nb-subtab[aria-pressed=true]{background:var(--nb-soft);color:var(--nb-text)}#nullius-builder .nb-bottom{display:flex;justify-content:space-between;align-items:center;gap:12px;border-top:1px solid var(--nb-line);padding-top:18px;margin-top:23px}#nullius-builder .nb-reviewrow{padding:14px 0;border-bottom:1px solid var(--nb-line);display:flex;justify-content:space-between;align-items:center;gap:12px}#nullius-builder .nb-reviewrow small{display:block;margin-bottom:3px}#nullius-builder .nb-reviewrow strong{overflow-wrap:anywhere}#nullius-builder .nb-custom{border:1px solid var(--nb-line);border-radius:8px;padding:13px;margin-bottom:10px;background:var(--nb-surface)}#nullius-builder .nb-custom .nb-field{margin-bottom:9px}#nullius-builder .nb-rowhead{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}#nullius-builder .nb-remove{border:0;background:none;color:var(--nb-muted);padding:3px 7px}#nullius-builder .nb-error{color:var(--nb-red);font-size:12px;margin-top:8px}#nullius-builder details{border-top:1px solid var(--nb-line);margin-top:16px;padding-top:12px}#nullius-builder summary{cursor:pointer;font-size:12px;color:var(--nb-muted)}#nullius-builder .nb-badge{color:var(--nb-blue);font-size:11px} -#nullius-builder .ic { width: var(--ic-sm); height: var(--ic-sm); } /* the builder's interface icons: a size under the page's .ic */ +#nullius-builder *{box-sizing:border-box}#nullius-builder button,#nullius-builder input,#nullius-builder select{font:inherit}#nullius-builder button{cursor:pointer}#nullius-builder button:disabled{cursor:default;opacity:.55}#nullius-builder button:focus-visible,#nullius-builder input:focus-visible,#nullius-builder select:focus-visible,#nullius-builder summary:focus-visible{outline:2px solid var(--nb-blue);outline-offset:3px}#nullius-builder [hidden]{display:none!important}#nullius-builder h1,#nullius-builder h2,#nullius-builder h3,#nullius-builder p{margin:0}#nullius-builder h2{font-size:19px;font-weight:500;letter-spacing:-.35px}#nullius-builder h3{font-size:14px;font-weight:500}#nullius-builder small{font-size:12px;color:var(--nb-muted)}#nullius-builder strong{font-weight:500}#nullius-builder .nb-mono{font:12px/1.65 var(--mono);overflow-wrap:anywhere}#nullius-builder .nb-kicker{font:11px/1.5 var(--mono);letter-spacing:1.2px;color:var(--nb-muted);text-transform:uppercase;margin-bottom:9px}#nullius-builder .nb-button{display:inline-flex;align-items:center;justify-content:center;gap:7px;border:1px solid var(--nb-line);color:var(--nb-text);background:var(--nb-surface);border-radius:7px;padding:8px 12px;white-space:nowrap;font-size:12px}#nullius-builder .nb-button:hover{border-color:var(--nb-blue)}#nullius-builder .nb-primary{background:var(--nb-blue);color:var(--nb-bg);border-color:var(--nb-blue)}#nullius-builder .nb-steps{display:flex;gap:4px;border-bottom:1px solid var(--nb-line);margin-bottom:24px}#nullius-builder .nb-step{flex:1;display:flex;align-items:center;justify-content:center;gap:7px;padding:12px 3px;background:none;border:0;border-bottom:2px solid transparent;color:var(--nb-muted);font-size:12px}#nullius-builder .nb-step[aria-pressed=true]{color:var(--nb-blue);border-bottom-color:var(--nb-blue)}#nullius-builder .nb-step em{font:11px var(--mono);font-style:normal;color:inherit}#nullius-builder .nb-layout{display:grid;grid-template-columns:minmax(0,1fr) minmax(265px,.68fr);gap:26px;align-items:start}#nullius-builder .nb-editor{min-width:0}#nullius-builder .nb-sectionhead{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:17px}#nullius-builder .nb-state{font:11px/1.4 var(--mono);color:var(--nb-ok);margin-top:4px;display:block}#nullius-builder .nb-state.warn{color:var(--nb-warn)}#nullius-builder .nb-note{padding:12px 0;color:var(--nb-muted);font-size:12px;line-height:1.7}#nullius-builder .nb-notice{padding:12px 14px;background:var(--nb-soft);border-left:2px solid var(--nb-warn);border-radius:0 6px 6px 0;font-size:12px;color:var(--nb-muted);margin:15px 0}#nullius-builder .nb-notice strong{display:block;color:var(--nb-warn);margin-bottom:3px}#nullius-builder .nb-field{display:grid;gap:7px;color:var(--nb-muted);font-size:12px;margin-bottom:16px}#nullius-builder .nb-field input,#nullius-builder .nb-field select{width:100%;min-width:0;color:var(--nb-text);border:1px solid var(--nb-line);border-radius:7px;background:var(--nb-surface);padding:10px 11px;font-size:13px}#nullius-builder select option{color:var(--nb-text);background:var(--nb-surface)}#nullius-builder .nb-field input[type=checkbox]{width:17px;height:17px;accent-color:var(--nb-blue)}#nullius-builder .nb-two{display:grid;grid-template-columns:1fr 1fr;gap:14px}#nullius-builder input[type=checkbox]{accent-color:var(--nb-blue);width:17px;height:17px;flex-shrink:0}#nullius-builder .nb-subtabs{display:flex;flex-wrap:wrap;gap:4px;margin-bottom:17px}#nullius-builder .nb-subtab{border:0;background:none;color:var(--nb-muted);border-radius:6px;padding:7px 10px;font-size:12px}#nullius-builder .nb-subtab[aria-pressed=true]{background:var(--nb-soft);color:var(--nb-text)}#nullius-builder .nb-bottom{display:flex;justify-content:space-between;align-items:center;gap:12px;border-top:1px solid var(--nb-line);padding-top:18px;margin-top:23px}#nullius-builder .nb-reviewrow{padding:14px 0;border-bottom:1px solid var(--nb-line);display:flex;justify-content:space-between;align-items:center;gap:12px}#nullius-builder .nb-reviewrow small{display:block;margin-bottom:3px}#nullius-builder .nb-reviewrow strong{overflow-wrap:anywhere}#nullius-builder .nb-custom{border:1px solid var(--nb-line);border-radius:8px;padding:13px;margin-bottom:10px;background:var(--nb-surface)}#nullius-builder .nb-custom .nb-field{margin-bottom:9px}#nullius-builder .nb-rowhead{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}#nullius-builder .nb-remove{display:inline-grid;place-items:center;border:0;background:none;color:var(--nb-muted);padding:3px 7px}#nullius-builder .nb-error{color:var(--nb-red);font-size:12px;margin-top:8px}#nullius-builder details{border-top:1px solid var(--nb-line);margin-top:16px;padding-top:12px}#nullius-builder summary{cursor:pointer;font-size:12px;color:var(--nb-muted)}#nullius-builder .nb-badge{color:var(--nb-blue);font-size:11px} @media(max-width:850px){#nullius-builder .nb-layout{grid-template-columns:1fr}} @media(max-width:520px){#nullius-builder .nb-step{font-size:11px;gap:3px;flex-direction:column}#nullius-builder .nb-two{grid-template-columns:1fr;gap:0}#nullius-builder .nb-field input,#nullius-builder .nb-field select{font-size:16px}} @media(pointer:coarse){#nullius-builder button{min-height:44px}} @@ -14,14 +13,14 @@ #nullius-builder .nb-saved { width: min(640px, calc(100vw - 32px)); max-height: min(70vh, 640px); } #nullius-builder .nb-dialoghead { display: flex; justify-content: space-between; align-items: center; gap: 12px; } #nullius-builder .nb-dialoghead h2 { margin: 0; } -#nullius-builder .nb-dialogclose { flex: none; width: 32px; height: 32px; border: 0; border-radius: 8px; background: none; color: var(--nb-muted); font-size: 20px; line-height: 1; cursor: pointer; } +#nullius-builder .nb-dialogclose { flex: none; display: grid; place-items: center; padding: 0; width: 32px; height: 32px; border: 0; border-radius: 8px; background: none; color: var(--nb-muted); font-size: 20px; line-height: 1; cursor: pointer; } #nullius-builder .nb-dialogclose:hover { background: var(--nb-soft); color: var(--nb-text); } /* a message: a toast at the bottom right, its bar counting down the seconds it stays; paused while pointed at */ #nullius-builder .nb-toast { position: fixed; inset: auto 16px 16px auto; margin: 0; z-index: 50; display: flex; align-items: center; gap: 12px; box-sizing: border-box; width: max-content; max-width: min(420px, calc(100vw - 32px)); padding: 12px 10px 14px 16px; border: 1px solid var(--nb-line); border-radius: 10px; background: var(--nb-surface); color: var(--nb-text); font-size: 13px; box-shadow: 0 12px 32px #0005; overflow: hidden; } #nullius-builder .nb-toast:not(:popover-open) { display: none; } #nullius-builder .nb-toast[hidden] { display: none; } #nullius-builder .nb-toast-text { flex: 1; min-width: 0; overflow-wrap: anywhere; } -#nullius-builder .nb-toast-close { flex: none; width: 28px; height: 28px; border: 0; border-radius: 6px; background: none; color: var(--nb-muted); font-size: 18px; line-height: 1; cursor: pointer; } +#nullius-builder .nb-toast-close { flex: none; display: grid; place-items: center; padding: 0; width: 28px; height: 28px; border: 0; border-radius: 6px; background: none; color: var(--nb-muted); font-size: 18px; line-height: 1; cursor: pointer; } #nullius-builder .nb-toast-close:hover { background: var(--nb-soft); color: var(--nb-text); } #nullius-builder .nb-toast-bar { position: absolute; left: 0; right: 0; bottom: 0; height: 3px; background: var(--nb-blue); transform-origin: left; animation: nb-toast-time 5s linear forwards; } #nullius-builder .nb-toast:hover .nb-toast-bar, #nullius-builder .nb-toast:focus-within .nb-toast-bar { animation-play-state: paused; } @@ -137,7 +136,6 @@ #nullius-builder .nb-fixed { color: var(--nb-text); font-size: 15px; font-weight: 400; } #nullius-builder .nb-radio-mark { flex: none; width: var(--ic-lg); height: var(--ic-lg); border-radius: 6px; color: var(--nb-text); } #nullius-builder .nb-radio-icon { display: grid; place-items: center; color: var(--nb-blue); } -#nullius-builder .nb-radio-icon svg { fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; } /* a button whose request is on its way: a spinner before its words until the answer's toast arrives */ #nullius-builder .nb-button.nb-loading { cursor: progress; opacity: 1; } @@ -156,7 +154,7 @@ #nullius-builder .nb-tile[aria-pressed=true] { border-color: var(--nb-blue); background: var(--nb-tint); } #nullius-builder .nb-tile-head { display: flex; align-items: center; gap: 10px; min-width: 0; } #nullius-builder .nb-tile-head .nb-mark { flex: none; width: 26px; height: 26px; display: grid; place-items: center; color: var(--nb-blue); font-size: 15px; font-weight: 500; } -#nullius-builder .nb-tile-head .nb-mark svg { width: var(--ic-lg); height: var(--ic-lg); } +#nullius-builder .nb-tile-head .nb-mark svg { width: var(--ic-lg); height: var(--ic-lg); } /* the marks; an icon here is .ic-lg */ #nullius-builder .nb-nullius-mark { width: 26px; height: 26px; color: var(--nb-text); } #nullius-builder .nb-tile-head strong { flex: 1; min-width: 0; font-size: 14.5px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } #nullius-builder .nb-tile-check { flex: none; width: 20px; height: 20px; border-radius: 50%; display: grid; place-items: center; font-size: 11px; color: var(--nb-bg); } @@ -222,12 +220,7 @@ #nullius-builder .ui-field-row > input, #nullius-builder .ui-field-row > textarea { background: var(--nb-surface); } @media (max-width: 650px) { #nullius-builder label.nb-field.ui-field-row { grid-template-columns: minmax(0, 1fr); gap: 10px; } #nullius-builder .ui-field-row > input, #nullius-builder .ui-select-trigger { font-size: 16px; } } -#nullius-builder .nb-model-control { display: flex; position: relative; min-width: 0; } #nullius-builder .nb-model-control input { padding: 6px 36px 6px 11px; min-height: 34px; font-size: 13px; } -#nullius-builder .nb-model-open { position: absolute; right: 1px; top: 1px; bottom: 1px; width: 32px; border: 0; background: transparent; color: var(--nb-muted); border-radius: 7px; } -.nb-model-option { display: flex; flex-direction: column; gap: 2px; } -.nb-model-option small, .nb-model-status { color: var(--text-dim); font-size: 12px; } -.nb-model-status { padding: 8px 9px; } @media (max-width: 650px) { #nullius-builder .nb-model-control input { font-size: 16px; } } /* Compact settings rows use one shared control column, including paired fields. */ diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index 03468123..27124be2 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -6,7 +6,8 @@ // the model's providers (POST /new-run/endpoints), a pick or a slug typed and Enter joins the list under it, each // removable. Empty: any provider. What a row shows is C.servedRow's; `compiled()` is the server's last compile and // the key of the recipe it was made for (C.servedKey). - function servedRows({C, root, r, compiled, esc, button, providers}) { + // A role whose model is being typed has no row: `typing(role)`. + function servedRows({C, root, r, compiled, esc, button, providers, typing = () => false}) { const NAME = {model: 'model', simulator: 'user simulator', judge: 'judge'}; // the model a Served by is for, as the step shows it: the field's, else the leaderboard's or the official one const shown = (rec, role) => { @@ -33,7 +34,7 @@ return C.servedRow(rec, role, shown(rec, role), out, entry && entry.result); }; const chips = (role, chosen) => chosen.map((slug, i) => `${esc(slug) || '“”'}` - + button('×', `data-served-remove="${i}" data-served-role="${role}" aria-label="Remove ${esc(slug)} from Served by, ${NAME[role]}"`, 'nb-remove') + '').join(''); + + button('', `data-served-remove="${i}" data-served-role="${role}" aria-label="Remove ${esc(slug)} from Served by, ${NAME[role]}"`, 'nb-remove') + '').join(''); const field = (rec, role) => { if (!C.servedRoles(rec).includes(role)) return ''; const s = row(rec, role); return ``; }; @@ -43,7 +44,7 @@ const rec = r(); root.querySelectorAll('input[data-served-by]').forEach(input => { const role = input.dataset.servedBy, s = row(rec, role), list = root.querySelector(`[data-served-list="${role}"]`); - input.closest('.std-served').hidden = !C.servedRoles(rec).includes(role) || !s.visible; + input.closest('.std-served').hidden = !C.servedRoles(rec).includes(role) || !s.visible || typing(role); Object.assign(input.dataset, {servedModel: s.model, servedPending: String(s.pending), chosen: s.chosen.join(',')}); input.placeholder = s.placeholder; if (list && list.dataset.of !== JSON.stringify(s.chosen)) { list.dataset.of = JSON.stringify(s.chosen); list.innerHTML = chips(role, s.chosen); } @@ -107,7 +108,10 @@ return false; }); } - if (typeof module === 'object' && module.exports) { module.exports = {servedRows, recipeStore, savedList, prereqHead, fieldErrors}; return; } + // Where the step bar's underline goes: under the active step `on`, raised from the bar's bottom edge (-1px, the last + // step's row) to on's own row when the steps wrap. + const underlineAt = (on, last) => ({left: on.offsetLeft, bottom: last.getBoundingClientRect().bottom - on.getBoundingClientRect().bottom - 1, width: on.offsetWidth}); + if (typeof module === 'object' && module.exports) { module.exports = {servedRows, recipeStore, savedList, prereqHead, fieldErrors, underlineAt}; return; } const root = document.getElementById('nullius-builder'); if (!root) return; const schema = JSON.parse(document.getElementById('nb-schema').textContent); @@ -178,7 +182,7 @@ const ref = vocab.filter(a => a.kind === 'reference'), ctl = vocab.filter(a => a.kind === 'control'); if (ref.length) html += `

Benchmark reference

${ref.map(a => chip(a.id, a.label, on(a.id), `title="${esc(a.summary || '')}"`)).join('')}
`; html += `

Under evaluation

${vocab.filter(a => a.kind === 'evaluated').map(a => chip(a.id, a.label, on(a.id), `title="${esc(a.summary || '')}"`)).join('')}` - + rec.customAgents.map((p, i) => `${chip('custom-' + i, 'custom', on('custom-' + i))}${button('×', `data-remove-custom-agent="${i}"`, 'nb-remove')}`).join('') + + rec.customAgents.map((p, i) => `${chip('custom-' + i, 'custom', on('custom-' + i))}${button('', `data-remove-custom-agent="${i}" aria-label="Remove custom agent ${i + 1}"`, 'nb-remove')}`).join('') + button('+ Custom agent', 'id="nb-add-custom-agent"', 'nb-subtab') + '
'; // Harbor's own agents: what the recipe's Harbor registers, once it has been scanned (Runner step). const builtin = vocab.filter(a => a.kind === 'builtin'); @@ -216,9 +220,10 @@ }; // The standard's recipe as the server compiles it from the definitions (POST // /new-run/runner). Nothing typed here is a command; Run sends the choices. - let runnerOut = null, runnerKey = '', runnerTimer, runnerServed = null; + let runnerOut = null, runnerKey = '', runnerOutKey = '', runnerTimer, runnerServed = null; // Served by's rows (servedRows above), given the models the server last named and what decided them (C.servedCompiled) - const {field: servedField, sync: syncServed, acceptCompile} = servedRows({C, root, r, esc, button, compiled: () => runnerServed, providers: window.NulliusServingProviders}); + const {field: servedField, sync: syncServed, acceptCompile} = servedRows({C, root, r, esc, button, compiled: () => runnerServed, providers: window.NulliusServingProviders, + typing: role => !!root.querySelector(`[data-field="${role === 'model' ? role : role + '_model'}"][data-typing]`)}); // Switching runner keeps the recipe being edited, one per runner, for as long as the page is open: switching back finds it as it was. const keptByRunner = {}; // Nullius's own mark for the standard; Harbor's for Harbor @@ -398,7 +403,7 @@ // Harbor's own mark where Harbor fetches the tasks; a plain icon where no one's mark belongs. Square tiles, so // a mark is never read as a second radio button. const HARBOR_MARK = ''; - const iconTile = name => ``; + const iconTile = name => ``; const SOURCE_MARK = { hub: HARBOR_MARK, registry: HARBOR_MARK, local: iconTile('folder'), generate: iconTile('wand') }; const SOURCE_HINT = { hub: 'Harbor fetches the tasks when the run starts.', registry: 'Harbor fetches the tasks when the run starts.', @@ -467,8 +472,9 @@ return ds.length > 1 ? `${ds.map(chip).join('')}` : chip(ds[0]); }; const checkChip = (name, proven, failed, says) => { const p = proofOf(proven, failed); if (p.state === 'ok') { p.title = [says, proven.passed, p.title].filter(Boolean).join(' · '); p.text = '✓'; } return `${esc(name)}${proofSpan(p)}`; }; - // The yes to an agent running as you: asked only for the local backend, where it is no sandbox. - const consentBox = rec => ``; + // The yes to an agent running as you: asked only for the local backend, where it is no sandbox. Its field names the + // error asking for it, said under the box (fieldErrors). + const consentBox = rec => ``; // A benchmark whose units each boot a VM of their own (OSWorld's guest): a Where option has a value declaring // one (needs..vm); vmMemory, that VM's memory in GB under the chosen values, 0 for none. const bootsVms = b => Object.values((b || {}).options || {}).some(o => o.step === 'where' && Object.values(o.needs || {}).some(n => n && n.vm)); @@ -516,11 +522,12 @@ + (list.some(w => w !== 'local') ? button('Test connection', 'id="nb-test-host"') + ' ' : '')) + '

Isolation

' + (sandboxes || vms - ? `
${vms ? `Each ${esc(noun)} in its own VM` : `The agent alone in each ${esc(noun)}'s VM`}` - + `${vms ? (provider ? (sandboxes ? `${esc((provider.names || {})[provider.values[0]] || words(provider.values[0]))}, inside the ${esc(noun)}'s Boat VM` : `${esc(provider.label)}: ${esc((provider.names || {})[provider.values[0]] || words(provider.values[0]))}`) : '') : 'Answers and keys stay on this machine'}
` - : `
${how('local', 'Local processes', 'Its commands run as you, not sandboxed.', '')}` - + how('container', 'Container', web ? 'Sandboxed: each unit in a container whose only ways out are its relay and a public web proxy.' - : 'Sandboxed: each unit in a container whose only way out is its relay.', containerWhy) + '
') + ? (vms && !sandboxes ? `
As you, on the machineA container that Nullius starts cannot start the ${esc(noun)}s' VMs
` : '') + + `
${vms ? `Each ${esc(noun)} in its own VM` : `The agent alone in each ${esc(noun)}'s VM`}` + + `${vms ? (provider ? (sandboxes ? `${esc((provider.names || {})[provider.values[0]] || words(provider.values[0]))}, inside the ${esc(noun)}'s Boat VM` : `${esc(provider.label)}: ${esc((provider.names || {})[provider.values[0]] || words(provider.values[0]))}, used by ${esc(b.label)} itself`) : '') : 'Answers and keys stay on this machine'}
` + : `
${how('local', 'Local processes', 'Its commands run as you, on the machine, not sandboxed.', '')}` + + how('container', 'Container', web ? 'Sandboxed: Nullius starts a container for each unit, whose only ways out are its relay and a public web proxy.' + : 'Sandboxed: Nullius starts a container for each unit, whose only way out is its relay.', containerWhy) + '
') + (b ? benchOptions(rec, b, 'where') : '') + (agentRun && backend === 'local' ? consentBox(rec) : '') + (dockerOnly.length && backend !== 'container' && agentRun ? `

${esc(dockerOnly.join(', '))}: ${dockerOnly.length > 1 ? 'these environments need' : 'this environment needs'} a container - ${sandboxes ? 'in a Boat VM' : 'on local processes'} their units are recorded as not run.

` : '') @@ -549,12 +556,14 @@ if ((rec.backend || 'local') === 'container' && chosen.length && chosen.every(o => o.setup)) return ''; const reqs = need.map(n => [n, (b.host || {})[n]]).filter(([, r]) => r); const local = ((schema.standardHere || {}).host || {})[b.key] || {}; + const lacks = []; // a chosen machine known to lack one: said once, under the requirements return reqs.map(([name, req]) => { const lines = req.install || []; const machines = C.whereList(rec); const rows = machines.map(w => { const st = hostState[b.key + ':' + w + ':' + name] || (w === 'local' ? {missing: local[name] ? {[name]: local[name]} : {}} : null); const missing = st && st.missing && st.missing[name]; + if (missing && missing.length) lacks.push(`${w === 'local' ? 'This machine' : C.machineLabel(w)} lacks ${req.label} (${missing.join(', ')})`); const state = !st ? 'Not checked' : st.error ? st.error : missing && missing.length ? 'Missing' : 'Ready'; const attrs = `data-hostreq-name="${esc(name)}"`; return `
${machines.length > 1 || w !== 'local' ? `${esc(w === 'local' ? 'This machine' : C.machineLabel(w))}` : ''}` @@ -566,7 +575,7 @@ }).join(''); return `

${esc(req.label)}

${rows}` + (lines.length ? `
Install manually
${esc(lines.join('\n'))}
` : '') + '
'; - }).join(''); + }).join('') + (lacks.length ? `

${esc(lacks.join('; '))}: ${esc(b.label)} cannot run there. Run waits until it is there.

` : ''); } async function hostReq(entry, what, name) { const rec = r(), b = C.standardBench(rec), key = b.key + ':' + entry + ':' + name; @@ -646,11 +655,11 @@ } // one tile: {attr, key, on, title, mark, line, note, meta, foot, data (more attributes), tip (its title)} const tile = t => `'; // a machine to run on: this one or a host, its connection state filled in by Test connection - const icon = name => ``; + const icon = name => ``; const machineTile = (attr, v, t, sub, on) => tile({attr, key: v, on, mark: v === 'local' ? icon('machine') : icon('network'), title: t, tip: sub, foot: v !== 'local' ? `` : ''}); // The grids drawn by the server and run by the card toolkit (tables.js): the Benchmark step's (/new-run/benchmarks, @@ -786,8 +795,10 @@ return '

Scope

' + field('Number of ' + u.nouns, 'limit', rec.limit, {type: 'number', min: 1, placeholder: all, hint: 'The first ones' + per + ', in its order.'}) + field('Concurrent ' + u.nouns, 'concurrency', rec.concurrency, {type: 'number', min: 1, max: 32, placeholder: rec.backend === 'boat' ? String((schema.standardHere || {}).boatSlots || 'Boat\'s limit') : '1'}) + '
' - + '
' + field('Attempts per ' + u.noun, 'repeat', rec.repeat || '', {type: 'number', min: 1, max: 32, placeholder: '1'}) - + field('Retries per attempt', 'retries', rec.retries ?? '', {type: 'number', min: 0, max: 9, placeholder: '0'}) + '
' + + '
' + field('Attempts per ' + u.noun, 'repeat', rec.repeat || '', {type: 'number', min: 1, max: 32, placeholder: '1', + hint: 'Each ' + esc(u.noun) + ' is run and scored this many times.'}) + + field('Retries after an error', 'retries', rec.retries ?? '', {type: 'number', min: 0, max: 9, placeholder: '0', + hint: 'Retry errors such as rate limits or crashes, but not failed ' + esc(u.nouns) + '.'}) + '
' // a conversation's most agent turns (recipe.py: run --max-turns): only a benchmark that holds conversations has turns + ((b.needs || []).includes('agent.conversation/v1') ? field('Turns per conversation', 'turns', rec.turns ?? '', {type: 'number', min: 1, placeholder: String((b.timeouts || {}).turns || ''), @@ -807,6 +818,7 @@ // take, each empty at its default, shown greyed - an agent's own under ``by`` (OSWorld's agents' steps). function benchLimits(rec, b) { const chosen = C.runsOf(rec), yours = chosen.some(k => !['original', 'model'].includes(k) && !(b.controls || []).some(x => x.key === k)); + const theirs = chosen.some(k => ['original', 'model'].includes(k)); // a default by agent: the chosen own agents' one when they share it const own = [...new Set(C.ownChosen(rec).map(a => a.agent))], given = rec.bench_options || {}; const of = k => k === 'agent' && own.length ? (own.length === 1 ? own[0] : '') : given[k] ?? (b.options[k] || {}).default; @@ -815,7 +827,8 @@ .filter(([, o]) => (o.setups || ['yours']).some(s => s === 'yours' ? yours : chosen.includes(s))) .map(([n, o]) => { const [k, by] = Object.entries(o.by || {})[0] || []; - const def = (!yours && k && by[of(k)]) || o.default; + // an agent's or a capability's run alone gets the benchmark's value for it (``yours``), the benchmark's own agents theirs + const def = yours ? (!theirs && o.yours) || o.default : (k && by[of(k)]) || o.default; return ``; }); return rows.length ? `

${esc(b.label)}

` + rows.join('') : ''; @@ -865,7 +878,7 @@ runnerServed = accepted.served; if (step === S.model) syncServed(); if (!accepted.current) return; - runnerOut = out; + runnerOut = out; runnerOutKey = key; if (step === REVIEW) renderForm(); refreshPlan(); }, 120); @@ -941,7 +954,7 @@ html='

Scope & execution

'; const allTasks=(()=>{const ds=schema.datasets.find(d=>d.benchmark===rec.benchmark);return ds&&ds.tasks?'all '+ds.tasks:'all';})(); html+=`
${field('Number of tasks','tasks',rec.tasks,{type:'number',min:1,placeholder:allTasks,hint:'Empty: '+allTasks+'.'})}${field('Concurrent trials','concurrency',rec.concurrency,{type:'number',min:1})}
`; - html+=`
${field('Retries per attempt','retries',rec.retries,{type:'number',min:0,placeholder:'0'})}${field('Include task names · optional glob','include',rec.include,{placeholder:'django*'})}
` + html+=`
${field('Retries after an error','retries',rec.retries,{type:'number',min:0,placeholder:'0'})}${field('Include task names · optional glob','include',rec.include,{placeholder:'django*'})}
` +harborExecutableFields(rec); html+=field('Output directory','output',rec.output,{}); } @@ -964,6 +977,32 @@ $('#nb-next').textContent=step===REVIEW?'Export recipe JSON':stepName(steps[nextShown(step,1)],nextShown(step,1))+' →'; placeThumb(); } + // The open step's errors. The Model step says none over a model being typed, nor before one is chosen or its field left. + let modelActed=false; + function localErrors() { + const rec=r(),el=document.activeElement,typing=root.contains(el)&&el.dataset.typing; + if(step===REVIEW)modelActed=true; + // nor the last check's while the next is on its way + const quiet=step===S.model&&(typing||C.isStandard(rec)&&runnerKey!==runnerOutKey); + $('#nb-localerrors').textContent=fieldErrors($('#nb-form'),quiet?[]:compiled.errors.filter(e=>e.step===step&&!e.shown&&!(e.unset&&!modelActed)),esc).map(e=>e.message).join(' '); + } + // A model picked, entered, or left in its field: the recipe takes it at once. What the page shows of it waits for a + // press to end, so a button pressed to leave the field does not move from under the pointer. + let pressing=false,afterPress=null; + document.addEventListener('pointerdown',()=>{pressing=true;},true); + for(const end of ['pointerup','pointercancel'])document.addEventListener(end,()=>{pressing=false;const show=afterPress;afterPress=null;if(show)setTimeout(show);},true); + function commitModel(el) { + if(document.activeElement===el&&!document.hasFocus())return; // the window lost the focus, not the field: still being typed + const rec=r(),key=el.dataset.field,value=el.value.trim(),changed=value!==(rec[key]||''); + modelActed=true;delete el.dataset.typing; + if(changed){ + if(rec.modelFormat!=='provider-id'){for(const k of ['model','userModel','evalModel'])if(typeof rec[k]==='string')rec[k]=C.bareModel(rec[k]);rec.modelFormat='provider-id';} + C.setModelOf(rec,key,value);saveDraft(); // the field's pin goes with its model + } + const show=()=>{syncServed();refreshPlan();}; // asks nothing of a recipe already checked + if(pressing)afterPress=show; + else queueMicrotask(show); + } function refreshPlan() { const rec=r(); if(C.isStandard(rec)){ @@ -971,7 +1010,7 @@ const out=runnerOut||{errors:[],notes:[]}; compiled={errors:out.errors||[],notes:out.notes||[]}; }else{compiled=C.compile(rec);} - $('#nb-localerrors').textContent=fieldErrors($('#nb-form'),compiled.errors.filter(e=>e.step===step&&!e.shown),esc).map(e=>e.message).join(' '); + localErrors(); const errors=$('#nb-errors'); if(errors){ errors.hidden=!compiled.errors.length; @@ -983,7 +1022,7 @@ } // The underline under the active step is one element that slides to it. It follows the nav's own width, not // the window's: the Getting started panel narrows the page without a resize event. - const moveUnderline=()=>{const nav=$('.nb-steps'),on=nav.querySelector('.nb-step[aria-pressed=true]'),bar=nav.querySelector('.nb-stepbar');if(!on||!bar)return;bar.style.left=on.offsetLeft+'px';bar.style.width=on.offsetWidth+'px';}; + const moveUnderline=()=>{const nav=$('.nb-steps'),on=nav.querySelector('.nb-step[aria-pressed=true]'),bar=nav.querySelector('.nb-stepbar');if(!on||!bar)return;const u=underlineAt(on,[...nav.querySelectorAll('.nb-step')].pop());bar.style.left=u.left+'px';bar.style.bottom=u.bottom+'px';bar.style.width=u.width+'px';}; new ResizeObserver(moveUnderline).observe($('.nb-steps')); function stepName(t,i){const rec=r(),b=C.isStandard(rec)&&C.standardBench(rec); return i===S.agent&&b?(b.family==='agent'?'Agent':(b.kind||'capability').replace(/^./,c=>c.toUpperCase())):t;} @@ -1161,7 +1200,7 @@ else if(b.id==='nb-next'){if(step===REVIEW){if(!compiled.errors.length)download(JSON.stringify(r(),null,2)+'\n',r().name+'.json','application/json');return;}step=nextShown(step,1);} else if(b.id==='nb-back')step=nextShown(step,-1); else if(b.id==='nb-save'){if(schema.local)openSave();return;} - else if(b.id==='nb-startover'){try{localStorage.removeItem(draftKey);}catch{}recipe=C.prefill({});savedId='';runnerOut=null;runnerKey='';step=S.benchmark;tab='select';status('Started over from the defaults.');} + else if(b.id==='nb-startover'){try{localStorage.removeItem(draftKey);}catch{}recipe=C.prefill({});savedId='';runnerOut=null;runnerKey='';modelActed=false;step=S.benchmark;tab='select';status('Started over from the defaults.');} else if(b.id==='nb-save-cancel'){$('#nb-save-dialog').close();return;} else if(b.id==='nb-saved-toggle'){renderSaved();$('#nb-saved').showModal();loadSaved();return;} else if(b.id==='nb-saved-close'){$('#nb-saved').close();return;} @@ -1179,7 +1218,8 @@ const el=event.target,d=el.dataset,rec=r(); if(el.id==='nb-recipe-title'){updateSavePreview();return;} if(d.servedBy!==undefined)return; // what is typed in a Served by filters its menu: a pick, or Enter, adds it (nb-pick) - if(d.providerModel && rec.modelFormat !== 'provider-id'){for(const key of ['model','userModel','evalModel'])if(typeof rec[key]==='string')rec[key]=C.bareModel(rec[key]);rec.modelFormat='provider-id';} + if(d.stdUnsandboxed!==undefined)return; // a box's value is no tick: its change sets the recipe + if(d.providerModel){d.typing='true';syncServed();localErrors();return;} // what is typed in a model field filters its list: a pick, Enter or leaving the field sets it if(d.field){const p=d.field.startsWith('param:')?C.parameters().find(p=>p.key===d.field.slice(6)):null; const value=el.type==='number'?(el.value===''?'':Number(el.value)):el.value; if(p)rec.params[p.key]=p.type==='optional-boolean'?(value==='__default__'?null:value==='true'):value; @@ -1188,7 +1228,6 @@ else if(!d.providerModel&&['model','userModel','evalModel'].includes(d.field)&&/^(openrouter|openai)\//.test(String(value))){rec.provider=C.providerOf(rec,value);rec[d.field]=C.bareModel(value); renderForm();refreshPlan();const f=root.querySelector(`[data-field="${d.field}"]`);if(f){f.focus();f.setSelectionRange(f.value.length,f.value.length);}return;} // the provider the prefix named, and whether it is set else if(d.field==='provider'){C.setChoice(rec,value);renderForm();refreshPlan();return;} // whether it is set in Settings, and the names a runner's models are sent as, follow the provider - else if(['model','simulator_model','judge_model'].includes(d.field)){C.setModelOf(rec,d.field,value);syncServed();} // the field's pin goes with its model; its Served by follows, in place else rec[d.field]=value; if(el.list?.id==='nb-paths')completeDirectory(el.value); }else if(d.stdMinutes){const t=Object.assign({},rec.timeouts);if(el.value===''||!(Number(el.value)>0))delete t[d.stdMinutes];else t[d.stdMinutes]=Number(el.value);if(Object.keys(t).length)rec.timeouts=t;else delete rec.timeouts;refreshPlan();return; @@ -1205,13 +1244,15 @@ // no cap, unsaid. It is said, and the field emptied, so that it shows what the recipe holds root.addEventListener('focusout',event=>{ const el=event.target; + if(el.dataset.providerModel)commitModel(el); // a change undone by hand since the focus fires no change event if(el.type==='number'&&(el.dataset.field||el.dataset.stdMinutes||el.dataset.benchOptSelect)&&el.validity&&el.validity.badInput){el.value='';window.nulliusNotify?.(`${el.getAttribute('aria-label')}: enter a number.`,{error:true,key:'bad-number'});} }); // a provider picked in a Served by, or slugs typed there and Enter: they join its list, after the ones there root.addEventListener('nb-pick',event=>{const role=event.target.dataset.servedBy;if(!role)return;C.addServed(r(),role,event.detail);syncServed();refreshPlan();}); root.addEventListener('change',async event=>{ const el=event.target,d=el.dataset; - if(d.custom?.endsWith(':type')){$('#nb-parameters').innerHTML=customRows(!['common','extra'].includes(tab)?tab:'');} + if(d.providerModel)commitModel(el); + else if(d.custom?.endsWith(':type')){$('#nb-parameters').innerHTML=customRows(!['common','extra'].includes(tab)?tab:'');} else if(d.stdUnsandboxed!==undefined){r().unsandboxed=el.checked;refreshPlan();} else if(d.stdVersion!==undefined){ // in place: only the card's count changes on this step, so nothing else is drawn again C.setStandardBenchmark(r(),el.value);benchTasks();render(false,false);} @@ -1229,7 +1270,7 @@ else if(d.harborChoice!==undefined){const rec=r(),v=el.value;if(v==='path')rec.harborDev='';else if(v==='dev')rec.harborDev=rec.harborDev||'~/harbor-dev/.venv/bin/harbor';renderForm();refreshPlan();if(v==='dev')root.querySelector('[data-field="harborDev"]')?.select();} else if(el.id==='nb-import-file'){ const file=el.files[0];if(!file)return; - try{if(file.size>100000)throw Error('Recipe file is too large.');recipe=C.fromJSON(await file.text());savedId='';step=REVIEW;render(true);status('Imported “'+(recipe.title||recipe.name)+'”. Review the recipe before copying commands.');}catch(error){status('Could not import recipe: '+error.message);}el.value=''; + try{if(file.size>100000)throw Error('Recipe file is too large.');recipe=C.fromJSON(await file.text());savedId='';step=REVIEW;render(true);status('Imported “'+(recipe.title||recipe.name)+'”. Check it, then Run.');}catch(error){status('Could not import recipe: '+error.message);}el.value=''; } }); { const dl=document.getElementById('nb-models'); if(dl){const seen=new Set(); for(const o of [...dl.options]){const v=C.bareModel(o.value); if(!v||seen.has(v)){o.remove();continue;} seen.add(v); o.value=v;}} } diff --git a/app/static/builder/recipes.css b/app/static/builder/recipes.css index 62a393be..f6a1ab9c 100644 --- a/app/static/builder/recipes.css +++ b/app/static/builder/recipes.css @@ -1,14 +1,13 @@ /* The Recipes page: one row per saved recipe; Info and Delete in one dialog (the Launches page's, runs/launches.css). */ .rcp-name { overflow-wrap: anywhere; } /* a name wraps, never cut */ .rcp-warn { display: flex; align-items: center; gap: 4px; margin-top: 2px; font-size: 12.5px; color: var(--patch_failed_tests); cursor: help; } -.rcp-warn .ic { width: 14px; height: 14px; } .rcp-val { display: block; max-width: 10rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* the whole value is its tooltip */ #recipes td[data-col="name"] { white-space: normal; } dialog.std-how.launch-delete.wide { width: min(56rem, calc(100vw - 32px)); } .launch-delete .rcp-problems { list-style: none; padding: 0; margin: 12px 0 0; } .rcp-problems li { display: flex; gap: 8px; align-items: baseline; padding: 6px 10px; margin-top: 4px; border-radius: 8px; font-size: 13px; background: color-mix(in srgb, var(--patch_failed_tests) 12%, var(--surface)); } -.rcp-problems .ic { width: 14px; height: 14px; color: var(--patch_failed_tests); align-self: center; } +.rcp-problems .ic { color: var(--patch_failed_tests); align-self: center; } .rcp-step h3 em { font-style: normal; margin-right: 8px; } .rcp-row { display: grid; grid-template-columns: minmax(7rem, 12rem) 1fr; gap: 12px; padding: 4px 0; border-top: 1px solid var(--border-soft); } .rcp-row small { color: var(--text-dim); } diff --git a/app/static/catalogue/catalogue.css b/app/static/catalogue/catalogue.css index 9caf1613..4087a55b 100644 --- a/app/static/catalogue/catalogue.css +++ b/app/static/catalogue/catalogue.css @@ -32,13 +32,15 @@ button.card-link:disabled { cursor: not-allowed; } .table-wrap .grid tbody tr:has([data-pick]:disabled) > td { color: var(--text-faint); } tr:has([data-pick]:disabled) .row-name > :first-child { opacity: .55; } tr:has([data-pick]:not(:disabled)) { cursor: pointer; } -.bench-card:has(> .bench-card-title [data-pick][aria-pressed="true"]) { border-color: var(--accent); background: var(--accent-soft); - --pick-fill: color-mix(in srgb, var(--accent) 16%, var(--accent-soft)); --pick-line: color-mix(in srgb, var(--accent) 40%, var(--border)); } -/* inside it, what is filled with --accent-soft (a category tag, a mark) or outlined with --border (a tag) stands out from - that background as it does on any card: a shade nearer the accent */ -.bench-card:has(> .bench-card-title [data-pick][aria-pressed="true"]) > * { --accent-soft: var(--pick-fill); --border: var(--pick-line); } +.bench-card:has(> .bench-card-title [data-pick][aria-pressed="true"]) { border-color: var(--accent); background: var(--accent-soft); } +/* inside a chosen card or a chosen row's cell, what is filled with --accent-soft (a category tag, a mark) or outlined with + --border (a tag) stands out from that background as it does unchosen: a shade nearer the accent, the outline at 3:1 */ +:is(.bench-card:has(> .bench-card-title [data-pick][aria-pressed="true"]), .table-wrap .grid tbody tr:has([data-pick]:checked) > td) { + --pick-fill: color-mix(in srgb, var(--accent) 16%, var(--accent-soft)); --pick-line: color-mix(in srgb, var(--accent) 60%, var(--border)); } +:is(.bench-card:has(> .bench-card-title [data-pick][aria-pressed="true"]), .table-wrap .grid tbody tr:has([data-pick]:checked) > td) > * { + --accent-soft: var(--pick-fill); --border: var(--pick-line); } .pick-check { flex: none; width: 20px; height: 20px; border-radius: 50%; display: grid; place-items: center; background: var(--accent); color: var(--btn-fg); visibility: hidden; } -.pick-check .ic { width: 12px; height: 12px; stroke-width: 3; } +.pick-check .ic { --ic-w16: 2; } /* 2px: a 1px diagonal breaks up, white on the accent */ .bench-card:has([data-pick][aria-pressed="true"]) .pick-check { visibility: visible; } .bench-card:has(> .bench-card-title [data-pick]:disabled) { opacity: .55; } .bench-card:has(> .bench-card-title [data-pick]:disabled):hover { border-color: var(--border-soft); } @@ -362,7 +364,6 @@ dialog.std-how::backdrop { background: rgba(0, 0, 0, .45); } .std-hostreq { margin-top: 14px; } /* what some options need on the machine: a note on the card, not a way to run */ .bench-card-setup { display: inline-flex; align-items: center; gap: 5px; margin-top: 8px; font-size: .78rem; color: var(--text-dim); } -.bench-card-setup svg { width: 13px; height: 13px; flex: none; } a.std-need { font-size: .78rem; color: var(--text-dim); text-decoration: underline dotted; } .std-setups { --setup-padding: 22px; } diff --git a/app/static/compare/columns.js b/app/static/compare/columns.js index 9da1d751..71a1f146 100644 --- a/app/static/compare/columns.js +++ b/app/static/compare/columns.js @@ -90,10 +90,13 @@ window.NulliusCompare = { }); list.addEventListener('click', e => { const o = e.target.closest('[role="option"]'); if (o && o.getAttribute('aria-disabled') !== 'true') pick(o); }); // fixed under its button (the table's scroll box would clip it), placed before it opens and takes the focus, - // so the focus never scrolls the table + // so the focus never scrolls the table; above it when there is more room there, its height kept to the room const place = () => { const b = btn.getBoundingClientRect(), w = Math.min(Math.max(b.width, 320), innerWidth - 16); - Object.assign(menu.style, {top: `${b.bottom + 4}px`, left: `${Math.max(8, Math.min(b.left, innerWidth - w - 8))}px`, width: `${w}px`}); + const below = innerHeight - b.bottom - 12, above = b.top - 12, up = above > below; + Object.assign(menu.style, {top: up ? 'auto' : `${b.bottom + 4}px`, bottom: up ? `${innerHeight - b.top + 4}px` : 'auto', + maxHeight: `${Math.max(up ? above : below, 0)}px`, + left: `${Math.max(8, Math.min(b.left, innerWidth - w - 8))}px`, width: `${w}px`}); }; btn.addEventListener('click', place); NulliusTable.menu(btn, menu); diff --git a/app/static/compare/comparison.css b/app/static/compare/comparison.css index 884e4ccc..a8f2a559 100644 --- a/app/static/compare/comparison.css +++ b/app/static/compare/comparison.css @@ -150,3 +150,10 @@ .fig-head .tools-menu a::before { content: ""; flex: 0 0 1em; text-align: center; color: var(--accent); } /* every item keeps the check's slot, so the names align */ .fig-head .tools-menu a[aria-current="true"]::before { content: "✓"; } /* the card's style or metric */ .fig-note { margin: 0; font-size: .84rem; color: var(--text-dim); } +/* the flag filters: one list of flagged tasks set aside in every column */ +.compare-flags{display:flex;flex-wrap:wrap;gap:.65rem;align-items:center;margin:.6rem 0} +.compare-flags .filter-heading{color:var(--text-faint);font-size:.8rem} +.compare-flags .filter-choice{display:flex;align-items:center;gap:.5rem;font-size:.8rem;cursor:pointer} +.compare-flags input[type=checkbox]{margin:0;flex:none;accent-color:var(--accent)} +.compare-flags #compare-set-aside{font-size:1rem;color:var(--text)} +.compare-flags .warn{color:var(--warn,var(--text-dim))} diff --git a/app/static/builder/model-picker.js b/app/static/model-picker.js similarity index 70% rename from app/static/builder/model-picker.js rename to app/static/model-picker.js index 25c64740..3268fbee 100644 --- a/app/static/builder/model-picker.js +++ b/app/static/model-picker.js @@ -1,9 +1,10 @@ // Provider model IDs stay verbatim; browsing a catalogue never chooses a model. // The same picker serves a model's Served by (list="nb-served"): its rows are the providers of the model the field // names (data-served-model), and a field of several takes each pick, or a slug typed as is, into its list. +// Outside the builder, data-model-picker on an input is the selector of its provider's select, in its form or judge card. (() => { - // the rows a typed query keeps: the query in the id or the name, case aside; the ones already chosen left out - const matching = (items, query, chosen = []) => items.filter(m => !chosen.includes(m.id) && (m.id + ' ' + m.name).toLowerCase().includes(query.toLowerCase())); + // the rows a typed query keeps, by the tables' search (tables.js); the ones already chosen left out + const matching = (items, query, chosen = []) => items.filter(m => !chosen.includes(m.id) && window.NulliusTable.matches(m.id + ' ' + m.name, query)); // what Enter takes: the highlighted row, else, in a field of several, the text as typed (a slug the list may lack) const entered = (items, index, text, several) => items[index] || (several && text.trim() ? {id: text.trim(), typed: true} : null); // The row and its menu share one request per model for five minutes, including failures. An in-flight request @@ -25,13 +26,22 @@ providers.subscribe = listener => listeners.add(listener); return providers; } - if (typeof module === 'object' && module.exports) { module.exports = {matching, entered, servingProviders}; return; } + // Where a provider's select says its models are: the list on its chosen option, Decision's live one, or the + // provider's catalogue. local:, a named endpoint in Settings, is custom: there. + const sourceOf = option => option?.dataset.models && !('live' in option.dataset) + ? {models: option.dataset.models.split('|').map(id => ({id, name: id}))} + : {url: option && 'live' in option.dataset ? '/settings/decision/models' : '/new-run/models', + provider: (option?.value || '').replace(/^local(?=$|:)/, 'custom'), listed: (option?.dataset.models || '').split('|').filter(Boolean)}; + if (typeof module === 'object' && module.exports) { module.exports = {matching, entered, servingProviders, sourceOf}; return; } const root = document.getElementById('nullius-builder'); - if (!root) return; - const schema = JSON.parse(document.getElementById('nb-schema').textContent); - const providers = window.NulliusServingProviders = servingProviders(nulliusFetch, schema.csrf); + const csrf = root ? JSON.parse(document.getElementById('nb-schema').textContent).csrf : document.querySelector('[name=csrf]')?.value; + const providers = root && (window.NulliusServingProviders = servingProviders(nulliusFetch, csrf)); const cache = new Map(); let active = null, serial = 0, choosing = false; const severalOf = input => input.dataset.pickerSeveral === 'true'; + const placeOf = input => { + if (root) return {url: '/new-run/models', provider: root.dataset.modelProvider}; + return sourceOf([input.closest('[data-judge-card]'), input.closest('form')].map(at => at?.querySelector(input.dataset.modelPicker)).find(Boolean)?.selectedOptions[0]); + }; function close() { if (!active) return; active.input.setAttribute('aria-expanded', 'false'); @@ -58,14 +68,17 @@ } function choose(model, input = active.input) { close(); choosing = true; + const card = input.closest('[data-judge-card]'); // a field of several hands the pick to the page, which lists it, and is left empty for the next one if (severalOf(input)) { input.value = ''; input.dispatchEvent(new CustomEvent('nb-pick', {bubbles: true, detail: model.id})); } else { input.value = model.id; + if (card) input.blur(); // autosave draws a saved field again only once it is left input.dispatchEvent(new Event('input', {bubbles: true})); input.dispatchEvent(new Event('change', {bubbles: true})); } - input.focus(); choosing = false; + if (!card) input.focus(); + choosing = false; } function paint() { if (!active) return; @@ -75,7 +88,7 @@ // no model yet, or the one the run sends not yet known (the server compiles it): no list is asked if (several && !input.dataset.servedModel) status.textContent = input.dataset.servedPending === 'true' ? 'Loading providers…' : 'Choose the model first'; else if (!result) status.textContent = several ? 'Loading providers…' : 'Loading models…'; - else if (result.ok && input.dataset.field === 'model' && JSON.parse(root.dataset.paperModels || 'null') !== null && !result.models.length) status.textContent = 'No paper models available from this provider.'; + else if (result.ok && root && input.dataset.field === 'model' && JSON.parse(root.dataset.paperModels || 'null') !== null && !result.models.length) status.textContent = 'No paper models available from this provider.'; else if (!result.ok) status.textContent = result.message || (several ? "Provider list unavailable. Enter a provider's slug by hand." : 'Model list unavailable. Enter a model ID manually.'); else { const matches = matching(result.models, query, several ? (input.dataset.chosen || '').split(',').filter(Boolean) : []); @@ -91,30 +104,34 @@ const name = document.createElement('span'); name.textContent = model.name; row.append(name); if (model.id !== model.name) { const id = document.createElement('small'); id.textContent = model.id; row.append(id); } - row.addEventListener('pointerdown', e => e.preventDefault()); row.addEventListener('click', () => choose(model)); menu.append(row); }); position(); } - async function models(provider) { - let entry = cache.get(provider); + async function models({models: given, url, provider, listed = []}) { + if (given) return {ok: true, models: given}; + const key = url + ' ' + provider; + let entry = cache.get(key); if (!entry || Date.now() - entry.at > 300000) { - entry = {at: Date.now(), promise: nulliusFetch('/new-run/models', {method: 'POST', headers: {'Content-Type': 'application/json', 'X-CSRF-Token': schema.csrf}, body: JSON.stringify({provider})}) + entry = {at: Date.now(), promise: nulliusFetch(url, {method: 'POST', headers: {'Content-Type': 'application/json', 'X-CSRF-Token': csrf}, body: JSON.stringify({provider})}) .then(r => r.json()).then(r => ({...r, models: Array.isArray(r.models) ? r.models : []})) .catch(() => ({ok: false, models: [], message: 'Model list unavailable. Enter a model ID manually.'}))}; - cache.set(provider, entry); + cache.set(key, entry); } const result = await entry.promise; - if (!result.ok) cache.delete(provider); - return result; + if (!result.ok) cache.delete(key); + // a live list that cannot be read leaves the one drawn with the page + return listed.length && !result.models.length ? {ok: true, models: listed.map(id => ({id, name: id}))} : result; } async function open(input, all = false) { close(); const menu = document.createElement('div'); menu.className = 'ui-select-menu nb-model-menu'; menu.id = input.getAttribute('aria-controls'); const several = severalOf(input); menu.setAttribute('popover', 'manual'); menu.setAttribute('role', 'listbox'); menu.setAttribute('aria-label', several ? 'Serving providers' : 'Provider models'); + // a press in the menu leaves the keyboard in the field + for (const press of ['pointerdown', 'mousedown']) menu.addEventListener(press, e => e.preventDefault()); document.body.append(menu); - const state = {input, menu, wrap: input.parentElement, several, provider: root.dataset.modelProvider, model: input.dataset.servedModel || '', query: all ? '' : input.value, result: null, items: [], index: -1}; + const state = {input, menu, wrap: input.parentElement, several, provider: root?.dataset.modelProvider, model: input.dataset.servedModel || '', query: all ? '' : input.value, result: null, items: [], index: -1}; active = state; input.setAttribute('aria-expanded', 'true'); paint(); if (menu.showPopover) menu.showPopover(); if (several) { @@ -123,44 +140,50 @@ if (active === state) { state.result = result; paint(); } return; } - const paper = input.dataset.field === 'model' ? JSON.parse(root.dataset.paperModels || 'null') : null; - const result = await models(state.provider); + const paper = root && input.dataset.field === 'model' ? JSON.parse(root.dataset.paperModels || 'null') : null; + const result = await models(placeOf(input)); state.result = paper === null || !result.ok ? result : {...result, models:Object.entries(paper) .filter(([, served])=>result.models.some(m=>m.id === served)) .map(([id, served])=>({id:root.dataset.standardModel === 'true' ? id : served, name:id === served ? id : id + ' · ' + served}))}; if (active === state) paint(); } function scan() { - if (active && (!active.input.isConnected || active.input.closest('[hidden]') || active.provider !== root.dataset.modelProvider)) close(); + if (active && (!active.input.isConnected || active.input.closest('[hidden]') || active.provider !== root?.dataset.modelProvider)) close(); // the model a Served by lists the providers of has moved (the server named the one the run sends): its rows follow else if (active && active.several && active.model !== (active.input.dataset.servedModel || '')) void open(active.input, !active.query); - root.querySelectorAll('input[list="nb-models"], input[list="nb-served"]').forEach(input => { + (root || document).querySelectorAll(root ? 'input[list="nb-models"], input[list="nb-served"]' : 'input[data-model-picker]:not([role])').forEach(input => { if (input.getAttribute('list') === 'nb-served') input.dataset.pickerSeveral = 'true'; else input.dataset.providerModel = 'true'; input.removeAttribute('list'); input.autocomplete = 'off'; input.setAttribute('role', 'combobox'); input.setAttribute('aria-autocomplete', 'list'); input.setAttribute('aria-expanded', 'false'); input.setAttribute('aria-controls', 'provider-models-' + (++serial)); const wrap = document.createElement('span'); wrap.className = 'nb-model-control'; input.before(wrap); wrap.append(input); - const button = document.createElement('button'); button.type = 'button'; button.className = 'nb-model-open'; button.textContent = '⌄'; + const button = document.createElement('button'); button.type = 'button'; button.className = 'nb-model-open'; button.innerHTML = ''; button.setAttribute('aria-label', severalOf(input) ? 'Browse the serving providers' : 'Browse provider models'); + // the field keeps the keyboard: pressing this is not leaving it, and ArrowDown opens the list + for (const press of ['pointerdown', 'mousedown']) button.addEventListener(press, e => e.preventDefault()); + button.tabIndex = -1; button.addEventListener('click', e => { e.preventDefault(); input.focus(); void open(input, true); }); wrap.append(button); input.addEventListener('focus', () => { if(!choosing)void open(input); }); // a field of several keeps the keyboard after a pick: a click on it opens its menu again for the next one if (severalOf(input)) input.addEventListener('click', () => { if(active?.input !== input)void open(input); }); input.addEventListener('input', () => { if(choosing)return; if (active?.input === input) { active.query = input.value; paint(); } else void open(input); }); input.addEventListener('keydown', e => { + if (e.isComposing || e.keyCode === 229) return; // an input method's own keys if (e.key === 'Escape' || e.key === 'Tab') { if(e.key === 'Escape' && active){e.preventDefault();e.stopPropagation();} close(); return; } if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); if(active?.input !== input)void open(input, true); else highlight(active.index + (e.key === 'ArrowDown' ? 1 : -1)); } if (e.key === 'Enter') { const pick = entered(active?.input === input ? active.items : [], active?.input === input ? active.index : -1, input.value, severalOf(input)); - if (!pick) return; + // the first Enter puts an open menu away (in the builder it takes the id as typed); it never submits a half-typed search + if (!pick) { if (active?.input === input) { e.preventDefault(); close(); if (root) input.dispatchEvent(new Event('change', {bubbles: true})); } return; } e.preventDefault(); choose(pick, input); } }); }); } - new MutationObserver(scan).observe(root, {childList: true, subtree: true, attributes: true, attributeFilter: ['data-model-provider', 'data-served-model']}); + if (root) new MutationObserver(scan).observe(root, {childList: true, subtree: true, attributes: true, attributeFilter: ['data-model-provider', 'data-served-model']}); document.addEventListener('pointerdown', e => { if(active && !active.wrap.contains(e.target) && !active.menu.contains(e.target))close(); }); document.addEventListener('scroll', e => { if(active && !active.menu.contains(e.target))close(); }, true); window.addEventListener('resize', close); + document.addEventListener('nullius-settings-saved', scan); // a saved field is drawn again scan(); })(); diff --git a/app/static/notifications.js b/app/static/notifications.js index 097a500a..5a5127fa 100644 --- a/app/static/notifications.js +++ b/app/static/notifications.js @@ -17,7 +17,7 @@ if (key) [...tray.children].filter(t => t.dataset.noticeKey === key).forEach(t => t.remove()); const toast = document.createElement('div'); toast.className = 'toast ' + (error ? 'bad' : 'ok'); toast.dataset.noticeKey = key; const text = document.createElement('span'); text.className = 'toast-text'; text.textContent = message; - const close = document.createElement('button'); close.type = 'button'; close.className = 'toast-close'; close.setAttribute('aria-label', 'Dismiss'); close.textContent = '×'; + const close = document.createElement('button'); close.type = 'button'; close.className = 'toast-close'; close.setAttribute('aria-label', 'Dismiss'); close.innerHTML = ''; const bar = document.createElement('span'); bar.className = 'toast-bar'; bar.setAttribute('aria-hidden', 'true'); const dismiss = () => { toast.remove(); if (!tray.children.length) tray.remove(); }; close.addEventListener('click', dismiss); bar.addEventListener('animationend', dismiss); diff --git a/app/static/onboarding.css b/app/static/onboarding.css index 79080837..ded67d03 100644 --- a/app/static/onboarding.css +++ b/app/static/onboarding.css @@ -61,7 +61,6 @@ body.onb-open .shell { margin-right: 310px; } .onb-rail { position: relative; } .onb-rail .onb-x { position: absolute; right: .35rem; top: 50%; transform: translateY(-50%); width: 22px; height: 22px; display: grid; place-items: center; border: 0; border-radius: 5px; background: none; color: var(--text-faint); cursor: pointer; padding: 0; } -.onb-rail .onb-x .ic { width: 13px; height: 13px; } .onb-rail .onb-count { margin-right: 22px; } .onb-rail .onb-x:hover { background: var(--surface-2); color: var(--text); } :root[data-rail="collapsed"] .onb-rail .onb-x { display: none; } diff --git a/app/static/onboarding.js b/app/static/onboarding.js index ae8e055c..1daa9ad6 100644 --- a/app/static/onboarding.js +++ b/app/static/onboarding.js @@ -152,6 +152,11 @@ if (e.target.closest('#onb-open')) { S.open = !S.open; save(); return renderPanel(); } if (pointed && pointed.contains(e.target)) unpoint(); }); + // Escape on the checklist or its toggle closes it, and the focus goes back to the toggle + document.addEventListener('keydown', e => { + if (e.key !== 'Escape' || !S.open || !(railItem?.contains(document.activeElement) || panel?.contains(document.activeElement))) return; + S.open = false; save(); unpoint(); renderPanel(); railItem?.focus(); + }); // ---- on load: the checklist read, this page's visit kept, then whatever was under way carried on nulliusFetch(STATE_URL, {headers: {Accept: 'application/json'}}).then(r => r.ok ? r.json() : {sections: []}).catch(() => ({sections: []})).then(j => { diff --git a/app/static/runs/board.css b/app/static/runs/board.css index 2c943dff..8bbbe5dd 100644 --- a/app/static/runs/board.css +++ b/app/static/runs/board.css @@ -103,7 +103,7 @@ .rp .meter .bar1 span.x { background: none; box-shadow: inset 0 0 0 1.5px var(--track-res); } .rp .meter b { font: 500 13px/1 var(--sans); color: var(--text); white-space: nowrap; } .rp .board.pv .meter i.lit { box-shadow: 0 0 0 2px var(--surface), 0 0 0 3.5px var(--text); } -.rp .hk { margin: 14px 18px 0; font-size: 12px; line-height: 22px; } +.rp .hk { margin: 24px 18px 0; font-size: 12px; line-height: 22px; } .rp .hk p { margin: 0; color: var(--text-faint); white-space: nowrap; } .rp .hk dl { display: grid; grid-template-columns: auto auto; justify-content: start; column-gap: 6px; margin: 0; } .rp .hk dt { color: var(--text-faint); white-space: nowrap; } @@ -372,3 +372,47 @@ box-shadow: var(--shadow); font: 12px/1.45 var(--sans); color: var(--text); pointer-events: none; } @media (prefers-reduced-motion: reduce) { .rp *, .rp *::before, .rp *::after { transition: none !important; } } + +/* Run identity belongs on the full run overview, above its views. */ +.run-identity{align-items:center;gap:10px} +.run-identity-card{display:flex;align-items:center;gap:12px;border:1px solid var(--border);border-radius:var(--radius);background:var(--surface);padding:6px 14px;min-height:52px;min-width:0;max-width:100%;color:var(--text);line-height:1.35} +.run-identity-card>div{min-width:0;overflow-wrap:anywhere} +.run-identity-card .k{display:block;color:var(--text-dim);font-size:.75rem} +.run-identity-card .v{display:block;font-weight:500} +.run-identity-sep{width:1px;flex:none;align-self:stretch;background:var(--border)} +.run-identity-mark{width:32px;height:32px;border-radius:8px;background:var(--accent-soft);color:var(--accent);display:grid;place-items:center;font:500 15px/1 var(--mono);flex:none;padding:6px} +.run-identity-mark:has(.agent-logo){padding:4px;background:color-mix(in srgb,var(--text) 8%,transparent);color:var(--text)} +.run-identity-model{display:block;font-size:.8rem;color:var(--text-dim);overflow-wrap:anywhere} +/* A card with more to say opens it beneath itself, over the page; the row keeps its height. */ +.run-identity-more{position:relative;min-width:0;max-width:100%} +.run-identity-more>summary{cursor:pointer;list-style:none} +.run-identity-more>summary::-webkit-details-marker{display:none} +.run-identity-more[open]>summary{border-color:var(--text-faint)} +.run-identity-more .dd-chev{color:var(--text-dim)} +.run-identity-more[open] .dd-chev{transform:rotate(180deg)} +.run-identity-details{position:absolute;z-index:6;left:0;top:calc(100% + 6px);display:grid;grid-template-columns:auto minmax(0,auto);gap:4px 24px;margin:0;padding:10px 16px;width:max-content;max-width:min(36rem,calc(100vw - 32px));border:1px solid var(--border);border-radius:var(--radius);background:var(--surface-2);box-shadow:var(--shadow);font-size:14px;line-height:1.5} +.run-identity-details dt{color:var(--text-dim)} +.run-identity-details dd{margin:0;color:var(--text);overflow-wrap:anywhere} +/* on a narrow screen it opens in the page's flow and pushes the cards below it down */ +@media(max-width:640px){.run-identity{align-items:flex-start}.run-identity-more>summary{width:fit-content;max-width:100%}.run-identity-details{position:static;margin-top:6px;max-width:100%}} + +.run-runner-logo{width:32px;height:32px;flex:none;color:var(--text)} +/* the Filtered score under the adjusted rate: a switch per kind of flag, and the rate without those tasks */ +.rp .filtered { display: flex; flex-wrap: wrap; gap: .65rem; align-items: center; margin: 1rem 18px 0; } +.rp .filtered .filter-heading { flex-basis: 100%; color: var(--text-faint); font-size: .8rem; } +.rp .filtered .filter-choice { display: flex; align-items: center; gap: .5rem; flex-basis: 100%; font-size: .8rem; cursor: pointer; } +.rp .filtered input[type=checkbox] { margin: 0; flex: none; accent-color: var(--accent); } +.rp .filtered p { margin: .5rem 0 0; flex-basis: 100%; color: var(--text-dim); font-size: 1rem; } +.rp .filtered p b { color: var(--text); font-weight: 600; font-size: 1.4rem; margin-left: .2rem; } + +/* the trial table's marks: a task's flag and a trial's failure label; a task left out of the Filtered score fades */ +.rp .tt .w-fa { width: 7.5rem; } +.rp .tt td.fa { white-space: nowrap; } +.rp .tt .tflag + .tlabel { margin-left: .3rem; } +.rp .tt .tflag, .rp .tt .tlabel { display: inline-block; padding: 0 .35rem; border-radius: 3px; + font-size: .72rem; line-height: 1.35; white-space: nowrap; vertical-align: middle; } +.rp .tt .tflag { border: 1px solid var(--text-dim); color: var(--text-dim); } +.rp .tt .tflag.tf-pending, .rp .tt .tflag.tf-other { border-style: dashed; color: var(--text-faint); border-color: var(--text-faint); } +.rp .tt .tlabel { border: 1px solid var(--text-faint); color: var(--text); font-style: italic; } +.rp .tt[data-leave-out~="flawed"] tr[data-task-flag="flawed"] > td, +.rp .tt[data-leave-out~="ambiguous"] tr[data-task-flag="ambiguous"] > td { opacity: .45; } diff --git a/app/static/runs/board.js b/app/static/runs/board.js index 780956f1..2872b5c3 100644 --- a/app/static/runs/board.js +++ b/app/static/runs/board.js @@ -66,9 +66,11 @@ facets.forEach(paint); sync(); } + // what lies open over the page: its own menus, and the header's cards above it + const opened = () => [...$$('.facet details[open], .pop[open]', page), ...$$('.run-identity-more[open]')]; // a legend row or segment sets the outcome; a cause outcome + cause + status; a flag line the flag. Pressed again: off. document.addEventListener('click', e => { - $$('.facet details[open], .pop[open]', page).forEach(d => { if (!d.contains(e.target)) d.open = false; }); + opened().forEach(d => { if (!d.contains(e.target)) d.open = false; }); const el = e.target.closest && e.target.closest('.fx'); if (!el || !page.contains(el)) return; e.preventDefault(); const ks = KEYS.filter(k => k in el.dataset), menu = el.closest('details'); @@ -128,10 +130,16 @@ r.style.transition = 'transform .28s var(--ease)'; r.style.transform = ''; }); })); + // a split that would open past the window's right edge (a narrow screen) opens leftwards instead + $$('.pop', page).forEach(d => d.addEventListener('toggle', () => { + const m = $('.popm', d); m.style.left = m.style.right = ''; + if (d.open && m.getBoundingClientRect().right > innerWidth) Object.assign(m.style, {left: 'auto', right: '0'}); + })); + // ---- Esc closes what is open, else clears the filters ---- document.addEventListener('keydown', e => { if (e.key !== 'Escape') return; - const open = $$('.facet details[open], .pop[open]', page); + const open = opened(); if (open.length) { open.forEach(d => { d.open = false; }); hide(); $('summary', open[0]).focus(); return; } if (tipFor) { hide(); return; } if (KEYS.some(k => st[k])) { KEYS.forEach(k => { st[k] = ''; }); apply(); light(null); } @@ -154,3 +162,22 @@ apply(); })(); + +// Each checkbox independently excludes one flag kind. The GET form works without JavaScript. +(() => { + const box = document.getElementById('filtered-score'); if (!box) return; + const choices = [...box.querySelectorAll('input[data-kind]')], rates = [...box.querySelectorAll('.filtered-rate')]; + const said = document.getElementById('filtered-live'); + const show = () => { + const on = choices.filter(c => c.checked).map(c => c.dataset.kind); + let shown = null; + rates.forEach(p => { const hit = p.dataset.kinds === on.join(','); p.hidden = !hit; if (hit) { p.id = 'filtered-rate'; shown = p; } else p.removeAttribute('id'); }); + const url = new URL(location.href); + choices.forEach(c => { if (c.checked) url.searchParams.set(c.dataset.kind, '1'); else url.searchParams.delete(c.dataset.kind); }); + const table = document.querySelector('.tt[data-leave-out]'); if (table) table.dataset.leaveOut = on.join(' '); + url.hash = ''; history.replaceState(null, '', url); + if (said) said.textContent = shown ? shown.textContent.replace(/\s+/g, ' ').trim() : 'Filtered score off'; + }; + choices.forEach(c => c.addEventListener('change', show)); + box.addEventListener('submit', e => { e.preventDefault(); show(); }); +})(); diff --git a/app/static/runs/live-board.css b/app/static/runs/live-board.css index 0f870e07..f961e883 100644 --- a/app/static/runs/live-board.css +++ b/app/static/runs/live-board.css @@ -1,4 +1,4 @@ -/* The job page's two views, and the Live board. +/* The job page's views, and the Live board. Scoped to .lb; the phase and outcome hues are the app's own. */ /* ---- the two views ---- */ @@ -124,7 +124,7 @@ .lb-drawer header { display: flex; align-items: start; justify-content: space-between; gap: 10px; } .lb-drawer h3 { margin: 0; font: 500 13.5px/1.35 var(--mono); text-transform: none; letter-spacing: 0; color: var(--text); overflow-wrap: anywhere; } .lb-drawer h3 small { display: block; margin-top: 3px; font: 400 12px var(--sans); text-transform: none; letter-spacing: 0; color: var(--text-dim); } -.lb-x { width: 28px; height: 28px; flex: none; border: 1px solid var(--lb-hair); border-radius: 7px; background: var(--surface); cursor: pointer; font-size: 16px; line-height: 1; color: var(--text-dim); } +.lb-x { display: grid; place-items: center; padding: 0; width: 28px; height: 28px; flex: none; border: 1px solid var(--lb-hair); border-radius: 7px; background: var(--surface); cursor: pointer; font-size: 16px; line-height: 1; color: var(--text-dim); } .lb-river { display: grid; gap: 6px; } .lb-rl { display: flex; justify-content: space-between; font-size: 11.5px; color: var(--text-dim); } .lb-track { position: relative; height: 22px; border-radius: 4px; background: var(--lb-track); } @@ -183,3 +183,5 @@ .lb-open-row:hover { text-decoration: underline; } /* the board counts the trials itself: the run strip's own task bar would say it twice */ body:has(#live-board) #execution-units { display: none; } + +.view-tabs [role="tab"]:disabled { color: var(--text-faint); cursor: default; } diff --git a/app/static/runs/live-board.js b/app/static/runs/live-board.js index f6a997bf..5dda0e4e 100644 --- a/app/static/runs/live-board.js +++ b/app/static/runs/live-board.js @@ -256,7 +256,7 @@ : t.state === 'running' ? `${PHASE_LABEL[t.phase] || t.phase}, ${clock(t.elapsed_sec)} of ${t.timeout_sec ? clock(t.timeout_sec) : 'no limit'}` : stateOf(s) === 'finished' ? 'Not run' : `Queued${t.position != null ? ', position ' + (t.position + 1) : ''}`; const href = trialHref(t, opts); - return `

${esc(shortTask(t))}${esc(state)}${t.agent ? ' · ' + esc(t.agent) : ''}

+ return `

${esc(shortTask(t))}${esc(state)}${t.agent ? ' · ' + esc(t.agent) : ''}

${t0 == null ? 'not started' : hms(starts[keys[0]])}${tl.ended ? 'ended ' + hms(tl.ended) : limEnd ? 'limit ' + clock(limEnd - t0) + ' in' : ''}
${segs}
${phases}
${t.state !== 'running' && (t.activity || t.last_line) ? `

Last line, redacted${redacted(t.activity || t.last_line)}

` : ''} @@ -307,8 +307,20 @@ let snap = null, timer = null, misses = 0; // opened while the run was going: the Results rendered with the page are older than its end const startedLive = board.dataset.state !== 'finished'; + let waiting = board.dataset.state === 'unknown'; function paint() { - if (!snap) return; + if (!snap || stateOf(snap) === 'unknown') return; + if (waiting) { + waiting = false; + doc.getElementById('preparing')?.remove(); + const liveTab = doc.getElementById('tab-live'); + if (liveTab) liveTab.disabled = false; + const resultsTab = doc.getElementById('tab-results'); + if (resultsTab) resultsTab.disabled = false; + const dot = doc.getElementById('live-dot'); + if (dot) dot.classList.toggle('on', stateOf(snap) !== 'finished'); + doc.dispatchEvent(new Event('live-ready')); + } const out = render(snap, opts); board.dataset.state = out.state; $('[data-lb-state]').textContent = out.stateLabel; @@ -338,8 +350,18 @@ async function tick() { try { const r = await nulliusFetch(endpoint, {headers: {'Accept': 'application/json'}, cache: 'no-store'}); - if (!r.ok) throw new Error('HTTP ' + r.status); - misses = 0; snap = await r.json(); + if (!r.ok) { + if (waiting && doc.getElementById('execution')?.dataset.live === 'no') { clearInterval(timer); timer = null; } + throw new Error('HTTP ' + r.status); + } + const next = await r.json(); + if (waiting && (next.state === 'unknown' || !next.counts)) { + if (next.state === 'finished' || doc.getElementById('execution')?.dataset.live === 'no') { + clearInterval(timer); timer = null; + } + return; + } + misses = 0; snap = next; } catch (e) { misses += 1; } paint(); } @@ -360,7 +382,7 @@ paint(); if (!snap || stateOf(snap) !== 'finished') { timer = setInterval(tick, 1000); tick(); } } - // The two views of the job page: switched in place, kept in the address as ?view=. + // The views of the job page: switched in place, kept in the address as ?view=. function mountTabs(doc) { const tabs = Array.from(doc.querySelectorAll('[data-view-tab]')); if (!tabs.length) return; @@ -376,11 +398,15 @@ if (view === 'results' && badge && badge.dataset.stale) { location.assign(u); return; } history.replaceState(null, '', u); } - tabs.forEach((t, i) => { + doc.addEventListener('live-ready', () => { + const requested = new URL(location.href).searchParams.get('view'); + if (requested !== 'logs' && requested !== 'results') show('live'); + }); + tabs.forEach(t => { t.addEventListener('click', () => show(t.dataset.viewTab)); t.addEventListener('keydown', e => { const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0; - if (d) { e.preventDefault(); const n = tabs[(i + d + tabs.length) % tabs.length]; n.focus(); show(n.dataset.viewTab); } + if (d) { e.preventDefault(); const enabled = tabs.filter(t => !t.disabled); const i = enabled.indexOf(t); const n = enabled[(i + d + enabled.length) % enabled.length]; n.focus(); show(n.dataset.viewTab); } }); }); } diff --git a/app/static/runs/start.css b/app/static/runs/start.css index 5b215f86..8c44e8e7 100644 --- a/app/static/runs/start.css +++ b/app/static/runs/start.css @@ -5,7 +5,6 @@ .start-ways { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 18px; } .start-card { display: flex; flex-direction: column; gap: 14px; padding: clamp(24px, 2vw, 36px); border: 1px solid var(--border-soft); border-radius: 14px; background: var(--surface); color: var(--text); } .start-ic { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; background: var(--accent-soft); color: var(--accent-strong); } -.start-ic .ic { width: 20px; height: 20px; } .start-t { margin: 0; font-size: 19px; font-weight: 500; letter-spacing: -.01em; text-transform: none; color: var(--text); } .start-d { margin: 0; font-size: 14px; line-height: 1.6; color: var(--text-dim); } .start-go { margin-top: auto; font-size: 14px; color: var(--accent); white-space: nowrap; } @@ -24,7 +23,6 @@ .start-card { min-height: clamp(256px, 22vh, 320px); box-shadow: var(--shadow); } .start-ic { flex: none; width: 42px; height: 42px; border: 1px solid color-mix(in srgb, var(--accent) 15%, transparent); } -.start-ic .ic { width: 22px; height: 22px; } .start-action { display: inline-flex; align-items: center; gap: 16px; align-self: flex-start; margin-top: auto; padding: 10px 15px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface-2); color: var(--text); font-size: 13px; font-weight: 500; } .start-action:hover { text-decoration: none; border-color: var(--accent); } .start-primary { background: var(--accent); color: var(--btn-fg); border-color: transparent; } diff --git a/app/static/settings/judges.js b/app/static/settings/judges.js index a0c2eed5..64108a51 100644 --- a/app/static/settings/judges.js +++ b/app/static/settings/judges.js @@ -37,35 +37,8 @@ const modelField = card.querySelector('.st-field[id$="_MODEL"]'); modelField.hidden = !on; const model = modelField.querySelector('input.st-input'); - const list = model?.list; - if (list) { - list.replaceChildren(); - for (const value of (on?.dataset.models || '').split('|').filter(Boolean)) { - const option = document.createElement('option'); option.value = value; list.append(option); - } - } if (model) model.placeholder = on?.dataset.default || ''; } - // A provider with no list of its own here: its catalogue, asked once when the field is first used; a live list - // replaces the one drawn with the page. Typing a model still works. - const catalogues = new Map(); - async function offerCatalogue(card, model) { - const on = chosen(card); - if (!on || (on.dataset.models && !('live' in on.dataset)) || !model.list) return; - const provider = on.value.replace(/^local(?=$|:)/, 'custom'); // local:, a named endpoint, is the builder's custom: - const url = 'live' in on.dataset ? '/settings/decision/models' : '/new-run/models'; - if (!catalogues.has(url + provider)) { - catalogues.set(url + provider, nulliusFetch(url, {method: 'POST', headers: {'Content-Type': 'application/json', - 'X-CSRF-Token': document.querySelector('#settings-form [name=csrf]').value}, body: JSON.stringify({provider})}) - .then(r => { if (!r.ok) throw new Error("Model catalogue unavailable"); return r.json(); }).then(j => { if (j.error) throw new Error(j.error); return j.models || []; }).catch(() => { catalogues.delete(url + provider); return []; })); - } - const models = await catalogues.get(url + provider); - if (!models.length) return; - if (chosen(card) !== on) return; - model.list.replaceChildren(...models.map(m => { - const option = document.createElement('option'); option.value = m.id; if (m.name !== m.id) option.label = m.name; return option; - })); - } cards.forEach(card => { // Runs before autosave's listener on the form: a protocol picked here is named, so it is saved. card.addEventListener('change', event => { @@ -75,7 +48,6 @@ } if (event.target.matches('[data-picker], [data-protocol-picker]')) update(card); }); - card.addEventListener('focusin', event => { if (event.target.matches('input.st-input')) offerCatalogue(card, event.target); }); }); // Initialize after autosave records the server state, so a sole replacement // for an unavailable saved provider is persisted rather than merely displayed. diff --git a/app/static/settings/prices.js b/app/static/settings/prices.js index 16598fe6..93e383f2 100644 --- a/app/static/settings/prices.js +++ b/app/static/settings/prices.js @@ -41,6 +41,11 @@ return row; })); $('[data-own-none]').hidden = own.length > 0; + // a row of the user's that cannot price is kept in their file and said, never dropped + $('[data-own-problems]').replaceChildren(...(state.problems || []).map(line => { + const p = document.createElement('p'); p.className = 'st-note st-warn'; p.textContent = line; + return p; + })); }; const update = $('[data-prices-update]'); diff --git a/app/static/settings/settings.css b/app/static/settings/settings.css index 66c20c84..f1d5793b 100644 --- a/app/static/settings/settings.css +++ b/app/static/settings/settings.css @@ -28,7 +28,7 @@ .st-card { margin: 0; padding: 16px 20px 14px; border: 1px solid var(--border-soft); border-radius: 12px; background: var(--surface); display: flex; flex-direction: column; gap: 14px; min-width: 0; } .st-card legend { display: inline-flex; align-items: center; gap: 9px; padding: 0 6px; font-weight: 500; font-size: 15px; } .st-logo { width: var(--ic-lg); height: var(--ic-lg); flex: none; color: var(--text); } -.st-icon { width: 20px; height: 20px; margin: 2px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; color: var(--text-dim); } +.st-icon { margin: 4px; color: var(--text-dim); } /* a 16 px icon in a logo's 24 px slot */ .st-card-unset { border-style: dashed; background: color-mix(in srgb, var(--surface) 55%, var(--bg)); } /* 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; } @@ -56,7 +56,6 @@ .st-key-card { border: 1px solid var(--border-soft); border-radius: 12px; background: var(--surface); min-width: 0; overflow: hidden; } .st-key-summary { display: grid; grid-template-columns: 36px minmax(0, 1fr) auto auto; align-items: center; gap: 14px; padding: 18px 20px; } .st-key-icon { display: grid; place-items: center; width: 36px; height: 36px; border-radius: 10px; background: var(--surface-2); color: var(--text-dim); } -.st-key-icon svg { width: 21px; height: 21px; } .st-key-copy { min-width: 0; } .st-key-copy h3, .st-key-new h3 { margin: 0; font-size: 15px; font-weight: 500; letter-spacing: 0; text-transform: none; color: var(--text); overflow-wrap: anywhere; } .st-key-state { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--text-faint); white-space: nowrap; } @@ -162,7 +161,7 @@ .st-constraint:has(.st-slider:not([hidden])) { margin-bottom: 0; } .st-constraint > .st-slider { grid-column: 1 / -1; grid-row: 1; margin-bottom: 14px; } } -.st-clear { flex: none; width: 28px; height: 28px; border: 0; border-radius: 50%; background: none; color: inherit; font: inherit; line-height: 1; cursor: pointer; opacity: .55; } +.st-clear { flex: none; display: grid; place-items: center; padding: 0; width: 28px; height: 28px; border: 0; border-radius: 50%; background: none; color: inherit; font: inherit; line-height: 1; cursor: pointer; opacity: .55; } .st-clear:hover, .st-clear:focus-visible { opacity: 1; background: color-mix(in srgb, var(--bad) 20%, transparent); } .st-clear.off { visibility: hidden; } .st-slider { grid-column: 1; } @@ -229,7 +228,6 @@ .st-nav-label { margin: 20px 12px 6px; font-size: 12px; color: var(--text-faint); } .st-index a { justify-content: flex-start; gap: 10px; } .st-index a span { color: inherit; font-size: 15px; } -.st-index a .ic { flex: none; width: 17px; height: 17px; } .st-index [hidden] { display: none; } .st-search-empty { padding: 8px 12px; font-size: 13px; color: var(--text-dim); } .st-theme-options { display: flex; flex-wrap: wrap; gap: 8px; } @@ -271,7 +269,6 @@ .st-provider-add span { font-size: 18px; font-weight: 400; line-height: 1; } .st-provider-back { align-self: flex-start; } .st-provider-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; } -#providers [data-provider-test-all] .ic, #providers [data-provider-test] .ic { width: 15px; height: 15px; } .st-provider-test:empty { display: none; } /* a phone: the actions take their own row under the name */ @media (max-width: 560px) { #providers .st-provider-summary { flex-wrap: wrap; justify-content: flex-end; } #providers .st-provider-summary > div { flex-basis: calc(100% - 34px); } } @@ -318,7 +315,6 @@ .st-sandbox-rows > .st-row + .st-row { padding-top: 14px; border-top: 1px solid var(--border-soft); } .settings-page .st-sandbox-rows .st-input { height: 34px; min-height: 34px; padding-block: 0; } .settings-page #sandbox .st-row-value.st-value, .settings-page #prices .st-row-value.st-value, .settings-page #data-providers .st-row-value.st-value { flex-direction: row; justify-content: flex-start; align-items: center; } -#prices [data-prices-update] .ic { width: 15px; height: 15px; } #prices [data-prices-update].busy .ic { animation: st-prices-spin .9s linear infinite; } @keyframes st-prices-spin { to { transform: rotate(360deg); } } @media (prefers-reduced-motion: reduce) { #prices [data-prices-update].busy .ic { animation: none; } } diff --git a/app/static/style.css b/app/static/style.css index d3f123cf..7f6b8ae3 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -6,6 +6,7 @@ --topbar-height: 56px; --ic-sm: 16px; /* an interface icon: inline with text, in a button, a row */ --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); --head-gap: 1.5rem; /* under a page's head, on every page */ @@ -303,12 +304,13 @@ h3 .total { margin-left: .15rem; color: var(--text); font-weight: 600; text-tran .judgement-provenance { margin: 0 0 8px; } .judgement-hygiene { margin: 0 0 6px; } /* the outcome questions as cards */ -.jcards { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: .9rem; margin: 1rem 0 1.6rem; } +.jcards { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, max(230px, calc((100% - 2.7rem) / 4))), 1fr)); gap: .9rem; margin: 1rem 0 1.6rem; } .jcard { background: var(--surface); border: 1px solid var(--border-soft); border-radius: var(--radius); padding: 1.1rem 1.2rem; display: flex; flex-direction: column; gap: .45rem; } .jcard-title { color: var(--text-dim); font-size: .85rem; } -.jcard-value { display: flex; align-items: baseline; gap: .5rem; } +.jcard-value { display: flex; flex-wrap: wrap; align-items: baseline; gap: .5rem; } +.jcard-value .jpill { max-width: 100%; white-space: normal; overflow-wrap: anywhere; } .jcard-value .jnum { font-size: 2rem; font-weight: 500; letter-spacing: -0.04em; font-variant-numeric: tabular-nums; line-height: 1; } -.jcard-value .junit { color: var(--text-dim); font-size: .95rem; } +.jcard-value .junit { white-space: nowrap; color: var(--text-dim); font-size: .95rem; } .jcard-blurb { min-height: 2.4em; } .jcard-foot { display: flex; justify-content: space-between; border-top: 1px solid var(--border-soft); padding-top: .55rem; margin-top: auto; } /* the pill says how an answer reads */ @@ -338,7 +340,7 @@ tr.tone-good .jdot { background: #4cc26a; } tr.tone-warn .jdot { background: #d9 tr.tone-good .jbar .fill { background: #4cc26a; } tr.tone-warn .jbar .fill { background: #d9a933; } tr.tone-bad .jbar .fill { background: #ee6b7a; } .jbar .floor { position: absolute; top: 0; height: 100%; background: repeating-linear-gradient(135deg, rgba(212, 167, 44, 0.55) 0 2px, transparent 2px 5px); } .jmore { width: 2rem; text-align: right; } -.jdisclose { border: 0; background: none; color: var(--text-dim); font-size: 1.2rem; cursor: pointer; padding: 0 .3rem; } +.jdisclose { display: inline-grid; place-items: center; border: 0; background: none; color: var(--text-dim); font-size: 1.2rem; cursor: pointer; padding: 0 .3rem; } .jdisclose[aria-expanded="true"] { transform: rotate(90deg); } .flag { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 0.8em; font-weight: 500; border: 1px solid var(--border-soft); } .flag.raised { color: var(--bad); border-color: currentColor; } @@ -393,14 +395,12 @@ button.seg:hover { filter: brightness(1.25); } .seg-toggle > [aria-current="true"], .seg-toggle > [aria-pressed="true"] { background: var(--accent-soft); color: var(--accent); } /* a search box, its icon first (the Settings page's too) */ .st-search { display: flex; align-items: center; gap: 8px; margin: 0 0 12px; padding: 8px 10px; border: 1px solid transparent; border-radius: 8px; background: var(--surface-2); color: var(--text-dim); } -.st-search .ic { flex: none; width: 17px; height: 17px; } .st-search input { min-width: 0; width: 100%; padding: 0; border: 0; background: transparent; color: var(--text); font: 13px var(--sans); } .st-search input:focus-visible { outline: none; } .st-search:focus-within { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); } /* the toolkit's one clear control; the browser's own is hidden */ .st-search [data-search]::-webkit-search-cancel-button { -webkit-appearance: none; appearance: none; } .st-search-clear { flex: none; display: inline-flex; align-items: center; justify-content: center; width: 20px; height: 20px; margin: -2px -4px -2px 0; padding: 0; border: 0; border-radius: 5px; background: transparent; color: var(--text-faint); cursor: pointer; } -.st-search-clear .ic { width: 14px; height: 14px; } .st-search-clear:hover { color: var(--text); background: var(--surface); } .st-search-clear:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } .menu-wrap { position: relative; } @@ -536,6 +536,7 @@ button.seg:hover { filter: brightness(1.25); } .grid.compare tr.row-differs { background: color-mix(in srgb, var(--patch_failed_tests) 8%, transparent); } .grid.compare tr.row-differs td:first-child { box-shadow: inset 2px 0 0 var(--patch_failed_tests); } .disclose { + display: inline-grid; place-items: center; font: inherit; font-size: .8rem; cursor: pointer; width: 1.4rem; background: none; border: none; padding: 0; margin-right: .3rem; color: var(--text-faint); @@ -766,6 +767,11 @@ button.seg:hover { filter: brightness(1.25); } .wf-tick:first-child { transform: none; } .wf-tick:last-child { transform: translateX(-100%); } .wf-head .wf-dur { text-align: right; } +/* a phone: the name column gives way, and the axis keeps its first and last ticks */ +@media (max-width: 640px) { + .wf-head, .wf-row { grid-template-columns: minmax(0, 3fr) minmax(0, 2fr) 5.5rem; } + .wf-tick:not(:first-child):not(:last-child) { display: none; } +} .wf-row { height: 24px; position: relative; } .wf-row:hover { background: var(--surface-2); } @@ -1076,7 +1082,7 @@ tr.control-row td { color: var(--text-dim); } .attempt-tab:hover { color: var(--text); border-color: var(--text-faint); } .attempt-tab[aria-current] { color: var(--text); background: var(--accent-soft); border-color: var(--accent); font-weight: 600; } .attempt-tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } -.attempt-retried { width: 12px; height: 12px; margin-left: -.15rem; flex: none; fill: none; stroke: currentColor; stroke-width: 2.4; stroke-linecap: round; stroke-linejoin: round; } +.attempt-retried { margin-left: -.15rem; } /* an attempt's tries, when its runner kept the ones before its last: tabs of their own under the attempt's, underlined, the last the one that counts */ .try-tabs { display: flex; flex-wrap: wrap; gap: 0 1.2rem; width: fit-content; max-width: 100%; margin-top: .6rem; padding-right: .4rem; border-bottom: 1px solid var(--border); } @@ -1189,6 +1195,7 @@ pre.msg { color: var(--text); max-height: 220px; } .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; @@ -1288,11 +1295,11 @@ input[type=text].invalid:focus { box-shadow: inset 0 0 0 1px var(--bad); } .alert { position: relative; padding-right: 2.1rem; } .alert-x { position: absolute; top: .35rem; right: .4rem; + display: grid; place-items: center; padding: 0; width: 1.5rem; height: 1.5rem; line-height: 1; cursor: pointer; background: none; border: none; border-radius: 6px; color: inherit; opacity: .5; font: inherit; font-size: .9rem; } -.alert-x::before { content: "×"; } .alert-x:hover { opacity: 1; background: color-mix(in srgb, currentColor 12%, transparent); } .alert-x:focus-visible { outline: none; opacity: 1; box-shadow: 0 0 0 2px var(--accent-soft); } @@ -1490,7 +1497,10 @@ a.chip { text-decoration: none; } @media (prefers-reduced-motion: no-preference) { .shell { transition: grid-template-columns .16s ease; } } -.ic { width: 18px; height: 18px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; } +.ic { width: var(--ic-sm); height: var(--ic-sm); flex: none; fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; } +/* A symbol drawn per size shows its 16-grid drawing unless the icon is sized --ic-lg or --ic-xl: each such rule picks its drawing. */ +.ic-lg { width: var(--ic-lg); height: var(--ic-lg); --ic-d16: none; --ic-d24: inline; --ic-d32: none; } +.ic-xl { width: var(--ic-xl); height: var(--ic-xl); --ic-d16: none; --ic-d24: none; --ic-d32: inline; } .side-top { display: flex; align-items: center; justify-content: space-between; gap: .3rem; padding: .1rem .45rem .65rem; min-height: 42px; } .side .brand { font-size: 1.35rem; font-weight: 500; gap: .5rem; padding: 0; letter-spacing: -.05em; } @@ -1531,7 +1541,7 @@ a.chip { text-decoration: none; } .ws-text { min-width: 0; display: flex; flex-direction: column; gap: 1px; flex: 1; } .ws-caption { font-size: .69rem; color: var(--text-dim); line-height: 1.4; margin-bottom: 3px; } .ws-label { font-weight: 500; font-size: .88rem; line-height: 1.35; overflow-wrap: anywhere; } /* a name wraps, never cut */ -.ws-chev { color: var(--text-faint); width: 16px; height: 16px; } +.ws-chev { color: var(--text-faint); } .ws-pop { position: absolute; top: calc(100% + 8px); left: 0; width: 272px; max-width: calc(100vw - 24px); z-index: 30; background: var(--surface); border: 1px solid var(--border); border-radius: 12px; @@ -1598,8 +1608,8 @@ a.chip { text-decoration: none; } /* small screens: the rail is a drawer */ @media (max-width: 900px) { .shell, :root[data-rail="collapsed"] .shell { grid-template-columns: 1fr; } - .side { position: fixed; left: 0; top: 0; width: var(--rail-w); transform: translateX(-100%); transition: transform .16s ease; box-shadow: 0 0 40px rgba(0, 0, 0, .3); } - .side.drawer-open { transform: none; } + .side { position: fixed; left: 0; top: 0; width: var(--rail-w); transform: translateX(-100%); transition: transform .16s ease; } + .side.drawer-open { transform: none; box-shadow: 0 0 40px rgba(0, 0, 0, .3); } body.drawer-active { overflow: hidden; } :root[data-rail="collapsed"] .side-top { flex-direction: row; } :root[data-rail="collapsed"] .nav { overflow-y: auto; gap: .9rem; } @@ -1632,7 +1642,7 @@ a.chip { text-decoration: none; } } .tree-caret:hover { color: var(--text); background: var(--surface); } .tree-caret:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; box-shadow: none; } -.tree-caret .ic { width: 15px; height: 15px; transition: transform .12s; } +.tree-caret .ic { transition: transform .12s; } .nav-tree.folded .tree-caret .ic { transform: rotate(-90deg); } .tree-kids { display: flex; flex-direction: column; gap: 1px; margin: 2px 0 .2rem .9rem; padding-left: .55rem; border-left: 1px solid var(--border-soft); } .tree-item { @@ -1694,8 +1704,9 @@ pre.instruction { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 32 .execution-line { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; } .run-delete { margin-left: auto; color: var(--text-dim); } .execution-stages { container: xs / inline-size; margin: 14px 0 8px; } -.xs-list { --mark: 1.6rem; list-style: none; margin: 0; padding: 0; display: flex; align-items: flex-start; } -.xs { position: relative; flex: 1 1 0; min-width: 0; display: flex; flex-direction: column; align-items: flex-start; gap: .1rem; padding-right: .9rem; font-size: .82rem; line-height: 1.3; color: var(--text-dim); } +/* more stages than the width holds scroll inside the strip, never the page; the padding keeps the running mark's ring unclipped */ +.xs-list { --mark: 1.6rem; list-style: none; margin: -6px; padding: 6px; display: flex; align-items: flex-start; overflow-x: auto; } +.xs { position: relative; flex: 1 1 0; min-width: 7rem; display: flex; flex-direction: column; align-items: flex-start; gap: .1rem; padding-right: .9rem; font-size: .82rem; line-height: 1.3; color: var(--text-dim); } .xs:last-child { flex: 0 1 auto; padding-right: 0; } .xs::before { content: ""; position: absolute; top: calc(var(--mark) / 2 - 1px); left: calc(var(--mark) + .4rem); right: .4rem; height: 2px; border-radius: 1px; background: var(--border-soft); transition: background .3s; } .xs:last-child::before { display: none; } @@ -1709,9 +1720,10 @@ pre.instruction { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 32 .xs.running { color: var(--text); font-weight: 500; } .xs.waiting { color: var(--text-faint); } .xs-time { font-family: var(--mono); font-size: .75rem; font-weight: 400; color: var(--text-faint); } -.xs-detail { font-size: .75rem; font-weight: 400; color: var(--text-faint); overflow-wrap: anywhere; } +.xs-detail { font-size: .75rem; font-weight: 400; color: var(--text-faint); } +.xs-label, .xs-detail { overflow-wrap: anywhere; } @container xs (max-width: 44rem) { - .xs-list { flex-direction: column; } + .xs-list { flex-direction: column; margin: 0; padding: 0; overflow: visible; } .xs, .xs:last-child { flex: none; width: 100%; min-height: var(--mark); padding: .1rem 0 .95rem calc(var(--mark) + .7rem); } .xs:last-child { padding-bottom: 0; } .xs::before { top: calc(var(--mark) + .3rem); bottom: .3rem; left: calc(var(--mark) / 2 - 1px); right: auto; width: 2px; height: auto; } @@ -1739,7 +1751,7 @@ pre.instruction { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 32 .toast { position: relative; display: flex; align-items: center; gap: 12px; padding: 12px 10px 14px 16px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); color: var(--text); font-size: 13px; box-shadow: 0 12px 32px #0005; overflow: hidden; } .toast.bad { border-color: color-mix(in srgb, var(--bad) 55%, var(--border)); } .toast-text { flex: 1; min-width: 0; overflow-wrap: anywhere; } -.toast-close { flex: none; width: 28px; height: 28px; border: 0; border-radius: 6px; background: none; color: var(--text-dim); font-size: 18px; line-height: 1; cursor: pointer; } +.toast-close { flex: none; display: grid; place-items: center; width: 28px; height: 28px; padding: 0; border: 0; border-radius: 6px; background: none; color: var(--text-dim); font-size: 18px; line-height: 1; cursor: pointer; } .toast-close:hover { background: var(--surface-2); color: var(--text); } .toast-bar { position: absolute; left: 0; right: 0; bottom: 0; height: 3px; background: var(--accent); transform-origin: left; animation: toast-time 5s linear forwards; } .toast.bad .toast-bar { background: var(--bad); animation-duration: 10s; } @@ -1801,6 +1813,15 @@ select.ui-select-native { display: none !important; } .ui-select-option[aria-disabled=true] { opacity: .45; cursor: default; } @media (max-width: 560px) { .ui-select-trigger { font-size: 16px; } } +/* A model field's picker (model-picker.js). */ +.nb-model-control { display: flex; position: relative; min-width: 0; } +.nb-model-open { display: grid; place-items: center; padding: 0; position: absolute; right: 1px; top: 1px; bottom: 1px; width: 32px; border: 0; background: transparent; color: var(--text-dim); border-radius: 7px; } +.nb-model-control > input[role=combobox] { width: 100%; min-width: 0; padding-right: 36px; } +.nb-model-control:has(> input[hidden]) { display: none; } +.nb-model-option { display: flex; flex-direction: column; gap: 2px; } +.nb-model-option small, .nb-model-status { color: var(--text-dim); font-size: 12px; } +.nb-model-status { padding: 8px 9px; } + /* Shared slider:
……
. --fill (0 to 1) is the filled part, kept by controls.js. .marked draws a tick at --mark (0 to 1): past it the track is dotted, a step beyond the values (No limit); .ui-range-at-mark labels the tick. .unset: no value chosen. @@ -1842,7 +1863,7 @@ select.ui-select-native { display: none !important; } /* Bundled upstream agent marks, shared by catalogue pages and the builder. */ .agent-logo { display: block; width: 100%; height: 100%; object-fit: contain; flex: none; } -.nav-agent-logo { width: 18px; height: 18px; } +.nav-agent-logo { width: var(--ic-sm); height: var(--ic-sm); } /* A mark with its own version for dark backgrounds: the one that suits the theme. */ :root[data-theme="dark"] .on-light-bg, :root:not([data-theme="dark"]) .on-dark-bg { display: none; } diff --git a/app/static/tables.js b/app/static/tables.js index fa09f614..c6a8411b 100644 --- a/app/static/tables.js +++ b/app/static/tables.js @@ -2,10 +2,10 @@ into (the macros of templates/_tables.html; their styles in style.css, "the table toolkit"), and the card toolkit's (templates/_cards.html). */ window.NulliusTable = { - /* Whether `text` holds every word of `query`, in any order and case. */ + /* Whether `text` holds every word of `query`, in any order and case, - _ / : aside. */ matches(text, query) { - const t = (text ?? '').toLowerCase(); - return query.toLowerCase().split(/\s+/).every(w => t.includes(w)); + const plain = s => s.toLowerCase().replace(/[-_/:]/g, ''), t = plain(text ?? ''); + return query.split(/\s+/).every(w => t.includes(plain(w))); }, /* A header with data-type sorts its column on a click or Enter; num sorts @@ -134,13 +134,15 @@ window.NulliusTable = { const close = () => { menu.hidden = true; btn.setAttribute('aria-expanded', 'false'); }; // a modal over the page (the first-visit guide) takes the focus and the clicks without closing the menu under it const away = to => !menu.contains(to) && !btn.contains(to) && !to.closest?.('[aria-modal="true"]'); + let flipped = false; btn.addEventListener('click', () => { const open = menu.hidden; menu.hidden = !open; btn.setAttribute('aria-expanded', String(open)); - // one that opens leftwards past the page's edge (a narrow screen) opens rightwards instead - menu.style.left = menu.style.right = ''; - if (open && menu.getBoundingClientRect().left < 0) Object.assign(menu.style, {left: '0', right: 'auto'}); + // one that opens leftwards past the page's edge (a narrow screen) opens rightwards instead; + // 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; } if (open) menu.querySelector('input:not(:disabled), button, a[href]')?.focus(); }); document.addEventListener('click', e => { if (!menu.hidden && away(e.target)) close(); }); @@ -192,6 +194,11 @@ window.NulliusTable = { /* A table's controls row: narrow's search and Filter, and the Sort by menu, which sets the sort and follows a header click. Returns {passes, resort}, as narrow and sortable do. */ + /* Sort by's icon, when it has one, says the direction of the sort on, or none. */ + sortIcon(btn, on, dir) { + btn?.querySelector('use')?.setAttribute('href', on ? (dir > 0 ? '#i-sort-asc' : '#i-sort-desc') : '#i-sort'); + }, + toolbar(table, tools, changed) { const passes = this.narrow(tools, changed); const [sbtn, smenu] = [tools.querySelector('[data-tools-btn="sort"]'), tools.querySelector('[data-tools="sort"]')]; @@ -201,6 +208,7 @@ window.NulliusTable = { const {col, dir} = resort.state(), on = col === null ? '' : heads[col].dataset.col; smenu.querySelectorAll('[data-sort-col]').forEach(r => { r.checked = r.value === on; }); smenu.querySelectorAll('[data-sort-dir]').forEach(r => { r.checked = Boolean(on) && r.value === (dir > 0 ? 'asc' : 'desc'); r.disabled = !on; }); + this.sortIcon(sbtn, on, dir); }; const resort = this.sortable(table, () => { sync(); changed(); }); if (smenu) { @@ -279,6 +287,7 @@ window.NulliusTable = { const c = smenu.querySelector('[data-sort-col]:checked'), on = c.value, num = c.dataset.type === 'num'; const dir = e?.target.matches('[data-sort-dir]') ? (e.target.value === 'asc' ? 1 : -1) : (num ? -1 : 1); dirs.forEach(r => { r.checked = Boolean(on) && r.value === (dir > 0 ? 'asc' : 'desc'); r.disabled = !on; }); + this.sortIcon(sbtn, on, dir); const key = card => { const raw = card.getAttribute('data-s-' + on) ?? ''; return num ? parseFloat(raw) || 0 : raw.toLowerCase(); }; (on ? [...items].sort((a, b) => { const x = key(a), y = key(b); return (x < y ? -1 : x > y ? 1 : 0) * dir; }) : items).forEach(c => c.parentNode.appendChild(c)); }; diff --git a/app/static/traces/conversation.css b/app/static/traces/conversation.css index 69ae22b7..d7493bc6 100644 --- a/app/static/traces/conversation.css +++ b/app/static/traces/conversation.css @@ -45,18 +45,29 @@ @media(max-width:850px){.reader-selected{padding:18px}.reader-layout{grid-template-columns:minmax(175px,30%) minmax(0,1fr)}.reader-step-nav{align-items:flex-start;flex-direction:column;gap:12px}} @media(max-width:600px){.reader-layout{grid-template-columns:minmax(0,1fr);min-height:0}.reader-index{border-right:0;border-bottom:1px solid var(--border)}.reader-rows{max-height:230px;overflow:auto}.reader-row{padding:10px 12px}.reader-row-preview{-webkit-line-clamp:1}.reader-selected{padding:16px}.reader-content pre{max-height:360px;padding:12px}.reader-search{gap:6px}.reader-toolbar{gap:10px}.reader-jump{width:100%}.reader-jump input{flex:1;min-width:0}.reader-content-nav{gap:6px;font-size:10px}.trial-tabs{gap:22px}.reader-filters{width:100%;justify-content:space-between}.reader-filters button{padding:7px 8px}} -/* the trial's head: what ran, then how it went, one row that wraps */ +/* The trial's own metrics, in a row that wraps. */ .trial-head{display:flex;flex-wrap:wrap;gap:10px;margin:14px 0 6px;align-items:stretch} -.th-card{display:flex;align-items:center;gap:12px;border:1px solid var(--border);border-radius:var(--radius);background:var(--surface);padding:9px 14px;min-width:0} -.th-card .k,.th-strip .k{display:block;color:var(--text-dim);font-size:.75rem} -.th-card .v{display:block;font-weight:500} -.th-sep{width:1px;align-self:stretch;background:var(--border)} -.th-mark{width:32px;height:32px;border-radius:8px;background:var(--accent-soft);color:var(--accent);display:grid;place-items:center;font:500 15px/1 var(--mono);flex:none;padding:6px} -.th-mark:has(.agent-logo){padding:4px;background:color-mix(in srgb,var(--text) 8%,transparent);color:var(--text)} -.th-model{display:block;font-size:.8rem;color:var(--text-dim);overflow-wrap:anywhere} -/* The cells keep their own width: the strip sits beside the cards while all of them fit on one - line, moves under the cards when they do not, and wraps its cells when the page itself is narrower. - The 1px gaps over the border colour are the rules between cells, on every row. */ +.th-strip .k{display:block;color:var(--text-dim);font-size:.75rem} +/* The 1px gaps over the border colour separate the cells on every row. */ .th-strip{display:flex;flex-wrap:wrap;flex:1 0 auto;max-width:100%;gap:1px;background:var(--border);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden} .th-strip>div{flex:1 0 auto;padding:9px 14px;background:var(--surface);white-space:nowrap} .th-strip .n{display:block;font-size:1.1rem;font-weight:500;font-variant-numeric:tabular-nums} + +/* A shared model-usage card, with compact token and growth charts. */ +#task-usage .mix-bar{height:8px;width:100%} +.usage-section-title{font-size:11px;font-weight:500;letter-spacing:.08em;text-transform:uppercase;color:var(--text-dim);margin:16px 0 10px} +.usage-growth-title{margin-top:24px} + +.usage-stat{display:inline-flex;align-items:center;gap:6px;color:var(--text-dim);font-size:12px;cursor:default}.usage-stat b{color:var(--text);font-weight:500} + +.task-activity{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:16px;align-items:start;margin-bottom:24px} +.task-activity>.panel,.task-activity-left>.panel{min-width:0;margin:0;padding:16px} +.task-activity-left{min-width:0;display:grid;gap:16px;align-content:start} +.usage-tools-table{overflow-x:auto} +#task-tools .tool-names td:first-child{white-space:normal;overflow-wrap:anywhere} +@media(max-width:1000px){.task-activity{grid-template-columns:minmax(0,1fr)}} +/* Failure analysis: what the benchmark recorded */ +table.grid.trial-evidence{width:auto;max-width:100%} +#trial-evidence .test-list li{overflow-wrap:anywhere} +.trial-evidence td{vertical-align:top;white-space:normal;overflow-wrap:anywhere}.trial-evidence td.muted{overflow-wrap:normal} +.trial-evidence pre{margin:0} diff --git a/app/static/traces/failure.css b/app/static/traces/failure.css new file mode 100644 index 00000000..5b7baeea --- /dev/null +++ b/app/static/traces/failure.css @@ -0,0 +1,10 @@ +/* the User judge tab: the trial's label and its task's flag, each a short form */ +.failure-analysis{display:grid;gap:1.4rem;max-width:46rem;padding:.4rem 0} +.failure-analysis h3{font-size:.85rem;margin:0 0 .5rem;color:var(--text-dim);font-weight:500} +.failure-analysis p{margin:.2rem 0} +.fa-form{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin-top:.5rem} +.fa-form input[type=text]{flex:1 1 14rem;min-width:0} +.fa-choices{display:flex;flex-wrap:wrap;gap:.4rem;flex-basis:100%} +.fa-choices .chip::before{display:none} +.fa-choices .chip input{margin:0} +.chip-pending{font-size:.72rem;color:var(--warn,var(--text-dim));border:1px solid currentColor;border-radius:99px;padding:.05rem .45rem} diff --git a/app/static/traces/failure.js b/app/static/traces/failure.js new file mode 100644 index 00000000..893cefe5 --- /dev/null +++ b/app/static/traces/failure.js @@ -0,0 +1,39 @@ +// Save only the submitted section; drafts in the other section stay in the DOM. +(() => { + const panel = document.getElementById('failure-analysis'); + if (!panel) return; + panel.addEventListener('change', event => { + const input = event.target; + if (!input.matches('input[type=radio]')) return; + input.closest('.fa-choices').querySelectorAll('label').forEach(label => { + label.classList.toggle('active', label.querySelector('input').checked); + }); + }); + panel.addEventListener('submit', async event => { + const form = event.target; + if (!form.matches('.fa-form')) return; + event.preventDefault(); + if (form.getAttribute('aria-busy') === 'true') return; + const section = form.closest('.fa-part'); + const data = new FormData(form); + data.set('action', event.submitter ? event.submitter.value : form.querySelector('button[name=action]').value); + const controls = [...form.elements].filter(control => !control.disabled); + controls.forEach(control => { control.disabled = true; }); + form.setAttribute('aria-busy', 'true'); + try { + const response = await nulliusFetch(form.getAttribute('action'), {method: 'POST', body: data}); + if (!response.ok) throw new Error('Save failed'); + const doc = new DOMParser().parseFromString(await response.text(), 'text/html'); + const updated = doc.getElementById(section.id); + if (!updated) throw new Error('Missing saved section'); + section.replaceWith(updated); + nulliusNotify('Saved', {key: section.id}); + updated.querySelector('button[type=submit]')?.focus({preventScroll: true}); + } catch (_) { + nulliusNotify('Could not save. Your edits are still here; try again.', {error: true, key: section.id}); + } finally { + controls.forEach(control => { control.disabled = false; }); + form.removeAttribute('aria-busy'); + } + }); +})(); diff --git a/app/templates/_icons.svg b/app/templates/_icons.svg index adf75c87..29618160 100644 --- a/app/templates/_icons.svg +++ b/app/templates/_icons.svg @@ -1,77 +1,152 @@ {#- The interface's icons, included by base.html: one symbol each, referenced by . - Hand-drawn on a 24-grid, stroke only, so they take the item's colour and weight (`.ic` in style.css). #} + Stroked in the item's colour (`.ic` in style.css), most with a tone under the strokes: the same colour at + --ic-duo's opacity. A redrawn symbol holds three drawings, one per + displayed size, each on its own grid and never scaled: a 16-grid and a 24-grid with a 1 px stroke, a 32-grid + with a 2 px stroke, horizontal and vertical lines on whole pixels. Detail is only added as the size grows, never + removed: what a smaller drawing shows, each larger one shows too. The size picks one through + --ic-d16/--ic-d24/--ic-d32 (style.css). + An alias is a second id for a symbol: its only child a of it, never of another alias. #} diff --git a/app/templates/_tables.html b/app/templates/_tables.html index 1cfe06b7..384cb1da 100644 --- a/app/templates/_tables.html +++ b/app/templates/_tables.html @@ -167,9 +167,9 @@
- + - +
{% endmacro %} diff --git a/app/templates/agents/entry.html b/app/templates/agents/entry.html index 80cf73ac..cf845eb0 100644 --- a/app/templates/agents/entry.html +++ b/app/templates/agents/entry.html @@ -107,7 +107,7 @@

Runs

- +
{% if kind == 'agent' %}{% endif %} @@ -120,6 +120,8 @@

Runs

{% endblock %} {% block scripts %} + + {% if kind == 'agent' %} {% endif %} {#- Every notice a page is sent (Flask's flash) is a toast at the bottom left, as the builder's: it goes after a - few seconds - an error after twice as many - its bar counting them, paused while pointed at, or on its ×. #} + few seconds - an error after twice as many - its bar counting them, paused while pointed at, or on its close. #} {% set notices = get_flashed_messages(with_categories=true) %} {% if notices %}
- {% for category, message in notices %}
{{ message }}
{% endfor %} + {% for category, message in notices %}
{{ message }}
{% endfor %}
- + {% endblock %} diff --git a/app/templates/catalogue/benchmark.html b/app/templates/catalogue/benchmark.html index 4a57c4fc..be84e2e4 100644 --- a/app/templates/catalogue/benchmark.html +++ b/app/templates/catalogue/benchmark.html @@ -93,7 +93,7 @@ {% if s.judged %} {% if providers %}{% endif %} - + {% endif %}
{% if s.judged and not providers %}

The judge needs a model key first: set one in Settings.

@@ -293,4 +293,6 @@

As published

{% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %} + +{% endblock %} diff --git a/app/templates/compare/compare.html b/app/templates/compare/compare.html index c35d24be..b6d3336e 100644 --- a/app/templates/compare/compare.html +++ b/app/templates/compare/compare.html @@ -31,8 +31,8 @@
{{ 'Baseline' if loop.first }} - {% if c.left %}←{% endif %} - {% if c.right %}→{% endif %} + {% if c.left %}{% endif %} + {% if c.right %}{% endif %} {% if c.remove %}{% endif %}
@@ -71,6 +71,7 @@ {% if j is not none %} {% if c.shards %}{% for s in c.shards %}{{ shard_link(s, workspace=c.ref.workspace) }}{% endfor %}{% else %}{{ j.job_id }}{% endif %} {% if cohort == 'matched' %}{{ comparison.excluded_trials[c.i] }} of {{ selections[c.i].job.trials|length }} trials outside this cohort{% endif %} + {% if comparison.set_aside_trials and comparison.set_aside_trials[c.i] %}{{ comparison.set_aside_trials[c.i] }} trials of flagged tasks set aside{% endif %} {% endif %} @@ -110,6 +111,19 @@ {{ controls(view or 'side', [], sort=false, views=side_views, actions=side_actions) }} {% if jobs %} {% if cohort == 'matched' and not n_shared %}

No shared cohort is available. Choose runs with overlapping coverage or return to whole runs.

{% endif %} +{% set ff = flag_filter %}{% if ff and ((ff.flagged.values()|sum) or ff.unreadable) %} +
+ {% if ff.flagged.values()|sum %}Exclude:{% endif %} + {% for key, value in request.args.items(multi=True) if key not in ('flawed', 'ambiguous') %}{% endfor %} + {% for k in ('flawed', 'ambiguous') %}{% if ff.flagged[k] %} + + {% endif %}{% endfor %} + {% if ff.flagged.values()|sum %}{% endif %} + {% if ff.on %}Filtered: {{ ff.set_aside|length }} task{{ '' if ff.set_aside|length == 1 else 's' }} set aside in every column{% endif %} + {% if ff.unreadable %}Flags unreadable: {{ ff.unreadable|join(', ') }}{% endif %} + {% if ff.differ %}Flags differ on {{ ff.differ|length }} task{{ '' if ff.differ|length == 1 else 's' }}{% endif %} +
+{% endif %} {% if comparison.datasets_known and not comparison.datasets_match %}

The recorded datasets differ: pick runs of the baseline's dataset to compare the same tasks.

{% endif %} {% endif %} {% if view == 'chart' %} @@ -262,10 +276,10 @@
- {# One glyph, rotated by CSS on aria-expanded. #} + {# One icon, rotated by CSS on aria-expanded. #} + aria-label="Compare details for {{ taskrow.task }}" title="Compare details"> {{ taskrow.task }}
{% if not comparison.datasets_match or not comparison.datasets_known %}{{ 'Dataset not recorded' if taskrow.dataset.startswith('[unidentified:') else taskrow.dataset|dsname }}{% endif %} @@ -335,6 +349,12 @@ NulliusCompare.wire({values: {{ picks|tojson }}, lists: {{ lists|tojson }}, dataset: {{ baseline|tojson }}, runs: {{ url_for('compare_runs')|tojson }}}); + (() => { + const flags = document.getElementById('compare-flags'); if (!flags) return; + flags.addEventListener('change', () => flags.requestSubmit()); + addEventListener('pageshow', () => flags.reset()); // Back shows the boxes as this page was filtered + })(); + /* ---- drag a task table's column header to reorder ---- Order is carried by qualified ?pick= params, so a drop navigates to the reordered URL. Both tables and every detail row follow automatically, and diff --git a/app/templates/error.html b/app/templates/error.html new file mode 100644 index 00000000..13b39137 --- /dev/null +++ b/app/templates/error.html @@ -0,0 +1,8 @@ +{% extends "base.html" %} +{% from '_page.html' import page_head %} +{# A page that is not there, or a request that failed: its title and the way back, never the error's details. #} +{% block title %}{{ title }} — Nullius{% endblock %} +{% block body %} +{{ page_head(title) }} +

← Runs

+{% endblock %} diff --git a/app/templates/runs/_execution.html b/app/templates/runs/_execution.html index 558b8058..c4a424bd 100644 --- a/app/templates/runs/_execution.html +++ b/app/templates/runs/_execution.html @@ -27,16 +27,16 @@ {% set sp = ex.stages() %}
    {% for st in sp.stages %} -
  1. {{ st.label }} +
  2. {{ st.label }} {%- if st.state == 'cached' %}cached{% elif st.get('seconds') is not none and st.state in ('done', 'failed') %}{{ st.seconds|secs }}{% endif %} {%- if st.state in ('running', 'failed') and st.detail and st.detail != sp.detail %}{{ st.detail }}{% endif %}
  3. {% endfor %}
-
{% if sp.units %}{% set u = sp.units %}{{ u.done }} / {{ u.n if u.n is not none else '?' }} {{ u.noun }}{% for k in ('passed', 'failed', 'scored', 'errors') if u[k] %} · {{ u[k] }} {{ 'error' + ('' if u[k] == 1 else 's') if k == 'errors' else k }}{% endfor %}{% if u.running %} · {{ u.running }} running{% endif %}{% endif %}
+
{% if sp.units %}{% set u = sp.units %}{{ u.done }} / {{ u.n if u.n is not none else '?' }} {{ u.noun }}{% for k in ('passed', 'failed', 'scored', 'errors') if u[k] %} · {{ u[k] }} {{ 'error' + ('' if u[k] == 1 else 's') if k == 'errors' else k }}{% endfor %}{% if u.running %} · {{ u.running }} running{% endif %}{% endif %}
{% if sp.ended == 'refused' %}Refused before its first unit: {{ sp.detail }}{% endif %}
{# a part downloading: its file, how much of it, as a bar #} -
Launch log
+
Launch log
+{% endmacro %} diff --git a/app/templates/runs/index.html b/app/templates/runs/index.html index 83e63f2f..51a2c7b1 100644 --- a/app/templates/runs/index.html +++ b/app/templates/runs/index.html @@ -42,6 +42,7 @@ {{ r.state }} {% if j and j.scored_only %}
{{ '%.2f'|format(j.mean_score) }}
+ {% if j.mean_score_planned is not none %}{{ '%.2f'|format(j.mean_score_planned) }} planned{% endif %} {%- elif j and j.adjusted_solve_rate is not none %}
{{ j.adjusted_solve_rate|pct }}
{%- else %}
—
{% endif %} @@ -238,7 +239,7 @@

{{ g.dataset_title if L.dataset else (L.name or g.dataset_title) }}{% if g.n {% set score_title = "This benchmark gives a score and no pass or fail: the mean score" ~ (" over its " ~ j.n_scored_parts ~ " scored" if j.n_scored_parts else "") ~ ", no solve rate" %} — — - {{ '%.2f'|format(j.mean_score) }} + {{ '%.2f'|format(j.mean_score) }}{% if j.mean_score_planned is not none %} {{ '%.2f'|format(j.mean_score_planned) }} planned{% endif %} {% else %} {{ j.n_resolved }} {# A run nothing scored (a standalone trajectory, a span export) has no diff --git a/app/templates/runs/job.html b/app/templates/runs/job.html index 92ce1898..df3475e1 100644 --- a/app/templates/runs/job.html +++ b/app/templates/runs/job.html @@ -1,3 +1,4 @@ +{% from 'runs/_live_board.html' import live_panel %} {% from 'runs/_execution.html' import execution_strip %} {% from 'traces/_attempts.html' import attempt_count %} {% extends "base.html" %} @@ -8,19 +9,54 @@ {% endblock %} {% block body %}{% set oc = job.counts %} +{#- What tells this run from another, as its records say it (job.identity), as (name, value) rows of the card each + belongs to; a fact not recorded has no row. The caps stay under Run totals. -#} +{%- macro fact_value(v) -%}{% if v is sameas true %}yes{% elif v is sameas false %}no{% elif v is mapping %}{{ v|tojson }}{% elif v is string or v is number %}{{ v }}{% else %}{{ v|join(', ') }}{% endif %}{%- endmacro %} +{%- macro calls(n) %}{{ n }} call{{ '' if n == 1 else 's' }}{% endmacro %} +{%- set facts = job.identity %}{% set lim = facts.limits or {} %} +{%- set benchmark_rows, agent_rows, limit_rows = [], [], [] %} +{%- for k, v in (facts.benchmark_options or {}).items() if v is not none %}{% set _ = benchmark_rows.append((names.benchmark_options[k], fact_value(v))) %}{% endfor %} +{%- for k, v in (facts.agent_options or {}).items() if v is not none %}{% set _ = agent_rows.append((names.agent_options[k], fact_value(v))) %}{% endfor %} +{%- if facts.provider %}{% set _ = agent_rows.append(('Provider', facts.provider|provider)) %}{% endif %} +{%- if facts.served_by %}{% set requested %}{% for m, slugs in facts.served_by.items() %}{% if not loop.first %} · {% endif %}{% if facts.served_by|length > 1 %}{{ m }}: {% endif %}{{ slugs|join(', ') }}{% endfor %}{% endset %}{% set _ = agent_rows.append(('Requested', requested)) %}{% endif %} +{%- if facts.served and (facts.served.calls or facts.served.unnamed) %}{% set answered %}{% for name, n in facts.served.calls.items() %}{% if not loop.first %}, {% endif %}{{ name }} · {{ calls(n) }}{% endfor %}{% if facts.served.unnamed %}{% if facts.served.calls %}, {% endif %}unnamed · {{ calls(facts.served.unnamed) }}{% endif %}{% endset %}{% set _ = agent_rows.append(('Answered by', answered)) %}{% endif %} +{%- for key, name in [('concurrency', 'Concurrent'), ('repeat', 'Attempts'), ('retries', 'Retries'), ('max_turns', 'Turns'), ('max_calls', 'Model calls')] if key in lim %}{% set _ = limit_rows.append((name, lim[key])) %}{% endfor %} +{%- for key, name in [('setup', 'Setup limit'), ('image', 'Image limit'), ('agent', 'Agent limit'), ('verify', 'Verifier limit'), ('score', 'Score limit')] if key in (lim.timeouts or {}) %}{% set _ = limit_rows.append((name, '%g min'|format(lim.timeouts[key] / 60))) %}{% endfor %} +{#- A card with rows has a chevron and opens them beneath it, by click or keyboard; `name` keeps one open at a time, + and `pop` keeps the sliding disclosures off a panel laid over the page. A card with none is as it was. -#} +{%- macro identity_card(rows) %}{% if rows %}
+ {{ caller() }} +
{% for k, v in rows %}
{{ k }}
{{ v }}
{% endfor %}
+
{% else %}
{{ caller() }}
{% endif %}{% endmacro %} + {% set meta %} -
- {% if job.agent_label %}{{ job.agent_label }}{% if job.agent_version %} v{{ job.agent_version }}{% endif %}{% endif %} - {{ job.model_name }} - {{ job.dataset|dsname }} +
+ {% set dataset = nav_catalog.dataset(job.dataset) if nav_catalog else none %} + {% set sources = job.trials|map(attribute='source')|select|unique|list %} + {% set benchmark = names.benchmark or (dataset.benchmark if dataset else (sources[0] if sources|length == 1 else none)) %} +
+ {% if not job.runner %}{% endif %} +
Runner{% if job.runner %}{{ job.runner }}{% if job.runner_commit %} {{ job.runner_commit }}{% endif %}{% else %}harbor{% if job.harbor_label %} {{ job.harbor_label }}{% endif %}{% endif %}
+
+ {% if job.dataset %}{% call identity_card(benchmark_rows) %} + {% if benchmark %}
Benchmark{{ benchmark }}
{% endif %} +
Dataset{{ job.dataset|dsname }}
+ {% endcall %}{% endif %} + {% if job.agent_label or job.model_name %} + {% call identity_card(agent_rows) %} + {% if job.agent_label %}{% endif %} +
{% if job.agent_label %}{{ job.agent_label }}{% if job.agent_version %} v{{ job.agent_version }}{% endif %}{% endif %} + {% if job.model_name %}{{ job.model_name }}{% endif %}
+ {% endcall %} + {% endif %} {% if control %}control {{ control.label }}{% endif %} - {% if job.runner %}{{ job.runner }}{% if job.runner_commit %} {{ job.runner_commit }}{% endif %} - {% else %}harbor {% if job.harbor_label %}{{ job.harbor_label }}{% else %}unknown{% endif %}{% endif %} - {{ job.trials|length }}{% if job.n_planned and job.n_planned != job.trials|length %} of {{ job.n_planned }} planned{% endif %} trials - {% if job.n_retries %}{{ job.n_retries }} retried{% endif %} - {% if job.duration_min %}{{ job.duration_min|runtime }}{% endif %} + {% call identity_card(limit_rows) %} +
Trials{{ job.trials|length }}{% if job.n_planned and job.n_planned != job.trials|length %} of {{ job.n_planned }} planned{% endif %}
+ {% if job.duration_min is not none %}
Duration{{ job.duration_min|runtime }}
{% endif %} + {% if job.n_retries %}
Retried{{ job.n_retries }}
{% endif %} + {% endcall %}
{% endset %} {% set actions %} {% if execution and execution.plan.recipe %}Copy command{% endif %}{% endset %} {{ page_head(job.job_id, sub=meta, actions=actions) }} -{% if execution %}{{ execution_strip(execution, csrf, own=own if execution.plan.steps()|length > 1 else none, deletable=deletable) }}{% endif %} +{% set board_ready = live_board and live_board.initial and live_board.initial.state != 'unknown' %} {% if job.is_preparing and not live_board and not ended %} {# Launched, not started: Harbor has written the configuration and nothing else. There is no result record and no feed to fold yet, so this page - waits for the feed and reloads itself when it appears. #} + waits for the feed and opens Live when it appears. #}
- Preparing — this run was launched and {{ job.runner or 'Harbor' }} has written its configuration; no trial has started yet. - The live board appears here as soon as the first event lands. This page refreshes itself. + Preparing — this run was launched and {% if job.runner %}{{ job.runner }}{% if job.runner_commit %} {{ job.runner_commit }}{% endif %}{% else %}harbor{% if job.harbor_label %} {{ job.harbor_label }}{% endif %}{% endif %} has written its configuration; no trial has started yet. + The live board appears here as soon as the first event lands.
{% elif (job.is_running or job.is_preparing) and ended %} {# Harbor's record says trials are running; the runner that started it says @@ -68,39 +104,20 @@
The live feed could not be read — {{ live_board.error }}. The sections below come from the trial results and are unaffected.
{% endif %} {% if view %} -{# Two views of one page. Live: the job's events.jsonl folded every second while it runs, and kept once it ended as the - record of how it ran. Results: the page rendered from the job's files when this page loaded. ?view= picks; without - it, Live while the feed says the job is going. At job.end Live stops asking and says Results is ready; no reload. #}
- - + + + {% if execution %}{% endif %}
+{% if execution %} +
+{{ execution_strip(execution, csrf, own=own if execution.plan.steps()|length > 1 else none, deletable=deletable) }} +
+{% endif %}
-
-
- {{ live_board.initial.state|capitalize }} - - -
-
-
- -
    - -
    -
    -
    -
    All trials
    -
    -
    - -
    - -
    - +{% if board_ready or execution or job.is_preparing %} +{{ live_panel(job.job_id, live_board, '' if job.runner and not job.standard and not job.trials else url_for('job', job_id=job.job_id), job.runner_items[0] if job.runner_items else '') }} +{% endif %}
    {% if job.is_running and not ended %} @@ -110,18 +127,6 @@
    {% endif %} {% endif %} -{% if job.is_preparing and not live_board and not ended %} - -{% endif %} - {#- Board counts are whole-run and never change under a filter; the trial rows are rendered here, and job.js only filters, sorts and links them. Every lane and tally count is nullius.judge.lanes, which is reconcile's. -#} @@ -174,6 +179,7 @@
    raw rate
    —
    + {% if job.mean_score_planned is not none %}
    planned
    {{ '%.2f'|format(job.mean_score_planned) }}
    {% endif %}
    infra
    {{ job.n_infra }}
    @@ -202,12 +208,27 @@ {% else %}
    —
    {% endif %} + {% if filtered %}{% set fv = filtered.view %} +
    + {% if fv.flagged.flawed or fv.flagged.ambiguous %}Exclude:{% endif %} + {% for key, value in request.args.items() if key not in ('flawed', 'ambiguous') %}{% endfor %} + {% for k in ('flawed', 'ambiguous') %}{% if fv.flagged[k] %} + + {% endif %}{% endfor %} + {% if fv.other_version %}{{ fv.other_version }} on another version{% endif %} + + {#- every combination of the switches, the one in the URL shown: runs/board.js switches between them in place #} + {% for v in filtered.views %} +

    Filtered score {{ v.filtered_score|pct }} {{ v.solved }}/{{ v.ran }}

    + {% endfor %} + {% if fv.flagged.flawed or fv.flagged.ambiguous %}{% endif %} +
    + {% endif %}
    - {% if job.has_verdict and job.raw_solve_rate == job.adjusted_solve_rate %}

    raw = adjusted

    {% endif %}
    {% if not job.has_verdict or job.raw_solve_rate != job.adjusted_solve_rate %}
    raw rate
    {{ job.raw_solve_rate|pct }}
    {% endif %} -
    infra
    {{ job.n_infra }} -
    broke tests
    {{ job.n_regressions }} + {% if job.n_infra %}
    infra
    {{ job.n_infra }}
    {% endif %} + {% if job.n_regressions %}
    broke tests
    {{ job.n_regressions }}
    {% endif %}
    {% if pass_k %} {%- set ks = range(1, pass_k.attempts + 1)|select('le', 3)|list + ([pass_k.attempts] if pass_k.attempts > 3 else []) %} @@ -329,6 +350,7 @@ {% if job.budget.over_unit %}
    {{ job.budget.over_unit|length }} reached it
    {% for u in job.budget.over_unit %}{{ u }}{% endfor %}
    {% endif %}{% endif %} {% if job.mean_score is not none %}
    Mean score{{ '%.2f'|format(job.mean_score) }}
    {% endif %} + {% if job.mean_score_planned is not none %}
    Mean over planned{{ '%.2f'|format(job.mean_score_planned) }}
    {% endif %} {% for g in job.score_by_group %}
    {{ job.parts_by|capitalize }} {{ g.group }}{{ '%.2f'|format(g.mean) }} {{ g.n }}
    {% endfor %} {% if job.duration_min %}
    Duration{{ job.duration_min|runtime }}
    {% endif %}
    @@ -342,35 +364,36 @@

    Trials

    OutcomeAll▾
    + {% if judgement and judgement.causes %}
    Judge causeAll▾
    {% for cause, n in judgement.causes %}{{ cause }}{{ n }}{% endfor %} -
    + {% endif %} {% if judgement and judgement.flags %}
    FlagAll▾
    {% for f, n in judgement.flags %}{{ f }}{{ n }}{% endfor %} -
    + {% endif %}

    + {% set show_fa = marks.flags or marks.labels %} {% set show_cause = show_judge %} {% set show_flags = show_judge and judgement.judged %} {% set n_judge = (1 if show_cause else 0) + (1 if show_flags else 0) + (1 if show_ins else 0) %}
    - +
    - {% if job.retries %}{% endif %}{% if show_cause %}{% endif %}{% if show_flags %}{% endif %}{% if show_ins %}{% endif %} + {% if show_fa %}{% endif %}{% if job.retries %}{% endif %}{% if show_cause %}{% endif %}{% if show_flags %}{% endif %}{% if show_ins %}{% endif %} {% if vocab.gained %}{% endif %}{% if vocab.held %}{% endif %} - + {% if n_judge %}{% endif %} {% if vocab.gained or vocab.held %}{% endif %} @@ -380,6 +403,7 @@

    Trials

    + {% if show_fa %}{% endif %} {% if job.retries %}{% endif %} {% if show_cause %}{% endif %} {% if show_flags %}{% endif %} @@ -394,6 +418,8 @@

    Trials

    Open +{% macro task_flag(t) %}{%- set f = marks.flags.get(t.task_base) %}{% if f %}{{ f.kind }}{% if f.other %} · other version{% elif f.pending %} · pending{% endif %}{% endif %}{% endmacro %} +{% macro trial_label(t) %}{%- set l = marks.labels.get(t.trial_name) %}{% if l %}{{ l.label }}{% endif %}{% endmacro %} {% macro instruction(t) %}{%- set q = task_quality_of(job, t) %}{% if q %}{{ '%.1f'|format(q.score) }}/{{ q.top }}{% else %}—{% endif %}{% endmacro %} {% for t, group in trial_rows %} @@ -401,10 +427,11 @@

    Trials

    + + {% if show_fa %}{% endif %} {% if job.retries %}{% endif %} {% if show_cause %}{% endif %} {% if show_flags %}{% endif %} @@ -425,7 +452,7 @@

    Trials

    {%- if group %} @@ -438,6 +465,7 @@

    Trials

    {{ t.exception_type }}{{ t.exception_message }} {%- else %}{{ t.exception_type }}{% endif %}{% endif %} + {% if show_fa %}{% endif %} {% if job.retries %}{% endif %} {% if show_cause %} @@ -347,7 +347,7 @@

    Judges

    {%- set tip = ([c.tip] if c.tip else []) + (['This machine has ' ~ m.capacity[c.key] ~ (' ' ~ c.unit if c.unit) ~ '.'] if m.capacity.get(c.key) else []) %} {%- if tip %} title="{{ tip | join(' ') }}" data-tip="{{ c.tip }}"{% endif %}{% if off %} disabled{% endif %}> {% if c.unit %}
    {% for u in ('MB', 'GB') %}{% endfor %}
    {% endif %} - {% if writable %}{% endif %} + {% if writable %}{% endif %} {% if m.warnings.get(c.key) %}

    {{ m.warnings[c.key] }}

    {% endif %} @@ -418,6 +418,7 @@

    Judges

    Your prices
    +
    {% if writable %}
    @@ -472,6 +473,8 @@

    General

    + + diff --git a/app/templates/traces/_attempts.html b/app/templates/traces/_attempts.html index cd804eae..5f57cf5b 100644 --- a/app/templates/traces/_attempts.html +++ b/app/templates/traces/_attempts.html @@ -10,7 +10,7 @@ {{ ('Attempt ' if attempts.n <= 4 else '') ~ loop.index }} - {%- if a.n_retries %}{% endif %} + {%- if a.n_retries %}{% endif %} {%- endfor %} All attempts diff --git a/app/templates/traces/_conversation.html b/app/templates/traces/_conversation.html index c2c902c6..cb3863a4 100644 --- a/app/templates/traces/_conversation.html +++ b/app/templates/traces/_conversation.html @@ -28,7 +28,7 @@

    Select a step to inspect its recorded evidence.

    diff --git a/app/templates/traces/_failure.html b/app/templates/traces/_failure.html new file mode 100644 index 00000000..de210fe3 --- /dev/null +++ b/app/templates/traces/_failure.html @@ -0,0 +1,50 @@ +{#- The User judge tab: the trial's label (failed trials only) and its task's flag. A person writes both. -#} +{% set fp = failure %}{% set act = url_for('failure_route', job_id=job.job_id, trial_name=trial.trial_name) %} +
    + {% if fp.error %}

    {{ fp.error }}

    {% endif %} + {% if fp.failed %} +
    +

    {% if fp.attempt %}Why attempt {{ fp.attempt[0] }} failed{% else %}Why it failed{% endif %}

    + {% if fp.can_write %} + +
    + {% for key, name in fp.labels.items() %} + + {% endfor %} +
    + + + {% if fp.label %}{% endif %} + + {% elif fp.label %} +

    {{ fp.labels[fp.label.label] }}{% if fp.label.note %} · {{ fp.label.note }}{% endif %}

    + {% endif %} + {% if fp.label %}

    {{ fp.labels[fp.label.label] }} · {{ fp.label.by }} · {{ fp.label.at[:10] }}

    {% endif %} + {% if fp.model_labels %}

    {% for m in fp.model_labels %}{{ ' · ' if not loop.first }}{{ m.name }}: {{ fp.labels.get(m.label, m.label|capitalize) }}{% if m.label_p is not none %} {{ '%.0f'|format(m.label_p * 100) }}%{% endif %}{% endfor %}

    + {% elif fp.suggests %}

    Judge suggests {% for k in fp.suggests %}{{ ' or ' if not loop.first }}{{ fp.labels[k] }}{% endfor %}

    {% endif %} +
    + {% endif %} +
    +

    {% if fp.attempt %}Task flag · all {{ fp.attempt[1] }} attempts{% else %}Task flag{% endif %}

    +

    One flag per task in this run{% if fp.attempt %}: it shows on every attempt{% endif %}.

    + {% set fl = fp.flag %} + {% if fp.can_write %} +
    +
    + {% for k in fp.kinds %}{% endfor %} +
    + + {% for c in fp.categories %} + + + {% if fl and fl.status == 'pending' %}{% endif %} + {% if fl %}{% endif %} + + {% elif fl %} +

    {{ fl.category|replace('_', ' ') }}

    + {% if fl.evidence %}

    {{ fl.evidence }}

    {% endif %} + {% else %}

    Not flagged

    {% endif %} + {% if fl %}

    {{ fl.kind|capitalize }} · {{ fl.by }} · {{ fl.at[:10] }}{% if fl.status == 'pending' %} pending{% endif %}{% if fl.accepted_by and fl.accepted_by != fl.by %} · accepted by {{ fl.accepted_by }}{% endif %}

    {% endif %} + {% if fp.model_flags %}

    {% if fp.attempt %}On this attempt: {% endif %}{% for m in fp.model_flags %}{{ ' · ' if not loop.first }}{{ m.name }}: {{ fp.flag_names.get(m.flag, m.flag) }}{% if m.flag_p is not none %} {{ '%.0f'|format(m.flag_p * 100) }}%{% endif %}{% endfor %}

    {% endif %} +
    +
    diff --git a/app/templates/traces/_head.html b/app/templates/traces/_head.html deleted file mode 100644 index e28ed44f..00000000 --- a/app/templates/traces/_head.html +++ /dev/null @@ -1,30 +0,0 @@ -{% from 'runs/_runtime.html' import what_ran %} -{# What ran, said the same on a trial's page and on its task's All attempts: where the task is from - and what ran it, then the agent, its mark (`mark`: base.html's agent_mark) and the model that - answered. An imported trial says its importer. - A block with nothing to say is not drawn. #} -{% macro ran_cards(job, trial, imported_from, mark) -%} - {# The trial records a bare model name ("gpt-5.6-luna"); the job keeps the - provider-qualified one ("openai/gpt-5.6-luna"). Prefer the fuller id. #} - {% set model = job.model_name if job.model_name and job.model_name.endswith(trial.model_name or '~') - else (trial.model_name or job.model_name) %} - {% set agent = trial.agent_info_name or job.agent_label %} - {% if imported_from %} -
    Imported from{{ imported_from }}
    - {% else %} -
    - {% if trial.source %}
    Benchmark{{ trial.source|dsname }}
    - {% endif %} -
    Runner{% if job.runner %}{{ what_ran(job) }}{% else %}Harbor{% endif %}
    -
    - {% endif %} - {% if agent or model %} -
    - {% if agent %}{% endif %} -
    - {% if agent %}{{ agent }}{% if trial.agent_version %} {{ trial.agent_version }}{% endif %}{% endif %} - {% if model %}{{ model }}{% endif %} -
    -
    - {% endif %} -{%- endmacro %} diff --git a/app/templates/traces/_judgement.html b/app/templates/traces/_judgement.html index fbebe32d..9a895a93 100644 --- a/app/templates/traces/_judgement.html +++ b/app/templates/traces/_judgement.html @@ -53,7 +53,7 @@

    {{ r.label }}{% if r.warnings %} ⚠{% endif %}

    - + diff --git a/app/templates/traces/_usage.html b/app/templates/traces/_usage.html new file mode 100644 index 00000000..4dfb5419 --- /dev/null +++ b/app/templates/traces/_usage.html @@ -0,0 +1,65 @@ +{# One summary shape for every task. Trajectory accounting preserves cache conventions; + recorded trial totals remain available when no per-call trajectory was saved. #} +{% macro usage_panel(trial, trajectory) %} +{% set traj = trajectory if trajectory and not trajectory.error else none %} +{% set series = traj.token_series if traj else [] %} +{% set cache = traj.cache if traj else none %} +{% set sent = cache.total if cache else trial.n_input_tokens or 0 %} +{% set cached = cache.reads if cache else [trial.n_cache_tokens or 0, sent]|min %} +{% set fresh = cache.new if cache else [sent - cached, 0]|max %} +{% set output = (series|sum(attribute='completion')) if series else ((traj.final_metrics.get('total_completion_tokens') if traj else none) or trial.n_output_tokens or 0) %} +{% set reasoning = traj.total_reasoning_tokens if traj else none %} +
    +

    Model usage

    +

    Tokens

    + {% if sent or output or series or reasoning is not none %} + {% if sent or output %}{% endif %} +
    + {% if sent or output or series %} + input {{ fresh|tokens('control') }} + cache {{ cached|tokens('control') }} + output {{ output|tokens('control') }} + {% if sent %}cache hit {{ (cached / sent)|hitrate }}{% endif %} + {% endif %} + {% if reasoning is not none %}reasoning {{ reasoning|tokens('control') }}{% endif %} +
    + {% else %}

    Token usage not recorded.

    {% endif %} + {% if series|length > 1 %} +

    Prompt growth

    + {% set max_sent = traj.token_series|map(attribute='sent')|max %} +
    + {% for p in traj.token_series %} + {% set h = (56 * p.sent / max_sent)|round(1) if max_sent else 0 %} + {% set ch = (56 * p.cached / max_sent)|round(1) if max_sent else 0 %} + + + {% if ch >= 1 %}{% endif %} + + {% endfor %} +
    +
    + input + cache + {% if traj.cache and traj.cache.hit is not none %} + + cache hit {{ traj.cache.hit|hitrate }} + {% if traj.cache.reported_diverges %} + + reported {{ traj.cache.reported_hit|hitrate }} + {% endif %} + {% endif %} + {% if traj.total_reasoning_tokens is not none %} + reasoning {{ traj.total_reasoning_tokens|tokens('control') }} + {% endif %} +
    +

    One column per LLM step, height ∝ input tokens; the gray band is what came from cache. + {%- if traj.cache and traj.cache.convention == 'anthropic' %} Anthropic-style usage: cache writes are added back onto the step that paid for them.{%- endif %}

    + {% endif %} + +
    +{% endmacro %} diff --git a/app/templates/traces/attempts.html b/app/templates/traces/attempts.html index caadbefc..943dfdb1 100644 --- a/app/templates/traces/attempts.html +++ b/app/templates/traces/attempts.html @@ -1,16 +1,14 @@ {% extends "base.html" %} {% from '_page.html' import page_head %} {% from 'traces/_attempts.html' import attempt_tabs, attempt_count %} -{% from 'traces/_head.html' import ran_cards %} {% block title %}{{ trial.task_base }}, all attempts — Nullius{% endblock %} {% block crumb %}/ {{ job.job_id }} / {{ trial.task_base }}{% endblock %} {% block body %} {% set workspace = request.args.get('workspace') %} -{# the head of an attempt's page (traces/trial.html): the name, what ran, then the tabs, so a tab +{# the head of an attempt's page (traces/trial.html): the name and the tabs, so a tab changes what is under it and nothing above #} {{ page_head(trial.task_base, mono=true) }} -
    {{ ran_cards(job, trial, imported_from, agent_mark) }}
    {{ attempt_count(attempts) }} {{ attempt_tabs(job, attempts, none, workspace) }} diff --git a/app/templates/traces/trial.html b/app/templates/traces/trial.html index 892653b0..1158dab0 100644 --- a/app/templates/traces/trial.html +++ b/app/templates/traces/trial.html @@ -23,10 +23,10 @@ {% from 'traces/_judgement.html' import judgement_panel %} {% from 'traces/_attempts.html' import attempt_tabs, attempt_count, try_tabs %} -{% from 'traces/_head.html' import ran_cards %} {% from '_page.html' import page_head %} {% block body %} + {% set sub %} @@ -38,7 +38,7 @@ {{ page_head(trial.task_base, sub=sub, mono=true) }} {# an earlier try of an attempt: evidence only, never judged #} {% set replaced = trial.trial_name != attempt.trial_name %} -{# What ran (traces/_head.html, the same on All attempts), then how it went: the dataset's own +{# How this trial went: the dataset's own checks, the reward or the score, the agent's time and its steps. A value the trial does not have has no cell, and a block with no cell is not drawn. #} {% set vocab = trial.vocab %} @@ -52,7 +52,6 @@ {%- if traj and not traj.error %}
    Steps{{ traj.n_steps }}
    {% endif -%} {% endset %} {% if attempts or tries %} -
    {{ ran_cards(job, trial, imported_from, agent_mark) }}
    {% if attempts %}
    {{ attempt_count(attempts) }} @@ -61,39 +60,17 @@ {% endif %} {% if tries %}{{ try_tabs(job, tries, trial, request.args.get('workspace')) }}{% endif %} {% if cells|trim %}
    {{ cells }}
    {% endif %} -{% else %} -
    - {{ ran_cards(job, trial, imported_from, agent_mark) }} - {% if cells|trim %}
    {{ cells }}
    {% endif %} -
    +{% elif cells|trim %} +
    {{ cells }}
    {% endif %} +{% set fell_short = evidence or detail or trial.is_regression or trial.f2p_failures %}
    -{% if trial.is_regression %} -
    -

    ⚠ This patch broke {{ trial.p2p_fail }} previously-passing test{{ '' if trial.p2p_fail == 1 else 's' }}

    -

    These passed before the patch was applied and fail after it — a - regression, not just a missed fix.

    -
      - {% for name in trial.p2p_failures %}
    • {{ name }}
    • {% endfor %} -
    -
    -{% endif %} - -{% if trial.f2p_failures %} -
    -

    Tests that had to pass, still failing

    -
      - {% for name in trial.f2p_failures %}
    • {{ name }}
    • {% endfor %} -
    -
    -{% endif %} - {% if trial.exception_type %}

    {{ trial.exception_type }}

    @@ -104,8 +81,9 @@

    {{ trial.exception_type }}

    {# The phase bar reads only trial.*, so it renders whether or not a trajectory was recorded: a trial that failed before writing one still shows its timing. #} {% set total = trial.dur_phases + trial.dur_other %} +
    +
    {% if total %} -

    Where the time went{% if trial.dur_total is not none %} {{ trial.dur_total|secs }}{% endif %}

    {# The phases the trial recorded, Harbor's four names for them. On a runner's trial Env is the @@ -129,70 +107,10 @@

    Where the time went{% if trial.dur_total is not none %} {% endfor %}

    -
    {% endif %} - -{% if traj and traj.error %} -

    Trajectory unreadable

    {{ traj.error }}
    -{% elif traj %} - {# usage and tool calls; a trajectory with neither (one answer, no per-step usage) has no panel #} - {% if traj.token_series or traj.total_reasoning_tokens is not none or traj.calls %} -
    - {% set has_growth = traj.token_series|length > 1 %} - {% if has_growth %} -

    Prompt growth

    - {% set max_sent = traj.token_series|map(attribute='sent')|max %} -
    - {% for p in traj.token_series %} - {% set h = (56 * p.sent / max_sent)|round(1) if max_sent else 0 %} - {% set ch = (56 * p.cached / max_sent)|round(1) if max_sent else 0 %} - - - {% if ch >= 1 %}{% endif %} - - {% endfor %} -
    -
    - new tokens - served from cache - {% if traj.cache and traj.cache.hit is not none %} - - cache hit {{ traj.cache.hit|hitrate }} - {% if traj.cache.reported_diverges %} - - reported {{ traj.cache.reported_hit|hitrate }} - {% endif %} - {% endif %} - {% if traj.total_reasoning_tokens is not none %} - reasoning {{ traj.total_reasoning_tokens|tokens('control') }} - {% endif %} -
    -

    One column per LLM step, height ∝ input tokens; the gray band is what came from cache. - {%- if traj.cache and traj.cache.convention == 'anthropic' %} Anthropic-style usage: cache writes are added back onto the step that paid for them.{%- endif %}

    - {% elif traj.token_series or traj.total_reasoning_tokens is not none %} - {# one call: no growth to draw, so the call itself - what came from cache, what was new, what the model wrote #} - {% set p = traj.token_series[0] if traj.token_series else none %} -

    Usage

    - {% if p and p.sent %} - - {% endif %} -
    - {% if p %}served from cache {{ p.cached|tokens('control') }} - new input {{ p.new|tokens('control') }} - output {{ p.completion|tokens('control') }} - {% if p.sent %}cache hit {{ (p.cached / p.sent)|hitrate }}{% endif %}{% endif %} - {% if traj.total_reasoning_tokens is not none %}reasoning {{ traj.total_reasoning_tokens|tokens('control') }}{% endif %} -
    -

    {% if job.runner %}{{ job.runner }} asks its model once for each of its {{ job.runner_items[1] if job.runner_items else 'items' }}, so the bar is that one call: its input, from cache or new, and what it wrote. An agent's run charts its calls one after another instead, as its context grows.{% else %}One step carried usage: the bar is that call; the growth strip needs two.{% endif %}

    - {% endif %} - - {% if traj.calls %} - Tool calls + {% if traj and not traj.error and traj.calls %} +
    +

    Tool calls

    {% for c in traj.calls %} Usage
    {% if traj.name_freq %} {# Each tool once, under the server that offers it. #} -
    Judge{% if tq %}instructions scored {{ tq.judged }}/{{ tq.tasks }}{% endif %}TestsTask OutcomeUser judgeRetriesCause{% if show_flags %} · flags{% endif %}Flags
    {{ attempt_count(group, false) }} {{ task_flag(t) }}attempt {{ k }}{% if not group %}{{ task_flag(t) }}{% endif %}{{ trial_label(t) }}{% if t.n_retries %}{{ t.n_retries }}/{{ job.retries }}{% else %}0/{{ job.retries }}{% endif %} {%- if t.outcome == 'resolved' %}not asked diff --git a/app/templates/runs/preparing.html b/app/templates/runs/preparing.html index fb4e35db..18aa21e1 100644 --- a/app/templates/runs/preparing.html +++ b/app/templates/runs/preparing.html @@ -1,3 +1,4 @@ +{% from 'runs/_live_board.html' import live_panel %} {% from 'runs/_execution.html' import execution_strip %} {% extends "base.html" %} {% from '_page.html' import page_head %} @@ -6,8 +7,15 @@ {% block head %}{% endblock %} {% block body %} {{ page_head(job_id) }} - {% if ex.plan.runner == 'harbor' %}

    Started from the builder. This page becomes the live board as soon as Harbor writes the job.

    - {% elif ex.plan.runner == 'standard' %}

    Started from the builder with Nullius. This page becomes the live board as soon as the install is done and the run starts.

    - {% else %}

    Started from the builder with the {{ ex.plan.runner }} runner. This page becomes the live board as soon as this arm's questions are chosen, after the install.

    {% endif %} +
    + + + +
    +
    {{ execution_strip(ex, csrf, waiting=true, own=own, deletable=deletable) }} +
    + + {% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/templates/runs/setup.html b/app/templates/runs/setup.html index 8f9d7c8c..5341cef7 100644 --- a/app/templates/runs/setup.html +++ b/app/templates/runs/setup.html @@ -34,9 +34,9 @@ - + + aria-label="Add another path"> @@ -73,7 +73,7 @@ const pathList = document.getElementById('path-list'); pathList.addEventListener('click', e => { - if (e.target.matches('.add-btn')) { + if (e.target.closest('.add-btn')) { const row = pathList.firstElementChild.cloneNode(true); const field = row.querySelector('input'); field.value = ''; @@ -84,7 +84,7 @@ pathList.appendChild(row); field.focus(); syncRowButtons(); - } else if (e.target.matches('.row-x')) { + } else if (e.target.closest('.row-x')) { e.target.closest('.path-row').remove(); syncRowButtons(); } @@ -125,6 +125,7 @@ x.type = 'button'; x.className = 'alert-x'; x.setAttribute('aria-label', 'Dismiss'); + x.innerHTML = ''; x.addEventListener('click', () => alert.remove()); alert.appendChild(x); }); @@ -215,7 +216,7 @@ const li = document.createElement('li'); li.innerHTML = ` - `; + `; li.querySelector('.staged-name').textContent = s.name; li.querySelector('.staged-count').textContent = `${s.files.length} file${s.files.length === 1 ? '' : 's'}`; diff --git a/app/templates/runs/start.html b/app/templates/runs/start.html index 9f997dbb..bcac1914 100644 --- a/app/templates/runs/start.html +++ b/app/templates/runs/start.html @@ -11,13 +11,13 @@
    - +

    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 diff --git a/app/templates/settings/custom_keys.html b/app/templates/settings/custom_keys.html index 849b0e23..653f177a 100644 --- a/app/templates/settings/custom_keys.html +++ b/app/templates/settings/custom_keys.html @@ -1,6 +1,6 @@ {% macro key_summary(name, state, editor) %}
    - +

    {{ name }}

    {{ {'saved': 'Saved', 'missing': 'Not set', 'expired': 'Expired'}[state] }} diff --git a/app/templates/settings/machine_info.html b/app/templates/settings/machine_info.html index 6de3a299..99f44657 100644 --- a/app/templates/settings/machine_info.html +++ b/app/templates/settings/machine_info.html @@ -18,5 +18,5 @@
    Local processes{% if not cap or m.scope is none %}{{ never }}{% elif m.scope.why %}{{ m.scope.why[:1] | upper }}{{ m.scope.why[1:] }}{% else %}{{ held(m.scope.enforced, m.scope.refused) }}{% endif %}
    {#- a container run's drivers take a scope where one holds, and run unlimited where none does -#} {{ line('Drivers', never if not cap or m.scope is none else 'Limited' if m.scope_ok else 'Not limited') }} - {{ line('Tested', f.at | replace('T', ' ') if f.at else 'Never') }} + {{ line('Tested', m.tested or 'Never') }}
    diff --git a/app/templates/settings/settings.html b/app/templates/settings/settings.html index 7093af77..92fd9257 100644 --- a/app/templates/settings/settings.html +++ b/app/templates/settings/settings.html @@ -15,7 +15,7 @@ {% set chosen = (hosts_row.shown.split(',') | map('trim') | select | list) if hosts_row else [] %} {#- mode, in a provider's editor: 'plain' is edited in place (a name, an endpoint's URL); 'key' is written, never shown, and replaced; 'optional-key' may also be removed. Elsewhere, Replace and Remove. -#} -{% macro field(r, label, writable, options=none, mode='', placeholder='', tip='') %} +{% macro field(r, label, writable, options=none, mode='', placeholder='', tip='', picker='') %} {% set plain = mode == 'plain' %}
    @@ -30,7 +30,7 @@ {% if mode != 'key' %}{% endif %}
    {% endif %} - + {% if r.problem %}

    {{ r.problem }}

    {% endif %} {% if options is not none %}{% for o in options %}{% endfor %}{% endif %} {% if r.source == 'environment' %}

    Also set in the process environment: the running process keeps that value until it is restarted; the file applies then.

    {% endif %} @@ -81,7 +81,7 @@ {{ section_link('data-providers', 'Data providers', 'cloud-down', 'hugging face huggingface hf_token docker hub login registry token dataset pull limit') }} {{ section_link('custom-keys', 'Custom keys', 'key', access_search.words) }} {{ section_link('judge', 'Judges', 'scale', 'typesafe decision llm model judgement') }} - {{ section_link('prices', 'Model prices', 'dollar', 'cost price estimate usd tokens list update') }} + {{ section_link('prices', 'Model prices', 'circle-dollar', 'cost price estimate usd tokens list update') }}
    Execution
    @@ -221,17 +221,17 @@

    Judges

    {% set srow = by.get('DECISION_PROVIDER') %} {% if srow and by.get('DECISION_MODEL') %}
    - Decision model + Decision model {{ judge_rows('DECISION', decision_providers, decision, 'Where the Decision model is asked') }} - {{ field(by['DECISION_MODEL'], 'Model', writable, decision_providers[decision.provider].models) }} + {{ field(by['DECISION_MODEL'], 'Model', writable, picker='[data-picker]') }}
    {% endif %} {% set prow = by.get('LLM_JUDGE_PROVIDER') %} {% if prow and by.get('LLM_JUDGE_MODEL') %}
    - LLM + LLM {{ judge_rows('LLM_JUDGE', llm_providers, llm, "The LLM judge's provider") }} - {{ field(by['LLM_JUDGE_MODEL'], 'Model', writable, []) }} + {{ field(by['LLM_JUDGE_MODEL'], 'Model', writable, picker='[data-picker]') }}
    {% endif %} @@ -260,7 +260,7 @@

    Judges

    {% if ssh_hosts %}
    - +
    {% if writable %}{% endif %} {{ act('info', 'info', m.label, 'Info', mi) }} - {% if m.host and writable %}{{ act('edit', 'plug', m.label, 'Connection', mi, ro) }}{% elif writable %}{{ never('plug', 'Connection: not for this machine') }}{% else %}{% endif %} + {% if m.host and writable %}{{ act('edit', 'plugs', m.label, 'Connection', mi, ro) }}{% elif writable %}{{ never('plugs', 'Connection: not for this machine') }}{% else %}{% endif %} {{ act('limits', 'sliders', m.label, 'Constraints', mi) }} {% if m.host and writable %}{{ act('delete', 'trash', m.label, 'Delete', mi, ro) }}{% elif writable %}{{ never('trash', 'Delete: this machine cannot be removed') }}{% else %}{% endif %} {% if r.answer %}{{ pill(r) }}{% else %}not judged{% endif %} {% if r.answer %}{{ r.headline }}% {% if r.floor is not none %}{% endif %}{% if r.floor is not none %} ±{{ '%.0f'|format(r.floor * 100) }}{% else %}±?{% endif %}{% endif %}
    +
    {% for t in traj.tools %} @@ -225,12 +143,19 @@

    Usage

    {% endfor %} -
    ToolCategoryCallsFailedTime
    - {% endif %} +
    {% endif %} {% endif %} + +{% from 'traces/_usage.html' import usage_panel %} +{{ usage_panel(trial, traj) }} + + +{% if traj and traj.error %} +

    Trajectory unreadable

    {{ traj.error }}
    +{% elif traj %} {% if loc %}

    Against the gold patch

    @@ -283,6 +208,45 @@

    {{ job.runner }}'s score gives the {{ judgement_panel(llm_judgement, job, trial, csrf) }} {% endif %} +{% if failure is not none %}
    +{% include "traces/_failure.html" %} +
    {% endif %} +{# What the benchmark recorded of a trial that fell short: its named rows, else its whole detail. #} +{% macro recorded(text) %}{% if '\n' in text or text|length > 200 %}
    {{ text }}
    {% else %}{{ text }}{% endif %}{% endmacro %} +{% if fell_short %}
    +{% if trial.is_regression %} +
    +

    ⚠ This patch broke {{ trial.p2p_fail }} previously-passing test{{ '' if trial.p2p_fail == 1 else 's' }}

    +

    These passed before the patch was applied and fail after it — a + regression, not just a missed fix.

    +
      + {% for name in trial.p2p_failures %}
    • {{ name }}
    • {% endfor %} +
    +
    +{% endif %} + +{% if trial.f2p_failures %} +
    +

    Tests that had to pass, still failing

    +
      + {% for name in trial.f2p_failures %}
    • {{ name }}
    • {% endfor %} +
    +
    +{% endif %} +{% if evidence or (detail and detail.fields) %} + {% for r in evidence %} + {% endfor %} + {% for f in (detail.fields if detail else []) %} + {% endfor %} +
    {{ r.label }}{{ recorded(r.text) }}
    {{ f.name[:1]|upper }}{{ f.name[1:]|replace("_", " ") }}{{ recorded(f.text) }}
    {% endif %} +{% if detail %}{% for g in detail.groups %} +

    {{ g.name|replace("_", " ")|replace(".", " / ") }}

    +
      + {% for x in g.flags %}
    • {% if x.held is sameas true %}✓{% elif x.held is sameas false %}×{% else %}·{% endif %} {{ x.name|replace("_", " ") }}{% if x.text %}: {% if x.cut %}
      {{ x.cut }}…{{ x.text }}
      {% else %}{{ x.text }}{% endif %}{% endif %}
    • + {% endfor %} +
    +{% endfor %}{% endif %} +
    {% endif %}
    {# The task's instruction, scored on its own text: once per dataset and task, the same for every attempt, nothing of any run read. The score changes no outcome. #} @@ -620,15 +584,20 @@

    Waterfall

    {% if artifacts %}
    + {#- the benchmark's own records, after Nullius's, under one heading row #} + {% set seen = namespace(declared=false) %} {% for artifact in artifacts %} - + {% if artifact.declared and not seen.declared %}{% set seen.declared = true %}{% endif %} + + {% if artifact.more %}{% endif %} {% endfor %}
    RecordSize
    {{ artifact.label }}{{ '%.2f'|format(artifact.size / 1024) }} KB
    The benchmark's own records
    {{ artifact.label }}{% if artifact.part %} {{ artifact.part }}{% endif %}{{ '%.2f'|format(artifact.size / 1024) }} KB ReadDownload
    More records in {{ artifact.label }}.
    {% endif %}
    + ", "api_key": hidden, "credentials": {"password": hidden}, + "flags": {"flag": True, "password": hidden, "held": True}, + "rows": [{"inner": {"secret": hidden}}]}) + self.assertNotIn("", html) + self.assertIn("<script>alert(1)</script>", html) + self.assertIn("<b>name</b>", html) + self.assertIn("<i>flag</i>", html) + self.assertNotIn(hidden, html) + self.assertIn("[REDACTED]", self.panel(html)) + self.assertIn("✓
    held", self.panel(html)) + + def test_a_score_without_a_detail_has_no_tab(self): + for detail in ({}, None, ["a"], {"result": 0.5, "by": "run.py, evaluate", "tool_calls": 3, "steps": 2}): + with self.subTest(detail=detail): + self.assertNotIn('id="tab-evidence"', self.page(detail)) + os.remove(os.path.join(self.root, "t1", "verifier", "score.json")) + job = parse.parse_job(self.root) + with patch.object(web.shared, "_jobs_for_request", return_value=[job]): + response = self.client.get(f"/trial/{job.job_id}/t1") + self.addCleanup(response.close) + self.assertNotIn('id="tab-evidence"', response.get_data(as_text=True)) + + def test_only_a_trial_that_fell_short_has_the_tab(self): + detail = {"extracted": "A", "target": "C"} + for kwargs, shown in (({"score": 0.4}, True), ({"score": 1.0}, False), ({"reward": 0.0}, True), ({"reward": 1.0}, False)): + with self.subTest(**kwargs): + html = self.page(detail, **kwargs) + self.assertEqual('id="tab-evidence"' in html, shown) + self.assertEqual('id="trial-evidence"' in html, shown) + self.assertIn('id="tab-failure"', html) # the User judge stays + + def test_a_benchmarks_named_rows_and_nothing_else(self): + html = self.panel(self.page({"scorer": "choice", "value": "I", "extracted": "A", "target": "C", "answer": "so\nA"}, + source="open-telco", reward=0.0)) + self.assertEqual(text_of(html), "Extracted answer A Expected answer C Reply so A") + self.assertIn("<b>C", html) + self.assertIn('
    so\nA
    ', html) + self.assertNotIn('id="tab-evidence"', self.page({"last_action": "click"}, source="osworld1", score=0.0)) + + def test_failing_tests_are_in_the_tab_once(self): + with open(os.path.join(self.root, "t1", "verifier", "report.json"), "w") as f: + json.dump({"t1": {"patch_exists": True, "patch_successfully_applied": True, "resolved": False, "tests_status": { + "FAIL_TO_PASS": {"success": [], "failure": ["test_wanted"]}, + "PASS_TO_PASS": {"success": [], "failure": ["test_broken"]}}}}, f) + html = self.page({}, source="swe-bench-verified", reward=0.0) + for name in ("test_wanted", "test_broken"): + self.assertIn(name, self.panel(html)) + self.assertEqual(html.count(name), 1) + + def test_the_agents_last_reply_stands_in_for_an_answer_not_recorded(self): + at = os.path.join(self.root, "t1", "agent", "trajectory.json") + with open(at) as f: + doc = json.load(f) + doc["steps"] = [{"step_id": 1, "source": "agent", "message": "the first"}, {"step_id": 2, "source": "agent", "message": "economics"}] + with open(at, "w") as f: + json.dump(doc, f) + said = text_of(self.panel(self.page({"reference": "business", "judge_said": "no"}, source="longmemeval", reward=0.0))) + self.assertEqual(said, "Answer economics Expected answer business Judge said no") + + +if __name__ == "__main__": + unittest.main() diff --git a/app/ui_tests/test_trial_head.py b/app/ui_tests/test_trial_head.py index 7c8f8345..62c8e953 100644 --- a/app/ui_tests/test_trial_head.py +++ b/app/ui_tests/test_trial_head.py @@ -1,8 +1,7 @@ -"""The trial page's head: what ran and how it went, in one row of blocks. +"""The trial page's head: its own metrics, without repeated run metadata. -A block says only what the trial has: no dash under a label, no benchmark or -runner for a trial an importer wrote, and Harbor named only for Harbor's own -job trees. Jobs are synthetic, from tests.test_feasibility, and the scored +A block says only what the trial has: no dash under a label and no repeated +benchmark, runner, agent or model cards. Jobs are synthetic, from tests.test_feasibility, and the scored runner fixture; nothing is run.""" from __future__ import annotations @@ -47,21 +46,58 @@ def head(self, job, trial): self.addCleanup(response.close) self.assertEqual(response.status_code, 200) html = response.get_data(as_text=True) - block = html.split('
    ', 1)[1].split('