diff --git a/app/nullius/catalogue/benchmarks/past-bench/benchmark.json b/app/nullius/catalogue/benchmarks/past-bench/benchmark.json new file mode 100644 index 000000000..c52f23329 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/past-bench/benchmark.json @@ -0,0 +1,150 @@ +{ + "key": "past-bench", + "title": "PAST-Bench", + "category": "General assistance", + "domain": "Cross-session self-evolution for personal agents: retaining preferences and constraints, reusing procedures, gathering prior context before acting, and replacing stale facts, rules and procedures. A family is an ordered sequence of episodes with matched persistence-on and persistence-off controls.", + "scoring": "Episode composite (0.8 × completion + 0.2 × robustness, × safety), family = evaluation-episode mean", + "harness": [ + "standard" + ], + "origin": "official", + "good_to_know": [ + "A unit is one family, not one episode: its episodes run in the publisher's sequence order, share a workspace, and are judged as a sequence. The run reports 26 units for 204 episodes.", + "The first message only explains how the session works and asks the agent to reply READY; every task then arrives as its own message, so the episodes can be counted and each gets its own fresh session where the manifest says so.", + "past-bench-nop and past-bench-isolated are Nullius's controls, not the publisher's: its persistence-off arm turns off the agent's memory tools, and it refuses that arm for any agent outside Hermes, nanobot and ZeroClaw.", + "The tools are the benchmark's: each episode declares its tools and their mock-service endpoints, and they reach the agent as MCP tools that change with the episode. An agent needs the tools port.", + "The mock services run beside the driver on ports it picks, so two families can run at once; their audit logs are the evidence the graders read.", + "Episode order, fresh-session rules and history anchors come from the publisher's configs/self_evolve_v2/*_only.yaml, which match what it generates from each family.yaml.", + "The publisher declares a judge, so a provider key is needed before any run, including the nop control. Override --judge-model when the benchmark's default model is not served by your provider.", + "An ablation compares past-bench's eval_near/eval_far episodes with past-bench-isolated's: same episodes, but the isolated unit never saw the learn episodes and has a fresh home. past-bench-nop alone is not that control - it only resets the workspace." + ], + "upstream_limitations": [ + "The official harness runs its own agents (Hermes, Hermes+, nanobot, ZeroClaw, Agent Zero, OpenClaw, Codex, Claude Code and a built-in baseline) and exposes no interface for any other. This entry runs the Nullius agent under test with the publisher's graders, services and manifests, not its runner or sandbox.", + "7 update episodes on disk are in no manifest; the upstream does not run them, nor does this entry.", + "Some episodes seed the agent's home (hermes_home_seed); the upstream applies a seed only to an agent it has a persistence backend for, so not here.", + "The graders reward the agent's own memory, skill and session-search calls, which the upstream reads only from the agents it has a persistence backend for (Hermes, nanobot, ZeroClaw). Any other agent is graded as the upstream grades Agent Zero: with nothing recorded, so 58 of the 60 evaluation episodes cap completion at 0.25, an episode at 0.40 at most.", + "The upstream sends a learn episode's reflection prompt only to an agent it has a persistence backend for; the agent under test gets none, as Agent Zero gets none." + ], + "limitations": [ + "No persistence means a cleaned workspace and a new session. The agent's own memory store lives in its home directory, which belongs to the unit and is not addressable by the benchmark, so an agent with durable internal memory is measured with that memory intact in both arms.", + "The graders see the episode's own exchange, its MCP tool calls and the services' audit logs; internal tool calls the agent makes outside the benchmark's MCP tools are not in that evidence.", + "The communication part of an episode's score is an LLM judge on the benchmark's default model unless --judge-model says otherwise; use one judge model across arms for comparable numbers.", + "The upstream runs each episode as its own trial, a new session, and applies history anchors to the agent's home. Here a continue episode keeps the session, anchors restore the workspace, and the agent's home is never reset; evaluation and control episodes always start a new session.", + "The upstream gives an episode 300 s and 20 steps, past which it scores 0; here only the whole family has a limit, 6 h." + ], + "datasets": [ + { + "key": "past-bench", + "title": "All 26 families · persistence on", + "tasks": 204, + "official": "https://github.com/Gen-Verse/PAST-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The publisher's grader for each episode, then the evaluation-episode mean per family.", + "notes": "26 units, 204 episodes: memory 5 families, procedural 8, information gathering 6, update 7." + }, + { + "key": "past-bench-nop", + "title": "All 26 families · workspace reset per episode (workspace-only control)", + "tasks": 204, + "official": "https://github.com/Gen-Verse/PAST-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The same graders, over the same episodes with the workspace reset before each one.", + "notes": "Workspace-only control: the workspace is reset before every episode, but the agent's own memory lives in its home directory and survives. Use past-bench-isolated for an ablation." + }, + { + "key": "past-bench-isolated", + "title": "Evaluation episodes alone · 60 units (the control)", + "tasks": 60, + "official": "https://github.com/Gen-Verse/PAST-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The publisher's grader for each evaluation episode, scored with nothing carried over.", + "notes": "Each eval_near/eval_far episode is one unit: its own container, its own home, its own workspace, and no learn episode before it. This is the arm an ablation compares against." + }, + { + "key": "past-bench-memory", + "title": "Memory · 5 families", + "tasks": 41, + "official": "https://github.com/Gen-Verse/PAST-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The publisher's graders over memory_ability families.", + "notes": "Retaining preferences, constraints and prior cases." + }, + { + "key": "past-bench-procedural", + "title": "Procedural reuse · 8 families", + "tasks": 64, + "official": "https://github.com/Gen-Verse/PAST-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The publisher's graders over procedural_ability families.", + "notes": "Reusing procedures and skills." + }, + { + "key": "past-bench-information-gathering", + "title": "Information gathering · 6 families", + "tasks": 48, + "official": "https://github.com/Gen-Verse/PAST-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The publisher's graders over proactive_information_gathering families.", + "notes": "Looking up prior context before acting." + }, + { + "key": "past-bench-update", + "title": "Update · 7 families", + "tasks": 51, + "official": "https://github.com/Gen-Verse/PAST-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The publisher's graders over update_ability families.", + "notes": "Replacing stale facts, rules and procedures." + }, + { + "key": "past-bench-smoke", + "title": "SM01 preference adoption · 1 family", + "tasks": 8, + "official": "https://github.com/Gen-Verse/PAST-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The publisher's graders over the family's eight episodes.", + "notes": "The smallest end-to-end check: baseline, two learn episodes, near and far transfer, three controls." + }, + { + "key": "past-bench-smoke-isolated", + "title": "SM01 evaluation episodes alone · 2 units", + "tasks": 2, + "official": "https://github.com/Gen-Verse/PAST-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The publisher's graders, scored with nothing carried over.", + "notes": "The smallest control check." + }, + { + "key": "past-bench-smoke-nop", + "title": "SM01 preference adoption · persistence off", + "tasks": 8, + "official": "https://github.com/Gen-Verse/PAST-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The same graders with the workspace reset before each episode.", + "notes": "The control that makes SM01's number mean something." + } + ], + "task_count": 204, + "citation": "@article{xue2026pastbench,\n title={PAST-Bench: Benchmarking the Foundations of Recursive Self-Improvement in Personal Agents},\n author={Xue, Shuhan and Ding, Zixin and Shen, Yichen and Wang, Yinjie and Yin, Zhenfei and Wu, Yingcheng and Chen, Yuxin and Wang, Mengdi and Yang, Ling},\n journal={arXiv preprint arXiv:2608.04003},\n year={2026}\n}", + "citation_source": "https://github.com/Gen-Verse/PAST-Bench" +} diff --git a/app/nullius/catalogue/benchmarks/past-bench/driver.py b/app/nullius/catalogue/benchmarks/past-bench/driver.py new file mode 100644 index 000000000..74180ce32 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/past-bench/driver.py @@ -0,0 +1,521 @@ +"""PAST-Bench (official, 26 families) on the Nullius standard. + +The benchmark is the publisher's: 26 task families over four abilities, 204 +episodes, each family an ordered sequence in which an early episode teaches and +later episodes ask, in different words, for what was taught. What it measures +is not one answer but whether the teaching survived: the same family run with +its persistence taken away is the control. This driver is glue only: + +units - the families the chosen dataset names. A family is one unit because + its episodes run in the publisher's order, share a workspace and are + judged as a sequence; a unit is a session that starts again between + episodes while the workspace stays. +setup - the family's episodes from the publisher's own sequence manifest + (``configs/self_evolve_v2/*_only.yaml``: order, fresh-session rule, + history anchors, whether persistence is allowed), the first episode's + mock services on ports this driver picks, and the tools those + services expose, as an MCP server of the benchmark's own (``past_mcp.py``) +turn - one episode per turn. The agent's reply is kept with the episode's + service audit logs and its tool calls; then the next episode's + services start and its prompt goes out, in a new session when the + manifest says ``requires_fresh_session``. +score - each episode through the publisher's own grader for that episode + (``/grader.py``, ``expectations.json``) and the publisher's + own composite (``0.8*completion + 0.2*robustness``, times safety), + through its own ``grade_episode``, as for an agent it has no + persistence backend for, + then the family's buckets: cold, learn, eval_near, eval_far, control. + +Two arms, two datasets: ``past-bench`` keeps persistence, and ``past-bench-nop`` +runs the same families with the workspace reset before every episode - a +control of Nullius's, since the publisher's own persistence-off arm turns off +an agent's memory tools and exists only for its own agents. The agent's own +memory store (its home directory) belongs to the unit and is not addressable +here, so a fresh session and a cleaned workspace are what "no persistence" +means for this driver; the publisher's own no-persistence episodes +(``persistence_disabled``) are honoured inside both arms. + +The publisher's harness (its runner, sandbox and simulated tools) is not used: +the Nullius agent under test takes the agent's place, the benchmark's tools +come over MCP, and its services run beside the driver. +""" +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import sys +import tarfile +import time +import traceback +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, List, Optional + +import yaml + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import services as mock # noqa: E402 + +UPSTREAM = Path(os.environ["NULLIUS_UPSTREAM"]).resolve() +SRC = UPSTREAM / "src" +TASKS = UPSTREAM / "self-evolve-tasks-v2" +MANIFESTS = UPSTREAM / "configs" / "self_evolve_v2" +MODEL_ID = "nullius" +STATE: Dict[str, dict] = {} +DATASET_ID = "past-bench" +PRELUDE = ( + "This session works through a series of tasks for the same user. That is all this message says: " + "the tasks follow one at a time, each as its own message, and your final message answers the task " + "in front of you. Tools for the current task are the MCP tools given to you; they change with the " + "task. Do not act on this message - reply READY and wait for the first task." +) + +DATASETS: Dict[str, tuple] = { + "past-bench": ("persist", None), + "past-bench-nop": ("nop", None), + "past-bench-isolated": ("isolated", None), + "past-bench-smoke": ("persist", ["SM01_preference_adoption"]), + "past-bench-smoke-nop": ("nop", ["SM01_preference_adoption"]), + "past-bench-smoke-isolated": ("isolated", ["SM01_preference_adoption"]), + "past-bench-memory": ("persist", ["memory_ability"]), + "past-bench-procedural": ("persist", ["procedural_ability"]), + "past-bench-information-gathering": ("persist", ["proactive_information_gathering"]), + "past-bench-update": ("persist", ["update_ability"]), +} +NOP = ".nop" # the control arm's unit id: a driver process does not see the dataset +ISO = ".iso." # one evaluation episode alone, in an instance that remembers nothing + + +def arm_of(unit: str) -> tuple: + """A unit id says its arm, because ``setup`` never learns the dataset's name. + + ``persist``: the family's whole sequence, one instance, workspace kept. + ``nop``: the same sequence with the workspace reset before every episode - + a workspace-only control; the agent's own memory lives in its home, + which belongs to the instance and survives. + ``isolated``: one evaluation episode alone in its own unit - own container, + own home, own workspace, no learn episodes at all. This is the + control an ablation needs: nothing can carry over. + """ + if unit.endswith(NOP): + return unit[:-len(NOP)], "nop" + if ISO in unit: + return unit.split(ISO, 1)[0], "isolated" + return unit, "persist" + + +# ── the publisher's own files ──────────────────────────────────────────────── +def upstream(): + """The publisher's models, graders and composite, imported once per driver.""" + if "modules" not in STATE: + sys.path.insert(0, str(SRC)) + sys.path.insert(0, str(UPSTREAM)) + from past_bench.models.task import TaskDefinition + from past_bench.models.trace import MediaLoad, ToolDispatch, TraceMessage + from past_bench.models.message import Message + from past_bench.models.scoring import compute_task_score + from past_bench.graders.base import AbstractGrader + from past_bench.models.trace import AuditSnapshot, TraceEnd, TraceStart + from past_bench.graders.llm_judge import LLMJudge + from past_bench.graders.registry import get_grader + from past_bench.runner.self_evolve import _empty_artifact_summary, grade_episode + from past_bench.trace.writer import TraceWriter + STATE["modules"] = {"TaskDefinition": TaskDefinition, "TraceMessage": TraceMessage, + "ToolDispatch": ToolDispatch, "MediaLoad": MediaLoad, + "Message": Message, "compute_task_score": compute_task_score, + "AbstractGrader": AbstractGrader, "LLMJudge": LLMJudge, + "TraceStart": TraceStart, "TraceEnd": TraceEnd, "AuditSnapshot": AuditSnapshot, + "TraceWriter": TraceWriter, "get_grader": get_grader, + "grade_episode": grade_episode, "empty_summary": _empty_artifact_summary} + return STATE["modules"] + + +def families() -> Dict[str, dict]: + """Every family on disk, keyed by id, with the ability folder it sits in.""" + out = {} + for path in sorted(TASKS.glob("*/*/family.yaml")): + meta = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + out[path.parent.name] = {"id": path.parent.name, "ability": path.parent.parent.name, + "dir": path.parent, "meta": meta} + return out + + +def manifests() -> Dict[str, dict]: + """The publisher's sequence manifests, keyed by the family each one covers.""" + out = {} + for path in sorted(MANIFESTS.glob("*_only.yaml")): + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + for episode in data.get("episodes") or []: + family = episode.get("family_id") + if family: + out.setdefault(family, {"path": path, "episodes": data["episodes"]}) + return out + + +def episodes(family: str) -> List[dict]: + """One family's sequence: the manifest's order and its rules, per episode.""" + got = manifests().get(family) + if not got: + raise ValueError(f"{family}: the publisher ships no sequence manifest") + out = [] + for episode in got["episodes"]: + path = (got["path"].parent / str(episode["task"])).resolve() + if path.is_dir(): + path = path / "task.yaml" + task = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + out.append({ + "dir": path.parent, "yaml": path, "family": family, + "stage": str(episode.get("stage") or episode.get("bucket") or "episode"), + "bucket": str(episode.get("bucket") or "episode"), + "label": str(episode.get("label") or path.parent.name), + "fresh": bool(episode.get("requires_fresh_session")), + "persistence": bool(episode.get("persistence_allowed", True)), + "mode": str(episode.get("history_mode") or "continue"), + "save_anchor": str(episode.get("history_save_anchor") or ""), + "load_anchor": str(episode.get("history_load_anchor") or ""), + # the manifest's own fallback (models/self_evolve.py): the mechanism + "signal": str(episode.get("expected_persistence_signal") or episode.get("mechanism") or "mixed"), + "task": task, + "prompt": str((task.get("prompt") or {}).get("text") or ""), + }) + return out + + +def units(dataset, setup=None): + """The dataset's units: every family of the ability it names, or the one it names.""" + global DATASET_ID + if dataset not in DATASETS: + raise ValueError(f"unknown PAST-Bench dataset {dataset!r}") + DATASET_ID = dataset + arm, which = DATASETS[dataset] + known = families() + if which is None: + chosen = sorted(known) + else: + chosen = sorted(f for f in known + if f in which or known[f]["ability"] in which) + if not chosen: + raise ValueError(f"{dataset}: no family matches {which!r}") + if arm == "isolated": + # One unit per evaluation episode: its own instance, so no learn episode, + # no earlier session and no agent home can reach it. + listed = [f"{family}{ISO}{e['dir'].name}" for family in chosen + for e in episodes(family) if e["bucket"] == "evaluation"] + if not listed: + raise ValueError(f"{dataset}: no evaluation episode to isolate") + return {"units": listed} + for family in chosen: + episodes(family) + return {"units": [f + NOP if arm == "nop" else f for f in chosen]} + + +# ── the unit ───────────────────────────────────────────────────────────────── +def _token(unit: str) -> str: + return hashlib.sha256(f"{unit}:{os.getpid()}:{time.time()}".encode()).hexdigest()[:12] + + +def _state_dir(workspace: str, unit: str) -> Path: + """Where the driver keeps its evidence: outside the workspace the agent may read.""" + trial = Path(workspace).resolve().parent + job = trial.parent + for root in (job, trial): + try: + path = root / ".past-bench" / f"{unit}-{_token(unit)}" + path.mkdir(parents=True, exist_ok=True) + return path + except OSError: + continue + path = Path(workspace).resolve() / ".past-bench-state" + path.mkdir(parents=True, exist_ok=True) + return path + + +def snapshot(workspace: Path, path: Path) -> None: + """The workspace as it stands, tarred: what a history anchor restores.""" + path.parent.mkdir(parents=True, exist_ok=True) + with tarfile.open(path, "w") as tar: + for item in workspace.iterdir(): + if item.name.startswith(".past-bench"): + continue + tar.add(item, arcname=item.name) + + +def restore(workspace: Path, path: Path) -> None: + """The workspace back to a snapshot: everything the agent wrote since, gone.""" + for item in workspace.iterdir(): + if item.name.startswith(".past-bench"): + continue + if item.is_dir() and not item.is_symlink(): + shutil.rmtree(item, ignore_errors=True) + else: + try: + item.unlink() + except OSError: + pass + if path.exists(): + with tarfile.open(path, "r") as tar: + tar.extractall(workspace) + + +def tools_for(task: dict, service_ports: Dict[str, int]) -> List[dict]: + """The episode's tools as MCP tools: its own schema, its service's port.""" + endpoints = {str(e.get("tool_name")): e for e in task.get("tool_endpoints") or [] if isinstance(e, dict)} + specs = task.get("services") or [] + out = [] + for tool in task.get("tools") or []: + if not isinstance(tool, dict) or not tool.get("name"): + continue + endpoint = endpoints.get(str(tool["name"])) or {} + url = str(endpoint.get("url") or "") + if url: + url = mock.rewrite(url, specs, service_ports) + out.append({"name": str(tool["name"]), "description": str(tool.get("description") or ""), + "input_schema": tool.get("input_schema") or {"type": "object", "properties": {}}, + "url": url, "method": str(endpoint.get("method") or "POST")}) + return out + + +def control(state: dict, index: int) -> None: + """Tell the MCP server which episode is in front of the agent.""" + episode = state["episodes"][index] + payload = {"episode": episode["label"], "stage": episode["stage"], "index": index, + "family": state["family"], "tools": state["tools"]} + path = state["state"] / "current.json" + path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") + + +def open_episode(state: dict, index: int) -> str: + """Start the episode's services and hand back its prompt text.""" + episode = state["episodes"][index] + if state["services"] is not None: + state["services"].stop() + workspace = Path(state["dir"]) + if state["arm"] in ("nop", "isolated") or not episode["persistence"]: + restore(workspace, state["state"] / "anchors" / "initial.tar") + elif episode["load_anchor"] and (state["state"] / "anchors" / f"{episode['load_anchor']}.tar").exists(): + restore(workspace, state["state"] / "anchors" / f"{episode['load_anchor']}.tar") + episode_services = mock.Episode(UPSTREAM, episode["task"], sys.executable) + ports = episode_services.start() + state["services"] = episode_services + state["tools"] = tools_for(episode["task"], ports) + state["dispatch_at"] = dispatch_count(state) # this episode's tool calls start here + state["index"] = index + control(state, index) + return episode["prompt"] + + +def dispatch_path(state: dict) -> Path: + return state["state"] / "dispatch.jsonl" + + +def setup(unit, dir): + """The family's episodes, the first one's services, and the benchmark's tools.""" + family, arm = arm_of(unit) + episodes_here = episodes(family) + if arm == "isolated": + name = unit.split(ISO, 1)[1] + episodes_here = [e for e in episodes_here if e["dir"].name == name] + if len(episodes_here) != 1: + raise ValueError(f"{unit}: {len(episodes_here)} episodes match that name") + workspace = Path(os.path.abspath(dir)) + workspace.mkdir(parents=True, exist_ok=True) + state_dir = _state_dir(str(workspace), family) + state = {"family": family, "unit": unit, "dir": str(workspace), "arm": arm, + "dataset": {"persist": "past-bench", "nop": "past-bench-nop", + "isolated": "past-bench-isolated"}[arm], + "episodes": episodes_here, "index": -1, "services": None, "tools": [], + "evidence": [], "state": state_dir, "dispatch_at": 0, "awaiting": "prelude", + "started": datetime.now().strftime("%Y%m%d_%H%M%S")} + STATE[unit] = state + snapshot(workspace, state_dir / "anchors" / "initial.tar") + dispatch_path(state).write_text("", encoding="utf-8") + open_episode(state, 0) + return {"prompt": PRELUDE, "agent_seconds": 21600, + "mcp": [{"name": "past", "server": "past", "args": [str(state_dir)]}]} + + +def dispatch_count(state: dict) -> int: + try: + return sum(1 for _ in dispatch_path(state).open(encoding="utf-8")) + except OSError: + return 0 + + +def dispatches_since(state: dict, start: int) -> List[dict]: + out = [] + try: + with dispatch_path(state).open(encoding="utf-8") as f: + for n, line in enumerate(f): + if n < start: + continue + try: + out.append(json.loads(line)) + except ValueError: + continue + except OSError: + pass + return out + + +def last_agent(transcript) -> str: + for item in reversed(transcript or []): + if item.get("role") == "agent": + return str(item.get("text") or "") + return "" + + +def capture(state: dict, reply: str) -> None: + """Keep one episode's evidence: what was asked, what was said, what ran, what it touched.""" + episode = state["episodes"][state["index"]] + audit = state["services"].audit() if state["services"] is not None else {} + state["evidence"].append({ + "index": state["index"], "stage": episode["stage"], "bucket": episode["bucket"], + "label": episode["label"], "dir": str(episode["dir"]), "yaml": str(episode["yaml"]), + "prompt": episode["prompt"], "reply": reply, "audit": audit, + "dispatches": dispatches_since(state, state["dispatch_at"]), "signal": episode["signal"], + }) + if episode["save_anchor"]: + snapshot(Path(state["dir"]), state["state"] / "anchors" / f"{episode['save_anchor']}.tar") + + +def turn(unit, dir, transcript, simulator=None, judge=None, attempt=None): + """One message at a time: the prelude first, then each episode, until none is left.""" + state = STATE.get(unit) + if state is None: + raise ValueError(f"turn before setup for {unit!r}") + if state["awaiting"] == "prelude": # the agent only said READY: the first task comes now + state["awaiting"] = "episode" + return {"message": state["episodes"][0]["prompt"]} + capture(state, last_agent(transcript)) + if state["index"] + 1 >= len(state["episodes"]): + return {"done": True} + index = state["index"] + 1 + text = open_episode(state, index) + fresh = state["episodes"][index]["fresh"] or state["arm"] in ("nop", "isolated") or \ + not state["episodes"][index]["persistence"] + return {"message": text, "restart": bool(fresh)} + + +# ── grading: the publisher's graders, over what the driver kept ────────────── +def write_trace(entry: dict, path: Path) -> None: + """One episode as the upstream's JSONL trace: what ``load_trace`` reads back.""" + mods = upstream() + trace_id = f"{MODEL_ID}:{entry['label']}" + task_id = mods["TaskDefinition"].from_yaml(entry["yaml"]).task_id + events = [mods["TraceStart"](trace_id=trace_id, task_id=task_id, model=MODEL_ID)] + for role, text in (("user", entry["prompt"]), ("assistant", entry["reply"])): + events.append(mods["TraceMessage"](trace_id=trace_id, message=mods["Message"](role=role, content=text))) + for i, call in enumerate(entry["dispatches"]): + events.append(mods["ToolDispatch"]( + trace_id=trace_id, tool_use_id=f"{trace_id}-{i}", tool_name=str(call.get("tool") or ""), + endpoint_url=str(call.get("endpoint_url") or ""), + request_body=call.get("request_body") if isinstance(call.get("request_body"), dict) else {}, + response_status=int(call.get("response_status") or 200), + response_body=call.get("response_body"), + latency_ms=float(call.get("latency_ms") or 0.0))) + for service, data in (entry["audit"] or {}).items(): + events.append(mods["AuditSnapshot"](trace_id=trace_id, service_name=str(service), audit_url="", + audit_data=data if isinstance(data, dict) else {"raw": data})) + events.append(mods["TraceEnd"](trace_id=trace_id, total_turns=1)) + path.parent.mkdir(parents=True, exist_ok=True) + with mods["TraceWriter"](path) as writer: + for event in events: + writer.write_event(event) + + +def grade(entry: dict, judge, state_dir: Path): + """One episode through the upstream's own ``grade_episode``, as it grades an + agent that has no persistence backend (its agent-zero path): an empty + artifact summary before and after, no environment snapshot.""" + mods = upstream() + task = mods["TaskDefinition"].from_yaml(entry["yaml"]) + trace = state_dir / "traces" / f"{entry['index']:03d}-{Path(entry['dir']).name}.jsonl" + write_trace(entry, trace) + task_dir = Path(entry["dir"]) + empty = mods["empty_summary"](state_dir / "artifacts") + result = mods["grade_episode"]( + trace_path=trace, task=task, tasks_dir=TASKS, task_dir=task_dir, + grader=mods["get_grader"](task.task_id, tasks_dir=TASKS, task_dir=task_dir), + judge=judge, env_snapshot=None, artifact_before=empty, artifact_summary=empty, + expected_persistence_signal=entry["signal"]) + return float(result["task_score"]), result + + +def mean(values: List[float]) -> float: + return round(sum(values) / len(values), 4) if values else 0.0 + + +def score(unit, dir, transcript, answer, judge=None, **_): + """The family's buckets, and the number the run shows: the evaluation episodes' mean.""" + state = STATE.get(unit) + if state is None: + return {"reward": 0.0, "detail": {"reason": "no conversation", "dataset": DATASET_ID}} + try: + if state["index"] >= 0 and (not state["evidence"] or state["evidence"][-1]["index"] != state["index"]): + text = last_agent(transcript) + if text: + capture(state, text) + if not state["evidence"]: + return {"reward": 0.0, "detail": {"reason": "no episode was answered", "dataset": DATASET_ID}} + if not isinstance(judge, dict): + raise ValueError("PAST-Bench's graders need the judge route") + mods = upstream() + llm = mods["LLMJudge"](model_id=judge["model"], api_key=judge["key"], base_url=judge["base_url"]) + graded = [] + for entry in state["evidence"]: + item = {"stage": entry["stage"], "bucket": entry["bucket"], "label": entry["label"]} + try: + value, result = grade(entry, llm, state["state"]) + dimensions = result["scores"] + item.update({"score": round(value, 4), "completion": dimensions.get("completion"), + "robustness": dimensions.get("robustness"), "safety": dimensions.get("safety"), + "passed": result["passed"]}) + except Exception as exc: # one episode's grader failing is that episode's score + item.update({"score": 0.0, "error": f"{type(exc).__name__}: {exc}", + "trace": traceback.format_exc()[-1200:]}) + graded.append(item) + def by(prefix: str) -> List[float]: + return [g["score"] for g in graded if g["stage"] == prefix or g["stage"].startswith(prefix + "_")] + evaluation = [g["score"] for g in graded if g["bucket"] == "evaluation"] + cold, learn = by("cold"), by("learn") + near, far = by("eval_near"), by("eval_far") + controls = [g["score"] for g in graded if g["bucket"] == "control"] + reward = mean(evaluation if evaluation else [g["score"] for g in graded]) + lift = round(mean(evaluation) - cold[0], 4) if evaluation and cold else None + reuse = round(sum(1 for v in evaluation if v >= 0.5) / len(evaluation), 4) if evaluation else 0.0 + transfer = round(min(1.0, mean(far) / mean(near)), 4) if far and near and mean(near) > 0 else None + evolve = None + if lift is not None and transfer is not None: + evolve = round(max(0.0, lift) * reuse * transfer, 4) + return {"reward": reward, + "detail": {"family": state["family"], "arm": state["arm"], "dataset": state["dataset"], + "episodes": len(graded), "cold": mean(cold), "learn": mean(learn), + "eval_near": near, "eval_far": far, "control": mean(controls), + "lift": lift, "reuse": reuse, "transfer": transfer, + "evolve": evolve, "judge": judge.get("model"), + "graded": graded}, + "parts": {"n": len(graded), "by": "episode", + "parts": [{"n": i + 1, "text": g["label"], "group": g["bucket"], + "score": g["score"]} for i, g in enumerate(graded)]}} + finally: + if state.get("services") is not None: + state["services"].stop() + state["services"] = None + + +HANDLERS = {"units": units, "setup": setup, "turn": turn, "score": score} +# The publisher's graders print to stdout, which is this driver's JSON channel. +if __name__ == "__main__": + _REPLY = sys.stdout + sys.stdout = sys.stderr + for line in sys.stdin: + try: + request = json.loads(line) + result = HANDLERS[request.pop("op")](**request) + except Exception as exc: + result = {"error": f"{type(exc).__name__}: {exc}"} + print(json.dumps(result, ensure_ascii=False, default=str), file=_REPLY, flush=True) + _REPLY.flush() diff --git a/app/nullius/catalogue/benchmarks/past-bench/past_mcp.py b/app/nullius/catalogue/benchmarks/past-bench/past_mcp.py new file mode 100644 index 000000000..b05d9541d --- /dev/null +++ b/app/nullius/catalogue/benchmarks/past-bench/past_mcp.py @@ -0,0 +1,147 @@ +"""The current episode's tools, as a stdio MCP server: the benchmark's own tools. + +PAST-Bench hands every task its tools through the task file - a name, a JSON +schema and an HTTP endpoint - and its graders read the services' audit logs to +see what the agent actually did. The tools are therefore the benchmark's, not +the agent's, and this server is how they reach an agent that only speaks MCP: + + python past_mcp.py STATE_DIR + +STATE_DIR/current.json is written by the driver before each episode and names +that episode's tools, each one already rewritten to the port its mock service +got. This server reads it on every listing and every call, so a new session +sees the new episode's tools; a call is one POST to the endpoint, and both the +request and the answer are appended to STATE_DIR/dispatch.jsonl for the +grader's ``dispatches``. + +The protocol is the stdio transport of MCP: JSON-RPC 2.0, one object per line, +the server answering requests and staying silent on notifications. +""" +from __future__ import annotations + +import json +import re +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path + +STATE = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else Path(".").resolve() +CONTROL = STATE / "current.json" +DISPATCH = STATE / "dispatch.jsonl" +PROTOCOL = "2024-11-05" +_TAG = re.compile(r"[^A-Za-z0-9_-]") + + +def current() -> dict: + try: + return json.loads(CONTROL.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {"tools": []} + + +def tools() -> list: + """The episode's tools, in MCP's spelling, each remembering its own name.""" + out, seen = [], set() + for tool in current().get("tools") or []: + if not isinstance(tool, dict) or not tool.get("name"): + continue + name = _TAG.sub("_", str(tool["name"]))[:64] + while name in seen: + name = name[:-1] + "_" + seen.add(name) + out.append({"name": name, + "description": str(tool.get("description") or ""), + "inputSchema": tool.get("input_schema") or {"type": "object", "properties": {}}, + "_upstream": str(tool["name"]), "_url": str(tool.get("url") or ""), + "_method": str(tool.get("method") or "POST")}) + return out + + +def dispatch(kind: str, tool: dict, body, reply: dict, ms: float) -> None: + line = {"episode": current().get("episode"), "tool": tool.get("_upstream") or tool["name"], + "endpoint_url": tool.get("_url", ""), "request_body": body, + "response_status": reply.get("status", 200), "response_body": reply.get("body"), + "latency_ms": round(ms, 1), "at": time.strftime("%Y-%m-%dT%H:%M:%S"), "kind": kind} + try: + with DISPATCH.open("a", encoding="utf-8") as f: + f.write(json.dumps(line, ensure_ascii=False) + "\n") + except OSError: + pass + + +def post(url: str, method: str, body) -> dict: + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(url, data=data, method=method.upper(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=60) as r: + raw = r.read().decode("utf-8", "replace") + status = r.status + except urllib.error.HTTPError as e: + raw, status = e.read().decode("utf-8", "replace"), e.code + except Exception as e: # unreachable service: a failed call, not a dead session + return {"status": 599, "body": {"error": f"{type(e).__name__}: {e}"}} + try: + return {"status": status, "body": json.loads(raw)} + except ValueError: + return {"status": status, "body": raw[:4000]} + + +def call(params: dict) -> dict: + name = str(params.get("name") or "") + body = params.get("arguments") or {} + tool = next((t for t in tools() if t["name"] == name), None) + if tool is None: + return {"content": [{"type": "text", "text": json.dumps({"error": f"no tool {name!r} in this episode"})}], + "isError": True} + started = time.time() + reply = post(tool["_url"], tool["_method"], body) if tool["_url"] else \ + {"status": 404, "body": {"error": "the tool has no endpoint"}} + dispatch("tool_call", tool, body, reply, (time.time() - started) * 1000.0) + text = reply["body"] if isinstance(reply["body"], str) else json.dumps(reply["body"], ensure_ascii=False) + return {"content": [{"type": "text", "text": text}], "isError": reply["status"] >= 400} + + +def answer(request_id, result=None, error=None) -> None: + message = {"jsonrpc": "2.0", "id": request_id} + message.update({"result": result} if error is None else {"error": {"code": error[0], "message": error[1]}}) + sys.stdout.write(json.dumps(message, ensure_ascii=False) + "\n") + sys.stdout.flush() + + +def main() -> None: + STATE.mkdir(parents=True, exist_ok=True) + for line in sys.stdin: + line = line.strip() + if not line: + continue + try: + request = json.loads(line) + except ValueError: + continue + method = request.get("method") + request_id = request.get("id") + if request_id is None: # a notification: initialized, cancelled, ... + continue + try: + if method == "initialize": + answer(request_id, {"protocolVersion": PROTOCOL, + "capabilities": {"tools": {"listChanged": True}}, + "serverInfo": {"name": "past-bench", "version": "1.0"}}) + elif method == "tools/list": + answer(request_id, {"tools": [{k: v for k, v in t.items() if not k.startswith("_")} + for t in tools()]}) + elif method == "tools/call": + answer(request_id, call(request.get("params") or {})) + elif method == "ping": + answer(request_id, {}) + else: + answer(request_id, error=(-32601, f"unknown method {method!r}")) + except Exception as exc: + answer(request_id, error=(-32603, f"{type(exc).__name__}: {exc}")) + + +if __name__ == "__main__": + main() diff --git a/app/nullius/catalogue/benchmarks/past-bench/serve.py b/app/nullius/catalogue/benchmarks/past-bench/serve.py new file mode 100644 index 000000000..532e6570b --- /dev/null +++ b/app/nullius/catalogue/benchmarks/past-bench/serve.py @@ -0,0 +1,37 @@ +"""Run one of the upstream's mock services on a port this driver picks. + +The upstream starts each service as ``python mock_services//server.py`` +and relies on the service to read ``PORT``. Four of the eighteen do not, so the +driver starts them through this file instead: it loads the service's own module +(the app object, its fixtures, its audit log are the upstream's, untouched) and +serves that app on the port that was free when the driver looked. + + python serve.py REPO_ROOT mock_services/notes/server.py 41001 + +REPO_ROOT goes on ``sys.path`` first, because each service imports +``mock_services._base`` and reads its fixtures relative to the repository. +""" +import importlib.util +import sys +from pathlib import Path + + +def main(argv): + if len(argv) != 4: + raise SystemExit("usage: serve.py REPO_ROOT MODULE_PATH PORT") + repo, module, port = Path(argv[1]).resolve(), argv[2], int(argv[3]) + sys.path.insert(0, str(repo)) + spec = importlib.util.spec_from_file_location(f"mock_service_{port}", repo / module) + if spec is None or spec.loader is None: + raise SystemExit(f"cannot load {module}") + loaded = importlib.util.module_from_spec(spec) + spec.loader.exec_module(loaded) + app = getattr(loaded, "app", None) + if app is None: + raise SystemExit(f"{module} defines no FastAPI app") + import uvicorn + uvicorn.run(app, host="127.0.0.1", port=port, log_level="warning", access_log=False) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/app/nullius/catalogue/benchmarks/past-bench/services.py b/app/nullius/catalogue/benchmarks/past-bench/services.py new file mode 100644 index 000000000..8f4b4cb28 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/past-bench/services.py @@ -0,0 +1,201 @@ +"""The episode's mock services: one process each, on ports this driver picks. + +The upstream declares, in each ``task.yaml``, the services an episode needs and +the port each one usually listens on (``notes`` on 9105, ``gmail`` on 9100). +Two units of one run would collide on those fixed ports, so the driver asks the +kernel for a free port and rewrites the service's health check, reset endpoint +and tool endpoints to it. Everything else is the upstream's: its server file, +its fixtures, its audit log, its error injection. + +What the services record is also the benchmark's evidence: a grader reads +``audit`` to see whether a note was really shared with the named owners, not +merely described in the reply. ``audit()`` is therefore collected while the +services are still up, once per episode. +""" +from __future__ import annotations + +import json +import os +import socket +import subprocess +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path +from typing import Any, Dict, List, Optional + +HERE = Path(__file__).resolve().parent +SERVE = HERE / "serve.py" +READY_SECONDS = 60.0 + + +def _free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return int(s.getsockname()[1]) + + +def _with_port(url: str, port: int) -> str: + """The same URL on another port (the driver's), path and scheme unchanged.""" + from urllib.parse import urlsplit, urlunsplit + parts = urlsplit(url) + if not parts.scheme: + return url + netloc = parts.hostname or "127.0.0.1" + return urlunsplit((parts.scheme, f"{netloc}:{port}", parts.path, parts.query, parts.fragment)) + + +def call(url: str, method: str = "POST", body: Any = None, timeout: float = 10.0) -> Dict[str, Any]: + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(url, data=data, method=method.upper(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + raw = r.read().decode("utf-8", "replace") + status = r.status + except urllib.error.HTTPError as e: + raw, status = e.read().decode("utf-8", "replace"), e.code + except (urllib.error.URLError, OSError) as e: # not listening yet, or gone: the caller waits + return {"status": 599, "body": {"error": str(e)}} + try: + parsed = json.loads(raw) + except ValueError: + parsed = raw[:2000] + return {"status": status, "body": parsed} + + +class Service: + """One upstream mock service, one process, one port, this episode.""" + + def __init__(self, repo: Path, spec: Dict[str, Any], python: str): + self.repo = repo + self.spec = spec + self.python = python + self.name = str(spec.get("name") or "service") + self.port = _free_port() + self.process: Optional[subprocess.Popen] = None + self.log = None + + @property + def module(self) -> str: + """The upstream's ``command`` names the server file; take that part.""" + words = str(self.spec.get("command") or "").split() + for word in words: + if word.endswith(".py"): + return word + raise ValueError(f"{self.name}: the service command names no .py file") + + def env(self) -> Dict[str, str]: + out = dict(os.environ) + for key, value in (self.spec.get("env") or {}).items(): + text = str(value) + if text and not os.path.isabs(text) and "/" in text: + text = str(self.repo / text) # fixtures are written relative to the repository + out[str(key)] = text + out["PORT"] = str(self.port) + out["PYTHONUNBUFFERED"] = "1" + return out + + def start(self) -> None: + log_path = self.repo.parent / "logs" + self.process = subprocess.Popen( + [self.python, str(SERVE), str(self.repo), self.module, str(self.port)], + cwd=str(self.repo), env=self.env(), + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, start_new_session=True) + ready = self.spec.get("health_check") + timeout = max(float(self.spec.get("ready_timeout") or READY_SECONDS), 30.0) + deadline = time.time() + timeout + while time.time() < deadline: + if self.process.poll() is not None: + tail = (self.process.stderr.read() or "")[-800:] if self.process.stderr else "" + raise RuntimeError(f"{self.name}: the service exited at startup: {tail.strip()}") + if not ready: + time.sleep(0.5) + return + method = str(self.spec.get("health_check_method") or "GET").upper() + got = call(_with_port(str(ready), self.port), method, + {} if method == "POST" else None, timeout=5.0) + if got["status"] != 599: # any HTTP answer means it is up; 422 is still an answer + return + time.sleep(0.3) + raise RuntimeError(f"{self.name}: not ready in {int(timeout)} s on port {self.port}") + + def reset(self) -> None: + url = self.spec.get("reset_endpoint") + if url: + call(_with_port(str(url), self.port), "POST", {}) + + def audit(self) -> Dict[str, Any]: + url = self.spec.get("reset_endpoint") or self.spec.get("health_check") + if not url: + return {} + base = str(url).rsplit("/reset", 1)[0] + got = call(_with_port(base + "/audit", self.port), "GET", None) + return got["body"] if isinstance(got["body"], dict) else {"raw": got["body"]} + + def stop(self) -> None: + if self.process is None: + return + try: + self.process.terminate() + self.process.wait(timeout=5) + except Exception: + try: + self.process.kill() + except Exception: + pass + finally: + self.process = None + + +class Episode: + """The services one episode declares, started together and stopped together.""" + + def __init__(self, repo: Path, task: Dict[str, Any], python: str): + self.services: List[Service] = [] + for spec in task.get("services") or []: + if isinstance(spec, dict) and spec.get("command"): + self.services.append(Service(repo, spec, python)) + + def start(self) -> Dict[str, int]: + try: + for svc in self.services: + svc.start() + svc.reset() + except Exception: + self.stop() + raise + return {svc.name: svc.port for svc in self.services} + + def endpoints(self, ports: Dict[str, int]) -> Dict[str, str]: + """Tool endpoint URL -> the same URL on the port the service got.""" + out = {} + for svc in self.services: + out[svc.name] = svc.port + return out + + def audit(self) -> Dict[str, Any]: + return {svc.name: svc.audit() for svc in self.services} + + def stop(self) -> None: + for svc in self.services: + svc.stop() + self.services = [] + + +def rewrite(declared: str, services: List[Dict[str, Any]], ports: Dict[str, int]) -> str: + """An upstream endpoint URL, on the port its service actually got. + + The declaration pairs each service with its port (``port: 9105``), and the + tool endpoints name that port in their URLs; the driver looks the port up + and swaps it, so a service on 41001 is what ``localhost:9105`` means now. + """ + from urllib.parse import urlsplit + parts = urlsplit(declared) + if not parts.port: + return declared + for spec in services: + if int(spec.get("port") or 0) == parts.port and str(spec.get("name")) in ports: + return _with_port(declared, ports[str(spec["name"])]) + return declared diff --git a/app/nullius/catalogue/benchmarks/past-bench/standard.json b/app/nullius/catalogue/benchmarks/past-bench/standard.json new file mode 100644 index 000000000..b17083996 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/past-bench/standard.json @@ -0,0 +1,122 @@ +{ + "schema": "nullius.benchmark/v1", + "key": "past-bench", + "label": "PAST-Bench", + "summary": "Cross-session self-evolution: a family of episodes teaches a preference, rule or procedure, then later episodes ask for it in another situation, with the same family run without persistence as the control.", + "family": "agent", + "needs": [ + "agent.conversation/v1", + "agent.tools/v1", + "agent.workspace/v1" + ], + "upstream": { + "repository": "https://github.com/Gen-Verse/PAST-Bench", + "tested": "f8223517ae7491e776b69793d9f11e9d074ab42e", + "tested_date": "2026-11-23", + "license": "Apache-2.0" + }, + "driver": { + "command": [ + "{install}/.venv/bin/python", + "{here}/driver.py" + ], + "install": { + "python": "3.12", + "pip": [ + "pydantic==2.11.7", + "pyyaml==6.0.2", + "openai==1.109.1", + "httpx==0.28.1", + "fastapi==0.116.1", + "uvicorn==0.35.0", + "openpyxl==3.1.5", + "python-docx==1.2.0", + "python-pptx==1.0.2", + "pypdf==5.9.0" + ] + } + }, + "mcp_servers": { + "past": { + "command": [ + "{install}/.venv/bin/python", + "{here}/past_mcp.py" + ], + "summary": "The current episode's own tools: each one the task file's name, schema and mock-service endpoint, on the port the driver gave that service. It reads the driver's current.json for each listing and call, and writes every call and answer to the driver's dispatch log." + } + }, + "datasets": [ + { + "id": "past-bench", + "label": "All 26 families · persistence on", + "units": 26 + }, + { + "id": "past-bench-nop", + "label": "All 26 families · workspace reset per episode (workspace-only control)", + "units": 26 + }, + { + "id": "past-bench-isolated", + "label": "Evaluation episodes alone · 60 units, nothing carried over (the control)", + "units": 60 + }, + { + "id": "past-bench-memory", + "label": "Memory · 5 families", + "units": 5 + }, + { + "id": "past-bench-procedural", + "label": "Procedural reuse · 8 families", + "units": 8 + }, + { + "id": "past-bench-information-gathering", + "label": "Information gathering · 6 families", + "units": 6 + }, + { + "id": "past-bench-update", + "label": "Update · 7 families", + "units": 7 + }, + { + "id": "past-bench-smoke", + "label": "SM01 preference adoption · 1 family", + "units": 1 + }, + { + "id": "past-bench-smoke-isolated", + "label": "SM01 evaluation episodes alone · 2 units", + "units": 2 + }, + { + "id": "past-bench-smoke-nop", + "label": "SM01 preference adoption · persistence off", + "units": 1 + } + ], + "units": { + "noun": "family", + "nouns": "families" + }, + "controls": { + "nop": { + "source": "nullius", + "from": "No agent runs, so no episode is answered and every family scores nothing." + } + }, + "score": { + "kind": "score", + "says": "Each episode through the publisher's own grader for that episode, and the publisher's own composite: safety × (0.8 × completion + 0.2 × robustness). The family's reward is the mean of its evaluation episodes (eval_near and eval_far); the detail carries the cold baseline, the learn episodes, the control episodes, and the Layer-1 shape: lift (evaluation − cold), reuse (share of evaluation episodes at 0.5 or more), transfer (eval_far ÷ eval_near), and evolve (max(0, lift) × reuse × transfer).", + "judge": { + "model": "MiniMax-M2.7", + "says": "The judge the publisher's config.yaml and README name, with its own judge prompt and parsing (graders/llm_judge.py), at its default temperature 0, asked for the communication part of an episode's score. Graders that need no judge still call it, so a run needs a judge route." + } + }, + "limits": { + "turn_seconds": 900, + "turns": 32 + } +} \ No newline at end of file diff --git a/app/nullius/catalogue/benchmarks/past-bench/upstream-settings.json b/app/nullius/catalogue/benchmarks/past-bench/upstream-settings.json new file mode 100644 index 000000000..91a94ccce --- /dev/null +++ b/app/nullius/catalogue/benchmarks/past-bench/upstream-settings.json @@ -0,0 +1,198 @@ +[ + { + "entry": "config.yaml", + "setting": "judge.enabled", + "values": "true, false", + "default": "true", + "nullius": "fixed:true - every episode's communication part is judged" + }, + { + "entry": "config.yaml", + "setting": "judge.model_id", + "values": "any chat model", + "default": "google/gemini-2.5-flash - config.yaml pins MiniMax-M2.7", + "nullius": "not offered - the Nullius judge route names the model, declared as score.judge" + }, + { + "entry": "config.yaml", + "setting": "judge.base_url", + "values": "an OpenAI-compatible base URL", + "default": "https://openrouter.ai/api/v1 - config.yaml pins https://api.minimaxi.com/v1", + "nullius": "not offered - the judge route supplies its base URL" + }, + { + "entry": "config.yaml", + "setting": "judge.api_key", + "values": "an API key", + "default": "an API key - config.yaml leaves it empty", + "nullius": "not offered - the judge route supplies its key" + }, + { + "entry": "configs/self_evolve_v2/*_only.yaml", + "setting": "episodes.*.persistence_allowed", + "values": "true, false", + "default": "true", + "nullius": "fixed:the dataset's arm - past-bench keeps the workspace, past-bench-nop resets it before every episode" + }, + { + "entry": "configs/self_evolve_v2/*_only.yaml", + "setting": "episodes.*.requires_fresh_session", + "values": "true, false", + "default": "false", + "nullius": "fixed:as the publisher declares - the driver starts a new session where it is true" + }, + { + "entry": "configs/self_evolve_v2/*_only.yaml", + "setting": "episodes.*.shared_cold_run", + "values": "true, false", + "default": "false", + "nullius": "not offered - the driver keeps one workspace per family; the publisher's shared cold run is not applied" + }, + { + "entry": "configs/self_evolve_v2/*_only.yaml", + "setting": "episodes.*.history_mode", + "values": "continue, save, load", + "default": "continue", + "nullius": "fixed:as the publisher declares - the driver keeps, saves or loads the workspace at the anchor" + }, + { + "entry": "configs/self_evolve_v2/*_only.yaml", + "setting": "episodes.*.history_save_anchor", + "values": "an episode label, or empty", + "default": "", + "nullius": "fixed:as the publisher declares - the workspace saved when that episode ends" + }, + { + "entry": "configs/self_evolve_v2/*_only.yaml", + "setting": "episodes.*.history_load_anchor", + "values": "an episode label, or empty", + "default": "", + "nullius": "fixed:as the publisher declares - the workspace as it stood when the anchor was saved" + }, + { + "entry": "configs/self_evolve_v2/*_only.yaml", + "setting": "episodes.*.initial_home_fixture_dir", + "values": "a directory, or empty", + "default": "", + "nullius": "not offered - the home directory belongs to the agent under test" + }, + { + "entry": "configs/self_evolve_v2/*_only.yaml", + "setting": "episodes.*.preseed_artifacts_dir", + "values": "a directory, or empty", + "default": "", + "nullius": "not offered - the driver starts the episode from the task's own workspace" + }, + { + "entry": "configs/self_evolve_v2/*_only.yaml", + "setting": "episodes.*.stage", + "values": "cold, learn_a, eval_near, eval_far", + "default": "cold", + "nullius": "fixed:as the publisher declares - the episode's place in the family sequence" + }, + { + "entry": "configs/self_evolve_v2/*_only.yaml", + "setting": "episodes.*.bucket", + "values": "baseline, learn, control, evaluation", + "default": "baseline", + "nullius": "fixed:as the publisher declares - which part of the composite the episode feeds" + }, + { + "entry": "configs/self_evolve_v2/*_only.yaml", + "setting": "episodes.*.expected_persistence_signal", + "values": "a mechanism name", + "default": "none", + "nullius": "fixed:as the publisher declares, else the episode's mechanism - grade_episode reads it" + }, + { + "entry": "configs/self_evolve_v2/*_only.yaml", + "setting": "episodes.*.reflection_required", + "values": "true, false", + "default": "false", + "nullius": "not offered - the upstream sends a reflection only to an agent it has a persistence backend for (Hermes, nanobot, ZeroClaw); it sends none to any other agent, as here" + }, + { + "entry": "configs/agents.yaml", + "setting": "agents.*.default_model.model_id", + "values": "any chat model", + "default": "anthropic/claude-sonnet-4.6", + "nullius": "not offered - the agent under test brings its own model" + }, + { + "entry": "configs/agents.yaml", + "setting": "agents.*.default_model.api_key_env", + "values": "an environment variable name", + "default": "OPENROUTER_API_KEY", + "nullius": "not offered - the agent under test reaches the Nullius relay itself" + }, + { + "entry": "configs/agents.yaml", + "setting": "agents.*.default_model.base_url", + "values": "an OpenAI-compatible base URL", + "default": "https://openrouter.ai/api/v1", + "nullius": "not offered - the agent under test reaches the Nullius relay itself" + }, + { + "entry": "configs/agents.yaml", + "setting": "agents.*.install_policy", + "values": "prebaked, build", + "default": "prebaked", + "nullius": "not offered - the upstream's runner and its agents are not used" + }, + { + "entry": "src/past_bench/config.py", + "setting": "defaults.trace_dir", + "values": "a directory", + "default": "traces", + "nullius": "fixed:the unit's trace folder - written by the driver in the upstream trace shape" + }, + { + "entry": "src/past_bench/config.py", + "setting": "sandbox.enabled", + "values": "true, false", + "default": "false", + "nullius": "fixed:false - Nullius runs the agent under test, not the upstream's Docker sandbox" + }, + { + "entry": "src/past_bench/config.py", + "setting": "sandbox.image", + "values": "a Docker image", + "default": "past-bench-agent:latest", + "nullius": "not offered - the upstream's sandbox image is not used" + }, + { + "entry": "src/past_bench/config.py", + "setting": "sandbox.container_timeout", + "values": "seconds", + "default": "900", + "nullius": "not offered - the run's own limits apply (limits.turn_seconds)" + }, + { + "entry": "src/past_bench/config.py", + "setting": "runtime.mode", + "values": "container, local", + "default": "container", + "nullius": "not offered - the upstream's agent runtime is not used" + }, + { + "entry": "src/past_bench/config.py", + "setting": "runtime.temperature", + "values": "a decimal", + "default": "0.0", + "nullius": "not offered - the agent under test sets its own model arguments" + }, + { + "entry": "src/past_bench/config.py", + "setting": "runtime.server_port", + "values": "a port", + "default": "8090", + "nullius": "not offered - the upstream's agent runtime is not used" + }, + { + "entry": "src/past_bench/graders/llm_judge.py", + "setting": "temperature", + "values": "a decimal", + "default": "0.0", + "nullius": "fixed:0 - the publisher's own judge call, at its default temperature" + } +] diff --git a/app/nullius/catalogue/benchmarks/pi-bench/appworld_mcp.py b/app/nullius/catalogue/benchmarks/pi-bench/appworld_mcp.py new file mode 100644 index 000000000..b111e0c60 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/pi-bench/appworld_mcp.py @@ -0,0 +1,146 @@ +"""The persona's AppWorld tools, as the standard's stdio MCP server. + +The official Pi-Bench image carries AppWorld's API server and its MCP server. +This file starts one AppWorld API container per unit, then joins this process's +stdin and stdout to the upstream's own MCP server inside that container +(``appworld serve mcp stdio``) - the tools are the upstream's, not ours. + + python3 appworld_mcp.py CONTAINER UPSTREAM_DATA_DIR PERSONA [CALLS] + +With CALLS, each tool call and its answer are appended to that file as the +upstream's nanobot records them in a turn's ``tool_steps``: the name +``mcp_appworld_``, the arguments, and the answer's text blocks joined by +newlines. The upstream's tool-scored checklist items read nothing else. + +The container is created on first use, named CONTAINER, with UPSTREAM_DATA_DIR +(pinned upstream's ``data/``) mounted read-only at ``/opt/proactive/bench/data`` +so the persona's ``tools.yaml`` is the upstream's own. The image is +``zzzhr97/pi-bench@sha256:3bdb960745315514150e97e7e867110ed797a51e3ae1abec94634e473ee8e41a`` unless ``NULLIUS_PI_BENCH_IMAGE`` names another. +""" +import json +import os +import subprocess +import sys +import threading +import time + +IMAGE = os.environ.get("NULLIUS_PI_BENCH_IMAGE", "zzzhr97/pi-bench@sha256:3bdb960745315514150e97e7e867110ed797a51e3ae1abec94634e473ee8e41a") +API_PORT = 9000 +API_WAIT_SECONDS = 180 + + +def say(message): + print(f"[pi-bench appworld] {message}", file=sys.stderr, flush=True) + + +def docker(*args, **kwargs): + return subprocess.run(["docker", *args], text=True, capture_output=True, **kwargs) + + +def running(container): + got = docker("inspect", "--format", "{{.State.Running}}", container) + return got.returncode == 0 and got.stdout.strip() == "true" + + +def start(container, data_dir, persona): + """Create (or restart) the unit's AppWorld API container, then wait for its port.""" + if docker("image", "inspect", IMAGE).returncode != 0: + raise SystemExit(f"[pi-bench appworld] image {IMAGE} is not present: docker pull {IMAGE}") + docker("rm", "-f", container) + tools = f"/opt/proactive/bench/data/{persona}/tools.yaml" + command = ( + f"appworld serve apis --root /opt/proactive/appworld --port {API_PORT} " + ">/tmp/appworld-api.log 2>&1 & sleep infinity" + ) + got = docker( + "run", "-d", "--rm", "--name", container, "--entrypoint", "bash", + "-v", f"{data_dir}:/opt/proactive/bench/data:ro", + IMAGE, "-lc", command, + ) + if got.returncode != 0: + raise SystemExit(f"[pi-bench appworld] docker run failed: {got.stderr.strip()[-800:]}") + deadline = time.time() + API_WAIT_SECONDS + probe = ( + "python -c \"import socket; " + f"s=socket.create_connection(('127.0.0.1',{API_PORT}),1); s.close()\"" + ) + while time.time() < deadline: + if running(container) and docker("exec", container, "bash", "-lc", probe).returncode == 0: + if docker("exec", container, "test", "-f", tools).returncode != 0: + raise SystemExit(f"[pi-bench appworld] missing tools config in image: {tools}") + return + time.sleep(1.0) + log = docker("exec", container, "bash", "-lc", "tail -20 /tmp/appworld-api.log") + raise SystemExit(f"[pi-bench appworld] API did not answer in {API_WAIT_SECONDS}s: {log.stdout.strip()}") + + +def answer_text(result): + """The answer as nanobot's MCP tool returns it: text blocks joined by newlines.""" + parts = [] + for block in (result or {}).get("content") or []: + parts.append(block.get("text", "") if block.get("type") == "text" else str(block)) + return "\n".join(parts) or "(no output)" + + +def relay(command, calls): + """Pass MCP messages both ways, and write down each tools/call with its answer.""" + child = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + pending = {} + + def upstream(): + for line in sys.stdin.buffer: + try: + message = json.loads(line) + except ValueError: + message = None + if isinstance(message, dict) and message.get("method") == "tools/call" and "id" in message: + params = message.get("params") or {} + pending[json.dumps(message["id"])] = (str(params.get("name") or ""), params.get("arguments") or {}) + child.stdin.write(line) + child.stdin.flush() + child.stdin.close() + + threading.Thread(target=upstream, daemon=True).start() + for line in child.stdout: + sys.stdout.buffer.write(line) + sys.stdout.buffer.flush() + try: + message = json.loads(line) + except ValueError: + continue + call = pending.pop(json.dumps(message.get("id")), None) if isinstance(message, dict) else None + if call is None: + continue + result = message.get("result") if "result" in message else {"content": [ + {"type": "text", "text": json.dumps(message.get("error"))}]} + with open(calls, "a", encoding="utf-8") as f: + f.write(json.dumps({"name": f"mcp_appworld_{call[0]}", "arguments": call[1], + "result": answer_text(result)}, ensure_ascii=False) + "\n") + return child.wait() + + +def main(argv): + if len(argv) not in (4, 5): + raise SystemExit("usage: appworld_mcp.py CONTAINER UPSTREAM_DATA_DIR PERSONA [CALLS]") + container, data_dir, persona = argv[1], argv[2], argv[3] + if not os.path.isdir(data_dir): + raise SystemExit(f"[pi-bench appworld] no data directory: {data_dir}") + if not running(container): + say(f"starting {container} for {persona}") + start(container, data_dir, persona) + tools = f"/opt/proactive/bench/data/{persona}/tools.yaml" + say(f"serving {persona}'s tools from {container}") + command = [ + "docker", "exec", "-i", container, + "appworld", "serve", "mcp", "stdio", + "--root", "/opt/proactive/appworld", + "--remote-apis-url", f"http://127.0.0.1:{API_PORT}", + "--tools-config-file", tools, + ] + if len(argv) == 4: + os.execvp("docker", command) + raise SystemExit(relay(command, argv[4])) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/app/nullius/catalogue/benchmarks/pi-bench/benchmark.json b/app/nullius/catalogue/benchmarks/pi-bench/benchmark.json new file mode 100644 index 000000000..b18bdbd13 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/pi-bench/benchmark.json @@ -0,0 +1,102 @@ +{ + "key": "pi-bench", + "title": "Pi-Bench", + "category": "General assistance", + "domain": "Long-horizon personal-assistant work for five role personas: research, marketing, pharmacy, legal training and finance, with hidden intents and a persistent workspace.", + "scoring": "COMP + PROC", + "harness": [ + "standard" + ], + "origin": "official", + "good_to_know": [ + "A unit is one persona; its 20 tasks run in the upstream's episode order, share a workspace and use earlier tasks' artifacts. Run all five personas for the 100-task benchmark.", + "The user is the upstream's hidden-intent simulator: it probes for requirements the opening request does not state, so several turns per task are normal.", + "The reward is COMP, the upstream checklist score; PROC, the hidden-intent coverage score, is reported beside it in the job.", + "The persona's AppWorld tools come from the official image, one container per unit. The image's own nanobot harness is not used.", + "Pull zzzhr97/pi-bench@sha256:3bdb960745315514150e97e7e867110ed797a51e3ae1abec94634e473ee8e41a before a run: it supplies AppWorld for the tools. A machine without Docker can answer text-only turns but cannot use the persona's apps.", + "Pi-Bench declares a simulated user and a judge, so a provider key is needed before any run, including the nop control.", + "Scoring runs an LLM judge over every task's trace; give the score phase time with --timeout score=3600 when a full persona is evaluated." + ], + "upstream_limitations": [ + "The official harness ships its own nanobot agent and a Docker image; it exposes no interface for an arbitrary agent, and its leaderboard ranks models inside nanobot, so scores here do not compare with it. This entry substitutes the Nullius agent under test and uses the image only for AppWorld.", + "Twenty-four tasks declare AppWorld tool use and 27 score some checklist items on the agent's AppWorld calls; the rest still run in an AppWorld-backed persona and may use the persona's apps.", + "The benchmark has no published reference solution, so no oracle control is declared." + ], + "limitations": [ + "A unit is a whole persona, not one task: a run reports five units for 100 tasks, and a single persona is a dataset of its own.", + "The agent under test must prove AppWorld tools, conversation and a workspace; an agent without the tools port cannot run the tool tasks.", + "The official image's harness entrypoint is not used; the driver starts only its AppWorld API and serves the upstream's MCP server, so image-level harness changes are not picked up.", + "The judge reads each turn's final message: nanobot's messages between tool calls, which the upstream trace also shows, are not in the Nullius transcript. The AppWorld calls are recorded, for the checklist items scored on them." + ], + "datasets": [ + { + "key": "pi-bench", + "title": "All five personas · 100 tasks", + "tasks": 100, + "official": "https://github.com/Simplified-Reasoning/Pi-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The upstream's TraceEvaluationRunner: ChecklistEvaluator (COMP) and ProactivenessEvaluator (PROC) over each task's trace and the user simulator's logs.", + "notes": "The full benchmark: researcher, marketer, pharmacist, law_trainee and Financier, 20 tasks each." + }, + { + "key": "pi-bench-researcher", + "title": "Researcher · 20 tasks", + "tasks": 20, + "official": "https://github.com/Simplified-Reasoning/Pi-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The upstream's TraceEvaluationRunner over the researcher persona.", + "notes": "One persona's 20-task episode." + }, + { + "key": "pi-bench-marketer", + "title": "Marketer · 20 tasks", + "tasks": 20, + "official": "https://github.com/Simplified-Reasoning/Pi-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The upstream's TraceEvaluationRunner over the marketer persona.", + "notes": "One persona's 20-task episode." + }, + { + "key": "pi-bench-pharmacist", + "title": "Pharmacist · 20 tasks", + "tasks": 20, + "official": "https://github.com/Simplified-Reasoning/Pi-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The upstream's TraceEvaluationRunner over the pharmacist persona.", + "notes": "One persona's 20-task episode." + }, + { + "key": "pi-bench-law-trainee", + "title": "Law trainee · 20 tasks", + "tasks": 20, + "official": "https://github.com/Simplified-Reasoning/Pi-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The upstream's TraceEvaluationRunner over the law_trainee persona.", + "notes": "One persona's 20-task episode." + }, + { + "key": "pi-bench-financier", + "title": "Financier · 20 tasks", + "tasks": 20, + "official": "https://github.com/Simplified-Reasoning/Pi-Bench", + "source": "GitHub", + "registry": "", + "hub": "", + "verifier": "The upstream's TraceEvaluationRunner over the Financier persona.", + "notes": "One persona's 20-task episode." + } + ], + "task_count": 100, + "citation": "@misc{zhang2026pibenchevaluatingproactivepersonal,\n title={$\\pi$-Bench: Evaluating Proactive Personal Assistant Agents in Long-Horizon Workflows},\n author={Haoran Zhang and Luxin Xu and Zhilin Wang and Runquan Gui and Shunkai Zhang and Haodi Lei and Zihao He and Bingsu He and Chicheng Qin and Tong Zhu and Xiaoye Qu and Yang Yang and Yu Cheng and Yafu Li},\n year={2026},\n eprint={2605.14678},\n archivePrefix={arXiv},\n primaryClass={cs.AI},\n url={https://arxiv.org/abs/2605.14678}\n}", + "citation_source": "https://github.com/Simplified-Reasoning/Pi-Bench" +} diff --git a/app/nullius/catalogue/benchmarks/pi-bench/driver.py b/app/nullius/catalogue/benchmarks/pi-bench/driver.py new file mode 100644 index 000000000..c433d9613 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/pi-bench/driver.py @@ -0,0 +1,402 @@ +"""Pi-Bench (official, 100 tasks) on the Nullius standard. + +The benchmark is the publisher's: 100 multi-turn tasks across five personas, +20 tasks each, drawn out by the upstream's own hidden-intent user simulator and +scored by the upstream's own checklist and proactiveness evaluators. This +driver is glue only: + +units - the personas the chosen dataset names; a persona is one unit because + its tasks run in the upstream's episode order, share a workspace and + depend on earlier tasks +setup - the upstream's data checked, the unit's prompt, and the persona's + AppWorld tools as an MCP server (``appworld_mcp.py`` starts the + official image's API and serves the upstream's own ``appworld serve + mcp stdio``) +turn - the upstream's ``UserAgent`` and ``BenchmarkRunner`` in a thread of + this driver, its own hidden-intent simulator and termination rules; + the agent's final message in each turn is what the runner receives +score - the unit's turns written in the upstream nanobot trace-log shape, then + the upstream's ``TraceEvaluationRunner`` (checklist + proactiveness) + run over them; COMP is the reward, PROC is reported beside it + +The official harness's nanobot agent is not used: the Nullius agent under test +takes its place, with the persona's AppWorld tools over MCP. The official +Docker image provides AppWorld, not the agent. +""" +import asyncio +import glob +import hashlib +import json +import os +import queue +import sys +import threading +import time +from datetime import datetime +from pathlib import Path + +UPSTREAM = Path(os.environ["NULLIUS_UPSTREAM"]) +DATA = UPSTREAM / "data" +HERE = Path(__file__).resolve().parent +HISTORY = UPSTREAM / "config" / "bench" / "evaluation" / "trace_history.yaml" +MODEL_ID = "nullius" # the trace/log folder: one driver, one run +STATE = {} +DATASET_ID = "pi-bench" +PERSONAS = ["researcher", "marketer", "pharmacist", "law_trainee", "Financier"] +DATASETS = { + "pi-bench": PERSONAS, + "pi-bench-researcher": ["researcher"], + "pi-bench-marketer": ["marketer"], + "pi-bench-pharmacist": ["pharmacist"], + "pi-bench-law-trainee": ["law_trainee"], + "pi-bench-financier": ["Financier"], +} +INSTRUCTION = ( + "You are the user's personal assistant in a long-horizon session. The user speaks in turns; " + "your final message in each turn is sent to them, and earlier turns stay in the conversation. " + "The AppWorld tools given to this session are your tools; your workspace is shared across the session. " + "Work the request to completion, and end each turn with what the user should know." +) +TURN_WAIT = 580 # a turn request's own limit is 600 s; leave the driver a margin +STOP = object() + + +class Stop(BaseException): + """The unit is being scored: end the upstream loop, do not try again.""" + + +def repository(): + from src.data import UserDataRepository + return UserDataRepository(data_root=str(DATA)) + + +def persona_tasks(persona): + profile, episode, tasks = repository().load_user(persona) + order = list(episode.task_order) + if len(order) != 20 or len(set(order)) != 20: + raise ValueError(f"{persona}: the upstream episode must name 20 distinct tasks, found {len(order)}") + missing = [task_id for task_id in order if task_id not in tasks] + if missing: + raise ValueError(f"{persona}: task files missing for {', '.join(missing)}") + return order + + +def units(dataset, setup=None): + global DATASET_ID + if dataset not in DATASETS: + raise ValueError(f"unknown Pi-Bench dataset {dataset!r}") + DATASET_ID = dataset + chosen = DATASETS[dataset] + for persona in chosen: + persona_tasks(persona) + return {"units": list(chosen)} + + +def setup(unit, dir): + persona = unit + if persona not in PERSONAS: + raise ValueError(f"unknown Pi-Bench persona {persona!r}") + order = persona_tasks(persona) + absolute = os.path.abspath(dir) + token = hashlib.sha256(f"{persona}:{os.getpid()}:{time.time()}".encode()).hexdigest()[:12] + out = os.path.join(os.path.dirname(absolute), f"pi-bench-{token}") + os.makedirs(out, exist_ok=True) + container = f"nullius-pi-{token}" + STATE[persona] = { + "persona": persona, "dir": absolute, "out": out, "trace": os.path.join(out, "trace_logs"), + "dataset": DATASET_ID, "container": container, "tasks": order, + "messages": {}, "session": {}, "turn_no": {}, "current": None, + "calls": os.path.join(out, "tool_calls.jsonl"), "calls_at": 0, + "in_q": queue.Queue(), "out_q": queue.Queue(), + "user_agent": None, "runner": None, "thread": None, "done": False, + } + return { + "prompt": INSTRUCTION, + "agent_seconds": 21600, + "mcp": [{"name": "appworld", "server": "appworld", + "args": [container, str(DATA), persona, os.path.join(out, "tool_calls.jsonl")]}], + } + + +class Bridge: + """The upstream's channel, with Nullius on the other side: what the runner + sends is ``turn``'s answer; what the agent says is put into ``in_q``.""" + + def __init__(self, state): + self.s = state + + async def connect(self): + return None + + async def disconnect(self): + return None + + async def send(self, message): + if message == "/new": # the runner's task reset, not a user message + return + task = self.s["current"] + if task is None: + raise RuntimeError("the upstream sent a message with no active task") + self.s["messages"].setdefault(task, []).append({"role": "user", "content": message}) + self.s["out_q"].put(("message", message)) + + async def wait_for_reply(self, timeout=None): + reply = await asyncio.wait_for(asyncio.to_thread(self.s["in_q"].get), timeout) + if reply is STOP: + raise Stop() + return reply + + async def reset(self): + return None + + def set_runtime_identity(self, *, sender_id, chat_id): + task = str(chat_id or "") + if not task: + return + if task != self.s["current"]: + self.s["current"] = task + self.s["session"].setdefault(task, datetime.now().strftime("%Y%m%d_%H%M%S")) + + +def start_runner(state, simulator): + from src.llm import LLMClient + from src.runner.runner import BenchmarkRunner + from src.user_agent.user_agent import UserAgent + + # The upstream's DEFAULT_MODEL_CONFIG["user_agent"], with the run's route. + llm = LLMClient(model=simulator["model"], base_url=simulator["base_url"], + api_key=simulator["key"], temperature=0.0, + request_timeout=360.0, max_concurrency=32, max_retries=4) + agent = UserAgent( + user_root=str(DATA / state["persona"]), llm_client=llm, repository=repository(), task_ids=None, + output_root=state["out"], model_id=MODEL_ID, workspace_dir=state["dir"], + copy_task_assets_to_workspace=True, history_config_path=str(HISTORY), + ) + runner = BenchmarkRunner(channel=Bridge(state), user_agent=agent, + max_turns=30, turn_timeout=2400.0) + state["user_agent"], state["runner"] = agent, runner + + def run(): + try: + state["result"] = asyncio.run(runner.run()) + state["done"] = True + state["out_q"].put(("done", None)) + except Stop: + return + except BaseException as exc: # the unit's error, said to Nullius + if not state.get("stopping"): + state["out_q"].put(("error", f"{type(exc).__name__}: {exc}")) + + state["thread"] = threading.Thread(target=run, daemon=True, name=f"pi-bench-{state['persona']}") + state["thread"].start() + + +def last_agent(transcript): + for item in reversed(transcript or []): + if item.get("role") == "agent": + return str(item.get("text") or "") + raise ValueError("the turn carries no agent message") + + +def new_tool_steps(state): + """The AppWorld calls the agent made since the last turn, as nanobot's tool_steps.""" + try: + with open(state["calls"], encoding="utf-8") as f: + lines = f.readlines() + except OSError: + return [] + steps = [] + for line in lines[state["calls_at"]:]: + try: + steps.append(json.loads(line)) + except ValueError: + continue + state["calls_at"] = len(lines) + return steps + + +def write_turn(state, task, force=False, steps=()): + messages = state["messages"].get(task) or [] + if not force and not any(message.get("role") == "assistant" for message in messages): + return + if not messages: + return + number = state["turn_no"].get(task, 0) + 1 + state["turn_no"][task] = number + folder = Path(state["trace"]) / MODEL_ID / state["persona"] / task / state["session"][task] + folder.mkdir(parents=True, exist_ok=True) + output = next((message["content"] for message in reversed(messages) + if message.get("role") == "assistant"), "") + payload = { + "session_key": f"{state['persona']}:{task}", + "session_started_at": state["session"][task], + "channel": "nullius", "chat_id": task, "sender_id": state["persona"], + "model": MODEL_ID, "input": messages[0].get("content", ""), + "messages": messages, "llm_steps": [], "tool_steps": list(steps), + "output": output, "iterations": 1, "tools_used": sorted({step["name"] for step in steps}), + } + (folder / f"turn_{number:04d}.json").write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") + + +def ensure_task_records(state): + """Every episode task needs a turn file and the user simulator's side logs. + + The upstream proactiveness evaluator walks the whole episode order and + refuses a task with no turn history. A unit the agent left early (its + timeout, an error) therefore gets its opening request recorded, with no + answer, and scores nothing for itself rather than failing the evaluation. + """ + _, _, tasks = repository().load_user(state["persona"]) + history = Path(state["out"]) / MODEL_ID / state["persona"] + for task in state["tasks"]: + state["session"].setdefault(task, datetime.now().strftime("%Y%m%d_%H%M%S")) + messages = state["messages"].setdefault(task, []) + if not messages: + messages.append({"role": "user", "content": tasks[task].initial_input}) + if not glob.glob(str(Path(state["trace"]) / MODEL_ID / state["persona"] / task / "*" / "turn_*.json")): + write_turn(state, task, force=True) + folder = history / task / "history" + folder.mkdir(parents=True, exist_ok=True) + stamp = state["session"][task] + if not list(folder.glob("*-messages.jsonl")): + message_path = folder / f"{stamp}-messages.jsonl" + with message_path.open("w", encoding="utf-8") as f: + for index, message in enumerate(messages, start=1): + f.write(json.dumps({ + "task_id": task, "agent_id": MODEL_ID, "round": index, + "role": message.get("role"), "message": message.get("content", ""), + "chars": len(message.get("content", "")), "timestamp": stamp, + "timestamp_iso": stamp, + }, ensure_ascii=False) + "\n") + if not list(folder.glob("*-log.jsonl")): + (folder / f"{stamp}-log.jsonl").write_text("", encoding="utf-8") + + +def wait_out(state, timeout=TURN_WAIT): + try: + kind, value = state["out_q"].get(timeout=timeout) + except queue.Empty: + raise TimeoutError(f"the upstream user simulator did not answer in {timeout} s") from None + if kind == "error": + raise RuntimeError(value) + if kind == "done": + return {"done": True} + return {"message": value} + + +def turn(unit, dir, transcript, simulator=None, judge=None, attempt=None): + state = STATE.get(unit) + if state is None: + raise ValueError(f"turn before setup for {unit!r}") + if state["runner"] is None: + if not isinstance(simulator, dict): + raise ValueError("Pi-Bench needs a simulated user: the run must give the simulator route") + start_runner(state, simulator) + return wait_out(state) + reply = last_agent(transcript) + task = state["current"] + if task is None: + raise RuntimeError("the upstream runner has no active task") + state["messages"].setdefault(task, []).append({"role": "assistant", "content": reply}) + write_turn(state, task, steps=new_tool_steps(state)) + state["in_q"].put(reply) + return wait_out(state) + + +def task_parts(state): + root = Path(state["out"]) / MODEL_ID / state["persona"] + latest = {} + for path in glob.glob(str(root / "*" / "eval" / "results" / "*_result.json")): + try: + payload = json.loads(Path(path).read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + task = payload.get("task") or {} + task_id = task.get("task_id") or Path(path).parents[2].name + latest[task_id] = payload + parts = [] + for task_id in sorted(latest): + task = latest[task_id]["task"] + comp = (task.get("checklist") or {}).get("average_score") + proc = (task.get("proactiveness") or {}).get("average_score") + score = comp if comp is not None else proc + if score is None: + continue + parts.append({"n": len(parts) + 1, "text": task_id, + "group": "checklist" if comp is not None else "proactiveness", + "score": round(float(score), 6)}) + return parts + + +def stop_runner(state): + state["stopping"] = True + state["in_q"].put(STOP) + thread = state.get("thread") + if thread is not None and thread.is_alive(): + thread.join(timeout=2) + + +def cleanup(state): + stop_runner(state) + name = state.get("container") + if not name: + return + try: + import subprocess + subprocess.run(["docker", "rm", "-f", name], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, check=False) + except OSError: + pass + + +def score(unit, dir, transcript, answer, judge=None, **_): + state = STATE.get(unit) + if state is None or state["runner"] is None: + return {"reward": 0.0, "detail": {"reason": "no conversation", "dataset": DATASET_ID}} + try: + if not any(any(message.get("role") == "assistant" for message in messages) + for messages in state["messages"].values()): + return {"reward": 0.0, "detail": {"reason": "no turn was completed", "dataset": DATASET_ID}} + if not isinstance(judge, dict): + raise ValueError("Pi-Bench's checklist evaluator needs the judge route") + ensure_task_records(state) + from src.evaluation import TraceEvaluationRunner + from src.llm import LLMClient + + # The upstream's DEFAULT_MODEL_CONFIG["judger"], with the run's route. + llm = LLMClient(model=judge["model"], base_url=judge["base_url"], api_key=judge["key"], + temperature=0.0, request_timeout=360.0, max_concurrency=128, max_retries=4, + reasoning_effort="high") + evaluator = TraceEvaluationRunner( + model_id=MODEL_ID, user_id=state["persona"], logs_dir=Path(state["trace"]), + workspace_dir=Path(state["dir"]), config_path=HISTORY, output_dir=Path(state["out"]), + scoring="both", llm_client=llm, data_root=DATA, + ) + result = asyncio.run(evaluator.run()) + comp = result.overall_average_score + proc = result.overall_proactiveness_average_score + parts = task_parts(state) + reward = comp if comp is not None else (proc if proc is not None else 0.0) + return {"reward": float(reward), + "detail": {"comp": comp, "proc": proc, "tasks": len(parts), + "persona": state["persona"], "judge": judge.get("model"), + "dataset": state["dataset"]}, + **({"parts": {"n": len(parts), "by": "task", "parts": parts}} if parts else {})} + finally: + cleanup(state) + + +HANDLERS = {"units": units, "setup": setup, "turn": turn, "score": score} +# The upstream logs to stdout, which is this driver's JSON channel: everything +# else goes to stderr, the real stdout carries replies only. +if __name__ == "__main__": + _REPLY = sys.stdout + sys.stdout = sys.stderr + for line in sys.stdin: + try: + request = json.loads(line) + result = HANDLERS[request.pop("op")](**request) + except Exception as exc: + result = {"error": f"{type(exc).__name__}: {exc}"} + print(json.dumps(result, ensure_ascii=False), file=_REPLY, flush=True) + _REPLY.flush() diff --git a/app/nullius/catalogue/benchmarks/pi-bench/proofs.json b/app/nullius/catalogue/benchmarks/pi-bench/proofs.json new file mode 100644 index 000000000..cc1a1e350 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/pi-bench/proofs.json @@ -0,0 +1,107 @@ +{ + "schema": "nullius.proofs/v1", + "kind": "benchmark", + "key": "pi-bench", + "versions": { + "": { + "proven": { + "pi-bench": { + "units": { + "units": 5, + "passed": "5 ids, the same twice, unique" + }, + "nop": { + "passed": "0/5", + "value": 0.0, + "expect": { + "at_most": 0.0 + }, + "units": 5, + "source": "nullius", + "judge": "gpt-5.4" + } + }, + "pi-bench-researcher": { + "units": { + "units": 1, + "passed": "1 ids, the same twice, unique" + }, + "nop": { + "passed": "0/1", + "value": 0.0, + "expect": { + "at_most": 0.0 + }, + "units": 1, + "source": "nullius", + "judge": "gpt-5.4" + } + }, + "pi-bench-marketer": { + "units": { + "units": 1, + "passed": "1 ids, the same twice, unique" + }, + "nop": { + "passed": "0/1", + "value": 0.0, + "expect": { + "at_most": 0.0 + }, + "units": 1, + "source": "nullius", + "judge": "gpt-5.4" + } + }, + "pi-bench-pharmacist": { + "units": { + "units": 1, + "passed": "1 ids, the same twice, unique" + }, + "nop": { + "passed": "0/1", + "value": 0.0, + "expect": { + "at_most": 0.0 + }, + "units": 1, + "source": "nullius", + "judge": "gpt-5.4" + } + }, + "pi-bench-law-trainee": { + "units": { + "units": 1, + "passed": "1 ids, the same twice, unique" + }, + "nop": { + "passed": "0/1", + "value": 0.0, + "expect": { + "at_most": 0.0 + }, + "units": 1, + "source": "nullius", + "judge": "gpt-5.4" + } + }, + "pi-bench-financier": { + "units": { + "units": 1, + "passed": "1 ids, the same twice, unique" + }, + "nop": { + "passed": "0/1", + "value": 0.0, + "expect": { + "at_most": 0.0 + }, + "units": 1, + "source": "nullius", + "judge": "gpt-5.4" + } + } + } + } + } +} diff --git a/app/nullius/catalogue/benchmarks/pi-bench/standard.json b/app/nullius/catalogue/benchmarks/pi-bench/standard.json new file mode 100644 index 000000000..ae94140c1 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/pi-bench/standard.json @@ -0,0 +1,95 @@ +{ + "schema": "nullius.benchmark/v1", + "key": "pi-bench", + "label": "Pi-Bench", + "summary": "Long-horizon personal-assistant work across five role personas; the upstream's hidden-intent user simulator and checklist/proactiveness evaluators score the whole episode.", + "family": "agent", + "needs": [ + "agent.tools/v1", + "agent.conversation/v1", + "agent.workspace/v1" + ], + "upstream": { + "repository": "https://github.com/Simplified-Reasoning/Pi-Bench", + "tested": "4f545be5d289b28ff022d2904d455007358ed3b7", + "tested_date": "2026-10-13", + "license": "Apache-2.0" + }, + "driver": { + "command": [ + "{install}/.venv/bin/python", + "{here}/driver.py" + ], + "install": { + "python": "3.12", + "project": "." + } + }, + "mcp_servers": { + "appworld": { + "command": [ + "{install}/.venv/bin/python", + "{here}/appworld_mcp.py" + ], + "summary": "The persona's AppWorld tools: the official image's API server and the upstream's own appworld serve mcp stdio, one container per unit." + } + }, + "datasets": [ + { + "id": "pi-bench", + "label": "All five personas · 100 tasks", + "units": 5 + }, + { + "id": "pi-bench-researcher", + "label": "Researcher · 20 tasks", + "units": 1 + }, + { + "id": "pi-bench-marketer", + "label": "Marketer · 20 tasks", + "units": 1 + }, + { + "id": "pi-bench-pharmacist", + "label": "Pharmacist · 20 tasks", + "units": 1 + }, + { + "id": "pi-bench-law-trainee", + "label": "Law trainee · 20 tasks", + "units": 1 + }, + { + "id": "pi-bench-financier", + "label": "Financier · 20 tasks", + "units": 1 + } + ], + "units": { + "noun": "persona", + "nouns": "personas" + }, + "controls": { + "nop": { + "source": "nullius", + "from": "Nullius: no agent runs, so no conversation or workspace exists to evaluate and every task scores nothing." + } + }, + "simulator": { + "model": "gpt-5.4", + "says": "the persona: the upstream's own user simulator (src/user_agent/user_agent.py), its hidden-intent satisfaction and targeted-followup prompts, at its default temperature 0" + }, + "score": { + "kind": "score", + "says": "the upstream's own TraceEvaluationRunner over the episode: ChecklistEvaluator's weighted checklist score is COMP (the reward); ProactivenessEvaluator's hidden-intent coverage is PROC, reported beside it. A task without a checklist contributes to PROC only; a task whose trace the evaluator cannot build is left out, as upstream leaves it out", + "judge": { + "model": "gpt-5.4", + "says": "the upstream's checklist judge: ChecklistEvaluator's own prompt and parsing, at its default temperature 0, asked over each task's rendered trace" + } + }, + "limits": { + "turn_seconds": 2400, + "turns": 600 + } +} diff --git a/app/nullius/catalogue/benchmarks/pi-bench/upstream-settings.json b/app/nullius/catalogue/benchmarks/pi-bench/upstream-settings.json new file mode 100644 index 000000000..bc4d888b2 --- /dev/null +++ b/app/nullius/catalogue/benchmarks/pi-bench/upstream-settings.json @@ -0,0 +1,156 @@ +[ + { + "entry": "config/models/example.full.yaml", + "setting": "model.model", + "values": "any chat model", + "default": "provider/model-name", + "nullius": "not offered - the agent under test brings its own model" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "model.base_url", + "values": "an OpenAI-compatible base URL", + "default": "${MODEL_BASE_URL}", + "nullius": "not offered - the agent under test reaches the Nullius relay itself" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "model.max_tool_iterations", + "values": "a whole number", + "default": "120", + "nullius": "not offered - the agent's own loop sets its iteration bound" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "model.memory_window", + "values": "a whole number", + "default": "100", + "nullius": "not offered - the agent's own memory is outside the benchmark" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "user_agent.model", + "values": "any chat model", + "default": "gpt-5.4", + "nullius": "fixed:gpt-5.4 - the upstream simulator's default, declared as simulator" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "user_agent.temperature", + "values": "a decimal", + "default": "0.0", + "nullius": "fixed:0.0 - the upstream simulator's default" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "user_agent.max_concurrency", + "values": "a whole number", + "default": "32", + "nullius": "fixed:32 - the upstream simulator's default" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "judger.model", + "values": "any chat model", + "default": "gpt-5.4", + "nullius": "fixed:gpt-5.4 - the upstream checklist judge's default, declared as score.judge" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "judger.temperature", + "values": "a decimal", + "default": "0.0", + "nullius": "fixed:0.0 - the upstream checklist judge's default" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "judger.reasoning_effort", + "values": "null, low, medium, high", + "default": "high", + "nullius": "fixed:high - the upstream checklist judge's default" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "tools.brave_search_api_key", + "values": "a Brave Search API key", + "default": "${BRAVE_SEARCH_API_KEY}", + "nullius": "not offered - the agent uses its own tools; AppWorld supplies the persona's apps" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "tools.web_search_max_results", + "values": "a whole number", + "default": "10", + "nullius": "not offered - the agent's own web tool decides its result count" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "nanobot.trace_logs_dir", + "values": "a directory", + "default": "~/.nanobot/trace_logs", + "nullius": "fixed:the unit's trace folder - written by the driver in the upstream turn-file shape" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "nanobot.workspace_dir", + "values": "a directory", + "default": "~/.nanobot/workspace", + "nullius": "fixed:the unit workspace - the agent and the upstream user simulator share it" + }, + { + "entry": "config/models/example.full.yaml", + "setting": "nanobot.heartbeat_enabled", + "values": "true, false", + "default": "true", + "nullius": "not offered - the benchmark's turns drive the session" + }, + { + "entry": "src/runtime/model_config.py", + "setting": "run.user_id", + "values": "one of the five persona ids", + "default": "law_trainee", + "nullius": "fixed:the dataset's persona - each dataset names one persona" + }, + { + "entry": "src/runtime/model_config.py", + "setting": "run.task_ids", + "values": "a list of task ids", + "default": "[] - the episode's order", + "nullius": "fixed:the episode order - the upstream runner reads it from the persona's episode.yaml" + }, + { + "entry": "src/runtime/model_config.py", + "setting": "run.scoring", + "values": "checklist, proactiveness, both", + "default": "both", + "nullius": "fixed:both - the upstream's COMP and PROC" + }, + { + "entry": "src/runtime/model_config.py", + "setting": "run.turn_timeout", + "values": "seconds", + "default": "2400.0", + "nullius": "fixed:2400 - the upstream simulator's per-turn limit" + }, + { + "entry": "src/runtime/model_config.py", + "setting": "run.user_mode", + "values": "llm, terminal", + "default": "llm", + "nullius": "fixed:llm - the upstream hidden-intent simulator" + }, + { + "entry": "config/bench/evaluation/trace_history.yaml", + "setting": "messages.include_assistant_tool_calls", + "values": "true, false", + "default": "false", + "nullius": "fixed:false - the upstream trace configuration renders messages, not tool calls" + }, + { + "entry": "src/docker_launcher.py", + "setting": "IMAGE_NAME", + "values": "a Docker image", + "default": "zzzhr97/pi-bench:latest", + "nullius": "fixed:zzzhr97/pi-bench@sha256:3bdb960745315514150e97e7e867110ed797a51e3ae1abec94634e473ee8e41a, the digest :latest names at the pin - the AppWorld service image, overridable by NULLIUS_PI_BENCH_IMAGE" + } +] diff --git a/app/static/catalogue/marks.svg b/app/static/catalogue/marks.svg index 8aea777fc..8734f3f78 100644 --- a/app/static/catalogue/marks.svg +++ b/app/static/catalogue/marks.svg @@ -35,6 +35,14 @@ + + + + + + + + diff --git a/app/tests/test_catalog.py b/app/tests/test_catalog.py index f26e9cd48..ab711d066 100644 --- a/app/tests/test_catalog.py +++ b/app/tests/test_catalog.py @@ -33,7 +33,7 @@ def test_shipped_catalogue_is_consistent(self): self.assertEqual(titles, sorted(titles, key=catalog.sort_key)) # what has a usable route is listed, whoever made it and whether or not it has run listed = {x.key for x in cat.listed_benchmarks} - self.assertEqual(sorted(listed), ["gaia", "gsm8k", "healthagentbench", "humaneval", "locomo", "longmemeval", "medagentbench", "open-telco", "osworld1", "osworld2", "swe-bench-verified", "tau3-bench", "terminal-bench", "vitabench"]) + self.assertEqual(sorted(listed), ["gaia", "gsm8k", "healthagentbench", "humaneval", "locomo", "longmemeval", "medagentbench", "open-telco", "osworld1", "osworld2", "past-bench", "pi-bench", "swe-bench-verified", "tau3-bench", "terminal-bench", "vitabench"]) self.assertEqual((cat.benchmark("longmemeval").origin, cat.benchmark("longmemeval").label), ("official", "Official")) self.assertEqual(cat.benchmark("tau3-bench").label, "Official") # τ³ files as "t3…", before "te…": a reader looking under T finds it diff --git a/app/tests/test_pi_bench_driver.py b/app/tests/test_pi_bench_driver.py new file mode 100644 index 000000000..82520d913 --- /dev/null +++ b/app/tests/test_pi_bench_driver.py @@ -0,0 +1,136 @@ +"""Pi-Bench's official entry: the persona units, the setup reply and the trace glue. + +No Docker, no model call and no upstream install: the data repository is +stubbed, and only the shapes the standard's driver has to honour are checked. +""" +import importlib.util +import json +import os +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace +import tempfile +import unittest +from unittest.mock import patch + + +DRIVER = Path(__file__).resolve().parents[1] / "nullius/catalogue/benchmarks/pi-bench/driver.py" + + +class PiBenchDriver(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="nullius-pi-bench-") + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + upstream = self.root / "upstream" + (upstream / "data").mkdir(parents=True) + (upstream / "config" / "bench" / "evaluation").mkdir(parents=True) + with patch.dict(os.environ, {"NULLIUS_UPSTREAM": str(upstream)}): + spec = importlib.util.spec_from_file_location("nullius_test_pi_bench_driver", DRIVER) + self.driver = importlib.util.module_from_spec(spec) + spec.loader.exec_module(self.driver) + self.tasks = [f"{persona}_task_{i:03d}" for persona in self.driver.PERSONAS for i in range(1, 21)] + self.repository = SimpleNamespace(load_user=self.load_user) + self.driver.repository = lambda: self.repository + + def load_user(self, persona): + order = [f"{persona}_task_{i:03d}" for i in range(1, 21)] + return SimpleNamespace(), SimpleNamespace(task_order=order), {task_id: object() for task_id in order} + + def test_units_are_the_personas_the_dataset_names(self): + self.assertEqual(self.driver.units("pi-bench"), {"units": self.driver.PERSONAS}) + self.assertEqual(self.driver.units("pi-bench-researcher"), {"units": ["researcher"]}) + self.assertEqual(self.driver.units("pi-bench-law-trainee"), {"units": ["law_trainee"]}) + with self.assertRaisesRegex(ValueError, "unknown Pi-Bench dataset"): + self.driver.units("not-a-dataset") + + def test_setup_returns_the_persona_tools_and_a_long_agent_budget(self): + got = self.driver.setup("researcher", str(self.root / "workspace")) + self.assertIn("personal assistant", got["prompt"]) + self.assertEqual(got["agent_seconds"], 21600) + self.assertEqual(got["mcp"][0]["server"], "appworld") + self.assertEqual(got["mcp"][0]["args"][2], "researcher") + state = self.driver.STATE["researcher"] + self.assertEqual(state["tasks"], [f"researcher_task_{i:03d}" for i in range(1, 21)]) + self.assertTrue(Path(state["out"]).is_dir()) + + def test_turn_before_setup_is_refused(self): + with self.assertRaisesRegex(ValueError, "turn before setup"): + self.driver.turn("nobody", str(self.root), []) + + def test_a_turn_without_the_simulator_route_is_refused(self): + self.driver.setup("researcher", str(self.root / "workspace")) + with self.assertRaisesRegex(ValueError, "simulated user"): + self.driver.turn("researcher", str(self.root / "workspace"), []) + + def test_score_without_a_conversation_is_zero(self): + self.driver.setup("researcher", str(self.root / "workspace")) + got = self.driver.score("researcher", str(self.root / "workspace"), [], "") + self.assertEqual(got["reward"], 0.0) + self.assertIn("no conversation", got["detail"]["reason"]) + + def test_the_last_agent_message_is_the_turn_reply(self): + transcript = [{"role": "user", "text": "hello"}, + {"role": "agent", "text": "first"}, + {"role": "user", "text": "more"}, + {"role": "agent", "text": "second"}] + self.assertEqual(self.driver.last_agent(transcript), "second") + with self.assertRaisesRegex(ValueError, "no agent message"): + self.driver.last_agent([{"role": "user", "text": "hello"}]) + + def test_a_turn_file_is_written_in_the_upstream_shape(self): + self.driver.setup("researcher", str(self.root / "workspace")) + state = self.driver.STATE["researcher"] + task = state["tasks"][0] + state["current"] = task + state["session"][task] = "20260101_000000" + state["messages"][task] = [{"role": "user", "content": "opening"}, + {"role": "assistant", "content": "reply"}] + self.driver.write_turn(state, task) + path = Path(state["trace"]) / "nullius" / "researcher" / task / "20260101_000000" / "turn_0001.json" + payload = json.loads(path.read_text(encoding="utf-8")) + self.assertEqual(payload["chat_id"], task) + self.assertEqual(payload["model"], "nullius") + self.assertEqual(payload["messages"][1], {"role": "assistant", "content": "reply"}) + + def test_the_agent_tool_calls_reach_the_turn_file_as_nanobot_records_them(self): + # The upstream's tool-scored checklist items read only tool_steps: a call + # relayed to AppWorld's MCP server must land there, named as nanobot names it. + server = ("import json,sys\n" + "for line in sys.stdin:\n" + " m=json.loads(line)\n" + " if m.get('method')=='tools/call':\n" + " r={'content':[{'type':'text','text':json.dumps({'response':{'cart_items':[{'product_id':1578}]}})}]}\n" + " else:\n" + " r={}\n" + " print(json.dumps({'jsonrpc':'2.0','id':m['id'],'result':r}),flush=True)\n") + calls = self.root / "tool_calls.jsonl" + relay = ("import sys; sys.path.insert(0, sys.argv[1]); import appworld_mcp; " + "raise SystemExit(appworld_mcp.relay([sys.executable, '-c', sys.argv[2]], sys.argv[3]))") + requests = [{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/call", + "params": {"name": "amazon__show_cart", "arguments": {"page": 0}}}] + done = subprocess.run([sys.executable, "-c", relay, str(DRIVER.parent), server, str(calls)], + input="".join(json.dumps(r) + "\n" for r in requests), + capture_output=True, text=True, timeout=30) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual([json.loads(line)["id"] for line in done.stdout.splitlines()], [1, 2]) + + self.driver.setup("researcher", str(self.root / "workspace")) + state = self.driver.STATE["researcher"] + state["calls"] = str(calls) + task = state["tasks"][0] + state["session"][task] = "20260101_000000" + state["messages"][task] = [{"role": "user", "content": "opening"}, + {"role": "assistant", "content": "reply"}] + self.driver.write_turn(state, task, steps=self.driver.new_tool_steps(state)) + path = Path(state["trace"]) / "nullius" / "researcher" / task / "20260101_000000" / "turn_0001.json" + steps = json.loads(path.read_text(encoding="utf-8"))["tool_steps"] + self.assertEqual(steps, [{"name": "mcp_appworld_amazon__show_cart", "arguments": {"page": 0}, + "result": json.dumps({"response": {"cart_items": [{"product_id": 1578}]}})}]) + self.assertEqual(self.driver.new_tool_steps(state), []) # the next turn starts after them + + +if __name__ == "__main__": + unittest.main() diff --git a/app/ui_tests/test_catalogue_routes.py b/app/ui_tests/test_catalogue_routes.py index 71c548b74..3f0a2cafb 100644 --- a/app/ui_tests/test_catalogue_routes.py +++ b/app/ui_tests/test_catalogue_routes.py @@ -128,7 +128,7 @@ def test_every_listed_benchmark_is_a_card_opening_its_page(self): cat = catalog.load() keys = re.findall(r' -GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2SWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBenchOne task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation +GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2PAST-BenchPi-BenchSWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBenchOne task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useConversation, MCP tools, Workspace filesMCP tools, Conversation, Workspace filesWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation -claude-code✓✓✓✓✓✓✓✓✓✓✓✓ -codex@2.2.2✓✓✓✓✓✓✓✓✓✓✓✓ -codex@0.16.0✓✓✓✓✓✓✗✗✓✓✓✓ -digitalmate@0.1.13✗✓✗✗✗✓✗✗✗✗✗✗ -digitalmate@0.1.13-fixes✓✓✓✓✓✓✗✗✓✓✓✓ -goose✓✓✓✓✓✓✗✗✓✓✓✓ -jiuwenswarm@0.2.7✗✓✓✓✓✓✗✗✓✓✓✓ -jiuwenswarm@0.2.8✓✓✓✓✓✓✗✗✓✓✓✓ -jiuwenswarm@0.2.9✗✓✓✓✓✓✗✗✓✓✓✓ -mini-swe-agent✗✗✗✗✗✗✗✗✓✗✗✗ -opencode✓✓✓✓✓✓✗✗✓✓✓✓ -swe-agent✗✗✗✗✗✗✗✗✓✗✗✗ -terminus-2✗✗✗✗✗✗✗✗✗✗✓✗ +claude-code✓✓✓✓✓✓✓✓✓✓✓✓✓✓ +codex@2.2.2✓✓✓✓✓✓✓✓✓✓✓✓✓✓ +codex@0.16.0✓✓✓✓✓✓✗✗✓✓✓✓✓✓ +digitalmate@0.1.13✗✓✗✗✗✓✗✗✗✗✗✗✗✗ +digitalmate@0.1.13-fixes✓✓✓✓✓✓✗✗✓✓✓✓✓✓ +goose✓✓✓✓✓✓✗✗✓✓✓✓✓✓ +jiuwenswarm@0.2.7✗✓✓✓✓✓✗✗✓✓✓✓✓✓ +jiuwenswarm@0.2.8✓✓✓✓✓✓✗✗✓✓✓✓✓✓ +jiuwenswarm@0.2.9✗✓✓✓✓✓✗✗✓✓✓✓✓✓ +mini-swe-agent✗✗✗✗✗✗✗✗✗✗✓✗✗✗ +opencode✓✓✓✓✓✓✗✗✓✓✓✓✓✓ +swe-agent✗✗✗✗✗✗✗✗✗✗✓✗✗✗ +terminus-2✗✗✗✗✗✗✗✗✗✗✗✗✓✗ - ✗: the missing port, on hover. diff --git a/docs/agents/supported/claude-code.md b/docs/agents/supported/claude-code.md index 84eb6cae2..6d4e9112c 100644 --- a/docs/agents/supported/claude-code.md +++ b/docs/agents/supported/claude-code.md @@ -32,7 +32,7 @@ Anthropic's coding agent. ## Benchmarks it fits - + - +
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2SWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2PAST-BenchPi-BenchSWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useConversation, MCP tools, Workspace filesMCP tools, Conversation, Workspace filesWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
claude-code✓✓✓✓✓✓✓✓✓✓✓✓
claude-code✓✓✓✓✓✓✓✓✓✓✓✓✓✓
diff --git a/docs/agents/supported/codex.md b/docs/agents/supported/codex.md index 8100e623c..b2e32d3c7 100644 --- a/docs/agents/supported/codex.md +++ b/docs/agents/supported/codex.md @@ -35,10 +35,10 @@ OpenAI's coding agent. ## Benchmarks it fits - + - - + +
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2SWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2PAST-BenchPi-BenchSWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useConversation, MCP tools, Workspace filesMCP tools, Conversation, Workspace filesWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
codex@2.2.2✓✓✓✓✓✓✓✓✓✓✓✓
codex@0.16.0✓✓✓✓✓✓✗✗✓✓✓✓
codex@2.2.2✓✓✓✓✓✓✓✓✓✓✓✓✓✓
codex@0.16.0✓✓✓✓✓✓✗✗✓✓✓✓✓✓
- ✗: the missing port, on hover. diff --git a/docs/agents/supported/digitalmate.md b/docs/agents/supported/digitalmate.md index ac6c66c48..5f23b02cb 100644 --- a/docs/agents/supported/digitalmate.md +++ b/docs/agents/supported/digitalmate.md @@ -32,10 +32,10 @@ None declared. ## Benchmarks it fits - + - - + +
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2SWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2PAST-BenchPi-BenchSWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useConversation, MCP tools, Workspace filesMCP tools, Conversation, Workspace filesWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
digitalmate@0.1.13✗✓✗✗✗✓✗✗✗✗✗✗
digitalmate@0.1.13-fixes✓✓✓✓✓✓✗✗✓✓✓✓
digitalmate@0.1.13✗✓✗✗✗✓✗✗✗✗✗✗✗✗
digitalmate@0.1.13-fixes✓✓✓✓✓✓✗✗✓✓✓✓✓✓
- ✗: the missing port, on hover. diff --git a/docs/agents/supported/goose.md b/docs/agents/supported/goose.md index 389497c54..f0f667f9c 100644 --- a/docs/agents/supported/goose.md +++ b/docs/agents/supported/goose.md @@ -30,9 +30,9 @@ The AAIF's open-source agent, formerly Block's. ## Benchmarks it fits - + - +
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2SWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2PAST-BenchPi-BenchSWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useConversation, MCP tools, Workspace filesMCP tools, Conversation, Workspace filesWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
goose✓✓✓✓✓✓✗✗✓✓✓✓
goose✓✓✓✓✓✓✗✗✓✓✓✓✓✓
- ✗: the missing port, on hover. diff --git a/docs/agents/supported/jiuwenswarm.md b/docs/agents/supported/jiuwenswarm.md index 8da7eda1b..461897e49 100644 --- a/docs/agents/supported/jiuwenswarm.md +++ b/docs/agents/supported/jiuwenswarm.md @@ -37,11 +37,11 @@ openJiuwen's WorkSwarm agent. ## Benchmarks it fits - + - - - + + +
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2SWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2PAST-BenchPi-BenchSWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useConversation, MCP tools, Workspace filesMCP tools, Conversation, Workspace filesWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
jiuwenswarm@0.2.7✗✓✓✓✓✓✗✗✓✓✓✓
jiuwenswarm@0.2.8✓✓✓✓✓✓✗✗✓✓✓✓
jiuwenswarm@0.2.9✗✓✓✓✓✓✗✗✓✓✓✓
jiuwenswarm@0.2.7✗✓✓✓✓✓✗✗✓✓✓✓✓✓
jiuwenswarm@0.2.8✓✓✓✓✓✓✗✗✓✓✓✓✓✓
jiuwenswarm@0.2.9✗✓✓✓✓✓✗✗✓✓✓✓✓✓
- ✗: the missing port, on hover. diff --git a/docs/agents/supported/mini-swe-agent.md b/docs/agents/supported/mini-swe-agent.md index 37c55cb09..c1346e011 100644 --- a/docs/agents/supported/mini-swe-agent.md +++ b/docs/agents/supported/mini-swe-agent.md @@ -30,9 +30,9 @@ Princeton's 100-line agent, bash only. ## Benchmarks it fits - + - +
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2SWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2PAST-BenchPi-BenchSWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useConversation, MCP tools, Workspace filesMCP tools, Conversation, Workspace filesWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
mini-swe-agent✗✗✗✗✗✗✗✗✓✗✗✗
mini-swe-agent✗✗✗✗✗✗✗✗✗✗✓✗✗✗
- ✗: the missing port, on hover. diff --git a/docs/agents/supported/opencode.md b/docs/agents/supported/opencode.md index c7d6f2af1..0579ac5e3 100644 --- a/docs/agents/supported/opencode.md +++ b/docs/agents/supported/opencode.md @@ -31,9 +31,9 @@ The open-source terminal coding agent. ## Benchmarks it fits - + - +
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2SWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2PAST-BenchPi-BenchSWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useConversation, MCP tools, Workspace filesMCP tools, Conversation, Workspace filesWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
opencode✓✓✓✓✓✓✗✗✓✓✓✓
opencode✓✓✓✓✓✓✗✗✓✓✓✓✓✓
- ✗: the missing port, on hover. diff --git a/docs/agents/supported/swe-agent.md b/docs/agents/supported/swe-agent.md index b030d68f0..0c3838306 100644 --- a/docs/agents/supported/swe-agent.md +++ b/docs/agents/supported/swe-agent.md @@ -28,9 +28,9 @@ None declared. ## Benchmarks it fits - + - +
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2SWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2PAST-BenchPi-BenchSWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useConversation, MCP tools, Workspace filesMCP tools, Conversation, Workspace filesWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
swe-agent✗✗✗✗✗✗✗✗✓✗✗✗
swe-agent✗✗✗✗✗✗✗✗✗✗✓✗✗✗
- ✗: the missing port, on hover. diff --git a/docs/agents/supported/terminus-2.md b/docs/agents/supported/terminus-2.md index 41213d4e9..d0f974eac 100644 --- a/docs/agents/supported/terminus-2.md +++ b/docs/agents/supported/terminus-2.md @@ -30,9 +30,9 @@ Harbor's terminal agent, used by Terminal-Bench. ## Benchmarks it fits - + - +
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2SWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
GAIAGSM8KHealthAgentBenchHumanEvalMedAgentBenchOpen TelcoOSWorld1OSWorld2PAST-BenchPi-BenchSWE-bench Verifiedτ³-benchTerminal-Bench 2.0VitaBench
One task, Workspace files, SearchOne taskWorkspace filesWorkspace filesConversationOne taskComputer useComputer useConversation, MCP tools, Workspace filesMCP tools, Conversation, Workspace filesWorkspace filesMCP tools, ConversationWorkspace filesMCP tools, Conversation
terminus-2✗✗✗✗✗✗✗✗✗✗✓✗
terminus-2✗✗✗✗✗✗✗✗✗✗✗✗✓✗
- ✗: the missing port, on hover. diff --git a/docs/benchmarks/supported/README.md b/docs/benchmarks/supported/README.md index 2fe4804d1..e5ceeef62 100644 --- a/docs/benchmarks/supported/README.md +++ b/docs/benchmarks/supported/README.md @@ -22,6 +22,8 @@ Every benchmark in the catalogue: where it runs, what it needs, the ways it runs Open Telco
open-telcoGSMA's eight telecom tests, from 3GPP standards and maths to 5G root-cause analysis and 6G reasoning.Telecom✓–20588Official OSWorld1
osworld1Open-ended tasks on a real Ubuntu desktop and its applications, each in a VM of its own.Computer use✓–368Official OSWorld2
osworld2Long-horizon, real-world tasks on an Ubuntu desktop, across its apps, each in a VM of its own.Computer use✓–108Official +PAST-Bench
past-benchCross-session self-evolution for personal agents: retaining preferences and constraints, reusing procedures, gathering prior context before acting, and replacing stale facts, rules and procedures. A family is an ordered sequence of episodes with matched persistence-on and persistence-off controls.General assistance✓–204Official +Pi-Bench
pi-benchLong-horizon personal-assistant work for five role personas: research, marketing, pharmacy, legal training and finance, with hidden intents and a persistent workspace.General assistance✓–100Official SWE-bench Verified
swe-bench-verifiedSoftware engineering: fix a real GitHub issue so the failing tests pass.Coding✓✓500Official τ³-bench
tau3-benchCustomer service with domain tools and a simulated user: airline, retail, telecom, banking.Customer service✓✓375Official Terminal-Bench 2.0
terminal-benchReal terminal tasks in a container: build, configure, debug.Terminal✓✓89Official @@ -43,6 +45,8 @@ Every benchmark in the catalogue: where it runs, what it needs, the ways it runs Open Telcoagent.task/v1NulliusNullius✓✓✓ OSWorld1agent.computer/v1Nullius–✓✓✓ OSWorld2agent.computer/v1Nullius–✓✓– +PAST-Benchagent.conversation/v1, agent.tools/v1, agent.workspace/v1Nullius–✓–– +Pi-Benchagent.tools/v1, agent.conversation/v1, agent.workspace/v1Nullius–✓–– SWE-bench Verifiedagent.workspace/v1Nulliusthe authors✓✓✓ τ³-benchagent.tools/v1, agent.conversation/v1NulliusNullius✓✓✓ Terminal-Bench 2.0agent.workspace/v1Nulliusthe authors✓✓✓ diff --git a/docs/benchmarks/supported/past-bench.md b/docs/benchmarks/supported/past-bench.md new file mode 100644 index 000000000..69f8b9685 --- /dev/null +++ b/docs/benchmarks/supported/past-bench.md @@ -0,0 +1,83 @@ + + +# PAST-Bench + +Cross-session self-evolution for personal agents: retaining preferences and constraints, reusing procedures, gathering prior context before acting, and replacing stale facts, rules and procedures. A family is an ordered sequence of episodes with matched persistence-on and persistence-off controls. + + + + + + + + + + +
Keypast-bench
CategoryGeneral assistance
OriginOfficial
Runs onNullius
Tasks204
PaperPAST-Bench: Benchmarking the Foundations of Recursive Self-Improvement in Personal Agents, arXiv · 2026
Needs, ports provenagent.conversation/v1, agent.tools/v1, agent.workspace/v1
+ +## Datasets + +| Dataset | Key | Tasks | From | Verifier | +|---|---|---|---|---| +| All 26 families · persistence on | `past-bench` | 204 | GitHub [Gen-Verse/PAST-Bench](https://github.com/Gen-Verse/PAST-Bench/tree/f8223517ae7491e776b69793d9f11e9d074ab42e) | The publisher's grader for each episode, then the evaluation-episode mean per family. | +| All 26 families · workspace reset per episode (workspace-only control) | `past-bench-nop` | 204 | GitHub [Gen-Verse/PAST-Bench](https://github.com/Gen-Verse/PAST-Bench/tree/f8223517ae7491e776b69793d9f11e9d074ab42e) | The same graders, over the same episodes with the workspace reset before each one. | +| Evaluation episodes alone · 60 units (the control) | `past-bench-isolated` | 60 | GitHub [Gen-Verse/PAST-Bench](https://github.com/Gen-Verse/PAST-Bench/tree/f8223517ae7491e776b69793d9f11e9d074ab42e) | The publisher's grader for each evaluation episode, scored with nothing carried over. | +| Memory · 5 families | `past-bench-memory` | 41 | GitHub [Gen-Verse/PAST-Bench](https://github.com/Gen-Verse/PAST-Bench/tree/f8223517ae7491e776b69793d9f11e9d074ab42e) | The publisher's graders over memory_ability families. | +| Procedural reuse · 8 families | `past-bench-procedural` | 64 | GitHub [Gen-Verse/PAST-Bench](https://github.com/Gen-Verse/PAST-Bench/tree/f8223517ae7491e776b69793d9f11e9d074ab42e) | The publisher's graders over procedural_ability families. | +| Information gathering · 6 families | `past-bench-information-gathering` | 48 | GitHub [Gen-Verse/PAST-Bench](https://github.com/Gen-Verse/PAST-Bench/tree/f8223517ae7491e776b69793d9f11e9d074ab42e) | The publisher's graders over proactive_information_gathering families. | +| Update · 7 families | `past-bench-update` | 51 | GitHub [Gen-Verse/PAST-Bench](https://github.com/Gen-Verse/PAST-Bench/tree/f8223517ae7491e776b69793d9f11e9d074ab42e) | The publisher's graders over update_ability families. | +| SM01 preference adoption · 1 family | `past-bench-smoke` | 8 | GitHub [Gen-Verse/PAST-Bench](https://github.com/Gen-Verse/PAST-Bench/tree/f8223517ae7491e776b69793d9f11e9d074ab42e) | The publisher's graders over the family's eight episodes. | +| SM01 evaluation episodes alone · 2 units | `past-bench-smoke-isolated` | 2 | GitHub [Gen-Verse/PAST-Bench](https://github.com/Gen-Verse/PAST-Bench/tree/f8223517ae7491e776b69793d9f11e9d074ab42e) | The publisher's graders, scored with nothing carried over. | +| SM01 preference adoption · persistence off | `past-bench-smoke-nop` | 8 | GitHub [Gen-Verse/PAST-Bench](https://github.com/Gen-Verse/PAST-Bench/tree/f8223517ae7491e776b69793d9f11e9d074ab42e) | The same graders with the workspace reset before each episode. | + +## On the standard + +| Control | Written by | +|---|---| +| `nop` | Nullius | + +### Versions + +| Version | Setups as published, whose model | Options | +|---|---|---| +| `past-bench` | none | none | + +## Good to know + +- A unit is one family, not one episode: its episodes run in the publisher's sequence order, share a workspace, and are judged as a sequence. The run reports 26 units for 204 episodes. +- The first message only explains how the session works and asks the agent to reply READY; every task then arrives as its own message, so the episodes can be counted and each gets its own fresh session where the manifest says so. +- past-bench-nop and past-bench-isolated are Nullius's controls, not the publisher's: its persistence-off arm turns off the agent's memory tools, and it refuses that arm for any agent outside Hermes, nanobot and ZeroClaw. +- The tools are the benchmark's: each episode declares its tools and their mock-service endpoints, and they reach the agent as MCP tools that change with the episode. An agent needs the tools port. +- The mock services run beside the driver on ports it picks, so two families can run at once; their audit logs are the evidence the graders read. +- Episode order, fresh-session rules and history anchors come from the publisher's configs/self_evolve_v2/*_only.yaml, which match what it generates from each family.yaml. +- The publisher declares a judge, so a provider key is needed before any run, including the nop control. Override --judge-model when the benchmark's default model is not served by your provider. +- An ablation compares past-bench's eval_near/eval_far episodes with past-bench-isolated's: same episodes, but the isolated unit never saw the learn episodes and has a fresh home. past-bench-nop alone is not that control - it only resets the workspace. + +## Upstream limitations + +- The official harness runs its own agents (Hermes, Hermes+, nanobot, ZeroClaw, Agent Zero, OpenClaw, Codex, Claude Code and a built-in baseline) and exposes no interface for any other. This entry runs the Nullius agent under test with the publisher's graders, services and manifests, not its runner or sandbox. +- 7 update episodes on disk are in no manifest; the upstream does not run them, nor does this entry. +- Some episodes seed the agent's home (hermes_home_seed); the upstream applies a seed only to an agent it has a persistence backend for, so not here. +- The graders reward the agent's own memory, skill and session-search calls, which the upstream reads only from the agents it has a persistence backend for (Hermes, nanobot, ZeroClaw). Any other agent is graded as the upstream grades Agent Zero: with nothing recorded, so 58 of the 60 evaluation episodes cap completion at 0.25, an episode at 0.40 at most. +- The upstream sends a learn episode's reflection prompt only to an agent it has a persistence backend for; the agent under test gets none, as Agent Zero gets none. + +## Nullius limitations + +- No persistence means a cleaned workspace and a new session. The agent's own memory store lives in its home directory, which belongs to the unit and is not addressable by the benchmark, so an agent with durable internal memory is measured with that memory intact in both arms. +- The graders see the episode's own exchange, its MCP tool calls and the services' audit logs; internal tool calls the agent makes outside the benchmark's MCP tools are not in that evidence. +- The communication part of an episode's score is an LLM judge on the benchmark's default model unless --judge-model says otherwise; use one judge model across arms for comparable numbers. +- The upstream runs each episode as its own trial, a new session, and applies history anchors to the agent's home. Here a continue episode keeps the session, anchors restore the workspace, and the agent's home is never reset; evaluation and control episodes always start a new session. +- The upstream gives an episode 300 s and 20 steps, past which it scores 0; here only the whole family has a limit, 6 h. + +## Cite + +??? citation "BibTeX" + + ```bibtex + @article{xue2026pastbench, + title={PAST-Bench: Benchmarking the Foundations of Recursive Self-Improvement in Personal Agents}, + author={Xue, Shuhan and Ding, Zixin and Shen, Yichen and Wang, Yinjie and Yin, Zhenfei and Wu, Yingcheng and Chen, Yuxin and Wang, Mengdi and Yang, Ling}, + journal={arXiv preprint arXiv:2608.04003}, + year={2026} + } + ``` diff --git a/docs/benchmarks/supported/pi-bench.md b/docs/benchmarks/supported/pi-bench.md new file mode 100644 index 000000000..4c3fee920 --- /dev/null +++ b/docs/benchmarks/supported/pi-bench.md @@ -0,0 +1,78 @@ + + +# Pi-Bench + +Long-horizon personal-assistant work for five role personas: research, marketing, pharmacy, legal training and finance, with hidden intents and a persistent workspace. + + + + + + + + + + +
Keypi-bench
CategoryGeneral assistance
OriginOfficial
Runs onNullius
Tasks100
Paper$\pi$-Bench: Evaluating Proactive Personal Assistant Agents in Long-Horizon Workflows, arXiv · 2026
Needs, ports provenagent.tools/v1, agent.conversation/v1, agent.workspace/v1
+ +## Datasets + +| Dataset | Key | Tasks | From | Verifier | +|---|---|---|---|---| +| All five personas · 100 tasks | `pi-bench` | 100 | GitHub [Simplified-Reasoning/Pi-Bench](https://github.com/Simplified-Reasoning/Pi-Bench/tree/4f545be5d289b28ff022d2904d455007358ed3b7) | The upstream's TraceEvaluationRunner: ChecklistEvaluator (COMP) and ProactivenessEvaluator (PROC) over each task's trace and the user simulator's logs. | +| Researcher · 20 tasks | `pi-bench-researcher` | 20 | GitHub [Simplified-Reasoning/Pi-Bench](https://github.com/Simplified-Reasoning/Pi-Bench/tree/4f545be5d289b28ff022d2904d455007358ed3b7) | The upstream's TraceEvaluationRunner over the researcher persona. | +| Marketer · 20 tasks | `pi-bench-marketer` | 20 | GitHub [Simplified-Reasoning/Pi-Bench](https://github.com/Simplified-Reasoning/Pi-Bench/tree/4f545be5d289b28ff022d2904d455007358ed3b7) | The upstream's TraceEvaluationRunner over the marketer persona. | +| Pharmacist · 20 tasks | `pi-bench-pharmacist` | 20 | GitHub [Simplified-Reasoning/Pi-Bench](https://github.com/Simplified-Reasoning/Pi-Bench/tree/4f545be5d289b28ff022d2904d455007358ed3b7) | The upstream's TraceEvaluationRunner over the pharmacist persona. | +| Law trainee · 20 tasks | `pi-bench-law-trainee` | 20 | GitHub [Simplified-Reasoning/Pi-Bench](https://github.com/Simplified-Reasoning/Pi-Bench/tree/4f545be5d289b28ff022d2904d455007358ed3b7) | The upstream's TraceEvaluationRunner over the law_trainee persona. | +| Financier · 20 tasks | `pi-bench-financier` | 20 | GitHub [Simplified-Reasoning/Pi-Bench](https://github.com/Simplified-Reasoning/Pi-Bench/tree/4f545be5d289b28ff022d2904d455007358ed3b7) | The upstream's TraceEvaluationRunner over the Financier persona. | + +## On the standard + +| Control | Written by | +|---|---| +| `nop` | Nullius | + +### Versions + +| Version | Setups as published, whose model | Options | +|---|---|---| +| `pi-bench` | none | none | + +## Good to know + +- A unit is one persona; its 20 tasks run in the upstream's episode order, share a workspace and use earlier tasks' artifacts. Run all five personas for the 100-task benchmark. +- The user is the upstream's hidden-intent simulator: it probes for requirements the opening request does not state, so several turns per task are normal. +- The reward is COMP, the upstream checklist score; PROC, the hidden-intent coverage score, is reported beside it in the job. +- The persona's AppWorld tools come from the official image, one container per unit. The image's own nanobot harness is not used. +- Pull zzzhr97/pi-bench@sha256:3bdb960745315514150e97e7e867110ed797a51e3ae1abec94634e473ee8e41a before a run: it supplies AppWorld for the tools. A machine without Docker can answer text-only turns but cannot use the persona's apps. +- Pi-Bench declares a simulated user and a judge, so a provider key is needed before any run, including the nop control. +- Scoring runs an LLM judge over every task's trace; give the score phase time with --timeout score=3600 when a full persona is evaluated. + +## Upstream limitations + +- The official harness ships its own nanobot agent and a Docker image; it exposes no interface for an arbitrary agent, and its leaderboard ranks models inside nanobot, so scores here do not compare with it. This entry substitutes the Nullius agent under test and uses the image only for AppWorld. +- Twenty-four tasks declare AppWorld tool use and 27 score some checklist items on the agent's AppWorld calls; the rest still run in an AppWorld-backed persona and may use the persona's apps. +- The benchmark has no published reference solution, so no oracle control is declared. + +## Nullius limitations + +- A unit is a whole persona, not one task: a run reports five units for 100 tasks, and a single persona is a dataset of its own. +- The agent under test must prove AppWorld tools, conversation and a workspace; an agent without the tools port cannot run the tool tasks. +- The official image's harness entrypoint is not used; the driver starts only its AppWorld API and serves the upstream's MCP server, so image-level harness changes are not picked up. +- The judge reads each turn's final message: nanobot's messages between tool calls, which the upstream trace also shows, are not in the Nullius transcript. The AppWorld calls are recorded, for the checklist items scored on them. + +## Cite + +??? citation "BibTeX" + + ```bibtex + @misc{zhang2026pibenchevaluatingproactivepersonal, + title={$\pi$-Bench: Evaluating Proactive Personal Assistant Agents in Long-Horizon Workflows}, + author={Haoran Zhang and Luxin Xu and Zhilin Wang and Runquan Gui and Shunkai Zhang and Haodi Lei and Zihao He and Bingsu He and Chicheng Qin and Tong Zhu and Xiaoye Qu and Yang Yang and Yu Cheng and Yafu Li}, + year={2026}, + eprint={2605.14678}, + archivePrefix={arXiv}, + primaryClass={cs.AI}, + url={https://arxiv.org/abs/2605.14678} + } + ```