From b9686a76272c3079c6477284951f64f81a6b0f22 Mon Sep 17 00:00:00 2001 From: Albert Zhao Date: Mon, 9 Nov 2026 02:53:54 -0500 Subject: [PATCH 01/13] mwm and RRSI: refuse a learner backend other than Codex or Claude Code at setup mwm ran a Pi learner without its bound model (its session settings carry no provider), and RRSI's roles, kept read-only through Codex's own sandbox mode or Claude Code's tool settings, ran with all of Pi's tools. Both now refuse an evolver.params.backend other than codex or claude before the first step. Each test fails without its check. Co-Authored-By: Claude Opus 5.5 --- hermit/agent/evolver/methods/mwm/evolver.py | 3 +++ hermit/agent/evolver/methods/rrsi_adapter/evolver.py | 3 +++ tests/methods/mwm/test_mwm_evolver.py | 10 ++++++++++ tests/methods/rrsi_adapter/test_rrsi_adapter.py | 2 ++ 4 files changed, 18 insertions(+) diff --git a/hermit/agent/evolver/methods/mwm/evolver.py b/hermit/agent/evolver/methods/mwm/evolver.py index 4ae8ac0d..9b3f473b 100644 --- a/hermit/agent/evolver/methods/mwm/evolver.py +++ b/hermit/agent/evolver/methods/mwm/evolver.py @@ -456,6 +456,9 @@ def _notes(admission: dict | None) -> str: # ------------------------------------------------------------------ steps def setup(self, ctx: Context) -> None: + if ctx.params.get("backend", "codex") not in ("codex", "claude"): # its session texts, homes and sign-ins + raise ValueError("the mwm Evolver's learner is a Codex or Claude Code session: evolver.params.backend is " + f"codex or claude, not {ctx.params.get('backend')!r}") if "network_isolation" in ctx.params: raise ValueError("evolver.params.network_isolation was removed: the learner runs in the run's evolver " "sandbox, whose network reaches only its models, the tool endpoint and " diff --git a/hermit/agent/evolver/methods/rrsi_adapter/evolver.py b/hermit/agent/evolver/methods/rrsi_adapter/evolver.py index 0ac28a4e..31add202 100644 --- a/hermit/agent/evolver/methods/rrsi_adapter/evolver.py +++ b/hermit/agent/evolver/methods/rrsi_adapter/evolver.py @@ -417,6 +417,9 @@ def setup(self, ctx) -> None: """What every step needs, checked once: a broken hyperparameter file or domain, or an unset web_search, stops the run here rather than failing each step.""" _require_rrsi() + if ctx.params.get("backend", "codex") not in ("codex", "claude"): # its roles' settings are those CLIs' + raise ValueError("the RRSI Adapter's proposer and roles are Codex or Claude Code sessions: " + f"evolver.params.backend is codex or claude, not {ctx.params.get('backend')!r}") if not isinstance(ctx.params.get("web_search"), bool): raise ValueError("evolver.params.web_search must be set, true or false") role = ctx.params.get("roles") or {} diff --git a/tests/methods/mwm/test_mwm_evolver.py b/tests/methods/mwm/test_mwm_evolver.py index 687f028b..edcaacf1 100644 --- a/tests/methods/mwm/test_mwm_evolver.py +++ b/tests/methods/mwm/test_mwm_evolver.py @@ -148,6 +148,16 @@ def make(tmp: Path, monkeypatch, steps: int = 2, deployment_param: bool = False) return path +def test_a_learner_that_is_not_codex_or_claude_code_is_refused_at_setup(): + """mwm's session is Codex's or Claude Code's (its texts, homes and sign-ins): another CLI Base Agent, which the + config takes as evolver.base (pi), is refused before any step rather than run without its model (mwm's session + settings carry no `provider`).""" + from types import SimpleNamespace + from hermit.agent.evolver.methods.mwm.evolver import MwmEvolver + with pytest.raises(ValueError, match="backend is codex or claude, not 'pi'"): + MwmEvolver().setup(SimpleNamespace(params={"backend": "pi"})) + + def test_bootstrap_review_mounts_and_records(tmp_path, monkeypatch): cfg = Config.load(make(tmp_path, monkeypatch), []) stale = tmp_path / "taskdir" / "evidence" / "block000" # a record already in the store: hidden from the bootstrap diff --git a/tests/methods/rrsi_adapter/test_rrsi_adapter.py b/tests/methods/rrsi_adapter/test_rrsi_adapter.py index 787b6782..1be09dca 100644 --- a/tests/methods/rrsi_adapter/test_rrsi_adapter.py +++ b/tests/methods/rrsi_adapter/test_rrsi_adapter.py @@ -818,6 +818,8 @@ def test_setup_checks_what_every_step_needs(tmp_path): ev.setup(ctx) with pytest.raises(ValueError, match="web_search"): ev.setup(context(ws, 1, dom, tmp_path, web_search=None)) + with pytest.raises(ValueError, match="backend is codex or claude, not 'pi'"): # its roles' settings are not Pi's + ev.setup(context(ws, 1, dom, tmp_path, backend="pi")) with pytest.raises(Exception): ev.setup(context(ws, 1, str(tmp_path / "dom" / "missing.py") + ":ToyDomain", tmp_path)) with pytest.raises(ValueError, match="roles.model"): From b35d2ea2a793c0cc14185c411c40610277c29353 Mon Sep 17 00:00:00 2001 From: Albert Zhao Date: Tue, 10 Nov 2026 00:44:58 -0500 Subject: [PATCH 02/13] mwm and RRSI backend check: test it from the config and across the allowed list The tests held only that `pi` is refused on a hand-built context. mwm's now goes from the config through the Trainer, for evolver.base and for evolver.params.backend; RRSI's also holds that claude passes setup and that a second backend is refused. mwm's comment gave a reason that does not hold (its session texts name neither CLI): it now names the missing `provider`. Co-Authored-By: Claude Opus 5.5 --- hermit/agent/evolver/methods/mwm/evolver.py | 2 +- tests/methods/mwm/test_mwm_evolver.py | 17 +++++++++-------- tests/methods/rrsi_adapter/test_rrsi_adapter.py | 6 ++++-- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/hermit/agent/evolver/methods/mwm/evolver.py b/hermit/agent/evolver/methods/mwm/evolver.py index 9b3f473b..3d37be56 100644 --- a/hermit/agent/evolver/methods/mwm/evolver.py +++ b/hermit/agent/evolver/methods/mwm/evolver.py @@ -456,7 +456,7 @@ def _notes(admission: dict | None) -> str: # ------------------------------------------------------------------ steps def setup(self, ctx: Context) -> None: - if ctx.params.get("backend", "codex") not in ("codex", "claude"): # its session texts, homes and sign-ins + if ctx.params.get("backend", "codex") not in ("codex", "claude"): # its session settings carry no `provider` raise ValueError("the mwm Evolver's learner is a Codex or Claude Code session: evolver.params.backend is " f"codex or claude, not {ctx.params.get('backend')!r}") if "network_isolation" in ctx.params: diff --git a/tests/methods/mwm/test_mwm_evolver.py b/tests/methods/mwm/test_mwm_evolver.py index edcaacf1..a8efe6ea 100644 --- a/tests/methods/mwm/test_mwm_evolver.py +++ b/tests/methods/mwm/test_mwm_evolver.py @@ -148,14 +148,15 @@ def make(tmp: Path, monkeypatch, steps: int = 2, deployment_param: bool = False) return path -def test_a_learner_that_is_not_codex_or_claude_code_is_refused_at_setup(): - """mwm's session is Codex's or Claude Code's (its texts, homes and sign-ins): another CLI Base Agent, which the - config takes as evolver.base (pi), is refused before any step rather than run without its model (mwm's session - settings carry no `provider`).""" - from types import SimpleNamespace - from hermit.agent.evolver.methods.mwm.evolver import MwmEvolver - with pytest.raises(ValueError, match="backend is codex or claude, not 'pi'"): - MwmEvolver().setup(SimpleNamespace(params={"backend": "pi"})) +@pytest.mark.parametrize("override, name", [("evolver.base=pi", "pi"), + ("evolver.params.backend=mini-swe-agent", "mini-swe-agent")]) +def test_a_learner_that_is_not_codex_or_claude_code_is_refused_at_setup(tmp_path, monkeypatch, override, name): + """From the config through the Trainer: mwm's session settings carry no `provider`, so a learner on another CLI + Base Agent could not use its bound model. The run stops at setup, naming the backends it takes, before any step.""" + trainer = Trainer(Config.load(make(tmp_path, monkeypatch), [override]), log=lambda *_: None) + with pytest.raises(SystemExit, match=f"backend is codex or claude, not '{name}'"): + trainer.train() + assert not (tmp_path / "runs" / "mwm-test" / "steps.jsonl").exists() def test_bootstrap_review_mounts_and_records(tmp_path, monkeypatch): diff --git a/tests/methods/rrsi_adapter/test_rrsi_adapter.py b/tests/methods/rrsi_adapter/test_rrsi_adapter.py index 1be09dca..58bb307d 100644 --- a/tests/methods/rrsi_adapter/test_rrsi_adapter.py +++ b/tests/methods/rrsi_adapter/test_rrsi_adapter.py @@ -818,8 +818,10 @@ def test_setup_checks_what_every_step_needs(tmp_path): ev.setup(ctx) with pytest.raises(ValueError, match="web_search"): ev.setup(context(ws, 1, dom, tmp_path, web_search=None)) - with pytest.raises(ValueError, match="backend is codex or claude, not 'pi'"): # its roles' settings are not Pi's - ev.setup(context(ws, 1, dom, tmp_path, backend="pi")) + ev.setup(context(ws, 1, dom, tmp_path, backend="claude")) + for other in ("pi", "mini-swe-agent"): # its roles' settings are those two CLIs' + with pytest.raises(ValueError, match=f"backend is codex or claude, not '{other}'"): + ev.setup(context(ws, 1, dom, tmp_path, backend=other)) with pytest.raises(Exception): ev.setup(context(ws, 1, str(tmp_path / "dom" / "missing.py") + ":ToyDomain", tmp_path)) with pytest.raises(ValueError, match="roles.model"): From 1bea09e9735e05366a7d7fd487896b214992dd1d Mon Sep 17 00:00:00 2001 From: Albert Zhao Date: Tue, 10 Nov 2026 11:23:50 -0500 Subject: [PATCH 03/13] Run every method on Pi: evolver.base: pi for all Evolvers Pi was a Base Agent and an Evolver of its own, but the methods either refused it, ignored it or could not reach their model through it. Every method now runs on `evolver.base: pi`: - mwm, the RRSI Adapter, the AHE Adapter, Harness2 and EvoSafe run their own sessions on Pi, on the bound model. RRSI's roles stay read-only Pi's way: no tools for the analyst and the critic, read, grep, find and ls for a digester. EvoSafe's roles have none of Pi's own tools and keep the TRAIN readers. - GEPA, SkillOpt, ACE, OPRO, ReHarness and Continual Harness call the run's model, so `evolver.base: pi` makes that model Pi: `llm: {cli: pi}`, one tool-less session per call. - The pi Base Agent gains text_only, allowed_tools, persist_session and a check of its efforts. Each Evolver was run with the real Pi 1.5.0 and a real model. Co-Authored-By: Claude Opus 5.5 --- docs/framework/agent-layers.md | 19 +-- docs/get-started/installation.md | 6 +- docs/guides/model-backends.md | 2 +- docs/methods/agent.md | 13 ++ docs/methods/ahe_adapter.md | 4 +- docs/methods/aspire.md | 4 +- docs/methods/evosafe.md | 10 +- docs/methods/harness2.md | 4 +- docs/methods/meta_harness_adapter.md | 8 +- docs/methods/mwm.md | 4 +- docs/methods/rrsi_adapter.md | 16 +-- docs/reference/config-fields.md | 8 +- .../adapter/templates/ahe/.hermit/EVOLVER.md | 2 +- hermit/agent/base/cli.py | 34 +++++- hermit/agent/base/endpoint.py | 31 +++-- hermit/agent/evolver/loader.py | 2 +- .../evolver/methods/ahe_adapter/debugger.py | 8 +- .../evolver/methods/ahe_adapter/evolver.py | 13 +- .../evolver/methods/ahe_adapter/evolver.yaml | 6 +- .../agent/evolver/methods/aspire/evolver.py | 2 +- .../agent/evolver/methods/aspire/evolver.yaml | 2 +- .../evolver/methods/evosafe/cli_roles.py | 9 +- .../agent/evolver/methods/evosafe/evolver.py | 11 +- .../evolver/methods/evosafe/evolver.yaml | 4 +- .../agent/evolver/methods/evosafe/pi_agent.py | 6 + hermit/agent/evolver/methods/evosafe/roles.py | 16 +-- .../methods/harness2_upstream/bench.py | 3 + .../methods/harness2_upstream/channel.py | 33 ++++- .../methods/harness2_upstream/evolver.py | 17 +-- .../methods/harness2_upstream/evolver.yaml | 3 +- .../methods/harness2_upstream/render.py | 31 +++++ .../methods/meta_harness_adapter/evolver.py | 2 +- .../methods/meta_harness_adapter/evolver.yaml | 2 +- hermit/agent/evolver/methods/mwm/evolver.py | 9 +- hermit/agent/evolver/methods/mwm/evolver.yaml | 2 +- .../evolver/methods/rrsi_adapter/evolver.py | 22 ++-- .../evolver/methods/rrsi_adapter/evolver.yaml | 4 +- .../evolver/methods/rrsi_adapter/roles.py | 12 +- hermit/agent/model/backends.py | 7 +- hermit/config.py | 28 ++++- tests/README.md | 4 +- tests/core/test_claude_subscription.py | 4 +- tests/core/test_pi_agent.py | 114 ++++++++++++++++++ tests/methods/ahe/test_ahe_on_claude.py | 4 +- tests/methods/ahe/test_ahe_on_pi.py | 43 +++++++ tests/methods/evosafe/test_evosafe_on_pi.py | 34 ++++++ tests/methods/harness2/test_harness2_on_pi.py | 42 +++++++ tests/methods/mwm/test_mwm_evolver.py | 13 +- tests/methods/mwm/test_mwm_on_pi.py | 56 +++++++++ .../methods/rrsi_adapter/test_rrsi_adapter.py | 7 +- tests/methods/rrsi_adapter/test_rrsi_on_pi.py | 47 ++++++++ tests/pi_stand.py | 73 +++++++++++ tests/selection.py | 3 +- 53 files changed, 720 insertions(+), 143 deletions(-) create mode 100644 hermit/agent/evolver/methods/evosafe/pi_agent.py create mode 100644 tests/methods/ahe/test_ahe_on_pi.py create mode 100644 tests/methods/evosafe/test_evosafe_on_pi.py create mode 100644 tests/methods/harness2/test_harness2_on_pi.py create mode 100644 tests/methods/mwm/test_mwm_on_pi.py create mode 100644 tests/methods/rrsi_adapter/test_rrsi_on_pi.py create mode 100644 tests/pi_stand.py diff --git a/docs/framework/agent-layers.md b/docs/framework/agent-layers.md index 638238f3..bc32e98f 100644 --- a/docs/framework/agent-layers.md +++ b/docs/framework/agent-layers.md @@ -103,7 +103,8 @@ What the Base Agent is used for. Two kinds: - The **Evolver Agent** learns. Its API to the Trainer is `step(ctx)` and `finalize(ctx)`. It reads the acting runs' trajectories and writes a new adapter, calling a Base Agent: `direct` for methods that decide every step in their own code (GEPA, SkillOpt, ReHarness, Continual Harness), `codex`, `claude` or `pi` for methods whose learner - is an agent (Meta-Harness Adapter, the `codex`, `claude` and `pi` Evolvers). The run's model reaches an Evolver as + is an agent (Meta-Harness Adapter, the `codex`, `claude` and `pi` Evolvers). With `evolver.base: pi`, a method that + decides every step in its own code calls Pi as its model ([every method on Pi](../methods/agent.md#every-method-on-pi)). The run's model reaches an Evolver as `ctx.agent`, a `direct` Base Agent metered against the budget; `ask(ctx.agent, messages, max_tokens=...)` returns the reply as the `llm` tool does. @@ -116,11 +117,11 @@ relayed to the URL it would have reached with its body, key and reply unchanged stream). CL-Bench's runner and ServeLearnBench's agent reach their model this way, through the launcher's meter as before. The same endpoint over a CLI Base Agent answers each request with one session of it (the system messages as its instructions, the rest as its prompt, its reply as the reply): `llm: {cli: claude, model: ..., login: claude, -...}` (or `cli: codex`, `login: chatgpt`) makes the run's model one only the CLI reaches, such as a model on a +...}` (or `cli: codex`, `login: chatgpt`, or `cli: pi` with a `/` reference) makes the run's model one only the CLI reaches, such as a model on a subscription, for the Evolvers that call `ctx.agent` and the `llm` tool, and `agent.model: {cli: ...}` the same for an acting pipeline, which sees a local URL. Such a session works in an empty directory of its own, in a bubblewrap sandbox of its own (`isolation: sandbox`, the default) or a container (`isolation: container`), and is given no tools -(`text_only`): a Claude Code session can only reply, a Codex session can still run commands inside its sandbox. A chat +(`text_only`): a Claude Code or Pi session can only reply, a Codex session can still run commands inside its sandbox. A chat call sees no files, so a role that is to read files runs a session itself (`make(...).run(prompt, workspace)`). What a session cannot do is refused, not dropped ([the model contract](../guides/claude-subscription.md#the-model-contract)). Each call's event stream is kept under the run's `llm_sessions/`. @@ -227,14 +228,14 @@ accepted; a key given in two layers is refused. On the command line a layer's se |---|---|---| | OfficeQA in Codex, every method | Acting Agent with OfficeQA's task functions (`utils/task.py`) | `codex` | | OfficeQA in direct chat | Acting Agent running SkillOpt's chat loop | `direct`, per turn | -| GEPA, SkillOpt, ReHarness, Continual Harness, OPRO | Evolver Agent | `direct` (`ctx.agent`); OPRO in OfficeQA: `codex` through `llm: {cli: codex}` | -| Meta-Harness Adapter, `codex` and `claude` Evolvers | Evolver Agent | `codex` or `claude` | +| GEPA, SkillOpt, ReHarness, Continual Harness, OPRO | Evolver Agent | `direct` (`ctx.agent`); OPRO in OfficeQA: `codex` through `llm: {cli: codex}`; with `evolver.base: pi`, `pi` through `llm: {cli: pi}` | +| Meta-Harness Adapter, ASPIRE, `codex` and `claude` Evolvers | Evolver Agent | `codex`, `claude` or `pi` | | `pi` Evolver | Evolver Agent | `pi` | -| RRSI Adapter | Evolver Agent: upstream's rules and roles, the proposer's prompt | `codex` or `claude` for the proposer, and the same, one call per upstream `generate`, for the analyst, digesters and critic | -| AHE Adapter | Evolver Agent: the Evolve Agent and the Agent Debugger | `codex` or `claude`, one session per step and per task | +| RRSI Adapter | Evolver Agent: upstream's rules and roles, the proposer's prompt | `codex`, `claude` or `pi` for the proposer, and the same, one call per upstream `generate`, for the analyst, digesters and critic | +| AHE Adapter | Evolver Agent: the Evolve Agent and the Agent Debugger | `codex`, `claude` or `pi`, one session per step and per task | | CL-Bench, ServeLearnBench | Acting Agent running the benchmark's loop | `direct`, per call, through the local endpoint | -| MWM | Evolver Agent | `codex` or `claude`, in a view of the run's sandbox with MWM's native mounts (`/w`, `/evidence`, ...) | -| Harness² | Evolver Agent: upstream's proposer | `claude`, one call per upstream session (or `codex`) | +| MWM | Evolver Agent | `codex`, `claude` or `pi`, in a view of the run's sandbox with MWM's native mounts (`/w`, `/evidence`, ...) | +| Harness² | Evolver Agent: upstream's proposer | `claude`, one call per upstream session (or `codex` or `pi`) | ## Outside the layers diff --git a/docs/get-started/installation.md b/docs/get-started/installation.md index ab9d2655..436534d4 100644 --- a/docs/get-started/installation.md +++ b/docs/get-started/installation.md @@ -110,11 +110,11 @@ python -m pip install "hermit-harness[mini-swe-agent]" | GEPA | `python -m pip install -e . --group gepa`, learner endpoint, validation split | | SkillOpt | `python -m pip install -e . --group skillopt`, learner endpoint, validation split | | Harness² | Python 3.12 or 3.13, `python -m pip install -e . --group harness2`, Claude Code, and the execution environment described in [Harness²](../methods/harness2.md) | -| RRSI Adapter | `python -m pip install -e . --group rrsi`, a CLI for the proposer and its analyst, digesters and critic (Codex or Claude Code), a training split evaluated k times per task | +| RRSI Adapter | `python -m pip install -e . --group rrsi`, a CLI for the proposer and its analyst, digesters and critic (Codex, Claude Code or Pi), a training split evaluated k times per task | | Codex / Claude learner | Selected authenticated CLI and supported program-execution environment | -| MWM | Linux learner environment, Codex or Claude Code, evidence store, task deployment contract, model access | +| MWM | Linux learner environment, Codex, Claude Code or Pi, evidence store, task deployment contract, model access | | Acting and learning on a Claude subscription | Claude Code 2.1.248 or later, `claude setup-token`, Linux with bubblewrap for its sandboxes; see [Claude subscription](../guides/claude-subscription.md) | -| Pi acting agent or learner | The `pi` release binary on `PATH` (GitHub release `pi-linux-x64.tar.gz`, checked against its `SHA256SUMS`) and a model reference | +| Pi acting agent or learner | The release's own directory on `PATH` (GitHub release `pi-linux-x64.tar.gz`, checked against its `SHA256SUMS`; the sandboxes follow no link from `/usr`) and a model reference | | Benchmark recipe | Its dataset, scorer, model settings, and environment; see [catalog](../recipes/index.md) | Core installation and the deterministic tutorial work on macOS. The sandboxes (the acting agent's, the judge's, the diff --git a/docs/guides/model-backends.md b/docs/guides/model-backends.md index dcbd316f..92aba08a 100644 --- a/docs/guides/model-backends.md +++ b/docs/guides/model-backends.md @@ -27,7 +27,7 @@ hermit train --config run.yaml model=vllm/Qwen/Qwen3-30B-A3B-Instruct-2507-FP8 | `agent.params.model` (or `agent.model`) with `agent.name: codex` / `claude-code` | the CLI acting agent | Responses API / Messages API | | `agent.params.model` (or `agent.model`) with `agent.name: mini-swe-agent` | mini-swe-agent, through litellm | chat completions | | `evolver.params.model` of the `codex`, `claude` and `mwm` Evolvers | the learner's CLI session | Responses API / Messages API | -| `agent.params.model` with `agent.name: pi`, `evolver.params.model` of the `pi` Evolver | Pi | chat completions, else the Messages API, else the Responses API: the first the backend serves | +| `agent.params.model` with `agent.name: pi`, the model of any method on `evolver.base: pi` | Pi | chat completions, else the Messages API, else the Responses API: the first the backend serves | | `model` (top level) | the default for all of the above when they name none | | | the examples' task agents (`agent.params.model`, or the launchers' `MW_MODEL`) | CL-Bench's litellm host, ServeLearnBench's loop, the SkillOpt rollout | chat completions | diff --git a/docs/methods/agent.md b/docs/methods/agent.md index 9ec8b88e..bd2f8f23 100644 --- a/docs/methods/agent.md +++ b/docs/methods/agent.md @@ -6,6 +6,19 @@ rewrite does not capture well. The `pi` learner signs in through a model referen `evolver.model: /`, or `evolver.params.model`); it copies no login from `~/.pi/agent` (`home: []`). On the single-file prompt-only template, the Codex learner is the [prompt-only](prompt-only.md) method. +## Every method on Pi + +`evolver.base: pi` with `evolver.model: /` runs any method's learner on Pi, on that model: + +| Method | What runs on Pi | +|---|---| +| `pi`, Meta-Harness Adapter, ASPIRE, MWM, AHE Adapter, Harness², RRSI Adapter, EvoSafe | The method's own sessions, as on Codex or Claude Code | +| GEPA, SkillOpt, ACE, OPRO, ReHarness, Continual Harness | They call the run's model, so that model becomes Pi: each call is one session with no tools (the same as `llm: {cli: pi, model: /}`) | + +Pi signs in only through the model reference and has no web search. A session cannot apply a request's `temperature`, +and a request that asks for one is refused: OPRO, whose default is `1.0`, needs `evolver.pi: {unapplied: [temperature]}` +or `evolver.params.temperature: null`. Pi has no sub-agents: an adapter's sub-agents stay files its acting agent can read. + ## Requirements and setup Install and authenticate the selected learner CLI in the environment where training runs. Sandboxed program diff --git a/docs/methods/ahe_adapter.md b/docs/methods/ahe_adapter.md index 07e7cff3..7799bf47 100644 --- a/docs/methods/ahe_adapter.md +++ b/docs/methods/ahe_adapter.md @@ -28,7 +28,7 @@ trainer: {epochs: 10, allow_early_stop: true} # the paper's ten iteration sandbox: {enabled: true, evolver: {allowed_hosts: [chatgpt.com, auth.openai.com]}} # the learners' ChatGPT login ``` -Both learners are sessions of the `codex` or `claude` Base Agent (`evolver.base`): the Agent Debugger one session per +Both learners are sessions of the `codex`, `claude` or `pi` Base Agent (`evolver.base`): the Agent Debugger one session per task and attempt, the Evolve Agent one session per step with `check_spec` as its only tool. A task's k rollouts are k rows of the training split that share `task_field` (a row without it is grouped by its id without the `#n`); the example's `make_rows.py` writes them. The learners' CLI does not depend on the acting agent's. The acting agent must @@ -102,7 +102,7 @@ Step N is AHE iteration N: step 1 scores the seed, and step N's edits are scored 2. Stop when pass@1 reaches `target_pass_rate` (with `trainer.allow_early_stop`). 3. `rollback: auto`: the files of every change judged HARMFUL are restored from before the change (the paper's Algorithm 1), undone again if `check_spec` then fails; `rollback: agent` only reports, as the released code. -4. The Agent Debugger: one session of the Evolver's CLI (Codex or Claude Code) per task over its rollouts' trajectories, +4. The Agent Debugger: one session of the Evolver's CLI (Codex, Claude Code or Pi) per task over its rollouts' trajectories, hook audits and the judge's verdicts, with upstream's query; a failed attempt is retried, and after `retries` upstream's fallback text stands in. The reports and an overview go to `state/analysis/step_N/`. 5. The Evolve Agent: one session of the same CLI reads the overview, the verdicts and the history (`START.md` and the diff --git a/docs/methods/aspire.md b/docs/methods/aspire.md index a1fe90a8..d71aca7a 100644 --- a/docs/methods/aspire.md +++ b/docs/methods/aspire.md @@ -7,7 +7,7 @@ execution engine that records every primitive call with RGB keyframes, debugs it what it learned. The coordinator turns those reports into a shared skill library: it repairs entries the actors graded badly and admits a new entry only after a fresh verifier re-solved the task from the library and the entry alone. It also chooses which task runs next (its curriculum). In ASPIRE all three roles are Claude Code sessions; here they are -Codex sessions (or Claude Code), run by the framework's coding-agent agents with ASPIRE's own prompts. The framework +Codex sessions (or Claude Code or Pi), run by the framework's coding-agent agents with ASPIRE's own prompts. The framework learns only the library: the actor's harness and prompts are fixed. ## Setup @@ -107,7 +107,7 @@ carry their own seeds. | Dimension | ASPIRE (NVlabs/ASPIRE) | This port | Why | |---|---|---|---| -| Roles | coordinator, fix-loop subagents and verifiers, all Claude Code | the same three roles, Codex (or Claude Code) sessions with ASPIRE's prompts | — | +| Roles | coordinator, fix-loop subagents and verifiers, all Claude Code | the same three roles, Codex (or Claude Code or Pi) sessions with ASPIRE's prompts | — | | When learning happens | after each subagent returns | after each task (one per step) | the Trainer's step | | Curriculum | the coordinator chooses each round's tasks and logs `curriculum.md` | the same, one task per step, through `StepResult.next_tasks` | the Trainer dispatches what the coordinator names | | Parallelism | one task per GPU | one task at a time | a decision: two GPUs | diff --git a/docs/methods/evosafe.md b/docs/methods/evosafe.md index 90bc1a14..c394bf19 100644 --- a/docs/methods/evosafe.md +++ b/docs/methods/evosafe.md @@ -54,14 +54,14 @@ reused, but the OpenAI SDK no longer sends requests. Bare native AgentDyn model are no longer accepted: configure `agent.base: direct` and `agent.model: /`. The Evolver keeps Designer/Criticizer/Analyzer orchestration and all selection gates in Layer 3. Each role calls -`make("claude" | "codex", settings).run(...)` with read-only TRAIN archive tools and a fresh session. Base Agents +`make("claude" | "codex" | "pi", settings).run(...)` with read-only TRAIN archive tools and a fresh session. Base Agents own process cleanup, cancellation, timeouts, configuration, login-plan scheduling and usage. The role's JSON schema -is given to Codex as `--output-schema` and to Claude in the prompt, both through the Base Agent's existing settings, +is given to Codex as `--output-schema` and to Claude and Pi in the prompt, all through the Base Agent's existing settings, and the reply is validated against it in Layer 3; a refusal is read from the reply and the trajectory's error -steps. The normalized trajectory of each role is archived. Claude's built-in tools are disabled (`--tools ""`); -Codex has web search disabled, a read-only sandbox by default, an ephemeral session, and instructions to use only the supplied TRAIN readers. Codex's read-only mode does not hide files; use the shared isolation settings for a filesystem boundary. +steps. The normalized trajectory of each role is archived. Claude's built-in tools are disabled (`--tools ""`), and +so are Pi's (`--no-builtin-tools`); Codex has web search disabled, a read-only sandbox by default, an ephemeral session, and instructions to use only the supplied TRAIN readers. Codex's read-only mode does not hide files; use the shared isolation settings for a filesystem boundary. -`evolver.base`, `evolver.model` and `evolver.claude`/`evolver.codex` are the preferred configuration. Legacy +`evolver.base`, `evolver.model` and `evolver.claude`/`evolver.codex`/`evolver.pi` are the preferred configuration. Legacy `proposer`, `claude_model`/`codex_model`, binary and timeout settings remain accepted when the corresponding shared setting is absent. For `proposer: llm`, the existing metered Trainer `llm` tool already calls `direct`. No extra usage is added for that path; CLI usage is returned once in `StepResult`. diff --git a/docs/methods/harness2.md b/docs/methods/harness2.md index 8ffc2e11..86cbf9c4 100644 --- a/docs/methods/harness2.md +++ b/docs/methods/harness2.md @@ -40,8 +40,8 @@ task through its benchmark seam. Each step hands the step's task to `harness2.co The adapter is never written, so every task starts from H0; the library lives in the Training State. The editor sessions are upstream's `claude_cli` channel (Claude Code on the bound model, which must serve the Messages API, or -on your subscription with `evolver.params.login: claude` and a model name), -each in a sandbox that shows only its evidence and reaches only the model. A task's score is the judge's score of +on your subscription with `evolver.params.login: claude` and a model name; with `evolver.base: pi`, Pi on the bound +model), each in a sandbox that shows only its evidence and reaches only the model. A task's score is the judge's score of its deliverable, in `step_NNNN/step_result.json` (`extra.harness2`), never seen by a session. At `k = 1` a task costs four executions and four sessions (two editors, the composer, the reflector). diff --git a/docs/methods/meta_harness_adapter.md b/docs/methods/meta_harness_adapter.md index f3f90c49..37ea810c 100644 --- a/docs/methods/meta_harness_adapter.md +++ b/docs/methods/meta_harness_adapter.md @@ -40,7 +40,7 @@ This fragment belongs in a complete [run config](../framework/configuration.md). ([What an adapter can rely on](../framework/adapter.md#what-an-adapter-can-rely-on)); what happens to the adapter's other files depends on the agent, and the task information must say so, because the proposer learns it from there. -- A Codex or Claude Code CLI for the proposer, as the built-in [`codex` and `claude` Evolvers](agent.md) run it. +- A Codex, Claude Code or Pi CLI for the proposer, as the built-in [agent Evolvers](agent.md) run it. ## The template @@ -80,7 +80,7 @@ first. | Paper (Algorithm 1) | Framework | |---|---| | The filesystem D | The Evolver's `state/`: `evolution_summary.jsonl` (one line per candidate: id, round, hypothesis, base, mean score, where its files and rollouts are), `candidates//adapter/`, and the learning material's `step_NNNN/` (for each task its input, the agent's output, the judge's score and feedback, the full trajectory) | -| The proposer | An `AgentEvolver` session (Codex or Claude Code) started afresh each round with the round's prompt, `PROPOSE.md`; it reads D and writes into `scratch/candidates/` | +| The proposer | An `AgentEvolver` session (Codex, Claude Code or Pi) started afresh each round with the round's prompt, `PROPOSE.md`; it reads D and writes into `scratch/candidates/` | | Interface validation | `check_spec` on each candidate, by the proposer and again by the Evolver | | Evaluation on the search set | The Trainer's rollouts of the next step, on the training split | | Selection | `finalize`: the best mean on the search set | @@ -99,7 +99,7 @@ candidates, do not run the evaluation. |---|---|---| | `k` | Positive integer / 2 | Candidates per proposal round (the paper: 2-3; its TerminalBench-2 run: 1) | | `max_rounds` | Integer or null / null | Proposal rounds; null starts a new round whenever every proposed candidate was evaluated, including on the run's last step, whose candidates are then never evaluated. With `max_rounds` R, `trainer.epochs` = 1 + R x k evaluates each candidate once; more epochs re-evaluate the best | -| `backend`, `model`, `args` | `codex` or `claude`; `/`; CLI arguments | The proposer and its model, as for the built-in [agent Evolvers](agent.md) | +| `backend`, `model`, `args` | `codex`, `claude` or `pi`; `/`; CLI arguments | The proposer and its model, as for the built-in [agent Evolvers](agent.md) | | `tools` | List / `[check_spec]` | The Trainer tools the proposer may call; `run_agent` is left out on purpose: the evaluation is the Trainer's | | `prompt` | File name / `PROPOSE.md` | The round's prompt; its placeholders (`{round}`, `{k}`, the paths) are filled per round | @@ -112,7 +112,7 @@ The rollout cost is (1 + R x k) x |search set| rollouts for R rounds, plus one p | What the proposer may change | The whole harness program, including the acting agent's loop | Every file of the adapter outside `.hermit/`; the acting agent, its loop and the host stay fixed | forced by the framework | | Selection | A population with a Pareto frontier (for example accuracy against context length); the frontier is tested | The best mean on the search set; one candidate is tested | decision | | Parent selection | None fixed: the proposer chooses what to build on | The same: each candidate names its `base`, or none | matched | -| Proposer | Claude Code with Claude Opus 4.6 at maximum effort | Codex or Claude Code with the run's choice of model | a setting | +| Proposer | Claude Code with Claude Opus 4.6 at maximum effort | Codex, Claude Code or Pi with the run's choice of model | a setting | | Interface validation | The candidate imports | `check_spec` against the template | forced by the framework | | Isolation | — | The proposer runs in the run's sandbox; candidates with symbolic links are rejected, since they are copied outside it; a stored candidate changed in place (content or executable bit) is never handed back; the Evolver's own writes after a round never follow a link the proposer left | the reproduction's | diff --git a/docs/methods/mwm.md b/docs/methods/mwm.md index c5a12aba..6984b8ab 100644 --- a/docs/methods/mwm.md +++ b/docs/methods/mwm.md @@ -1,8 +1,8 @@ # MetaWorld Model (MWM) MWM maintains dated, scoped environment knowledge, a briefing, examples, an open-questions docket, and callable -programs. Acting agents use its context and one `wm` tool. A coding-agent learner (Codex by default, Claude Code with -`evolver.params.backend: claude`) reviews evidence after each block of episodes and maintains the world model. +programs. Acting agents use its context and one `wm` tool. A coding-agent learner (Codex by default, Claude Code or +Pi with `evolver.params.backend: claude` or `pi`) reviews evidence after each block of episodes and maintains the world model. Choose MWM for an ordered environment stream with a task-owned evidence store. It requires more task integration than a context-only optimizer; it is not a drop-in switch for an arbitrary prompt-only config. diff --git a/docs/methods/rrsi_adapter.md b/docs/methods/rrsi_adapter.md index 629c5731..21b1b4fa 100644 --- a/docs/methods/rrsi_adapter.md +++ b/docs/methods/rrsi_adapter.md @@ -25,7 +25,7 @@ evolver: params: # Layer 3: the method domain: domain.py:MyDomain # the benchmark's texts and rules (an AdapterDomain) rrsi: rrsi.json # RRSI's hyperparameters (upstream's RRSIConfig fields) - base: codex # Layer 2: the proposer and the roles are Codex (or Claude Code) sessions + base: codex # Layer 2: the proposer and the roles are Codex (or Claude Code or Pi) sessions model: {name: gpt-5.6-luna, login: chatgpt, effort: medium} # Layer 1: the proposer's model (and the roles') data: step_size: 178 # the whole evolve set (k rows per task, `#`) per step @@ -38,8 +38,8 @@ trainer: It needs the `rrsi` dependency group (`python -m pip install -e . --group rrsi`): upstream's package at a pinned commit, whose code runs unchanged for every rule and for the analyst and the critic. The analyst, its digesters and the critic are sessions of the proposer's CLI with the proposer's model, login and effort, or with -`evolver.params.roles`'. On Claude Code the analyst and the critic have no tools and a digester only those that read -(`Read`, `Grep`, `Glob`), as on Codex its read-only sandbox. +`evolver.params.roles`'. On Claude Code and Pi the analyst and the critic have no tools and a digester only those +that read (Claude Code's `Read`, `Grep`, `Glob`; Pi's `read`, `grep`, `find`, `ls`), as on Codex its read-only sandbox. ## The template @@ -111,8 +111,8 @@ The method's roles on the [agent layers](../framework/agent-layers.md): | Role | Layer 3 | Layer 2 | Layer 1 | |---|---|---|---| | The acting agent | the benchmark's Acting Agent (OfficeQA: the framework's Codex agent with OfficeQA's task functions) | `codex` | the run's `agent.model` | -| The proposer | this Evolver: its prompt, the variant's working directory and its view of the run's sandbox, `done.json` and the repairs (the session resumed) | `codex` or `claude`, `make(backend, settings).run(...)` | `evolver.model` | -| The analyst, its digesters and the critic | upstream's code; its `generate` is one session of the proposer's CLI per call (`roles.py`), each in a view of the run's sandbox showing its own call directory, in an empty directory or, a digester's, in the round's rendered traces, read-only: on Codex its own read-only sandbox, on Claude Code no tools (the analyst, the critic) or only those that read (a digester: `Read`, `Grep`, `Glob`); the digesters' read-only shell under the run's sandbox | `codex` or `claude` (the proposer's), `make(backend, settings).instructed(...)`, then `run(...)` | `evolver.model`, or `roles` | +| The proposer | this Evolver: its prompt, the variant's working directory and its view of the run's sandbox, `done.json` and the repairs (the session resumed) | `codex`, `claude` or `pi`, `make(backend, settings).run(...)` | `evolver.model` | +| The analyst, its digesters and the critic | upstream's code; its `generate` is one session of the proposer's CLI per call (`roles.py`), each in a view of the run's sandbox showing its own call directory, in an empty directory or, a digester's, in the round's rendered traces, read-only: on Codex its own read-only sandbox, on Claude Code and Pi no tools (the analyst, the critic) or only those that read (a digester: `Read`, `Grep`, `Glob`; on Pi `read`, `grep`, `find`, `ls`); the digesters' read-only shell under the run's sandbox | `codex`, `claude` or `pi` (the proposer's), `make(backend, settings).instructed(...)`, then `run(...)` | `evolver.model`, or `roles` | | The smoke | the Trainer's `run_agent` tool | the acting agent's | the acting agent's | What the method reuses rather than writes: the sessions' settings are `AgentEvolver.settings` (the login, its plan @@ -133,8 +133,8 @@ digesters' sessions in the traces, 17). |---|---| | `Evaluate(H', D_evolve, k)` | the next step's rollouts: the step's rows are the evolve set with k rows per task, credited to the candidate handed back last only when the working copy that ran is the stored candidate (its digest) | | baseline and delta (`baseline`, `calibrate(["base"])`) | step 1 evaluates H_0; delta is upstream's `calibrate` on that evaluation when the config gives none | -| `analyze` (analyst and digesters) | upstream's code; its `generate` is one session of the `codex` or `claude` Base Agent per call, the digesters' sessions in the round's rendered traces | -| proposer (a JSON-action Claude agent, `done()`) | a session of the `codex` or `claude` Base Agent on a copy of the incumbent adapter, writing `done.json`; upstream's `done()` contract is checked and every problem goes back to the same session | +| `analyze` (analyst and digesters) | upstream's code; its `generate` is one session of the `codex`, `claude` or `pi` Base Agent per call, the digesters' sessions in the round's rendered traces | +| proposer (a JSON-action Claude agent, `done()`) | a session of the `codex`, `claude` or `pi` Base Agent on a copy of the incumbent adapter, writing `done.json`; upstream's `done()` contract is checked and every problem goes back to the same session | | critic with five repairs, tag validation | upstream's `review` and `normalize`; each objection goes back to the same proposer session with upstream's repair text | | liveness smoke | `check_spec`, then `run_agent` on the domain's smoke tasks | | `select_round`, history, attribution, frontier | `select_round` and the history are upstream's code, unchanged; the attribution and the frontier are ported from upstream's driver (H_{t+1}, S* and the trajectory in `state/rrsi/frontier.json`) | @@ -163,7 +163,7 @@ stop ends the run anyway. | Dimension | The paper | Here | Kind | |---|---|---|---| | What the proposer may change | The whole harness program | Every file of the adapter outside `.hermit/`; the acting agent, its loop and the host stay fixed | forced by the framework | -| The proposer | Claude Opus 4.8 in upstream's JSON-action loop | A session of the `codex` or `claude` Base Agent with `evolver.model`, upstream's system text, context sections and done() contract | a setting | +| The proposer | Claude Opus 4.8 in upstream's JSON-action loop | A session of the `codex`, `claude` or `pi` Base Agent with `evolver.model`, upstream's system text, context sections and done() contract | a setting | | The search roles | Claude Opus 4.8, one completion per call; the analyst and the critic answer from the text they are given | The proposer's model (or `roles`), one session of the proposer's CLI per call, read-only (Codex's own sandbox, or on Claude Code no tools or only those that read): the analyst and the critic in an empty directory, a digester in the round's rendered traces, which it may read with its own tools as well as through upstream's actions; none of them sees the run's records, the step's output, the proposers' directories or the other role calls' | a setting | | Component vocabulary | Signals in the Terminus-2 source | The same K, with signals for adapter files (`domain.ADAPTER_SIGNALS`) | forced by the framework | | delta | Measured from repeated base evaluations (coding: 0.017) | Upstream's `calibrate` on H_0's one evaluation unless the config gives one (its within-task bootstrap reads low by about sqrt(2) with two trials, as upstream's does; on OfficeQA the spread of H_0's own evaluations across the runs, sd 0.035, gives a band of about 0.10 for a difference, against a calibrated 0.045–0.061) | matched to upstream's driver | diff --git a/docs/reference/config-fields.md b/docs/reference/config-fields.md index 2812088b..5cd60067 100644 --- a/docs/reference/config-fields.md +++ b/docs/reference/config-fields.md @@ -57,9 +57,9 @@ Task row fields become training material, so private labels require judge-owned | `evolver.name` | string / null; required | Built-in method or directory containing its Evolver definition | | `evolver.resume` | boolean / false | Request learner-session continuation; method must support it | | `evolver.params` | mapping / {} | Overrides merged with the chosen method's defaults | -| `evolver.base` | string / null | Layer 2 the method runs on: `codex`, `claude` or `pi` (an agent Evolver: sets `evolver.params.backend`) or `direct` | +| `evolver.base` | string / null | Layer 2 the method runs on: `codex`, `claude` or `pi` (an agent Evolver: sets `evolver.params.backend`) or `direct`. On a method that calls the run's model, `pi` makes that model Pi (`llm: {cli: pi, ...}`) | | `evolver.model` | string / mapping / null | Layer 1, as `agent.model`; with `evolver.base: direct` it is the run's `llm` | -| `evolver.codex`, `evolver.claude`, `evolver.pi`, `evolver.direct` | mapping / null | Layer 2's settings, read into `evolver.params` | +| `evolver.codex`, `evolver.claude`, `evolver.pi`, `evolver.direct` | mapping / null | Layer 2's settings, read into `evolver.params` (`evolver.pi` on a method that calls the run's model: into `llm`) | | `evolver_access.environment` | list / [] | Granted environment resources; required for MWM's evidence integration | | `evolver_access.tools` | list / [] | Task tool declarations offered to the learner | | `evolver_access.send_material_out` | boolean / false | Consent declaration checked for methods requesting that need; not a network filter | @@ -102,12 +102,12 @@ cached-input price falls back to the input price. Supply all applicable prices r Per-call arguments override matching `extra_body` fields. The underlying client defaults to a 600-second HTTP timeout and four retries; `llm.timeout` (seconds) is forwarded, `llm.max_retries` is not. A model only a CLI reaches, as `llm` or as an acting pipeline's `agent.model`: each chat call is one session with no -tools, which on Claude Code can only reply ([Claude subscription](../guides/claude-subscription.md)). Any other key is +tools, which on Claude Code or Pi can only reply ([Claude subscription](../guides/claude-subscription.md)). Any other key is the Base Agent's setting (`hermit/agent/base/cli.py`). | Field | Type / default | Meaning | |---|---|---| -| `cli` | `codex`, `claude` | The Base Agent | +| `cli` | `codex`, `claude`, `pi` | The Base Agent. Pi takes a `/` reference, `isolation: sandbox` and no `login` | | `model` | string | The CLI's model name; required with `login: claude`. A `/` reference binds it to that backend's key instead | | `login` | `chatgpt`, `claude` | The user's subscription on that CLI | | `isolation` | string / `sandbox` | `sandbox`: a bubblewrap sandbox of its own (role `llm`, an acting pipeline's `agent-model`: its empty workspace and home, its model's or login's hosts through a proxy of its own, its key or token, nothing of the run); `container`: a Docker container of its own. With `sandbox.enabled: false` it runs unconfined | diff --git a/hermit/adapter/templates/ahe/.hermit/EVOLVER.md b/hermit/adapter/templates/ahe/.hermit/EVOLVER.md index 594714b4..070ede41 100644 --- a/hermit/adapter/templates/ahe/.hermit/EVOLVER.md +++ b/hermit/adapter/templates/ahe/.hermit/EVOLVER.md @@ -94,7 +94,7 @@ only the stdlib: nothing else is installed where the agent runs. `nexau.txt`: a hook that never fires, always errors, or denies the wrong commands is visible there and nowhere else. `hook-state/.json` beside it holds the final session states. (The runner writes both under `.hermit-hooks/` in the session's workspace; each rollout's trajectory carries them at its root, beside the - agent's event stream: `agent-codex.jsonl` from Codex, `agent-claude.jsonl` from Claude Code.) + agent's event stream: `agent-codex.jsonl` from Codex, `agent-claude.jsonl` from Claude Code, `agent-pi.jsonl` from Pi.) - A veto's reason is what the model reads: say what to do instead, not only what was blocked. The same holds for an `after_tool` note: one or two lines, specific to the command that just ran. diff --git a/hermit/agent/base/cli.py b/hermit/agent/base/cli.py index 0ef83dc8..9a06d429 100644 --- a/hermit/agent/base/cli.py +++ b/hermit/agent/base/cli.py @@ -61,15 +61,18 @@ caller that would rather start over from its own files text_only a session that can only reply (a model behind a chat endpoint, a role that answers from its prompt). Claude Code: `--restricted`, no tools, no MCP servers, no commands, no settings or - memory files, `@` mentions left as text, and a session that reports otherwise has failed + memory files, `@` mentions left as text, and a session that reports otherwise has failed. Pi: no + tools, no MCP, no extensions, skills, prompt templates or context files, and a session that runs a + tool has failed Claude Code only: output_format (stream-json, or json: one result object), allowed_tools (its --tools; empty: none), persist_session (false: --no-session-persistence), system_prompt (in place of its own; written to a file in the home), append_system_prompt (a long one goes the same way), effort, permission_mode, usage_credits (true: sessions on `login: claude` may draw the account's usage credits; default: a session that did holds the next ones back) Pi only: provider (its models.json entry for a bound model, from the binding: Binding.pi_provider), image_input (true: the bound model takes images, such as a tool's result; default: text only, Pi's default for a - model it does not know), append_system_prompt, effort (its --thinking level). Pi takes no roles, has no web search - and runs under isolation none or sandbox. + model it does not know), append_system_prompt, effort (its --thinking level), allowed_tools (Pi's own tools by name, + its --tools: read, grep, find, ls, bash, edit, write; the call's tools stay; empty: none of its own), persist_session + (false: --no-session). Pi takes no roles, has no web search and runs under isolation none or sandbox. mini-swe-agent only: model_class, config, step_limit (MiniSweAgent; hermit.agent.base.mini_swe_agent). It takes no roles, no session and no login, has no web search and runs under isolation none or sandbox. @@ -1339,6 +1342,7 @@ class Pi(CliAgent): home_var, user_folder = "PI_CODING_AGENT_DIR", ".pi/agent" home_files = ("auth.json",) turn_done = "agent_settled" + efforts = ("off", "minimal", "low", "medium", "high", "xhigh") # what --thinking takes; it warns and ignores others def home_env(self, home): """Every variable Pi reads goes here, so that it passes the sandbox's filter: its agent directory, its HOME @@ -1417,9 +1421,12 @@ def errors(cls, event): def outcome(self, raw, stream, last_file): """Pi's JSON mode exits 0 however the session ended: one that did not settle, aborted, or whose last request - failed, was aborted or was cut at the output limit (Pi's text mode exits 1 for each) has failed.""" + failed, was aborted or was cut at the output limit (Pi's text mode exits 1 for each) has failed, and so has a + session that was to have no tools and ran one.""" notes, done = self.notices(raw), self.served(raw) cut = self._last_assistant(raw).get("stopReason") == "length" + if self.settings.get("text_only") and any(e.get("type") == "tool_execution_start" for e in _objects(raw)[0]): + notes, done = "the session was to have no tools, and it ran one", False return {"reply": self.last_message(stream, last_file), "served": done, "unavailable": bool(UNAVAILABLE.search(notes)), "refused": False, "failed": not done or cut, "failure": (notes or ("the reply was cut at its output limit" if cut else "the session did not settle") @@ -1453,8 +1460,24 @@ def parse(cls, log, model): def steps(cls, stream): return pi_steps(stream) + def _access(self, tools_url) -> list[str]: + """What a limited session may use: with `text_only` nothing but its prompt; with `allowed_tools` those of Pi's + own tools and the call's, which an allow-list would otherwise drop.""" + s = self.settings + if s.get("text_only"): + return ["--no-tools", "--no-mcp", "--no-extensions", "--no-skills", "--no-prompt-templates", + "--no-context-files"] + names = s.get("allowed_tools") + if names is None: + return [] + if not names: + return ["--no-builtin-tools"] + return ["--tools", ",".join([*names, *([f"mcp__{s.get('tools_name') or 'hermit_tools'}__*"] if tools_url else [])])] + def command(self, prompt, workspace, last_file, *, session=None, roles=(), tools_url=None): s, home = self.settings, last_file.parent # the session's home + if s.get("effort") and s["effort"] not in self.efforts: # the CLI would warn and go on at its default + raise Unsupported(f"Pi takes effort {', '.join(self.efforts)}, not {s['effort']!r}") system = s.get("append_system_prompt") if system and len(str(system).encode()) > ARG_MAX: # too long for one argument _clear(home / "append_system.md") @@ -1466,7 +1489,8 @@ def command(self, prompt, workspace, last_file, *, session=None, roles=(), tools *(["--model", s["model"]] if s.get("model") else []), *(["--thinking", s["effort"]] if s.get("effort") else []), *(["--append-system-prompt", system] if system else []), - *self.web_search_args(bool(s.get("web_search"))), + *self.web_search_args(bool(s.get("web_search"))), *self._access(tools_url), + *(["--no-session"] if s.get("persist_session") is False else []), *(["--session", str(resume)] if resume else []), *(s.get("args") or []), *([] if s.get("stdin") else ["--", prompt])] diff --git a/hermit/agent/base/endpoint.py b/hermit/agent/base/endpoint.py index 35c46395..05691f96 100644 --- a/hermit/agent/base/endpoint.py +++ b/hermit/agent/base/endpoint.py @@ -334,11 +334,11 @@ def _usage_of(result) -> dict: def cli_answer(agent: BaseAgent, request: dict, abort: threading.Event | None = None): - """A chat-completions request answered by one session of a CLI Base Agent (`codex`, `claude`): a model reachable - only through the CLI (a subscription) for code that calls a chat API (an Evolver's `llm`, an acting pipeline's - model). The system messages are the session's instructions, the rest its prompt (split_messages), given on stdin; - the session works in an empty workspace of its own and only replies (`text_only`: Claude Code's session has no - tools; a Codex session's commands are held by its sandbox or container), and its reply is the content, with its + """A chat-completions request answered by one session of a CLI Base Agent (`codex`, `claude`, `pi`): a model reached + through the CLI (a subscription, or the Evolver's own agent) for code that calls a chat API (an Evolver's `llm`, an + acting pipeline's model). The system messages are the session's instructions, the rest its prompt (split_messages), + given on stdin; the session works in an empty workspace of its own and only replies (`text_only`: a Claude Code or + Pi session has no tools; a Codex session's commands are held by its sandbox or container), and its reply is the content, with its token usage. `reasoning_effort` is the session's effort; max_tokens is not applied and the reply says so (`unapplied`); what else a session cannot do is refused (contract_problems). A session that gave no reply is never an answer (_no_reply). The session sees no files: a caller that wants a session to read files runs one itself @@ -416,16 +416,31 @@ def cli_problems(spec: dict) -> list[str]: its own (`isolation: container`, with container: {image, network, proxy}); a machine without bubblewrap runs it unconfined only as the run says (sandbox.enforce: best_effort, sandbox.enabled: false), which the run's records keep. Codex's model can run commands, and Codex's own read-only sandbox still reads the whole machine (the test - answers, the keys); Claude Code's has no tools at all (the Base Agent's `text_only`), and the sandbox holds what - the CLI might do besides. A login is the CLI's own: chatgpt for codex, claude for claude.""" + answers, the keys); Claude Code's and Pi's have no tools at all (the Base Agent's `text_only`), and the sandbox holds + what the CLI might do besides. A login is the CLI's own: chatgpt for codex, claude for claude; Pi has none, and + reaches its model through a `/` reference.""" isolation = spec.get("isolation") or "sandbox" if spec.get("cli") == "codex": out = [] if isolation in ("sandbox", "container") else [CODEX_BOUNDARY] if spec.get("login") and spec["login"] != "chatgpt": out.append(f"cli: codex signs in with login: chatgpt (Codex's sign-in), not login: {spec['login']}") return out + if spec.get("cli") == "pi": + from hermit.agent.base.cli import Pi + out = [] if isolation == "sandbox" else ["cli: pi needs isolation: sandbox (the default: a bubblewrap sandbox of " + "its own); without bubblewrap, sandbox.enforce: best_effort runs it " + "unconfined and records that"] + if spec.get("login"): + out.append(f"cli: pi signs in through a / reference, not login: {spec['login']}") + elif not spec.get("binding"): + out.append("cli: pi needs a / reference: without one, Pi would pick a provider itself") + if spec.get("web_search") is True: + out.append("cli: pi: a text session has no tools, so web_search cannot be on") + if spec.get("effort") is not None and spec["effort"] not in Pi.efforts: # the CLI would ignore it + out.append(f"cli: pi takes effort {', '.join(Pi.efforts)}, not {spec['effort']!r}") + return out if spec.get("cli") != "claude": - return [f"cli must be codex or claude, not {spec.get('cli')!r}"] + return [f"cli must be codex, claude or pi, not {spec.get('cli')!r}"] out = [] if not spec.get("binding") and spec.get("login") != "claude": out.append("cli: claude needs login: claude (your subscription) or a / reference (that " diff --git a/hermit/agent/evolver/loader.py b/hermit/agent/evolver/loader.py index 375b633e..fef8189a 100644 --- a/hermit/agent/evolver/loader.py +++ b/hermit/agent/evolver/loader.py @@ -68,7 +68,7 @@ def load_class(spec: EvolverSpec) -> type[Evolver]: def instantiate(spec: EvolverSpec, params: dict, *, backends: dict | None = None, default_model=None) -> tuple[Evolver, dict]: """The Evolver instance and its effective params (manifest defaults overridden by the run config). An Evolver - that is a Codex or Claude Code agent (`backend` in its params) gets its model bound: a `/` + that is a Codex, Claude Code or Pi agent (`backend` in its params) gets its model bound: a `/` reference in `model` (or the run's default) becomes the provider settings in `args` or `env`. A param the Evolver class lists in `model_params` that holds a reference becomes that model's resolved spec.""" merged = {**spec.params, **(params or {})} diff --git a/hermit/agent/evolver/methods/ahe_adapter/debugger.py b/hermit/agent/evolver/methods/ahe_adapter/debugger.py index 39ba9e9b..05045a03 100644 --- a/hermit/agent/evolver/methods/ahe_adapter/debugger.py +++ b/hermit/agent/evolver/methods/ahe_adapter/debugger.py @@ -1,4 +1,4 @@ -"""The Agent Debugger stage of the AHE Adapter (spec B.5): one CLI session (Codex or Claude Code) per task over the +"""The Agent Debugger stage of the AHE Adapter (spec B.5): one CLI session (Codex, Claude Code or Pi) per task over the step's rollouts. Upstream (evolve.py:1216-1315, 1381-1543, 1722-1790) built one `TaskAnalysisJob` per task from the trial directories @@ -181,7 +181,11 @@ def trace_source(log: Path | None) -> tuple[Path, str] | None: ("the raw Codex event stream", "the raw Claude Code event stream"), ("the Codex event stream", "the Claude Code event stream"), ("`codex exec --json` event stream", - "`claude -p --output-format stream-json` event stream"))} + "`claude -p --output-format stream-json` event stream")), + "agent-pi.jsonl": (("agent-codex.jsonl", "agent-pi.jsonl"), + ("the raw Codex event stream", "the raw Pi event stream"), + ("the Codex event stream", "the Pi event stream"), + ("`codex exec --json` event stream", "`pi --mode json` event stream"))} def stream_of(logs) -> str: diff --git a/hermit/agent/evolver/methods/ahe_adapter/evolver.py b/hermit/agent/evolver/methods/ahe_adapter/evolver.py index fca90243..d32812fd 100644 --- a/hermit/agent/evolver/methods/ahe_adapter/evolver.py +++ b/hermit/agent/evolver/methods/ahe_adapter/evolver.py @@ -236,18 +236,19 @@ class AHEAdapterEvolver(AgentEvolver): supports_resume = False # a fresh CLI session per step, as run_evolve_agent builds a new agent each loop def setup(self, ctx: Context) -> None: - if ctx.params.get("backend", "codex") not in ("codex", "claude"): + if ctx.params.get("backend", "codex") not in ("codex", "claude", "pi"): raise ValueError("the AHE Adapter's Evolve Agent and Agent Debugger are sessions of a CLI Base Agent: " - f"evolver.params.backend is codex or claude, not {ctx.params.get('backend')!r}") + f"evolver.params.backend is codex, claude or pi, not {ctx.params.get('backend')!r}") if not isinstance(ctx.params.get("web_search"), bool): raise ValueError("evolver.params.web_search must be set, true or false") from hermit.agent.evolver.methods.ahe_adapter import debugger as D - if ctx.params.get("backend") == "claude": # an effort Claude Code takes, for both agents (else refused) - from hermit.agent.base.cli import Claude + if ctx.params.get("backend") in ("claude", "pi"): # an effort the CLI takes, for both agents (else refused) + from hermit.agent.base.cli import CLIS + cli = CLIS[ctx.params["backend"]] efforts = (("effort", ctx.params.get("effort")), ("debugger.effort", D.settings(ctx.params).get("effort"))) for name, effort in efforts: - if effort and effort not in Claude.efforts: - raise ValueError(f"evolver.params.{name} is one of {', '.join(Claude.efforts)} for Claude Code, " + if effort and effort not in cli.efforts: + raise ValueError(f"evolver.params.{name} is one of {', '.join(cli.efforts)} for {cli.label}, " f"not {effort!r}") own = D.settings(ctx.params).get("model") if own != ctx.params.get("model") and (ctx.params.get("binding") or ctx.params.get("price")): diff --git a/hermit/agent/evolver/methods/ahe_adapter/evolver.yaml b/hermit/agent/evolver/methods/ahe_adapter/evolver.yaml index 43d3ddf5..f563a902 100644 --- a/hermit/agent/evolver/methods/ahe_adapter/evolver.yaml +++ b/hermit/agent/evolver/methods/ahe_adapter/evolver.yaml @@ -4,7 +4,7 @@ description: >- the step's k rollouts per task (pass / fail / exception), diffs them against the previous step (flipped / regressed / rollout moves / infra buckets), scores the previous step's change manifest (EFFECTIVE ... HARMFUL, upstream's rules verbatim), rolls HARMFUL changes back file by file (Algorithm 1; `rollback: agent` leaves it to the agent as the released code does), runs the - Agent Debugger as one session of the Evolver's Base Agent (codex or claude) per task over the rollouts' trajectories and + Agent Debugger as one session of the Evolver's Base Agent (codex, claude or pi) per task over the rollouts' trajectories and verdicts (upstream's queries verbatim), writes the deterministic analysis overview, and runs the Evolve Agent (AgentEvolver's session of the same Base Agent on upstream's evolve prompt) that edits the adapter and writes the step's change manifest. No Explore Agent; no Best-of-N; finalize hands back the best-ever evaluated snapshot; tokens/trial is recorded, which upstream @@ -12,13 +12,13 @@ description: >- class: evolver.py:AHEAdapterEvolver needs: [] params: - backend: codex # the Evolve Agent's and the Agent Debugger's Base Agent: codex or claude + backend: codex # the Evolve Agent's and the Agent Debugger's Base Agent: codex, claude or pi model: null # the Evolve Agent's model (the example sets it); with a login, the CLI's model name # (required with login: claude) login: null # the user's subscription and its plan (hermit.agent.base.login): chatgpt (codex, its # shared login copy) or claude (claude, CLAUDE_CODE_OAUTH_TOKEN) effort: null # Codex's model_reasoning_effort, or Claude Code's --effort (low..max) (the example sets it) - bin: null # the CLI's program; null: codex or claude on PATH + bin: null # the CLI's program; null: codex, claude or pi on PATH args: [] # extra arguments for the CLI prompt: START.md resume_prompt: null # a fresh session every step (evolve.py:3055) diff --git a/hermit/agent/evolver/methods/aspire/evolver.py b/hermit/agent/evolver/methods/aspire/evolver.py index 4fb5ec5e..b69a40de 100644 --- a/hermit/agent/evolver/methods/aspire/evolver.py +++ b/hermit/agent/evolver/methods/aspire/evolver.py @@ -1,6 +1,6 @@ """AspireEvolver: the coordinator of ASPIRE (Agentic Skills Discovery for Robotics; arXiv:2607.00272, §2.2 and §2.4; github.com/NVlabs/ASPIRE, `.claude/skills/iterative-debugging/main-agent-prompt.md`) as an Evolver on the `aspire` -template: a Codex (or Claude Code) session, as the built-in agent Evolvers run it, given the guide's own sections on +template: a Codex (or Claude Code or Pi) session, as the built-in agent Evolvers run it, given the guide's own sections on updating skills, dispatching verifiers and choosing the curriculum (COORDINATOR.md). In ASPIRE a coordinator agent dispatches one fix-loop subagent per robot task, runs its Stage 2 evaluation, updates diff --git a/hermit/agent/evolver/methods/aspire/evolver.yaml b/hermit/agent/evolver/methods/aspire/evolver.yaml index b9dec631..788512ce 100644 --- a/hermit/agent/evolver/methods/aspire/evolver.yaml +++ b/hermit/agent/evolver/methods/aspire/evolver.yaml @@ -1,5 +1,5 @@ description: >- - ASPIRE's coordinator (arXiv:2607.00272): a Codex or Claude Code session that updates the skill library from each + ASPIRE's coordinator (arXiv:2607.00272): a Codex, Claude Code or Pi session that updates the skill library from each finished robot task's findings and skill report, admits proposals only after a fresh verifier re-solves the task from the library and the proposals alone (run_agent on the task's verifier row), and chooses the next task. class: evolver.py:AspireEvolver diff --git a/hermit/agent/evolver/methods/evosafe/cli_roles.py b/hermit/agent/evolver/methods/evosafe/cli_roles.py index ccbf21e8..251ad1a9 100644 --- a/hermit/agent/evolver/methods/evosafe/cli_roles.py +++ b/hermit/agent/evolver/methods/evosafe/cli_roles.py @@ -1,4 +1,4 @@ -"""EvoSafe's role orchestration over the shared CLI Base Agents (`codex`, `claude`). +"""EvoSafe's role orchestration over the shared CLI Base Agents (`codex`, `claude`, `pi`). Each role is one fresh session of the configured CLI through `make(backend, settings).run(...)`; the Base Agent owns the process, the login plan, the timeout, cancellation and usage. The structured answer is checked here, @@ -14,7 +14,8 @@ # The Layer 1/2 settings a configuration may give the role CLI; the rest are set per call below. CLI_SETTINGS = ("model", "binding", "login", "login_root", "plan_dir", "plan_max_wait_s", "plan_rerun", "usage_credits", "effort", "codex_sandbox", "permission_mode", "shell_env", "project_doc_max_bytes", - "home_files", "args", "env", "env_drop", "price", "timeout_s", "bin") + "home_files", "args", "env", "env_drop", "price", "timeout_s", "bin", "provider", "image_input") +CLI_PROPOSERS = ("codex", "claude", "pi") # Provider messages that mean the role request itself was refused (stop, never retried). REFUSAL = ("usage policy", "content_policy_violation", "flagged for possible cybersecurity risk") @@ -87,6 +88,10 @@ def call_role(ctx, messages, schema, name, backend): # No built-in tools (files, commands, browsing); TRAIN readers remain available over MCP. settings.update(args=args + ["--tools", ""], persist_session=False, append_system_prompt=system) prompt = instructions + answer_format + user + elif backend == "pi": + # None of Pi's own tools (files, commands); TRAIN readers remain available over MCP. + settings.update(allowed_tools=[], persist_session=False, append_system_prompt=system) + prompt = instructions + answer_format + user else: # Codex enforces the schema on its last message; the session is ephemeral and read-only. (root / "output-schema.json").write_text(json.dumps(schema)) diff --git a/hermit/agent/evolver/methods/evosafe/evolver.py b/hermit/agent/evolver/methods/evosafe/evolver.py index badaf81a..021c88b4 100644 --- a/hermit/agent/evolver/methods/evosafe/evolver.py +++ b/hermit/agent/evolver/methods/evosafe/evolver.py @@ -29,8 +29,8 @@ def step(self, ctx): if not ids or len(set(ids)) != len(ids): return StepResult("failed", "provide unique fixed eval_task_ids or a validation split") proposer = role_backend(ctx.params) - if proposer not in {"llm", "codex", "claude"}: - return StepResult("failed", "proposer must be llm, codex or claude") + if proposer not in {"llm", "codex", "claude", "pi"}: + return StepResult("failed", "proposer must be llm, codex, claude or pi") if proposer == "llm" and "llm" not in ctx.tools: return StepResult("failed", "configure the run's llm tool for defense proposals") search_mode = ctx.params.get("search_mode", "single") @@ -59,11 +59,12 @@ def step(self, ctx): (ws.adapter / ".hermit" / "EVOLVER.md").read_text()}, {"role": "user", "content": json.dumps({"files": files, "parent_metrics": parent, "previous_trials": prior, "evidence": evidence})}] - if proposer in ("codex", "claude"): - from hermit.agent.evolver.methods.evosafe.claude_code import call_role as claude_call + if proposer in ("codex", "claude", "pi"): + from hermit.agent.evolver.methods.evosafe import claude_code, pi_agent from hermit.agent.evolver.methods.evosafe.codex import proposal_schema + call = {"claude": claude_code.call_role, "pi": pi_agent.call_role}.get(proposer) response, usage, error = (codex_propose(ctx, messages) if proposer == "codex" - else claude_call(ctx, messages, proposal_schema(), "proposal")) + else call(ctx, messages, proposal_schema(), "proposal")) if error: raise RuntimeError(error) else: diff --git a/hermit/agent/evolver/methods/evosafe/evolver.yaml b/hermit/agent/evolver/methods/evosafe/evolver.yaml index 89a78c7e..8eec840c 100644 --- a/hermit/agent/evolver/methods/evosafe/evolver.yaml +++ b/hermit/agent/evolver/methods/evosafe/evolver.yaml @@ -10,14 +10,14 @@ params: reuse_rollout_parent: true parent_error_policy: reject # reject | conservative_bounds (failed parent runs get their best possible verdict) candidate_error_policy: reject # reject | worst_case_bounds (failed candidate runs get their worst possible verdict) - role_retries: 0 # extra attempts for a failed codex/claude role call (never for refusals) + role_retries: 0 # extra attempts for a failed CLI role call (never for refusals) review_revisions: 2 # extra Criticizer rounds (total capped at 3), then a final Designer repair spec_repair_attempts: 2 # extra repairs for size/spec failures; no Criticizer call is spent max_defense_bytes: 32000 # role search budget in UTF-8 bytes; never exceeds the template limit evidence_chars_per_case: 2000 # initial summaries; complete TRAIN observations available through role tools robustness_task_ids: [] # Prefer evolver.base/model/; these fields keep old configurations readable. - proposer: llm # llm | codex | claude (Claude Code CLI; read-only TRAIN experience tools) + proposer: llm # llm | codex | claude | pi (a CLI with read-only TRAIN experience tools) codex_bin: codex codex_model: gpt-6-sol codex_timeout_s: 600 diff --git a/hermit/agent/evolver/methods/evosafe/pi_agent.py b/hermit/agent/evolver/methods/evosafe/pi_agent.py new file mode 100644 index 00000000..174eb206 --- /dev/null +++ b/hermit/agent/evolver/methods/evosafe/pi_agent.py @@ -0,0 +1,6 @@ +"""Pi defense roles through the shared Base Agent API.""" +from .cli_roles import call_role as _call_role + + +def call_role(ctx, messages, schema, name): + return _call_role(ctx, messages, schema, name, "pi") diff --git a/hermit/agent/evolver/methods/evosafe/roles.py b/hermit/agent/evolver/methods/evosafe/roles.py index 00474eb5..7646bff0 100644 --- a/hermit/agent/evolver/methods/evosafe/roles.py +++ b/hermit/agent/evolver/methods/evosafe/roles.py @@ -10,11 +10,11 @@ import shutil from hermit.adapter.manifest import read_meta, structure_of -from .cli_roles import proposer as role_backend +from .cli_roles import CLI_PROPOSERS, proposer as role_backend from hermit.agent.evolver.base import StepResult from .codex import call_role, proposal_schema from .contract import aggregate, completed, injected as is_injected, qualifying_gain, verdict -from . import claude_code +from . import claude_code, pi_agent from .evidence import result_evidence, failure_packet from .experience import TrainingExperience @@ -274,7 +274,7 @@ def messages(value): return [{'role': 'system', 'content': COMMON + '\n' + role}, {'role': 'user', 'content': json.dumps(value, ensure_ascii=False)}] result = messages(payload) - if role_backend(ctx.params) not in ('codex', 'claude') or len(json.dumps(result, ensure_ascii=False)) <= 800000: + if role_backend(ctx.params) not in CLI_PROPOSERS or len(json.dumps(result, ensure_ascii=False)) <= 800000: return result if not (ctx.workspace.state / 'training-experience/index.json').is_file(): raise ValueError('role input too large; no complete TRAIN archive is available') @@ -309,8 +309,8 @@ def invoke_role(ctx, role, payload, schema, name, usage, *, retries=None): messages = role_messages(ctx, role, payload) (ctx.workspace.output / (name + '-input.json')).write_text(json.dumps(messages, indent=2)) proposer = role_backend(ctx.params) - if proposer in ('codex', 'claude'): - call = call_role if proposer == 'codex' else claude_code.call_role + if proposer in CLI_PROPOSERS: + call = {'codex': call_role, 'claude': claude_code.call_role, 'pi': pi_agent.call_role}[proposer] # Transient CLI/API failures get a bounded number of fresh attempts; # a refusal or a cancellation is never retried. for attempt in range(int(ctx.params.get('role_retries', 0) if retries is None else retries) + 1): @@ -628,7 +628,7 @@ def run(ctx, ids): 'priority_cases': priority_cases, 'previous_candidate_evidence': designer_feedback(previous_candidate_evidence), 'training_evidence': evidence, 'lessons': lessons[-12:], - 'training_experience': experience.brief(interactive=role_backend(p) in ('codex', 'claude')), + 'training_experience': experience.brief(interactive=role_backend(p) in CLI_PROPOSERS), 'previous_trials': [training_trial(t) for t in trials[:-1]], 'iteration': number} trial['reviews'] = [] trial['criticizer_calls'] = 0 @@ -673,7 +673,7 @@ def run(ctx, ids): 'mechanism_plan': mechanism, 'review_call': trial['criticizer_calls'], 'max_criticizer_calls': review_limit, 'previous_required_changes': (revision_request or {}).get('required_changes'), - 'training_evidence': evidence, 'training_experience': experience.brief(interactive=role_backend(p) in ('codex', 'claude')), + 'training_evidence': evidence, 'training_experience': experience.brief(interactive=role_backend(p) in CLI_PROPOSERS), 'spec_check': trial['check']}, REVIEW_SCHEMA, stem + '-criticizer' + suffix, usage, retries=0) trial['last_criticizer_review'] = review @@ -783,7 +783,7 @@ def run(ctx, ids): experience.put(version + '/trial', training_trial(trial), kind='trial', version=version) try: analysis = invoke_role(ctx, ANALYZER, { - 'trial': training_trial(trial), 'training_experience': experience.brief(interactive=role_backend(p) in ('codex', 'claude')), + 'trial': training_trial(trial), 'training_experience': experience.brief(interactive=role_backend(p) in CLI_PROPOSERS), 'priority_cases': packet, 'measured_comparison': measured_comparison(parent_rows, candidate_rows), 'parent_files': files, diff --git a/hermit/agent/evolver/methods/harness2_upstream/bench.py b/hermit/agent/evolver/methods/harness2_upstream/bench.py index 047029c8..b474a545 100644 --- a/hermit/agent/evolver/methods/harness2_upstream/bench.py +++ b/hermit/agent/evolver/methods/harness2_upstream/bench.py @@ -207,6 +207,9 @@ def trajectory(self, run_dir: Path, *, obs_trunc: int) -> str: elif (log / "agent-claude.jsonl").is_file(): # a Claude Code session, in upstream's grammar from hermit.agent.evolver.methods.harness2_upstream.render import render_claude_events text = render_claude_events(log / "agent-claude.jsonl", obs_trunc=obs_trunc, max_chars=limit) + elif (log / "agent-pi.jsonl").is_file(): # a Pi session, in upstream's grammar + from hermit.agent.evolver.methods.harness2_upstream.render import render_pi_events + text = render_pi_events(log / "agent-pi.jsonl", obs_trunc=obs_trunc, max_chars=limit) else: return f"(no trajectory recorded for {Path(run_dir).name})" output = run.get("output") if isinstance(run.get("output"), dict) else {} diff --git a/hermit/agent/evolver/methods/harness2_upstream/channel.py b/hermit/agent/evolver/methods/harness2_upstream/channel.py index d139f3cb..9e92748a 100644 --- a/hermit/agent/evolver/methods/harness2_upstream/channel.py +++ b/hermit/agent/evolver/methods/harness2_upstream/channel.py @@ -62,10 +62,13 @@ def _claude_cli(self, cwd: Path, mission: str, system: str, wall: int) -> tuple[ """One upstream session as one call of a CLI Base Agent (docs/framework/agent-layers.md): `claude` by default, upstream's command (stdin mission, its system prompt, one JSON result, its tools, no session kept); `codex` with `params.backend: codex` (a model only Codex reaches: a ChatGPT login), the mission on stdin, the system - text as its developer instructions, its own sandbox off inside the run's. Either has its own config directory, - runs in the run's sandbox with the session directory writable, and is stopped at `wall` or by the Trainer.""" + text as its developer instructions, its own sandbox off inside the run's; `pi` with `params.backend: pi`, on + the bound model. Each has its own config directory, runs in the run's sandbox with the session directory + writable, and is stopped at `wall` or by the Trainer.""" if self.params.get("backend") == "codex": return self._codex_cli(cwd, mission, system, wall) + if self.params.get("backend") == "pi": + return self._pi_cli(cwd, mission, system, wall) home = Path(cwd) / ".claude-home" stdin = mission if system and len(system) > SYSTEM_ARG_MAX: @@ -141,10 +144,34 @@ def _codex_cli(self, cwd: Path, mission: str, system: str, wall: int) -> tuple[s "writable": [Path(cwd)], "timeout_s": wall, "cancel": self.cancel} settings = {k: v for k, v in settings.items() if v is not None or k == "plan_max_wait_s" and k in self.params} result = make("codex", settings).run(mission, workspace=Path(cwd)) # plan_max_wait_s: null is no limit + return self._reply("codex", result, err, wall) + + def _pi_cli(self, cwd: Path, mission: str, system: str, wall: int) -> tuple[str, float, str]: + """The session on Pi: the `pi` Base Agent on the bound model (its models.json provider), the mission on stdin, + upstream's system text appended to Pi's own, Pi's own tools (read, bash, edit, write) inside the run's sandbox, + no session kept.""" + from hermit.agent.base.cli import EFFORTS + own = {k: str(v) for k, v in (self.params.get("env") or {}).items()} + err = Path(cwd) / ".session.err" + settings = {"web_search": False, "bin": self.params.get("claude_bin") or "pi", "stdin": True, + "effort": EFFORTS.get(self.spec.effort, self.spec.effort), # Claude Code's max is Pi's xhigh + "model": self.params.get("model") or self.spec.model, "binding": self.params.get("binding"), + "provider": self.params.get("provider"), "image_input": self.params.get("image_input"), + "price": self.params.get("price"), "args": self.params.get("args"), + "append_system_prompt": system or None, "persist_session": False, + "home": Path(cwd) / ".pi-home", "home_files": [], "log": Path(cwd) / ".session.out", + "stderr_log": err, "env": {**QUIET, **own}, "env_drop": sorted(_DROP_ENV), + "isolation": "sandbox" if self.sandbox is not None else "none", "sandbox": self.sandbox, + "writable": [Path(cwd)], "timeout_s": wall, "cancel": self.cancel} + result = make("pi", {k: v for k, v in settings.items() if v is not None}).run(mission, workspace=Path(cwd)) + return self._reply("pi", result, err, wall) + + def _reply(self, program: str, result, err: Path, wall: int) -> tuple[str, float, str]: + """(reply, cost, problem) of a Codex or Pi session, its usage kept for the step.""" if result.extra["cancelled"]: raise RuntimeError("the session was stopped by the Trainer (budget or timeout)") if result.timed_out: - raise subprocess.TimeoutExpired(["codex"], wall) + raise subprocess.TimeoutExpired([program], wall) if not result.extra["served"] or not result.reply.strip(): tail = (_read_own(err) or result.extra.get("output_tail", ""))[-300:] return "", 0.0, f"rc={result.exit_code}: {tail}" diff --git a/hermit/agent/evolver/methods/harness2_upstream/evolver.py b/hermit/agent/evolver/methods/harness2_upstream/evolver.py index 5a31a350..a203d067 100644 --- a/hermit/agent/evolver/methods/harness2_upstream/evolver.py +++ b/hermit/agent/evolver/methods/harness2_upstream/evolver.py @@ -88,14 +88,14 @@ class Harness2UpstreamEvolver(Evolver): def setup(self, ctx) -> None: context = _upstream()[0] - if ctx.params.get("proposer") is None and ctx.params.get("backend") not in ("claude", "codex"): - raise ValueError("harness2_upstream runs its sessions as Claude Code or Codex: set params.backend: claude " - "or codex") + if ctx.params.get("proposer") is None and ctx.params.get("backend") not in ("claude", "codex", "pi"): + raise ValueError("harness2_upstream runs its sessions as Claude Code, Codex or Pi: set params.backend: " + "claude, codex or pi") login = ctx.params.get("login") if ctx.params.get("proposer") is None and login is not None: # refused here, not by every session: upstream turns a session's error into the starting harness backend = ctx.params.get("backend") - if login != {"claude": "claude", "codex": "chatgpt"}[backend]: + if login != {"claude": "claude", "codex": "chatgpt"}.get(backend): raise ValueError(f"evolver.params.login: {login} is not the sign-in of backend {backend} " f"(claude: login claude; codex: login chatgpt)") model = str(ctx.params.get("model") or "") @@ -223,14 +223,15 @@ def _endpoint_down(params: dict, cancel, wait_s: int = 600) -> str: return reason or "stopped" def _claude(self, ws, backend: str | None = None) -> str: - """The sessions' CLI binary (Claude Code, or Codex with `backend: codex`), pinned for the whole run (it updates - itself): `params.claude_bin` (a copy the launcher made), else its versioned path, kept in state.""" + """The sessions' CLI binary (Claude Code, or Codex or Pi with `backend: codex` or `pi`), pinned for the whole + run (it updates itself): `params.claude_bin` (a copy the launcher made), else its versioned path, kept in + state.""" if self._pinned_bin: return self._pinned_bin pin = ws.state / "claude_bin.txt" if pin.is_file() and Path(pin.read_text().strip()).is_file(): return pin.read_text().strip() - program = "codex" if backend == "codex" else "claude" + program = backend if backend in ("codex", "pi") else "claude" found = shutil.which(program) path = os.path.realpath(found) if found else program pin.write_text(path + "\n") @@ -321,7 +322,7 @@ def _same_settings(run: Path, params: dict, base: Path | None) -> None: if not (a and b and a.is_file() and b.is_file() and filecmp.cmp(a, b, shallow=False)): differ.append(key) pin = run / "workspace" / "state" / "claude_bin.txt" - program = "codex" if params.get("backend") == "codex" else "claude" + program = params.get("backend") if params.get("backend") in ("codex", "pi") else "claude" found = shutil.which(program) # as _claude pins it: the bare name when it is not installed mine = params.get("claude_bin") or (os.path.realpath(found) if found else program) other = theirs.get("claude_bin") or (pin.read_text().strip() if pin.is_file() else "") diff --git a/hermit/agent/evolver/methods/harness2_upstream/evolver.yaml b/hermit/agent/evolver/methods/harness2_upstream/evolver.yaml index 856e190d..6aed9b4e 100644 --- a/hermit/agent/evolver/methods/harness2_upstream/evolver.yaml +++ b/hermit/agent/evolver/methods/harness2_upstream/evolver.yaml @@ -10,7 +10,8 @@ class: evolver.py:Harness2UpstreamEvolver needs: [] params: backend: claude # the editor sessions run Claude Code (upstream's claude_cli channel) on the bound model; - # codex: Codex (a model only Codex reaches: login: chatgpt with model a Codex model name) + # codex: Codex (a model only Codex reaches: login: chatgpt with model a Codex model name); + # pi: Pi on the bound model (/; `tools` is Claude Code's and does not apply) model: null # a / reference whose backend serves the Messages API; with a login, the # CLI's own model name (claude-haiku-5-5, gpt-5.6-luna) effort: medium # Claude Code's --effort for every session diff --git a/hermit/agent/evolver/methods/harness2_upstream/render.py b/hermit/agent/evolver/methods/harness2_upstream/render.py index 8cc38261..e39a2965 100644 --- a/hermit/agent/evolver/methods/harness2_upstream/render.py +++ b/hermit/agent/evolver/methods/harness2_upstream/render.py @@ -147,3 +147,34 @@ def emit(line: str) -> None: if len(rendered) > max_chars: rendered = rendered[:max_chars] + "\n" + TRUNCATED.format(n=len(rendered) - max_chars) return rendered + + +def render_pi_events(path: Path, *, obs_trunc: int, max_chars: int, args_trunc: int = 2000) -> str: + """Render a Pi `--mode json` stream into upstream's shared grammar, from its standard steps.""" + from hermit.agent.base.trajectory import events, pi_steps + try: + steps = pi_steps(events(path)) + except OSError as exc: + return f"(failed to read trajectory: {exc})" + lines: list[str] = [] + for step in steps: + if step.kind == "message": + lines.append(f"[ASSISTANT] {clip(step.text, obs_trunc)}") + elif step.kind == "reasoning": + lines.append(f"[REASONING] {clip(step.text, obs_trunc)}") + elif step.kind == "command": + lines.append(f"[ACTION] bash: {clip(step.command, args_trunc)}") + tag = "OBSERVATION" if step.exit_code == 0 else "OBSERVATION ERROR" + lines.append(f"[{tag}] {clip(step.output, obs_trunc)}") + elif step.kind == "error": + lines.append(f"[ERROR] {clip(step.text, 1000)}") + else: # a file change or a tool call: its summary, then its result + lines.append(f"[ACTION] {clip(step.text, args_trunc)}") + if step.output: + lines.append(f"[OBSERVATION] {clip(step.output, obs_trunc)}") + rendered = "\n".join(lines).strip() + if not rendered: + return "(no parseable events in trajectory)" + if len(rendered) > max_chars: + rendered = rendered[:max_chars] + "\n" + TRUNCATED.format(n=len(rendered) - max_chars) + return rendered diff --git a/hermit/agent/evolver/methods/meta_harness_adapter/evolver.py b/hermit/agent/evolver/methods/meta_harness_adapter/evolver.py index 311dc181..b0eedce5 100644 --- a/hermit/agent/evolver/methods/meta_harness_adapter/evolver.py +++ b/hermit/agent/evolver/methods/meta_harness_adapter/evolver.py @@ -11,7 +11,7 @@ 1. The step's rollouts are the evaluation of the candidate handed back last time (the starting adapter, `seed`, on the first step); their scores and trajectories are in the step's learning material. The step records them. -2. When no proposed candidate is left to evaluate, a proposer session (a Codex or Claude Code agent, as the built-in +2. When no proposed candidate is left to evaluate, a proposer session (a Codex, Claude Code or Pi agent, as the built-in `codex` / `claude` Evolvers run it, with check_spec as its only tool) writes k candidates into the scratch directory; each that passes check_spec is stored under state/candidates// and queued. 3. The next queued candidate is handed back (its files replace the working copy's, `.hermit/` kept), so the next diff --git a/hermit/agent/evolver/methods/meta_harness_adapter/evolver.yaml b/hermit/agent/evolver/methods/meta_harness_adapter/evolver.yaml index 9789ae14..3f65f1dd 100644 --- a/hermit/agent/evolver/methods/meta_harness_adapter/evolver.yaml +++ b/hermit/agent/evolver/methods/meta_harness_adapter/evolver.yaml @@ -6,7 +6,7 @@ description: The outer loop of Meta-Harness (Lee et al., arXiv:2603.28052) on th class: evolver.py:MetaHarnessAdapterEvolver needs: [] params: - backend: codex # the proposer: codex or claude (the paper: Claude Code) + backend: codex # the proposer: codex, claude or pi (the paper: Claude Code) prompt: PROPOSE.md # the round's prompt (placeholders filled per round) args: [] # extra arguments for the proposer's CLI, e.g. codex `-c model_reasoning_effort="medium"` model: null # the proposer's model, `/`; null: the agent's default diff --git a/hermit/agent/evolver/methods/mwm/evolver.py b/hermit/agent/evolver/methods/mwm/evolver.py index 3d37be56..6c26d3de 100644 --- a/hermit/agent/evolver/methods/mwm/evolver.py +++ b/hermit/agent/evolver/methods/mwm/evolver.py @@ -239,11 +239,12 @@ def _settings(self, ctx: StepContext, home: Path, log: Path, box) -> dict: """The CLI Base Agent's settings for one learner session: the CLI as natively (Codex's own sandbox off, every variable for its commands, a fresh home, the session's clock), inside the native mounts, told /w as its working directory, the channels' JSON entrance as MW_TOOLSRV (the venue's shell client). `login` and `effort` - are the model's; a binding's Claude Code provider settings come in `env`.""" + are the model's; a binding's Claude Code provider settings come in `env`, Pi's in `provider`.""" params = ctx.params if not isinstance(params.get("web_search"), bool): raise ValueError("evolver.params.web_search must be set, true or false") return {**{k: params[k] for k in ("model", "binding", "args", "login", "login_root", "effort", "price", + "provider", "image_input", "plan_dir", "plan_max_wait_s", "plan_rerun", "usage_credits") if params.get(k) is not None or (k == "plan_max_wait_s" and k in params)}, # None: no limit "web_search": params["web_search"], "isolation": "sandbox", "sandbox": box, @@ -456,9 +457,9 @@ def _notes(admission: dict | None) -> str: # ------------------------------------------------------------------ steps def setup(self, ctx: Context) -> None: - if ctx.params.get("backend", "codex") not in ("codex", "claude"): # its session settings carry no `provider` - raise ValueError("the mwm Evolver's learner is a Codex or Claude Code session: evolver.params.backend is " - f"codex or claude, not {ctx.params.get('backend')!r}") + if ctx.params.get("backend", "codex") not in ("codex", "claude", "pi"): # the CLIs its sessions are set up for + raise ValueError("the mwm Evolver's learner is a Codex, Claude Code or Pi session: evolver.params.backend " + f"is codex, claude or pi, not {ctx.params.get('backend')!r}") if "network_isolation" in ctx.params: raise ValueError("evolver.params.network_isolation was removed: the learner runs in the run's evolver " "sandbox, whose network reaches only its models, the tool endpoint and " diff --git a/hermit/agent/evolver/methods/mwm/evolver.yaml b/hermit/agent/evolver/methods/mwm/evolver.yaml index 42d5959e..21128385 100644 --- a/hermit/agent/evolver/methods/mwm/evolver.yaml +++ b/hermit/agent/evolver/methods/mwm/evolver.yaml @@ -3,7 +3,7 @@ description: The MetaWorld Model learner (MWM V2 default, docket on, hypothesis class: evolver.py:MwmEvolver needs: [environment] params: - backend: codex # the learner's CLI, codex or claude (a model reference binds it, as for those Evolvers) + backend: codex # the learner's CLI, codex, claude or pi (a model reference binds it, as for those Evolvers) model: null # the learner model; null: the CLI's default web_search: false # web search, set explicitly: Codex's hosted search runs at the provider, past the # network namespace diff --git a/hermit/agent/evolver/methods/rrsi_adapter/evolver.py b/hermit/agent/evolver/methods/rrsi_adapter/evolver.py index 31add202..6d4489f7 100644 --- a/hermit/agent/evolver/methods/rrsi_adapter/evolver.py +++ b/hermit/agent/evolver/methods/rrsi_adapter/evolver.py @@ -417,9 +417,9 @@ def setup(self, ctx) -> None: """What every step needs, checked once: a broken hyperparameter file or domain, or an unset web_search, stops the run here rather than failing each step.""" _require_rrsi() - if ctx.params.get("backend", "codex") not in ("codex", "claude"): # its roles' settings are those CLIs' - raise ValueError("the RRSI Adapter's proposer and roles are Codex or Claude Code sessions: " - f"evolver.params.backend is codex or claude, not {ctx.params.get('backend')!r}") + if ctx.params.get("backend", "codex") not in ("codex", "claude", "pi"): # what keeps its roles read-only + raise ValueError("the RRSI Adapter's proposer and roles are Codex, Claude Code or Pi sessions: " + f"evolver.params.backend is codex, claude or pi, not {ctx.params.get('backend')!r}") if not isinstance(ctx.params.get("web_search"), bool): raise ValueError("evolver.params.web_search must be set, true or false") role = ctx.params.get("roles") or {} @@ -431,10 +431,14 @@ def setup(self, ctx) -> None: # the roles run on the proposer's CLI: refused here, not by every role call raise ValueError(f"evolver.params.roles.login: {role['login']} is not the sign-in of backend {backend} " "(codex: login chatgpt; claude: login claude)") + if backend == "pi" and role.get("model") is not None and role.get("binding") is None: + raise ValueError("evolver.params.roles.model on Pi needs roles.binding too: Pi reaches a model through a " + "binding, and would otherwise look the name up in its own catalog") if isinstance(role.get("binding"), dict): # read at every step (_roles), before its errors count from hermit.agent.model.backends import Binding try: - Binding.from_spec(role["binding"]).codex_args() + binding = Binding.from_spec(role["binding"]) + binding.pi_provider() if backend == "pi" else binding.codex_args() except ValueError as exc: raise ValueError(f"evolver.params.roles.binding: {exc}") from exc cfg = self._cfg(ctx) @@ -549,9 +553,9 @@ def _models(self, ctx) -> dict: def _roles(self, ctx) -> Roles: """The roles' sessions: the proposer's Base Agent and its settings (its model, login and effort unless `roles` gives the roles' own; with the roles' own model, the proposer's binding, price and the provider - settings its binding put in `args` or `env` are not theirs; `roles.args` replaces the proposer's own arguments, - not those provider arguments), read-only (Codex's own sandbox mode; Claude Code's by its tools, - Roles._session), `role_timeout_s` each. They do not see the run's + settings its binding put in `args`, `env` or `provider` are not theirs; `roles.args` replaces the proposer's own + arguments, not those provider arguments), read-only (Codex's own sandbox mode; Claude Code's and Pi's by their + tools, Roles._session), `role_timeout_s` each. They do not see the run's records, the step's output, the proposers' directories or the other calls' (Roles._session; upstream's roles see only the text they are given). Each call's prompt, events and reply are kept in the step's output (`rrsi_roles/`), its home and working directory in the scratch.""" @@ -569,7 +573,7 @@ def _roles(self, ctx) -> Roles: provider = provider if list(base.get("args") or [])[:len(provider)] == provider else [] if role.get("model") is not None: # nor its provider arguments args = list(base.get("args") or [])[len(provider):] - base = {k: v for k, v in base.items() if k not in ("binding", "price", "args")} | ( + base = {k: v for k, v in base.items() if k not in ("binding", "price", "args", "provider")} | ( {"args": args} if args else {}) base["env"] = {k: v for k, v in (base.get("env") or {}).items() if k not in CLAUDE_ENV} provider = [] @@ -582,6 +586,8 @@ def _roles(self, ctx) -> Roles: binding = Binding.from_spec(role["binding"]) if backend == "codex": settings["args"] = [*binding.codex_args(), *(role.get("args") or [])] + elif backend == "pi": + settings["provider"] = binding.pi_provider() else: # the proposer's provider settings give way to the roles' own = {k: v for k, v in (settings.get("env") or {}).items() if k not in CLAUDE_ENV} settings["env"] = {**own, **binding.claude_env()} diff --git a/hermit/agent/evolver/methods/rrsi_adapter/evolver.yaml b/hermit/agent/evolver/methods/rrsi_adapter/evolver.yaml index b123216f..aa2b24de 100644 --- a/hermit/agent/evolver/methods/rrsi_adapter/evolver.yaml +++ b/hermit/agent/evolver/methods/rrsi_adapter/evolver.yaml @@ -7,12 +7,12 @@ description: RRSI (Xia et al., arXiv:2609.24972; google-research/rrsi) on the Tr class: evolver.py:RRSIAdapterEvolver needs: [] params: - backend: codex # the proposer: codex or claude (upstream: Claude Opus 4.8 in its own JSON-action loop) + backend: codex # the proposer: codex, claude or pi (upstream: Claude Opus 4.8 in its own JSON-action loop) prompt: PROPOSE.md # the proposer's prompt (placeholders filled per variant) args: [] # extra arguments for the proposer's CLI, e.g. codex `-c key=value` pairs model: null # the proposer's model, `/`, or the CLI's model name with `login` # (required with login: claude); null: the agent's default - login: null # the proposer's and the roles' subscription and its plan: chatgpt (codex) or claude + login: null # the proposer's and the roles' subscription and its plan (not on Pi): chatgpt (codex) or claude # (claude, CLAUDE_CODE_OAUTH_TOKEN) effort: null # the proposer's reasoning effort (Codex's model_reasoning_effort, Claude Code's --effort) price: null # USD per million tokens {input, cached_input, output} diff --git a/hermit/agent/evolver/methods/rrsi_adapter/roles.py b/hermit/agent/evolver/methods/rrsi_adapter/roles.py index 9689ed99..8de12a9f 100644 --- a/hermit/agent/evolver/methods/rrsi_adapter/roles.py +++ b/hermit/agent/evolver/methods/rrsi_adapter/roles.py @@ -2,12 +2,12 @@ Upstream's analyst, digester and critic (rrsi.analyst, rrsi.digester, rrsi.critic) call `generate(prompt, system, json_only, ...)`, Claude Opus 4.8 on Vertex AI (rrsi.llm). Here `generate` is rebound in those three modules, for the -duration of a call, to `Roles.generate`: one call of the `codex` or `claude` Base Agent the proposer runs on +duration of a call, to `Roles.generate`: one call of the `codex`, `claude` or `pi` Base Agent the proposer runs on (`make(backend, settings).run`, docs/framework/agent-layers.md), the way the Evolver's proposer is one, with the role's system text as the session's instructions (`instructed`) and the prompt on stdin. The session runs in a view of the run's sandbox that shows its own call directory and nothing else the run keeps, in an empty directory, read-only -(Codex's own sandbox mode; on Claude Code the analyst and the critic have no tools, `text_only`, and a digester only -the tools that read), so a role answers from the text it is given, as upstream's do; a digester's session runs in the +(Codex's own sandbox mode; on Claude Code and Pi the analyst and the critic have no tools, `text_only`, and a digester +only the tools that read), so a role answers from the text it is given, as upstream's do; a digester's session runs in the round's rendered traces instead (shown read-only in its view), the directory upstream's digester reads with its read_file/grep/bash actions. The reply is the session's last message; with `json_only`, upstream's own `extract_json` cuts the JSON out of it, as upstream's `generate` does. @@ -42,7 +42,8 @@ ROLE_MODULES = ("rrsi.analyst", "rrsi.digester", "rrsi.critic") DIGESTER_TOOLS = ["Read", "Grep", "Glob"] # Claude Code's tools that only read, as Codex's read-only sandbox allows -LABELS = {"codex": "Codex", "claude": "Claude Code"} +PI_DIGESTER_TOOLS = ["read", "grep", "find", "ls"] # Pi's own +LABELS = {"codex": "Codex", "claude": "Claude Code", "pi": "Pi"} class Stop(BaseException): @@ -192,7 +193,8 @@ def _session(self, system: str, prompt: str) -> Result: cwd = self.traces if digester else work settings = {**self.settings, "home": call / "home", "log": rec / "events.jsonl", "stdin": True, "cancel": self.ctx.cancel, - **({"allowed_tools": DIGESTER_TOOLS} if digester else {"text_only": True})} + **({"allowed_tools": PI_DIGESTER_TOOLS if self.backend == "pi" else DIGESTER_TOOLS} + if digester else {"text_only": True})} # Each session sees only its own call directory and, a digester, the round's traces: not the run's records, # the other calls' homes or the records in progress. box = None diff --git a/hermit/agent/model/backends.py b/hermit/agent/model/backends.py index af8c8295..450ac059 100644 --- a/hermit/agent/model/backends.py +++ b/hermit/agent/model/backends.py @@ -491,8 +491,8 @@ def _cli_model(spec: dict, backends: dict[str, Backend], where: str) -> dict: """A model reached through a CLI: its `cli` the Base Agent's name, its model bound when it is a reference. It stays in this form and is never read as a chat endpoint's spec: the key or the login that pays is the session's.""" cli = {"claude-code": "claude"}.get(spec["cli"], spec["cli"]) - if cli not in ("codex", "claude"): - raise ValueError(f"{where}.cli must be codex or claude, not {spec['cli']!r}") + if cli not in ("codex", "claude", "pi"): + raise ValueError(f"{where}.cli must be codex, claude or pi, not {spec['cli']!r}") spec = {**spec, "cli": cli} return bind_agent_params(spec, cli, backends) if is_ref(spec.get("model"), backends) else spec @@ -512,7 +512,8 @@ def bindings_of(data: dict, evolver_params: dict | None = None) -> list[tuple[st params = agent.get("params") or {} for who, spec in (("llm tool", data.get("llm")), (f"model of agent {agent.get('name')}", params.get("model"))): if isinstance(spec, dict) and spec.get("cli") and isinstance(spec.get("binding"), dict): - out.append((f"{who} through {spec['cli']}", Binding.from_spec(spec["binding"]), NEEDS[spec["cli"]])) + binding = Binding.from_spec(spec["binding"]) + out.append((f"{who} through {spec['cli']}", binding, needs(spec["cli"], binding))) kind = _cli_kind(agent, params) if kind in CLI_KINDS and isinstance(params.get("binding"), dict): binding = Binding.from_spec(params["binding"]) diff --git a/hermit/config.py b/hermit/config.py index 67b6155f..c903d5c7 100644 --- a/hermit/config.py +++ b/hermit/config.py @@ -107,10 +107,22 @@ def _model(params: dict, model, where: str, cli: bool = True) -> None: _put(params, "model", {"model": name, **model} if model else name, where) -def layered(data: dict) -> None: +def _calls_the_runs_model(name, base: Path | None) -> bool: + """Whether the Evolver `name` decides each step in its own code and calls the run's model (`ctx.agent`, the `llm` + tool): its manifest names no CLI of its own (no `backend`, no `proposer`).""" + from hermit.agent.evolver.loader import find + try: + params = find(str(name), base).params + except ValueError: # no such Evolver: said where the Evolver is loaded + return False + return "backend" not in params and "proposer" not in params + + +def layered(data: dict, base_dir: Path | None = None) -> None: """The per-layer form of `agent` and `evolver` (docs/framework/agent-layers.md#settings-by-layer) as the flat form the framework reads: `params` (Layer 3), `base` and its section (Layer 2), `model` (Layer 1). A key given in - two layers is refused.""" + two layers is refused. `evolver.base: pi` on a method that calls the run's model makes that model Pi: `llm: {cli: + pi}`, one session per call.""" agent = data["agent"] base = agent.pop("base", None) model = agent.pop("model", None) @@ -151,6 +163,16 @@ def layered(data: dict) -> None: if base not in ("codex", "claude", "claude-code", "pi", "direct"): raise ValueError(f"evolver.base must be codex, claude, pi or direct, not {base!r}") params = dict(evolver.get("params") or {}) + if base == "pi" and _calls_the_runs_model(evolver.get("name"), base_dir): + if data.get("llm") is not None: + raise ValueError("evolver.base: pi makes the run's model Pi, and llm names it too: give one") + llm: dict = {"cli": "pi"} + _model(llm, model if model is not None else data.get("model"), "evolver") + for key, value in (sections.get("pi") or {}).items(): + _put(llm, key, value, "evolver.pi") + data["llm"] = llm + evolver["params"] = params + return if base == "direct": if model is not None: llm = _chat_spec(model, "evolver") @@ -218,7 +240,7 @@ def load(cls, path: Path, overrides: list[str] = ()) -> "Config": data["agent"]["params"] = {**data["agent"].get("params", {}), **data["pipeline"]["params"]} if data["pipeline"].get("concurrency") is not None: data["agent"]["concurrency"] = data["pipeline"]["concurrency"] - layered(data) # per-layer settings -> the flat form + layered(data, Path(path).parent) # per-layer settings -> the flat form normalize_config(data) # model references -> the endpoints they name config = cls(data, Path(path).parent) config.validate() diff --git a/tests/README.md b/tests/README.md index 2aa96b24..a8c4a9f4 100644 --- a/tests/README.md +++ b/tests/README.md @@ -34,8 +34,8 @@ Shared helpers: the repository root's `conftest.py` (the options and the groups) ChatGPT-login directory and Claude plan for every test, and no copy of the user's own sign-in), `fakes.py` (scripted models), `toy_task.py` (the toy task the Trainer tests run on), `claude_stand.py` (the stand-in `claude` that replays `fixtures/claude_streams/`, and the probe for a working bubblewrap, for core's and the methods' Claude tests), -`fixtures/` (`pi/`: Pi's recorded streams, read by -`core/test_pi_agent.py`). +`pi_stand.py` (the stand-in `pi` that replays `fixtures/pi/`, for the methods' Pi tests), +`fixtures/` (`pi/`: Pi's recorded streams, read by `core/test_pi_agent.py` and `pi_stand.py`). A new or changed test follows the [test checklist](../.agents/skills/prepare-pr/references/test-checklist.md): where it goes, how it is named and documented, what it asserts, and what it may touch. diff --git a/tests/core/test_claude_subscription.py b/tests/core/test_claude_subscription.py index dc9a6b54..f7a9f0e4 100644 --- a/tests/core/test_claude_subscription.py +++ b/tests/core/test_claude_subscription.py @@ -106,8 +106,8 @@ def test_a_model_through_the_cli_stays_a_cli_spec_for_learning_and_acting(): assert data["llm"]["env"]["ANTHROPIC_BASE_URL"].startswith("https://") data = layers(evolver={"base": "direct", "model": dict(spec)}) # the per-layer spelling of the same `llm` assert data["llm"] == spec - with pytest.raises(ValueError, match="llm.cli must be codex or claude"): - normalize_config({"llm": {"cli": "pi"}, "agent": {}}) + with pytest.raises(ValueError, match="llm.cli must be codex, claude or pi"): + normalize_config({"llm": {"cli": "aider"}, "agent": {}}) with pytest.raises(ValueError, match="is that CLI itself"): normalize_config({"agent": {"name": "claude-code", "params": {"model": dict(spec)}}}) diff --git a/tests/core/test_pi_agent.py b/tests/core/test_pi_agent.py index b2f38218..ba01bb4e 100644 --- a/tests/core/test_pi_agent.py +++ b/tests/core/test_pi_agent.py @@ -287,6 +287,92 @@ def test_a_model_that_takes_images_is_declared_so_to_pi(fake): [model] = json.loads(seen(fake)[-1]["files"]["models.json"])["providers"]["hermit"]["models"] assert model.get("input") == declared +def test_a_session_that_only_replies_is_given_nothing_else_and_one_that_ran_a_tool_has_failed(fake, monkeypatch): + """`text_only`: a role that answers from its prompt, or a model behind a chat endpoint. The recorded stream ran three + tools, so that session is no reply; the one without tool calls is.""" + work = fake / "work" + work.mkdir() + agent = make("pi", {**bound(), "web_search": False, "home": str(fake / "home"), "text_only": True, "stdin": True}) + result = agent.run("go", workspace=work) + args = seen(fake)[0]["args"] + assert {"--no-tools", "--no-mcp", "--no-extensions", "--no-skills", "--no-prompt-templates", + "--no-context-files"} <= set(args) + assert result.extra["failed"] and not result.extra["served"] and "no tools" in result.extra["failure"] + monkeypatch.setenv("FAKE_PI_STREAM", str(STREAMS / "resume.jsonl")) + assert agent.run("go", workspace=work).extra["served"] + + +def test_allowed_tools_are_pis_own_and_keep_the_calls_tools(fake): + work = fake / "work" + work.mkdir() + agent = make("pi", {**bound(), "web_search": False, "home": str(fake / "home"), "allowed_tools": ["read", "grep"]}) + agent.run("go", workspace=work) + agent.run("go", workspace=work, tools=[echo()]) + agent.configured(allowed_tools=[]).run("go", workspace=work, tools=[echo()]) + alone, beside, none = [c["args"] for c in seen(fake)] + assert alone[alone.index("--tools") + 1] == "read,grep" + assert beside[beside.index("--tools") + 1] == "read,grep,mcp__hermit_tools__*" + assert "--no-builtin-tools" in none and "--tools" not in none + + +def test_pi_refuses_an_effort_it_does_not_take_and_keeps_no_session_when_told(fake): + """Pi warns about an unknown --thinking level and goes on at its default: refused, as for Claude Code.""" + work = fake / "work" + work.mkdir() + agent = make("pi", {**bound(), "web_search": False, "home": str(fake / "home")}) + with pytest.raises(Unsupported, match="Pi takes effort .*not 'max'"): + agent.configured(effort="max").run("go", workspace=work) + agent.configured(persist_session=False, effort="xhigh").run("go", workspace=work) + args = seen(fake)[0]["args"] + assert "--no-session" in args and args[args.index("--thinking") + 1] == "xhigh" + + +def test_a_model_through_pi_answers_each_request_with_a_session_that_only_replies(fake, monkeypatch): + from hermit.agent.base.endpoint import cli_answer + monkeypatch.setenv("FAKE_PI_STREAM", str(STREAMS / "resume.jsonl")) + agent = make("pi", {**bound(), "web_search": False}) + status, body, _ = cli_answer(agent, {"messages": [{"role": "system", "content": "Be exact."}, + {"role": "user", "content": "hello"}], "max_tokens": 10}) + reply = json.loads(body) + [call] = seen(fake) + assert status == 200 and reply["choices"][0]["message"]["content"] == "the answer" and reply["unapplied"] == ["max_tokens"] + assert call["stdin"] == "hello" and "--no-tools" in call["args"] + assert call["args"][call["args"].index("--append-system-prompt") + 1] == "Be exact." + + +@pytest.mark.parametrize("spec, match", [({}, "needs a / reference"), + ({"login": "chatgpt"}, "not login: chatgpt"), + ({"binding": {"x": 1}, "isolation": "container"}, "needs isolation: sandbox"), + ({"binding": {"x": 1}, "web_search": True}, "web_search cannot be on"), + ({"binding": {"x": 1}, "effort": "max"}, "takes effort off")]) +def test_what_a_model_through_pi_cannot_be_is_said_before_any_session(spec, match): + from hermit.agent.base.endpoint import cli_problems + assert any(match in problem for problem in cli_problems({"cli": "pi", **spec})) + + +def test_evolver_base_pi_is_the_run_model_of_a_method_that_calls_it_and_the_learner_of_one_that_has_a_cli(): + """One setting for every method: GEPA, SkillOpt and the rest call the run's model, so on Pi that model is a Pi session + (`llm: {cli: pi}`); mwm, EvoSafe and the others run a CLI of their own, and Pi is that CLI.""" + from hermit.agent.model.backends import bindings_of, normalize_config + from hermit.config import layered + fake_backend = {"base_url": "http://127.0.0.1:9/v1", "api_key_env": "FAKE_KEY", "apis": ["chat"]} + data = {"agent": {}, "llm": None, "backends": {"fake": fake_backend}, + "evolver": {"name": "gepa", "base": "pi", "model": "fake/m-1", "pi": {"unapplied": ["temperature"]}, "params": {}}} + layered(data) + normalize_config(data) + assert data["llm"]["cli"] == "pi" and data["llm"]["provider"]["apiKey"] == "$FAKE_KEY" + assert data["llm"]["unapplied"] == ["temperature"] and data["llm"]["model"] == "m-1" + assert "backend" not in data["evolver"]["params"] + [(who, _, dialect)] = bindings_of(data) + assert who == "llm tool through pi" and dialect == "chat" + for name in ("mwm", "evosafe", "rrsi_adapter", "ahe_adapter", "harness2_upstream", "meta_harness_adapter", "aspire"): + data = {"agent": {}, "llm": None, "evolver": {"name": name, "base": "pi", "model": "fake/m-1", "params": {}}} + layered(data) + assert data["evolver"]["params"]["backend"] == "pi" and data["llm"] is None, name + with pytest.raises(ValueError, match="llm names it too"): + layered({"agent": {}, "llm": "fake/m-1", "evolver": {"name": "opro", "base": "pi", "model": "fake/m-1", "params": {}}}) + + # ---------- the installed pi (integration) ---------- def serve_chat(script): @@ -373,3 +459,31 @@ def script(body): data = json.loads(record.read_text()) assert data["network"] == "isolated" and data["probe"]["passed"] assert {"PI_CODING_AGENT_DIR", "PI_OFFLINE", "MOCK_KEY"} <= set(data["environment"]) + + +@pytest.mark.integration +@pytest.mark.skipif(not shutil.which("pi"), reason="needs the pi CLI") +@pytest.mark.parametrize("limit, offered", [({"text_only": True, "stdin": True}, []), + ({"allowed_tools": []}, ["mcp__hermit_tools__echo"]), + ({"allowed_tools": ["read", "grep"]}, + ["grep", "mcp__hermit_tools__echo", "read"])]) +def test_with_the_pi_cli_a_limited_session_is_offered_only_what_it_may_use(tmp_path, monkeypatch, limit, offered): + """The installed Pi, bound to a scripted model: what the model is offered is what a role or a text session can do. + A role's read-only tools keep the call's tools, and none of them is offered to a session that only replies.""" + asked = [] + + def script(body): + asked.append(sorted(t["function"]["name"] for t in body.get("tools") or [])) + + server, url = serve_chat(script) + monkeypatch.setenv("MOCK_KEY", "sk-mock") + params = bind_agent_params({"model": "mock/m-1"}, "pi", + registry({"mock": {"base_url": url, "api_key_env": "MOCK_KEY", "apis": ["chat"]}})) + work = tmp_path / "work" + work.mkdir() + settings = {**params, "web_search": False, "home": str(tmp_path / "home"), "timeout_s": 300, **limit} + try: + result = make("pi", settings).run("Do the task.", workspace=work, tools=[] if limit.get("text_only") else [echo()]) + finally: + server.shutdown() + assert result.extra["served"] and result.reply == "the answer" and asked == [offered] diff --git a/tests/methods/ahe/test_ahe_on_claude.py b/tests/methods/ahe/test_ahe_on_claude.py index a11e63ce..edf56fb0 100644 --- a/tests/methods/ahe/test_ahe_on_claude.py +++ b/tests/methods/ahe/test_ahe_on_claude.py @@ -17,8 +17,8 @@ def test_the_ahe_learners_take_the_evolvers_cli(stand, tmp_path): ctx = roles_ctx(tmp_path, {"prompt": "START.md", "k": 1}) evolver = AHEAdapterEvolver() evolver.setup(ctx) # no refusal for claude - with pytest.raises(ValueError, match="codex or claude"): - AHEAdapterEvolver().setup(roles_ctx(tmp_path, {"backend": "pi"})) + with pytest.raises(ValueError, match="codex, claude or pi"): + AHEAdapterEvolver().setup(roles_ctx(tmp_path, {"backend": "mini-swe-agent"})) base = evolver.settings(ctx, "claude") runner = D.Runner(ctx, {"model": None}, base, tmp_path / "scratch") job = D.Job.__new__(D.Job) diff --git a/tests/methods/ahe/test_ahe_on_pi.py b/tests/methods/ahe/test_ahe_on_pi.py new file mode 100644 index 00000000..d33129ad --- /dev/null +++ b/tests/methods/ahe/test_ahe_on_pi.py @@ -0,0 +1,43 @@ +"""The AHE Adapter's Evolve Agent and Agent Debugger on Pi (`evolver.base: pi`), against the stand-in `pi` +(tests/pi_stand.py).""" +from dataclasses import fields +import json + +import pytest + +from claude_stand import roles_ctx +from pi_stand import bound_params, pi_stand # noqa: F401 (pi_stand: the fixture) + + +def test_the_ahe_learners_run_on_pi_with_its_bound_model(pi_stand, tmp_path): # noqa: F811 + from hermit.agent.evolver.methods.ahe_adapter import debugger as D + from hermit.agent.evolver.methods.ahe_adapter.evolver import AHEAdapterEvolver + ctx = roles_ctx(tmp_path, {"login": None, "prompt": "START.md", "k": 1, **bound_params()}) + evolver = AHEAdapterEvolver() + evolver.setup(ctx) + runner = D.Runner(ctx, {"model": None}, evolver.settings(ctx, "pi"), tmp_path / "scratch") + job = D.Job.__new__(D.Job) + for f in fields(D.Job): + setattr(job, f.name, {"task": "t1"}.get(f.name) if f.name == "task" else None) + job_dir = tmp_path / "job" + job_dir.mkdir() + (job_dir / "question.md").write_text("why did it fail?") + pi_stand.play(edits={"answer.md": "written answer"}) + assert runner.attempt(job, job_dir, 1, 30) == ("written answer", "") + [call] = pi_stand.seen() + assert call["stdin"] == "why did it fail?" and call["args"][:6] == ["--mode", "json", "--provider", "hermit", "--model", + "m-1"] + assert json.loads(call["files"]["models.json"])["providers"]["hermit"]["apiKey"] == "$FAKE_KEY" + + +def test_an_effort_pi_does_not_take_is_refused_at_setup(tmp_path): + from hermit.agent.evolver.methods.ahe_adapter.evolver import AHEAdapterEvolver + with pytest.raises(ValueError, match="evolver.params.effort is one of off, minimal.*for Pi, not 'max'"): + AHEAdapterEvolver().setup(roles_ctx(tmp_path, {"login": None, **bound_params(), "effort": "max"})) + + +def test_the_learners_texts_name_a_pi_acting_agents_stream(): + from hermit.agent.evolver.methods.ahe_adapter import debugger as D + text = "the Codex event stream, `agent-codex.jsonl` (the raw Codex event stream, `codex exec --json` event stream)" + assert D.for_stream(text, "agent-pi.jsonl") == ("the Pi event stream, `agent-pi.jsonl` (the raw Pi event stream, " + "`pi --mode json` event stream)") diff --git a/tests/methods/evosafe/test_evosafe_on_pi.py b/tests/methods/evosafe/test_evosafe_on_pi.py new file mode 100644 index 00000000..db4ee664 --- /dev/null +++ b/tests/methods/evosafe/test_evosafe_on_pi.py @@ -0,0 +1,34 @@ +"""EvoSafeHarness's per-role sessions on Pi (`evolver.base: pi`), against the stand-in `pi` (tests/pi_stand.py).""" +import json +from types import SimpleNamespace as NS + +from pi_stand import bound_params, pi_stand # noqa: F401 (pi_stand: the fixture) + + +def ctx_of(tmp_path): + ws = NS(scratch=tmp_path / "scratch", output=tmp_path / "out") + ws.scratch.mkdir() + ws.output.mkdir() + return NS(workspace=ws, params=bound_params(), sandbox=None, cancel=None, tools={}) + + +def test_a_role_on_pi_has_none_of_its_own_tools_and_answers_the_schema(pi_stand, tmp_path): # noqa: F811 + from hermit.agent.evolver.methods.evosafe import cli_roles, pi_agent + assert cli_roles.proposer({"backend": "pi"}) == "pi" + pi_stand.play(reply='{"verdict": "ok"}') + messages = [{"role": "system", "content": "Be exact."}, {"role": "user", "content": "the evidence"}] + schema = {"type": "object", "properties": {"verdict": {"type": "string"}}, "required": ["verdict"]} + response, usage, error = pi_agent.call_role(ctx_of(tmp_path), messages, schema, "trial-001-designer") + [call] = pi_stand.seen() + assert error is None and json.loads(response["content"]) == {"verdict": "ok"} and usage[0].calls == 1 + assert "--no-builtin-tools" in call["args"] and "--no-session" in call["args"] + assert call["args"][:6] == ["--mode", "json", "--provider", "hermit", "--model", "m-1"] + assert call["args"][call["args"].index("--append-system-prompt") + 1] == "Be exact." + assert "the evidence" in call["stdin"] and "satisfies this JSON schema" in call["stdin"] + + +def test_a_reply_that_is_no_answer_fails_the_role(pi_stand, tmp_path): # noqa: F811 + from hermit.agent.evolver.methods.evosafe import pi_agent + response, _, error = pi_agent.call_role(ctx_of(tmp_path), [{"role": "user", "content": "x"}], + {"type": "object", "required": ["verdict"]}, "trial-002-designer") + assert response is None and error.startswith("pi role failed") diff --git a/tests/methods/harness2/test_harness2_on_pi.py b/tests/methods/harness2/test_harness2_on_pi.py new file mode 100644 index 00000000..55f3f1f4 --- /dev/null +++ b/tests/methods/harness2/test_harness2_on_pi.py @@ -0,0 +1,42 @@ +"""Harness²'s editors on Pi (`evolver.base: pi`), against the stand-in `pi` (tests/pi_stand.py), and a Pi acting agent's +trajectory in upstream's grammar.""" +import pytest + +from pi_stand import STREAMS, bound_params, pi_stand # noqa: F401 (pi_stand: the fixture) + + +def proposer(**more): + pytest.importorskip("harness2") + from harness2.core.spec import ChannelSpec + from hermit.agent.evolver.methods.harness2_upstream.channel import FrameworkProposer + return FrameworkProposer(spec=ChannelSpec(kind="claude_cli", model="m-1", effort="max"), + params={**bound_params(), **more}) + + +def test_harness2s_session_on_pi_takes_its_bound_model_and_keeps_its_usage(pi_stand, tmp_path): # noqa: F811 + prop = proposer() + cwd = tmp_path / "session" + cwd.mkdir() + text, cost, problem = prop._claude_cli(cwd, "the mission", "be brief", wall=60) + [call] = pi_stand.seen() + assert (text, problem) == ("the answer", "") and prop.served == 1 and cost == pytest.approx(prop.usages[0].cost_usd) + assert call["stdin"] == "the mission" and "--no-session" in call["args"] + assert call["args"][:6] == ["--mode", "json", "--provider", "hermit", "--model", "m-1"] + assert call["args"][call["args"].index("--append-system-prompt") + 1] == "be brief" + assert call["args"][call["args"].index("--thinking") + 1] == "xhigh" # Claude Code's max is Pi's xhigh + + +def test_a_pi_session_that_failed_is_no_reply(pi_stand, tmp_path): # noqa: F811 + prop = proposer() + cwd = tmp_path / "session" + cwd.mkdir() + pi_stand.play("failure") + text, cost, problem = prop._claude_cli(cwd, "the mission", "", wall=60) + assert text == "" and cost == 0.0 and problem.startswith("rc=0") and prop.served == 0 + + +def test_a_pi_trajectory_reads_in_upstreams_grammar(): + from hermit.agent.evolver.methods.harness2_upstream.render import render_pi_events + text = render_pi_events(STREAMS / "success.jsonl", obs_trunc=1000, max_chars=100000) + assert "[ACTION] bash: echo hi && exit 3" in text and "[OBSERVATION ERROR] hi" in text + assert '"tool": "echo"' in text and text.rstrip().endswith("[ASSISTANT] the answer") diff --git a/tests/methods/mwm/test_mwm_evolver.py b/tests/methods/mwm/test_mwm_evolver.py index a8efe6ea..d9c4ba46 100644 --- a/tests/methods/mwm/test_mwm_evolver.py +++ b/tests/methods/mwm/test_mwm_evolver.py @@ -148,13 +148,12 @@ def make(tmp: Path, monkeypatch, steps: int = 2, deployment_param: bool = False) return path -@pytest.mark.parametrize("override, name", [("evolver.base=pi", "pi"), - ("evolver.params.backend=mini-swe-agent", "mini-swe-agent")]) -def test_a_learner_that_is_not_codex_or_claude_code_is_refused_at_setup(tmp_path, monkeypatch, override, name): - """From the config through the Trainer: mwm's session settings carry no `provider`, so a learner on another CLI - Base Agent could not use its bound model. The run stops at setup, naming the backends it takes, before any step.""" - trainer = Trainer(Config.load(make(tmp_path, monkeypatch), [override]), log=lambda *_: None) - with pytest.raises(SystemExit, match=f"backend is codex or claude, not '{name}'"): +@pytest.mark.parametrize("name", ["react", "mini-swe-agent"]) +def test_a_learner_on_a_cli_mwm_is_not_set_up_for_is_refused_at_setup(tmp_path, monkeypatch, name): + """From the config through the Trainer: mwm's sessions are set up for Codex, Claude Code and Pi (each one's way to its + model, home and sign-in). The run stops at setup, naming the backends it takes, before any step.""" + trainer = Trainer(Config.load(make(tmp_path, monkeypatch), [f"evolver.params.backend={name}"]), log=lambda *_: None) + with pytest.raises(SystemExit, match=f"backend is codex, claude or pi, not '{name}'"): trainer.train() assert not (tmp_path / "runs" / "mwm-test" / "steps.jsonl").exists() diff --git a/tests/methods/mwm/test_mwm_on_pi.py b/tests/methods/mwm/test_mwm_on_pi.py new file mode 100644 index 00000000..c275a938 --- /dev/null +++ b/tests/methods/mwm/test_mwm_on_pi.py @@ -0,0 +1,56 @@ +"""MWM's learner on Pi (`evolver.base: pi`): a whole training against a stand-in `pi` that does what an MWM session does, +its stream the one the real CLI printed (tests/fixtures/pi).""" +import json +import shutil + +import pytest +import yaml + +from hermit.config import Config + +NEEDS_BWRAP = pytest.mark.skipif(not shutil.which("bwrap"), reason="needs bubblewrap") +BACKENDS = {"fake": {"base_url": "http://127.0.0.1:9/v1", "api_key_env": "FAKE_KEY", "apis": ["chat"], + "prices": {"m-1": {"input": 1.0, "cached_input": 0.1, "output": 2.0}}}} + +FAKE_MWM_PI = r'''#!/usr/bin/env python3 +"""The MWM learner on Pi: it writes a note in its working directory, the world model, records what it was given, and +prints the stream the real Pi printed (three tool calls).""" +import json, os, sys +from pathlib import Path +home = Path(os.environ["PI_CODING_AGENT_DIR"]) +n = len(list(Path("memory").glob("note*.md"))) +Path("memory", f"note{n}.md").write_text( + f"last_confirmed_t: {n}\nscope: always\nderived_from: none (reasoning only)\nbrief: note {n}\n\nA fact.\n") +Path("meta", "pi.json").write_text(json.dumps({"args": sys.argv[1:-1], "cwd": os.getcwd(), + "models": (home / "models.json").read_text()})) +sys.stdout.write(Path(__file__).with_name("stream.jsonl").read_text()) +''' + + +@NEEDS_BWRAP +def test_the_mwm_learner_runs_on_pi_with_its_bound_model(tmp_path, monkeypatch): + """From `evolver.base: pi` through the Trainer: each session is told its bound model (Pi's provider, written from the + model reference), works in /w, and is adopted by what the standard steps say it did.""" + import test_mwm_evolver as M + from hermit.trainer.trainer import Trainer + from pi_stand import STREAMS + monkeypatch.setenv("FAKE_KEY", "sk-fake") + path = M.make(tmp_path, monkeypatch) + data = yaml.safe_load(path.read_text()) + data["evolver"].update(base="pi", model="fake/m-1") + data["backends"] = BACKENDS + path.write_text(yaml.safe_dump(data)) + fake = tmp_path / "fakebin" / "pi" + fake.write_text(FAKE_MWM_PI) + fake.chmod(0o755) + shutil.copy(STREAMS / "success.jsonl", fake.with_name("stream.jsonl")) + Trainer(Config.load(path), log=lambda *_: None).train() + run = tmp_path / "runs" / "mwm-test" + steps = [json.loads(line) for line in (run / "steps.jsonl").read_text().splitlines()] + assert [s["evolver"]["status"] for s in steps] == ["done", "done", "done"] + sessions = json.loads((run / "step_0001" / "output" / "sessions.json").read_text()) + assert sessions[0]["status"] == "adopted" and sessions[0]["tool_calls"] == 3 and sessions[0]["turns"] == 4 + assert (run / "step_0001" / "output" / "review_0001.pi.jsonl").is_file() + saw = json.loads((run / "checkout" / "meta" / "pi.json").read_text()) + assert saw["cwd"] == "/w" and saw["args"][:6] == ["--mode", "json", "--provider", "hermit", "--model", "m-1"] + assert json.loads(saw["models"])["providers"]["hermit"]["apiKey"] == "$FAKE_KEY" diff --git a/tests/methods/rrsi_adapter/test_rrsi_adapter.py b/tests/methods/rrsi_adapter/test_rrsi_adapter.py index 58bb307d..f2960531 100644 --- a/tests/methods/rrsi_adapter/test_rrsi_adapter.py +++ b/tests/methods/rrsi_adapter/test_rrsi_adapter.py @@ -819,9 +819,12 @@ def test_setup_checks_what_every_step_needs(tmp_path): with pytest.raises(ValueError, match="web_search"): ev.setup(context(ws, 1, dom, tmp_path, web_search=None)) ev.setup(context(ws, 1, dom, tmp_path, backend="claude")) - for other in ("pi", "mini-swe-agent"): # its roles' settings are those two CLIs' - with pytest.raises(ValueError, match=f"backend is codex or claude, not '{other}'"): + ev.setup(context(ws, 1, dom, tmp_path, backend="pi")) + for other in ("react", "mini-swe-agent"): # no way to keep its roles read-only + with pytest.raises(ValueError, match=f"backend is codex, claude or pi, not '{other}'"): ev.setup(context(ws, 1, dom, tmp_path, backend=other)) + with pytest.raises(ValueError, match="roles.model on Pi needs roles.binding"): + ev.setup(context(ws, 1, dom, tmp_path, backend="pi", roles={"model": "m"})) with pytest.raises(Exception): ev.setup(context(ws, 1, str(tmp_path / "dom" / "missing.py") + ":ToyDomain", tmp_path)) with pytest.raises(ValueError, match="roles.model"): diff --git a/tests/methods/rrsi_adapter/test_rrsi_on_pi.py b/tests/methods/rrsi_adapter/test_rrsi_on_pi.py new file mode 100644 index 00000000..9d27d292 --- /dev/null +++ b/tests/methods/rrsi_adapter/test_rrsi_on_pi.py @@ -0,0 +1,47 @@ +"""The RRSI Adapter's roles on Pi (`evolver.base: pi`), against the stand-in `pi` (tests/pi_stand.py): what keeps a role +read-only on the other CLIs, Pi's own way.""" +import json +from pathlib import Path + +import pytest + +from claude_stand import roles_ctx +from pi_stand import bound_params, pi_stand # noqa: F401 (pi_stand: the fixture) + + +def roles_of(tmp_path, **more): + from hermit.agent.evolver.methods.rrsi_adapter import roles as R + from hermit.agent.evolver.methods.rrsi_adapter.evolver import RRSIAdapterEvolver + ctx = roles_ctx(tmp_path, {"login": None, **bound_params(), **more}) + evolver = RRSIAdapterEvolver() + evolver.directory = Path(R.__file__).parent + return evolver._roles(ctx) + + +def test_a_role_on_pi_has_no_tools_a_digester_only_those_that_read_and_each_its_bound_model(pi_stand, tmp_path): # noqa: F811 + pytest.importorskip("rrsi") + roles = roles_of(tmp_path) + assert roles.backend == "pi" + assert roles.generate("look at this", system="You are the analyst.") == "the answer" + [analyst] = pi_stand.seen() + assert {"--no-tools", "--no-mcp", "--no-context-files"} <= set(analyst["args"]) + assert analyst["args"][:6] == ["--mode", "json", "--provider", "hermit", "--model", "m-1"] + assert analyst["args"][analyst["args"].index("--append-system-prompt") + 1] == "You are the analyst." + assert analyst["stdin"] == "look at this" + assert json.loads(analyst["files"]["models.json"])["providers"]["hermit"]["apiKey"] == "$FAKE_KEY" + roles.traces = tmp_path / "traces" + roles.traces.mkdir() + assert roles.generate("read it", system="You are a trajectory digester.") == "the answer" + [digester] = pi_stand.seen() + assert digester["args"][digester["args"].index("--tools") + 1] == "read,grep,find,ls" + assert "--no-tools" not in digester["args"] and digester["cwd"] == str(roles.traces.resolve()) + + +def test_the_roles_own_binding_is_their_provider_on_pi(pi_stand, tmp_path): # noqa: F811 + pytest.importorskip("rrsi") + from hermit.agent.model.backends import Binding, as_binding, registry + backends = registry({"other": {"base_url": "http://127.0.0.1:8/v1", "api_key_env": "OTHER_KEY", "apis": ["chat"]}}) + binding: Binding = as_binding("other/m-2", backends) + roles = roles_of(tmp_path, roles={"model": "m-2", "binding": binding.spec()}) + assert roles.settings["provider"]["baseUrl"] == "http://127.0.0.1:8/v1" and roles.settings["model"] == "m-2" + assert roles.settings["provider"]["apiKey"] == "$OTHER_KEY" diff --git a/tests/pi_stand.py b/tests/pi_stand.py new file mode 100644 index 00000000..aabc6eb6 --- /dev/null +++ b/tests/pi_stand.py @@ -0,0 +1,73 @@ +"""The stand-in `pi` the methods' Pi tests run (tests/methods/*/test_*_on_pi.py): a script on PATH that replays a stream +the real CLI printed (tests/fixtures/pi), makes the edits a test names and records what each call was given. No test +reaches a real host or needs the real CLI.""" +import json +import os +from pathlib import Path +import stat +import sys + +import pytest + +from hermit.agent.model.backends import bind_agent_params, registry + +ROOT = Path(__file__).resolve().parents[1] +STREAMS = ROOT / "tests" / "fixtures" / "pi" + +SCRIPT = f'''#!{sys.executable} +"""A stand-in for `pi --mode json ...`: records its arguments, working directory, home files and stdin, makes the +edits in edits.json (relative to its working directory), then prints stream.jsonl.""" +import json, os, sys +from pathlib import Path +here = Path(__file__).resolve().parent +home = Path(os.environ["PI_CODING_AGENT_DIR"]) +seen = {{"args": sys.argv[1:], "cwd": os.getcwd(), "stdin": sys.stdin.read(), + "files": {{p.name: p.read_text() for p in sorted(home.glob("*.json")) if p.is_file()}}}} +with open(here / "seen.jsonl", "a") as f: + f.write(json.dumps(seen) + "\\n") +for name, text in json.loads((here / "edits.json").read_text()).items(): + Path(name).parent.mkdir(parents=True, exist_ok=True) + Path(name).write_text(text) +sys.stdout.write((here / "stream.jsonl").read_text()) +''' + + +class Stand: + def __init__(self, folder: Path): + self.folder = folder + + def play(self, stream: str = "resume", reply: str | None = None, edits: dict | None = None) -> None: + """The next calls replay `stream` (a file of tests/fixtures/pi), `reply` as the final answer, and make `edits`. + `resume` has no tool calls, `success` has three.""" + text = (STREAMS / f"{stream}.jsonl").read_text() + (self.folder / "stream.jsonl").write_text( + text if reply is None else text.replace("the answer", json.dumps(reply)[1:-1])) + (self.folder / "edits.json").write_text(json.dumps(edits or {})) + + def seen(self) -> list[dict]: + """What each call so far was given, and forget them.""" + path = self.folder / "seen.jsonl" + out = [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else [] + path.unlink(missing_ok=True) + return out + + +@pytest.fixture +def pi_stand(tmp_path, monkeypatch): + folder = tmp_path / "pi-bin" + folder.mkdir() + exe = folder / "pi" + exe.write_text(SCRIPT) + exe.chmod(exe.stat().st_mode | stat.S_IEXEC) + monkeypatch.setenv("PATH", f"{folder}{os.pathsep}{os.environ['PATH']}") + monkeypatch.setenv("FAKE_KEY", "sk-fake") + stand = Stand(folder) + stand.play() + return stand + + +def bound_params(**more) -> dict: + """A learner's params with its model bound for Pi (`fake/m-1`), as the Evolver's loader binds them.""" + backends = registry({"fake": {"base_url": "http://127.0.0.1:9/v1", "api_key_env": "FAKE_KEY", "apis": ["chat"], + "prices": {"m-1": {"input": 1.0, "cached_input": 0.1, "output": 2.0}}}}) + return {**bind_agent_params({"model": "fake/m-1", "backend": "pi"}, "pi", backends), "web_search": False, **more} diff --git a/tests/selection.py b/tests/selection.py index 999fc0dd..f3336bba 100644 --- a/tests/selection.py +++ b/tests/selection.py @@ -66,10 +66,11 @@ def fnmatch(path: str, pattern: str) -> bool: "hermit/task.py", "hermit/__init__.py", "hermit/adapter/templates/prompt_only/*", # the toy task's "pyproject.toml", "conftest.py", "tests/conftest.py", "tests/fakes.py", "tests/toy_task.py", "tests/selection.py", + "tests/pi_stand.py", "tests/fixtures/pi/*", # the Pi stand-in: the methods' "tests/claude_stand.py", "tests/fixtures/claude_streams/*", # the Claude stand-in: core's and the methods' ".github/workflows/tests.yml"] # how CI runs them: a change to it runs them all # the rest of the framework, the templates no method group owns, the documentation's examples: the core group -CORE = ["hermit/*", "tests/core/*", "tests/fixtures/pi/*", "docs/_examples/*"] +CORE = ["hermit/*", "tests/core/*", "docs/_examples/*"] # nothing to run: documentation, and files no test reads NONE = ["docs/*", "*.md", "tests/README.md", "LICENSE", "NOTICE", ".github/*", ".agents/*", "assets/*", ".gitignore"] From abb035071b207fe5584d5568af9a5af1d72aece3 Mon Sep 17 00:00:00 2001 From: Albert Zhao Date: Tue, 10 Nov 2026 11:36:00 -0500 Subject: [PATCH 04/13] Backends can give Pi a longer reply: max_output_tokens Pi caps one reply at 16384 tokens for a model it does not know. A model that reasons at length was cut before it answered, and EvoSafe's whole-file answer failed in one of three real runs. A backend's max_output_tokens now becomes the model's maxTokens in Pi's models.json. Unset, Pi's default stands. Co-Authored-By: Claude Opus 5.5 --- docs/guides/model-backends.md | 3 ++- docs/methods/agent.md | 3 +++ docs/reference/config-fields.md | 2 +- hermit/agent/model/backends.py | 19 +++++++++++++------ tests/core/test_cli_agent.py | 2 +- tests/core/test_pi_agent.py | 6 +++++- 6 files changed, 25 insertions(+), 10 deletions(-) diff --git a/docs/guides/model-backends.md b/docs/guides/model-backends.md index 92aba08a..4d5f1268 100644 --- a/docs/guides/model-backends.md +++ b/docs/guides/model-backends.md @@ -93,7 +93,8 @@ lab-sglang: # a new one, like the built-in sglang at | `litellm` | the litellm route prefix, for task agents that call through litellm (`fireworks_ai`, `hosted_vllm`) | | `prices` | per model id, `{input, cached_input, output}` in USD per million tokens; a model without one has an unknown cost (never zero) | | `extra_body` | fields added to every chat request, such as `reasoning_effort` | -| `context_window` | tokens; Codex is told it as `model_context_window`, Claude Code as `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | +| `context_window` | tokens; Codex is told it as `model_context_window`, Claude Code as `CLAUDE_CODE_MAX_CONTEXT_TOKENS`, Pi as `contextWindow` | +| `max_output_tokens` | tokens one request may answer with; Pi is told it as `maxTokens`, and otherwise uses its default of 16384: a model that reasons long can be cut before it answers, and that session fails | | `developer_role` | `keep` (default), or `system`: a relay in front of the backend renames the `developer` role Codex uses, for an endpoint that refuses it (the built-in `fireworks` sets it, as the examples always did; Qwen3.6's chat template refuses a `system` message after the first, so a local server keeps the role) | | `models` | aliases: short names for model ids | | `from` | start from a copy of another backend (the examples put a metering relay in front of one this way); the copy keeps the source's key variable, and a copy at another `base_url` drops the source's `messages_url` | diff --git a/docs/methods/agent.md b/docs/methods/agent.md index bd2f8f23..cf773bb9 100644 --- a/docs/methods/agent.md +++ b/docs/methods/agent.md @@ -18,6 +18,9 @@ On the single-file prompt-only template, the Codex learner is the [prompt-only]( Pi signs in only through the model reference and has no web search. A session cannot apply a request's `temperature`, and a request that asks for one is refused: OPRO, whose default is `1.0`, needs `evolver.pi: {unapplied: [temperature]}` or `evolver.params.temperature: null`. Pi has no sub-agents: an adapter's sub-agents stay files its acting agent can read. +Pi caps one reply at 16384 tokens unless the backend says otherwise: where a long answer is due (EvoSafe's whole files) +and the model reasons at length, give the backend a larger +[`max_output_tokens`](../guides/model-backends.md). ## Requirements and setup diff --git a/docs/reference/config-fields.md b/docs/reference/config-fields.md index 5cd60067..61011c59 100644 --- a/docs/reference/config-fields.md +++ b/docs/reference/config-fields.md @@ -75,7 +75,7 @@ dialects it serves, prices). See [Model backends](../guides/model-backends.md). | Field | Type / default | Meaning and constraints | |---|---|---| | `model` | string / null | The run's default model, a `/` reference; used by `llm`, `agent.params.model` and the `codex`, `claude` and `mwm` Evolvers' `evolver.params.model` when they name none | -| `backends` | mapping / {} | Backends declared for this run by name, over `~/.config/hermit/backends.yaml` and the built-ins. Fields: `base_url`, `api_key_env`, `key_required`, `apis`, `messages_url`, `litellm`, `prices`, `extra_body`, `context_window`, `models`, or `from: ` to copy one | +| `backends` | mapping / {} | Backends declared for this run by name, over `~/.config/hermit/backends.yaml` and the built-ins. Fields: `base_url`, `api_key_env`, `key_required`, `apis`, `messages_url`, `litellm`, `prices`, `extra_body`, `context_window`, `max_output_tokens`, `models`, or `from: ` to copy one | | `llm` | reference, mapping / null | The run's chat-completions `llm` tool: a reference, `{model: , price, extra_body}`, the endpoint itself (below), or a CLI's sessions, `{cli: ..., ...}` (below) | `agent.params.model` takes the same forms. For a Codex or Claude Code acting agent or Evolver a reference becomes diff --git a/hermit/agent/model/backends.py b/hermit/agent/model/backends.py index 450ac059..5894466c 100644 --- a/hermit/agent/model/backends.py +++ b/hermit/agent/model/backends.py @@ -25,7 +25,9 @@ litellm the litellm route prefix, for task agents that call through litellm (fireworks_ai, hosted_vllm) prices per model id: {input, cached_input, output}, USD per million tokens extra_body fields added to every chat request (for example reasoning_effort) - context_window tokens; Codex is told it (model_context_window), Claude Code too (CLAUDE_CODE_MAX_CONTEXT_TOKENS) + context_window tokens; Codex is told it (model_context_window), Claude Code too (CLAUDE_CODE_MAX_CONTEXT_TOKENS), + Pi too (contextWindow) + max_output_tokens tokens one request may answer with; Pi is told it (maxTokens; else its default, 16384) developer_role what a relay in front of the backend does with the `developer` role Codex uses: keep (default), or system for an endpoint that refuses the role (the examples' wire meter renames it) models aliases: short names for model ids (`vllm/qwen` for a long id) @@ -58,7 +60,7 @@ def user_file() -> Path: return Path(os.environ.get("HA_BACKENDS") or Path.home() / ".config" / "hermit" / "backends.yaml") APIS = ("chat", "responses", "messages") FIELDS = {"from", "base_url", "api_key_env", "key_required", "apis", "messages_url", "litellm", "prices", "extra_body", - "context_window", "developer_role", "models", "description"} + "context_window", "max_output_tokens", "developer_role", "models", "description"} DEVELOPER_ROLES = ("keep", "system") # What each consumer speaks: the dialect a backend must serve for it. NEEDS = {"chat": "chat", "react": "chat", "llm": "chat", "codex": "responses", "claude": "messages", "pi": "chat", @@ -83,6 +85,7 @@ class Backend: prices: dict = field(default_factory=dict) extra_body: dict = field(default_factory=dict) context_window: int | None = None + max_output_tokens: int | None = None developer_role: str = "keep" models: dict = field(default_factory=dict) description: str = "" @@ -111,14 +114,14 @@ def from_dict(cls, name: str, data: dict) -> "Backend": messages_url=(str(data["messages_url"]).rstrip("/") if data.get("messages_url") else None), litellm=data.get("litellm"), prices=dict(data.get("prices") or {}), extra_body=dict(data.get("extra_body") or {}), context_window=data.get("context_window"), - developer_role=role, models=dict(data.get("models") or {}), + max_output_tokens=data.get("max_output_tokens"), developer_role=role, models=dict(data.get("models") or {}), description=str(data.get("description") or "")) def to_dict(self) -> dict: return {"base_url": self.base_url, "api_key_env": self.api_key_env, "key_required": self.key_required, "apis": list(self.apis), "messages_url": self.messages_url, "litellm": self.litellm, "prices": self.prices, "extra_body": self.extra_body, "context_window": self.context_window, - "developer_role": self.developer_role, "models": self.models, "description": self.description} + "max_output_tokens": self.max_output_tokens, "developer_role": self.developer_role, "models": self.models, "description": self.description} @property def messages_root(self) -> str: @@ -247,7 +250,8 @@ def spec(self) -> dict: "api_key_env": self.api_key_env, "key_required": self.backend.key_required, "apis": list(self.backend.apis), "messages_url": self.backend.messages_root, "litellm": self.litellm_model, "price": self.price, "extra_body": dict(self.extra_body), - "context_window": self.backend.context_window} + "context_window": self.backend.context_window, + "max_output_tokens": self.backend.max_output_tokens} @classmethod def from_spec(cls, spec: dict) -> "Binding": @@ -259,7 +263,8 @@ def from_spec(cls, spec: dict) -> "Binding": key_required=bool(spec.get("key_required", True)), apis=tuple(spec.get("apis") or ["chat"]), messages_url=spec.get("messages_url"), litellm=(spec["litellm"].split("/", 1)[0] if spec.get("litellm") else None), - context_window=spec.get("context_window")) + context_window=spec.get("context_window"), + max_output_tokens=spec.get("max_output_tokens")) return cls(backend, str(spec["model"]), price=spec.get("price"), extra_body=dict(spec.get("extra_body") or {})) # ---- provider settings for the CLI agents --------------------------------------------------------------- @@ -316,6 +321,8 @@ def pi_provider(self) -> dict: model: dict = {"id": self.model} if self.backend.context_window: model["contextWindow"] = int(self.backend.context_window) + if self.backend.max_output_tokens: # else Pi's 16384: a model that reasons long is cut before it answers + model["maxTokens"] = int(self.backend.max_output_tokens) if self.price: p = self.price model["cost"] = {"input": p.get("input", 0), "output": p.get("output", 0), diff --git a/tests/core/test_cli_agent.py b/tests/core/test_cli_agent.py index 6cb3b61b..91b9f658 100644 --- a/tests/core/test_cli_agent.py +++ b/tests/core/test_cli_agent.py @@ -665,7 +665,7 @@ def test_a_cli_llm_is_left_to_the_trainer_and_bound_when_its_model_is_a_referenc normalize_config(data) assert data["llm"]["binding"] and any("model_provider" in a for a in data["llm"]["args"]) with pytest.raises(ValueError, match="llm.cli must be codex"): - normalize_config({"llm": {"cli": "pi"}, "agent": {}}) + normalize_config({"llm": {"cli": "aider"}, "agent": {}}) def test_a_fresh_home_is_not_in_the_temporary_directory(tmp_path, monkeypatch): diff --git a/tests/core/test_pi_agent.py b/tests/core/test_pi_agent.py index ba01bb4e..a1ac325b 100644 --- a/tests/core/test_pi_agent.py +++ b/tests/core/test_pi_agent.py @@ -18,7 +18,7 @@ from hermit.agent.base import trajectory from hermit.agent.base.interface import Unsupported, make from hermit.agent.base.tool import Tool -from hermit.agent.model.backends import bind_agent_params, registry +from hermit.agent.model.backends import Binding, bind_agent_params, registry ROOT = Path(__file__).resolve().parents[2] STREAMS = ROOT / "tests" / "fixtures" / "pi" @@ -85,6 +85,10 @@ def test_a_bound_model_is_pis_provider_with_its_key_as_a_variable_in_the_dialect assert messages["api"] == "anthropic-messages" and messages["baseUrl"] == "http://127.0.0.1:9" system = bound(developer_role="system", context_window=32000)["provider"] assert system["compat"] == {"supportsDeveloperRole": False} and system["models"][0]["contextWindow"] == 32000 + assert "maxTokens" not in params["provider"]["models"][0] # Pi's own default, unless the backend says + long = bound(max_output_tokens=64000) + assert long["provider"]["models"][0]["maxTokens"] == 64000 + assert Binding.from_spec(long["binding"]).pi_provider()["models"][0]["maxTokens"] == 64000 # a role's own binding free = bound(api_key_env="NO_SUCH_KEY_VAR", key_required=False)["provider"] assert free["apiKey"] == "local" # a server that needs no key gets the placeholder From 47791e91103a2b862d6e11a8be73f7f1f5819015 Mon Sep 17 00:00:00 2001 From: Albert Zhao Date: Tue, 10 Nov 2026 13:13:27 -0500 Subject: [PATCH 05/13] Pi on every method: fixes from the post-PR audit of 03ed729 - A reply cut at Pi's output limit comes back through the chat endpoint marked finish_reason: length, as from an API, and is no reply to Harness2's channel; Harness2 keeps a failed session's usage. - `evolver.base: pi` makes the run's model Pi only for a method whose manifest says it calls it (needs: [llm]); a custom agent Evolver keeps Pi as its CLI, as before. - Pi applies a request's temperature and top_p, and the backend's extra_body, as its model's samplingParams where the API is OpenAI-compatible; it takes effort max. - RRSI resumes a proposer session whose provider failed though Pi exited 0, and gives a digester Pi's grep and find only where rg and fd are installed. - Harness2 keeps the bound model's key variable; EvoSafe refuses `proposer: pi` with no model. Co-Authored-By: Claude Opus 5.5 --- docs/framework/agent-layers.md | 2 +- docs/framework/custom-evolver.md | 3 +- docs/framework/evolver.md | 2 +- docs/get-started/installation.md | 4 +- docs/guides/claude-subscription.md | 2 +- docs/guides/model-backends.md | 2 +- docs/methods/agent.md | 13 +- docs/methods/index.md | 10 +- docs/methods/meta_harness_adapter.md | 8 +- docs/methods/rrsi_adapter.md | 2 +- .../adapter/templates/ahe/.hermit/EVOLVER.md | 2 +- hermit/agent/base/cli.py | 16 ++- hermit/agent/base/endpoint.py | 17 ++- hermit/agent/evolver/loader.py | 2 +- hermit/agent/evolver/methods/ace/evolver.yaml | 2 +- .../evolver/methods/ahe_adapter/evolver.py | 2 +- .../methods/continual_harness/evolver.yaml | 2 +- .../agent/evolver/methods/evosafe/evolver.py | 3 + .../evolver/methods/evosafe/evolver.yaml | 2 +- .../agent/evolver/methods/gepa/evolver.yaml | 2 +- .../methods/harness2_upstream/channel.py | 23 ++-- .../methods/harness2_upstream/evolver.yaml | 4 +- .../methods/meta_harness_adapter/evolver.yaml | 2 +- hermit/agent/evolver/methods/mwm/evolver.py | 6 +- .../agent/evolver/methods/opro/evolver.yaml | 2 +- .../evolver/methods/reharness/evolver.yaml | 2 +- .../evolver/methods/rrsi_adapter/evolver.py | 8 +- .../evolver/methods/rrsi_adapter/roles.py | 12 +- .../evolver/methods/skillopt/evolver.yaml | 2 +- hermit/agent/model/backends.py | 2 + hermit/config.py | 5 +- tests/core/test_pi_agent.py | 127 +++++++++++++++++- tests/methods/ahe/test_ahe_on_pi.py | 13 +- tests/methods/evosafe/test_evosafe_on_pi.py | 72 +++++++++- tests/methods/harness2/test_harness2_on_pi.py | 47 ++++++- .../methods/rrsi_adapter/test_rrsi_adapter.py | 24 ++++ tests/methods/rrsi_adapter/test_rrsi_on_pi.py | 16 ++- tests/pi_stand.py | 22 +-- 38 files changed, 398 insertions(+), 89 deletions(-) diff --git a/docs/framework/agent-layers.md b/docs/framework/agent-layers.md index 9e8dda74..d8f22602 100644 --- a/docs/framework/agent-layers.md +++ b/docs/framework/agent-layers.md @@ -231,7 +231,7 @@ accepted; a key given in two layers is refused. On the command line a layer's se | OfficeQA in Codex, every method | Acting Agent with OfficeQA's task functions (`utils/task.py`) | `codex` | | OfficeQA in direct chat | Acting Agent running SkillOpt's chat loop | `direct`, per turn | | GEPA, SkillOpt, ReHarness, Continual Harness, OPRO | Evolver Agent | `direct` (`ctx.agent`); OPRO in OfficeQA: `codex` through `llm: {cli: codex}`; with `evolver.base: pi`, `pi` through `llm: {cli: pi}` | -| Meta-Harness Adapter, ASPIRE, `codex` and `claude` Evolvers | Evolver Agent | `codex`, `claude` or `pi` | +| Meta-Harness Adapter, ASPIRE, `codex` and `claude` Evolvers | Evolver Agent | `codex`, `claude`, `pi` or `opencode` | | `pi` Evolver | Evolver Agent | `pi` | | `opencode` Evolver | Evolver Agent | `opencode` | | RRSI Adapter | Evolver Agent: upstream's rules and roles, the proposer's prompt | `codex`, `claude` or `pi` for the proposer, and the same, one call per upstream `generate`, for the analyst, digesters and critic | diff --git a/docs/framework/custom-evolver.md b/docs/framework/custom-evolver.md index 70bc3701..e1908372 100644 --- a/docs/framework/custom-evolver.md +++ b/docs/framework/custom-evolver.md @@ -41,7 +41,8 @@ evolver: ``` Use `needs` to declare required resources: `validation_data`, `environment`, or `send_material_out`. The Trainer -checks them against the run settings before starting. Set `supports_resume = True` if the method understands the +checks them against the run settings before starting. `llm` says that the method calls the run's model (`ctx.agent`, +the `llm` tool) rather than a CLI of its own, so that `evolver.base: pi` makes that model Pi. Set `supports_resume = True` if the method understands the previous session handle; this is independent of storing files in `state/`. A param that names a model other than the run's `llm` (an embedding model, for one) is listed in the class's `model_params`, for example `model_params = ("embedding",)`: the loader binds a `/` reference there against the run's backends, diff --git a/docs/framework/evolver.md b/docs/framework/evolver.md index 50e8cc91..17eed51f 100644 --- a/docs/framework/evolver.md +++ b/docs/framework/evolver.md @@ -138,7 +138,7 @@ For selection guidance, setup, and the complete parameter defaults, use [Choose | `ahe_adapter` | [AHE Adapter](../methods/ahe_adapter.md), with `template: ahe@1.0`: one AHE iteration per step. It classifies each task by its k rollouts, scores the previous step's change manifest and rolls HARMFUL changes back, then runs an Agent Debugger session per task and an Evolve Agent session that edits the adapter; finalize hands back the best-ever iteration. | The Codex CLI, k rows per task sharing `task_field`, an acting agent that runs the adapter's hooks (Codex, Claude Code) | | `mwm` | MetaWorld Model, with `template: mwm`: one native MWM learner session per block (the step), under the MWM contract, with the task's evidence store mounted at `/evidence`, in its own network namespace. See `docs/methods/mwm.md`. | The Codex CLI, a task that keeps an MWM evidence store (`evolver_access.environment`), `task-info/mwm/`, `data.shuffle: false` | | `reharness` | [ReHarness](../methods/reharness.md), with `template: reharness`: one instance of the stream per step. It revises each reflection the acting agent retrieved, from that reflection's own source trajectory with the new trajectory as feedback, then writes the instance's reflection with the revised ones as demonstrations, through the run's `llm` tool with the paper's prompts; no validation data. | `llm`, `data.step_size: 1` and `data.shuffle: false`, an embedding endpoint (`evolver.params.embedding`, and `REHARNESS_EMBED_URL` for the acting side's reader; BM25 without) | -| `meta_harness_adapter` | [Meta-Harness Adapter](../methods/meta_harness_adapter.md), with `template: meta-harness-adapter`: one candidate per step. Each step's rollouts evaluate the candidate handed back last; when none is waiting, a Codex or Claude Code proposer reads every earlier candidate's files, scores and trajectories and writes k new adapters, which pass `check_spec` before they are queued; no validation data. | The proposer CLI, `data.step_size` covering the training split (the search set) | +| `meta_harness_adapter` | [Meta-Harness Adapter](../methods/meta_harness_adapter.md), with `template: meta-harness-adapter`: one candidate per step. Each step's rollouts evaluate the candidate handed back last; when none is waiting, a Codex, Claude Code, Pi or OpenCode proposer reads every earlier candidate's files, scores and trajectories and writes k new adapters, which pass `check_spec` before they are queued; no validation data. | The proposer CLI, `data.step_size` covering the training split (the search set) | | `rrsi_adapter` | [RRSI Adapter](../methods/rrsi_adapter.md), with `template: rrsi-adapter`: one candidate per step. Each step's rollouts evaluate the candidate handed back last; when a round's candidates are all measured, upstream's selection decides it, upstream's analyst reads the incumbent's evaluation, and m Codex or Claude Code proposer sessions edit the incumbent under RRSI's edit budget, each diff screened by upstream's critic and a smoke before it is queued; no validation data. | The proposer CLI and the Codex CLI (the analyst, digesters and critic), `data.step_size` covering the training split with k rows per task, `evolver.params.domain`, `python -m pip install -e . --group rrsi` | Change a parameter with `evolver.params` in the run config; each Evolver's `evolver.yaml` under diff --git a/docs/get-started/installation.md b/docs/get-started/installation.md index a7433c5f..d645aea1 100644 --- a/docs/get-started/installation.md +++ b/docs/get-started/installation.md @@ -109,12 +109,12 @@ python -m pip install "hermit-harness[mini-swe-agent]" | Prompt-only learner | The Codex CLI, Linux with bubblewrap, and a learner backend that serves the Responses API | | GEPA | `python -m pip install -e . --group gepa`, learner endpoint, validation split | | SkillOpt | `python -m pip install -e . --group skillopt`, learner endpoint, validation split | -| Harness² | Python 3.12 or 3.13, `python -m pip install -e . --group harness2`, Claude Code, and the execution environment described in [Harness²](../methods/harness2.md) | +| Harness² | Python 3.12 or 3.13, `python -m pip install -e . --group harness2`, Claude Code (or Codex or Pi), and the execution environment described in [Harness²](../methods/harness2.md) | | RRSI Adapter | `python -m pip install -e . --group rrsi`, a CLI for the proposer and its analyst, digesters and critic (Codex, Claude Code or Pi), a training split evaluated k times per task | | Codex / Claude learner | Selected authenticated CLI and supported program-execution environment | | MWM | Linux learner environment, Codex, Claude Code or Pi, evidence store, task deployment contract, model access | | Acting and learning on a Claude subscription | Claude Code 2.1.248 or later, `claude setup-token`, Linux with bubblewrap for its sandboxes; see [Claude subscription](../guides/claude-subscription.md) | -| Pi acting agent or learner | The release's own directory on `PATH` (GitHub release `pi-linux-x64.tar.gz`, checked against its `SHA256SUMS`; the sandboxes follow no link from `/usr`) and a model reference | +| Pi acting agent or learner | The `pi` release binary on `PATH` (GitHub release `pi-linux-x64.tar.gz`, checked against its `SHA256SUMS`) and a model reference. For a Pi acting agent put the release's directory on `PATH`, or link `pi` from outside `/usr`: its task sandbox shows a program's own directory and follows no link from `/usr` | | OpenCode acting agent or learner | The `opencode` 2.2 release binary on `PATH` (GitHub release `opencode-linux-x64.tar.gz` of `anomalyco/opencode`, checked against the release's sha256 digest) and a model reference | | Benchmark recipe | Its dataset, scorer, model settings, and environment; see [catalog](../recipes/index.md) | diff --git a/docs/guides/claude-subscription.md b/docs/guides/claude-subscription.md index d646029d..5ae1328a 100644 --- a/docs/guides/claude-subscription.md +++ b/docs/guides/claude-subscription.md @@ -250,7 +250,7 @@ A session is not a model API. This is what a chat request through the endpoint g | `reasoning_effort` | The session's effort; on Claude Code low, medium, high, xhigh or max, else 400 | | `model` | Must be the endpoint's; another is 400, never a quiet substitute | | `max_tokens`, `max_completion_tokens` | Accepted and not applied, and the reply's `unapplied` says so: methods send them as a cap, and the CLI's own cap would cut the reply and continue it by itself | -| `temperature`, `top_p`, `stop`, `seed`, `logprobs`, penalties, anything else | 400: the CLI has no setting. `llm.unapplied: [temperature]` accepts a named field going unapplied | +| `temperature`, `top_p`, `stop`, `seed`, `logprobs`, penalties, anything else | 400: the CLI has no setting. `llm.unapplied: [temperature]` accepts a named field going unapplied. Pi applies `temperature` and `top_p` where its backend speaks an OpenAI-compatible API | | `n` above 1; a `response_format` other than text | 400 | | `stream`, `stream_options` | Kept: the reply arrives whole, as chunks at the end | | `parallel_tool_calls`; `tools: []`; `tool_choice` `none` or `auto` | Accepted: they ask for nothing a session would do | diff --git a/docs/guides/model-backends.md b/docs/guides/model-backends.md index 0fca0504..1c84ff38 100644 --- a/docs/guides/model-backends.md +++ b/docs/guides/model-backends.md @@ -96,7 +96,7 @@ lab-sglang: # a new one, like the built-in sglang at | `messages_url` | the root the Anthropic Messages API is under, when it is not `base_url` without its `/v1` | | `litellm` | the litellm route prefix, for task agents that call through litellm (`fireworks_ai`, `hosted_vllm`) | | `prices` | per model id, `{input, cached_input, output}` in USD per million tokens; a model without one has an unknown cost (never zero) | -| `extra_body` | fields added to every chat request, such as `reasoning_effort` | +| `extra_body` | fields added to every chat request, such as `reasoning_effort`; Pi sends them as its model's `samplingParams` to an OpenAI-compatible API | | `context_window` | tokens; Codex is told it as `model_context_window`, Claude Code as `CLAUDE_CODE_MAX_CONTEXT_TOKENS`, Pi as `contextWindow` | | `max_output_tokens` | tokens one request may answer with; Pi is told it as `maxTokens`, and otherwise uses its default of 16384: a model that reasons long can be cut before it answers, and that session fails | | `developer_role` | `keep` (default), or `system`: a relay in front of the backend renames the `developer` role Codex uses, for an endpoint that refuses it (the built-in `fireworks` sets it, as the examples always did; Qwen3.6's chat template refuses a `system` message after the first, so a local server keeps the role) | diff --git a/docs/methods/agent.md b/docs/methods/agent.md index 25335151..342c3ea3 100644 --- a/docs/methods/agent.md +++ b/docs/methods/agent.md @@ -17,11 +17,14 @@ On the single-file prompt-only template, the Codex learner is the [prompt-only]( | `pi`, Meta-Harness Adapter, ASPIRE, MWM, AHE Adapter, Harness², RRSI Adapter, EvoSafe | The method's own sessions, as on Codex or Claude Code | | GEPA, SkillOpt, ACE, OPRO, ReHarness, Continual Harness | They call the run's model, so that model becomes Pi: each call is one session with no tools (the same as `llm: {cli: pi, model: /}`) | -Pi signs in only through the model reference and has no web search. A session cannot apply a request's `temperature`, -and a request that asks for one is refused: OPRO, whose default is `1.0`, needs `evolver.pi: {unapplied: [temperature]}` -or `evolver.params.temperature: null`. Pi has no sub-agents: an adapter's sub-agents stay files its acting agent can read. -Pi caps one reply at 16384 tokens unless the backend says otherwise: where a long answer is due (EvoSafe's whole files) -and the model reasons at length, give the backend a larger +Pi signs in only through the model reference and has no web search. Where the backend speaks an OpenAI-compatible API +(chat completions or the Responses API), a request's `temperature` and `top_p`, and the backend's `extra_body`, reach +the model as Pi's `samplingParams`; on the Messages API Pi ignores them, so there a request that asks for a +`temperature` is refused unless `evolver.pi.unapplied` names it. Pi has no sub-agents: an adapter's sub-agents stay +files its acting agent can read. Pi's `grep` and `find` tools run `rg` and `fd`, which an offline Pi cannot fetch: RRSI's +digesters get them only where the machine has them. Pi caps one reply at 16384 tokens unless the backend says otherwise: +a reply cut there comes back with `finish_reason: length`, or fails the session that needed it whole. Where a long answer +is due (EvoSafe's whole files) and the model reasons at length, give the backend a larger [`max_output_tokens`](../guides/model-backends.md). ## Requirements and setup diff --git a/docs/methods/index.md b/docs/methods/index.md index 23c83d78..67cefd7e 100644 --- a/docs/methods/index.md +++ b/docs/methods/index.md @@ -13,15 +13,15 @@ template–method combinations meaningful. | Refine a harness per task from trajectories without labels, with a library of adopted harnesses | [Harness²](harness2.md) | `harness2-codex@1.1` | Learner model endpoint, Codex, the `harness2` dependency group | | Refine a policy, sub-agents, skills and memory in place from each step's trajectories, without a gate | [Continual Harness](continual_harness.md) | `continual-harness@1.1` | Learner model endpoint, Codex | | Grow an itemised playbook by incremental deltas from reflections, keeping the best validation playbook | [ACE](ace.md) | `ace@1.0` | Learner model endpoint; optional validation split | -| Evolve an agent's harness (prompt, middleware, scripts, skills, sub-agents, memory) from k rollouts per task, with each change attributed and reversible | [AHE Adapter](ahe_adapter.md) | `ahe@1.0` | An acting agent that runs hooks (Codex, Claude Code), a learner CLI (Codex or Claude Code), k rows per task | +| Evolve an agent's harness (prompt, middleware, scripts, skills, sub-agents, memory) from k rollouts per task, with each change attributed and reversible | [AHE Adapter](ahe_adapter.md) | `ahe@1.0` | An acting agent that runs hooks (Codex, Claude Code), a learner CLI (Codex, Claude Code or Pi), k rows per task | | Search a dual-surface defense (prompt + tool hooks) for a frozen victim against frozen attack cases | [EvoSafeHarness](evosafe.md) | `evosafe@1.0` | Hook-bridge pipeline, utility/attack judge (verdicts in `JudgeResult.extra`), optional validation split, Claude Code or Codex | | Search instructions with a model that reads the best earlier instructions with their training scores | [OPRO](opro.md) | `prompt-only@1.0` | Learner model endpoint; validation split for `select: validation` | -| Build a persistent world model from an ordered environment stream | [MWM](mwm.md) | `mwm` | Evidence store, deployment description, tools, Linux learner environment, a learner CLI (Codex or Claude Code) | +| Build a persistent world model from an ordered environment stream | [MWM](mwm.md) | `mwm` | Evidence store, deployment description, tools, Linux learner environment, a learner CLI (Codex, Claude Code or Pi) | | Learn a bank of reflections online, retrieved per instance of an ordered stream | [ReHarness](reharness.md) | `reharness` | The run's `llm`, an embedding endpoint (or BM25), an agent that reads the adapter through `Session.context(query, task)` | -| Search whole adapters with a coding-agent proposer that reads every earlier candidate's files, scores and trajectories | [Meta-Harness Adapter](meta_harness_adapter.md) | `meta-harness-adapter` | A training split (the search set), a proposer CLI (Codex or Claude Code), an acting agent that delivers the adapter | -| Evolve whole adapters round by round under regularizers against overfitting the evolve set: an annealed edit budget, the edit history, exploration when stalled, a pre-evaluation leakage critic, a noise-adjusted floor and a cost rule | [RRSI Adapter](rrsi_adapter.md) | `rrsi-adapter` | A training split (the evolve set, k rows per task), a proposer CLI (Codex or Claude Code), the `rrsi` dependency group, a domain module with the benchmark's texts | +| Search whole adapters with a coding-agent proposer that reads every earlier candidate's files, scores and trajectories | [Meta-Harness Adapter](meta_harness_adapter.md) | `meta-harness-adapter` | A training split (the search set), a proposer CLI (Codex, Claude Code or Pi), an acting agent that delivers the adapter | +| Evolve whole adapters round by round under regularizers against overfitting the evolve set: an annealed edit budget, the edit history, exploration when stalled, a pre-evaluation leakage critic, a noise-adjusted floor and a cost rule | [RRSI Adapter](rrsi_adapter.md) | `rrsi-adapter` | A training split (the evolve set, k rows per task), a proposer CLI (Codex, Claude Code or Pi), the `rrsi` dependency group, a domain module with the benchmark's texts | | Learn the framework contract offline | [Quick Start](../get-started/quickstart.md) | Prompt-only with a teaching learner | Included toy tasks | -| Grow a library of verified skill entries from robot tasks, each proposal re-solved by a fresh actor before it is admitted, with the coordinator choosing the next task | [ASPIRE](aspire.md) | `aspire` | A coordinator CLI (Codex or Claude Code), verifier task rows in `data.val`, an acting agent that delivers the adapter | +| Grow a library of verified skill entries from robot tasks, each proposal re-solved by a fresh actor before it is admitted, with the coordinator choosing the next task | [ASPIRE](aspire.md) | `aspire` | A coordinator CLI (Codex, Claude Code or Pi), verifier task rows in `data.val`, an acting agent that delivers the adapter | A learner model endpoint above can be your Claude subscription, and a learner CLI can run on it, with no API key: [Claude subscription](../guides/claude-subscription.md) says which roles go which way. diff --git a/docs/methods/meta_harness_adapter.md b/docs/methods/meta_harness_adapter.md index 37ea810c..c3c1d788 100644 --- a/docs/methods/meta_harness_adapter.md +++ b/docs/methods/meta_harness_adapter.md @@ -40,7 +40,7 @@ This fragment belongs in a complete [run config](../framework/configuration.md). ([What an adapter can rely on](../framework/adapter.md#what-an-adapter-can-rely-on)); what happens to the adapter's other files depends on the agent, and the task information must say so, because the proposer learns it from there. -- A Codex, Claude Code or Pi CLI for the proposer, as the built-in [agent Evolvers](agent.md) run it. +- A Codex, Claude Code, Pi or OpenCode CLI for the proposer, as the built-in [agent Evolvers](agent.md) run it. ## The template @@ -80,7 +80,7 @@ first. | Paper (Algorithm 1) | Framework | |---|---| | The filesystem D | The Evolver's `state/`: `evolution_summary.jsonl` (one line per candidate: id, round, hypothesis, base, mean score, where its files and rollouts are), `candidates//adapter/`, and the learning material's `step_NNNN/` (for each task its input, the agent's output, the judge's score and feedback, the full trajectory) | -| The proposer | An `AgentEvolver` session (Codex, Claude Code or Pi) started afresh each round with the round's prompt, `PROPOSE.md`; it reads D and writes into `scratch/candidates/` | +| The proposer | An `AgentEvolver` session (Codex, Claude Code, Pi or OpenCode) started afresh each round with the round's prompt, `PROPOSE.md`; it reads D and writes into `scratch/candidates/` | | Interface validation | `check_spec` on each candidate, by the proposer and again by the Evolver | | Evaluation on the search set | The Trainer's rollouts of the next step, on the training split | | Selection | `finalize`: the best mean on the search set | @@ -99,7 +99,7 @@ candidates, do not run the evaluation. |---|---|---| | `k` | Positive integer / 2 | Candidates per proposal round (the paper: 2-3; its TerminalBench-2 run: 1) | | `max_rounds` | Integer or null / null | Proposal rounds; null starts a new round whenever every proposed candidate was evaluated, including on the run's last step, whose candidates are then never evaluated. With `max_rounds` R, `trainer.epochs` = 1 + R x k evaluates each candidate once; more epochs re-evaluate the best | -| `backend`, `model`, `args` | `codex`, `claude` or `pi`; `/`; CLI arguments | The proposer and its model, as for the built-in [agent Evolvers](agent.md) | +| `backend`, `model`, `args` | `codex`, `claude`, `pi` or `opencode`; `/`; CLI arguments | The proposer and its model, as for the built-in [agent Evolvers](agent.md) | | `tools` | List / `[check_spec]` | The Trainer tools the proposer may call; `run_agent` is left out on purpose: the evaluation is the Trainer's | | `prompt` | File name / `PROPOSE.md` | The round's prompt; its placeholders (`{round}`, `{k}`, the paths) are filled per round | @@ -112,7 +112,7 @@ The rollout cost is (1 + R x k) x |search set| rollouts for R rounds, plus one p | What the proposer may change | The whole harness program, including the acting agent's loop | Every file of the adapter outside `.hermit/`; the acting agent, its loop and the host stay fixed | forced by the framework | | Selection | A population with a Pareto frontier (for example accuracy against context length); the frontier is tested | The best mean on the search set; one candidate is tested | decision | | Parent selection | None fixed: the proposer chooses what to build on | The same: each candidate names its `base`, or none | matched | -| Proposer | Claude Code with Claude Opus 4.6 at maximum effort | Codex, Claude Code or Pi with the run's choice of model | a setting | +| Proposer | Claude Code with Claude Opus 4.6 at maximum effort | Codex, Claude Code, Pi or OpenCode with the run's choice of model | a setting | | Interface validation | The candidate imports | `check_spec` against the template | forced by the framework | | Isolation | — | The proposer runs in the run's sandbox; candidates with symbolic links are rejected, since they are copied outside it; a stored candidate changed in place (content or executable bit) is never handed back; the Evolver's own writes after a round never follow a link the proposer left | the reproduction's | diff --git a/docs/methods/rrsi_adapter.md b/docs/methods/rrsi_adapter.md index 21b1b4fa..a98151a0 100644 --- a/docs/methods/rrsi_adapter.md +++ b/docs/methods/rrsi_adapter.md @@ -164,7 +164,7 @@ stop ends the run anyway. |---|---|---|---| | What the proposer may change | The whole harness program | Every file of the adapter outside `.hermit/`; the acting agent, its loop and the host stay fixed | forced by the framework | | The proposer | Claude Opus 4.8 in upstream's JSON-action loop | A session of the `codex`, `claude` or `pi` Base Agent with `evolver.model`, upstream's system text, context sections and done() contract | a setting | -| The search roles | Claude Opus 4.8, one completion per call; the analyst and the critic answer from the text they are given | The proposer's model (or `roles`), one session of the proposer's CLI per call, read-only (Codex's own sandbox, or on Claude Code no tools or only those that read): the analyst and the critic in an empty directory, a digester in the round's rendered traces, which it may read with its own tools as well as through upstream's actions; none of them sees the run's records, the step's output, the proposers' directories or the other role calls' | a setting | +| The search roles | Claude Opus 4.8, one completion per call; the analyst and the critic answer from the text they are given | The proposer's model (or `roles`), one session of the proposer's CLI per call, read-only (Codex's own sandbox, or on Claude Code and Pi no tools or only those that read): the analyst and the critic in an empty directory, a digester in the round's rendered traces, which it may read with its own tools as well as through upstream's actions; none of them sees the run's records, the step's output, the proposers' directories or the other role calls' | a setting | | Component vocabulary | Signals in the Terminus-2 source | The same K, with signals for adapter files (`domain.ADAPTER_SIGNALS`) | forced by the framework | | delta | Measured from repeated base evaluations (coding: 0.017) | Upstream's `calibrate` on H_0's one evaluation unless the config gives one (its within-task bootstrap reads low by about sqrt(2) with two trials, as upstream's does; on OfficeQA the spread of H_0's own evaluations across the runs, sd 0.035, gives a band of about 0.10 for a difference, against a calibrated 0.045–0.061) | matched to upstream's driver | | Unexplored components U_t | K minus the components with a measured edit | The same, without the components outside the domain's carriers (`AdapterDomain.carriers`, for what the benchmark's agent cannot carry; OfficeQA's: the five its reported runs could carry, whose deployment connected no hooks and no roles, kept until a run measures the rest): a reserved slot never asks for one | forced by the setting (OfficeQA: a decision, the runs' setting) | diff --git a/hermit/adapter/templates/ahe/.hermit/EVOLVER.md b/hermit/adapter/templates/ahe/.hermit/EVOLVER.md index 070ede41..594714b4 100644 --- a/hermit/adapter/templates/ahe/.hermit/EVOLVER.md +++ b/hermit/adapter/templates/ahe/.hermit/EVOLVER.md @@ -94,7 +94,7 @@ only the stdlib: nothing else is installed where the agent runs. `nexau.txt`: a hook that never fires, always errors, or denies the wrong commands is visible there and nowhere else. `hook-state/.json` beside it holds the final session states. (The runner writes both under `.hermit-hooks/` in the session's workspace; each rollout's trajectory carries them at its root, beside the - agent's event stream: `agent-codex.jsonl` from Codex, `agent-claude.jsonl` from Claude Code, `agent-pi.jsonl` from Pi.) + agent's event stream: `agent-codex.jsonl` from Codex, `agent-claude.jsonl` from Claude Code.) - A veto's reason is what the model reads: say what to do instead, not only what was blocked. The same holds for an `after_tool` note: one or two lines, specific to the command that just ran. diff --git a/hermit/agent/base/cli.py b/hermit/agent/base/cli.py index 6eaeb422..880995c0 100644 --- a/hermit/agent/base/cli.py +++ b/hermit/agent/base/cli.py @@ -72,7 +72,7 @@ image_input (true: the bound model takes images, such as a tool's result; default: text only, Pi's default for a model it does not know), append_system_prompt, effort (its --thinking level), allowed_tools (Pi's own tools by name, its --tools: read, grep, find, ls, bash, edit, write; the call's tools stay; empty: none of its own), persist_session - (false: --no-session). Pi takes no roles, has no web search and runs under isolation none or sandbox. + (false: --no-session), sampling (fields for the bound model's samplingParams: a chat request's temperature, top_p). Pi takes no roles, has no web search and runs under isolation none or sandbox. mini-swe-agent only: model_class, config, step_limit (MiniSweAgent; hermit.agent.base.mini_swe_agent). It takes no roles, no session and no login, has no web search and runs under isolation none or sandbox. OpenCode only: provider (its config's provider for the bound model, from the binding: Binding.opencode_provider; @@ -1349,7 +1349,15 @@ class Pi(CliAgent): home_var, user_folder = "PI_CODING_AGENT_DIR", ".pi/agent" home_files = ("auth.json",) turn_done = "agent_settled" - efforts = ("off", "minimal", "low", "medium", "high", "xhigh") # what --thinking takes; it warns and ignores others + efforts = ("off", "minimal", "low", "medium", "high", "xhigh", "max") # --thinking's levels; it ignores others + sampling = ("temperature", "top_p") # request fields a session applies (models.json samplingParams) + + def applied_fields(self) -> tuple[str, ...]: + """The request fields a session applies (the chat endpoint's contract_problems): a bound model's sampling + fields, which Pi sends to an OpenAI-compatible API as the model's samplingParams; the Messages API ignores + them, so there a request that asks for one is refused, as on the other CLIs.""" + api = (self.settings.get("provider") or {}).get("api") + return self.sampling if api in ("openai-completions", "openai-responses") else () def home_env(self, home): """Every variable Pi reads goes here, so that it passes the sandbox's filter: its agent directory, its HOME @@ -1379,6 +1387,9 @@ def prepare_home(self, home, roles, tools_url, tools_name): if s.get("image_input"): # else Pi sends the model no image (a text-only model refuses them) for model in provider.get("models") or []: model["input"] = ["text", "image"] + if s.get("sampling"): # a request's own (cli_answer), over the backend's extra_body + for model in provider.get("models") or []: + model["samplingParams"] = {**(model.get("samplingParams") or {}), **s["sampling"]} (home / "models.json").write_text(json.dumps({"providers": {PI_PROVIDER: provider}}, indent=1)) # A tool call may take minutes (a Trainer tool runs rollouts): Codex's tool_timeout_sec, not Pi's 60 s servers = {tools_name: {"url": tools_url, "exposure": "direct", "timeout": 1800}} if tools_url else {} @@ -1436,6 +1447,7 @@ def outcome(self, raw, stream, last_file): notes, done = "the session was to have no tools, and it ran one", False return {"reply": self.last_message(stream, last_file), "served": done, "unavailable": bool(UNAVAILABLE.search(notes)), "refused": False, "failed": not done or cut, + "finish_reason": "length" if cut else ("stop" if done else None), "failure": (notes or ("the reply was cut at its output limit" if cut else "the session did not settle") )[-600:]} diff --git a/hermit/agent/base/endpoint.py b/hermit/agent/base/endpoint.py index 05691f96..bf192154 100644 --- a/hermit/agent/base/endpoint.py +++ b/hermit/agent/base/endpoint.py @@ -22,7 +22,7 @@ The URL carries a random token, so that only whoever was handed it can call the model; it listens on loopback unless told otherwise. -Over a CLI Base Agent (`codex`, `claude`) the endpoint is no relay: each request is one session of it, for code that +Over a CLI Base Agent (`codex`, `claude`, `pi`) the endpoint is no relay: each request is one session of it, for code that calls a chat API and a model only the CLI reaches (cli_answer, cli_model). A session is not a model API, and what it cannot do is refused rather than dropped: docs/guides/claude-subscription.md has the contract. """ @@ -276,6 +276,7 @@ def contract_problems(agent: BaseAgent, request: dict) -> tuple[list[str], list[ not isinstance(p, dict) or p.get("type") not in ("text", "input_text", "output_text") for p in m["content"]): problems.append("a message part that is not text: a session takes text") + applied = set(agent.applied_fields()) if hasattr(agent, "applied_fields") else set() # the session sets them session = agent.settings.get("model") if session and request.get("model") and request["model"] != session: problems.append(f"model {request['model']!r}: this endpoint's sessions run {session!r}") @@ -283,7 +284,7 @@ def contract_problems(agent: BaseAgent, request: dict) -> tuple[list[str], list[ if effort and efforts and effort not in efforts: problems.append(f"reasoning_effort {effort!r}: {agent.name} takes {list(efforts)}") for key, value in request.items(): - if value is None or key in ("model", "messages", "reasoning_effort", "parallel_tool_calls"): + if value is None or key in ("model", "messages", "reasoning_effort", "parallel_tool_calls") or key in applied: continue if key in UNAPPLIED: unapplied.append(key) @@ -352,6 +353,10 @@ def cli_answer(agent: BaseAgent, request: dict, abort: threading.Event | None = return 400, json.dumps({"error": {"message": "; ".join(problems)}}).encode(), {} system, prompt = split_messages(request["messages"]) own = {"stdin": True, "text_only": True, **({"cancel": abort} if abort is not None else {})} + sampling = {k: request[k] for k in (agent.applied_fields() if hasattr(agent, "applied_fields") else ()) + if request.get(k) is not None} + if sampling: # Pi's: sent with the request, as an API would + own["sampling"] = sampling if request.get("reasoning_effort"): own["effort"] = str(request["reasoning_effort"]) log_dir, scratch = agent.settings.get("log_dir"), None @@ -376,8 +381,8 @@ def cli_answer(agent: BaseAgent, request: dict, abort: threading.Event | None = redact_file(Path(os.path.realpath(kept))) # through a link the caller made: its target if result.extra.get("cancelled"): return _DROP - if not result.extra.get("served") or not result.reply.strip(): - return _no_reply(agent, result) + if not result.extra.get("served") or not (result.reply.strip() or result.finish_reason == "length"): + return _no_reply(agent, result) # a reply cut at the output limit is one, marked so body = {"id": f"chatcmpl-{secrets.token_hex(6)}", "object": "chat.completion", "created": int(time.time()), "model": result.extra.get("served_model") or request.get("model") or agent.settings.get("model"), "choices": [{"index": 0, "message": {"role": "assistant", "content": result.reply}, @@ -468,7 +473,7 @@ def cli_problems(spec: dict) -> list[str]: def cli_endpoint(spec: dict, log_dir=None, *, sandbox=None) -> ChatEndpoint: - """A chat endpoint over the CLI a spec names (`{cli: codex | claude, model: ..., login: ..., ...}`), started: each + """A chat endpoint over the CLI a spec names (`{cli: codex | claude | pi, model: ..., login: ..., ...}`), started: each request is one session of that Base Agent (cli_answer). Every key but `cli` and `timeout` is the Base Agent's setting (hermit.agent.base.cli). With `isolation: sandbox` (the default) every session runs in `sandbox`, the one the run made for them (hermit.isolate.cli_sandbox: its empty workspace and home, its model's or its login's @@ -513,7 +518,7 @@ def endpoint_spec(endpoint: ChatEndpoint, spec: dict) -> dict: def cli_model(spec: dict, log_dir=None, sandbox=None): - """The run's `llm` when it names a CLI (`llm: {cli: codex | claude, model: ..., login: chatgpt | claude, ...}`): a + """The run's `llm` when it names a CLI (`llm: {cli: codex | claude | pi, model: ..., login: chatgpt | claude, ...}`): a chat client over a ChatEndpoint over that CLI (cli_endpoint), for a model only the CLI reaches; its sessions run in `sandbox`, which the Trainer makes (isolation: sandbox, the default), or each in a container of its own. `close()` closes the endpoint.""" diff --git a/hermit/agent/evolver/loader.py b/hermit/agent/evolver/loader.py index fef8189a..cfdc7847 100644 --- a/hermit/agent/evolver/loader.py +++ b/hermit/agent/evolver/loader.py @@ -12,7 +12,7 @@ from hermit.agent.evolver.base import Evolver BUILTIN = Path(__file__).resolve().parent / "methods" -NEEDS = {"validation_data", "environment", "send_material_out"} +NEEDS = {"validation_data", "environment", "send_material_out", "llm"} # llm: it calls the run's model @dataclass diff --git a/hermit/agent/evolver/methods/ace/evolver.yaml b/hermit/agent/evolver/methods/ace/evolver.yaml index 4693c2d4..8d61591e 100644 --- a/hermit/agent/evolver/methods/ace/evolver.yaml +++ b/hermit/agent/evolver/methods/ace/evolver.yaml @@ -6,7 +6,7 @@ description: ACE, Agentic Context Engineering (Zhang et al., ICLR 2026, arXiv:25 (ADD only, as upstream) every curator_frequency samples. Validation (val_every) keeps the best playbook, which finalize hands back. Uses the run's `llm` tool; data.step_size 1 is upstream's per-sample loop. class: evolver.py:ACEEvolver -needs: [] +needs: [llm] # it calls the run's model (ctx.agent, the llm tool) params: feedback: true # the judge's verdict is the Reflector's environment feedback and gates the # retry rounds (labels); false: label-free, the run's own status only, no retry diff --git a/hermit/agent/evolver/methods/ahe_adapter/evolver.py b/hermit/agent/evolver/methods/ahe_adapter/evolver.py index d32812fd..c8fa71f7 100644 --- a/hermit/agent/evolver/methods/ahe_adapter/evolver.py +++ b/hermit/agent/evolver/methods/ahe_adapter/evolver.py @@ -2,7 +2,7 @@ 8b2a55d, `evolve.py`) as an Evolver on the `ahe` template, confined to the adapter (the acting agent is fixed). On the agent layers (docs/framework/agent-layers.md) both of its agents are Layer 3 over the Evolver's CLI Base Agent -(`codex` or `claude`, `backend`): the +(`codex`, `claude` or `pi`, `backend`): the Evolve Agent is AgentEvolver's session (the prompt on stdin, the run's sandbox, `check_spec` as its only tool), and the Agent Debugger is one call of the same Base Agent per attempt of each task (debugger.py), with the Evolve Agent's settings (the login and its plan, web search, the isolation, the price) and its own model, clock and home. diff --git a/hermit/agent/evolver/methods/continual_harness/evolver.yaml b/hermit/agent/evolver/methods/continual_harness/evolver.yaml index fd233c99..0630c951 100644 --- a/hermit/agent/evolver/methods/continual_harness/evolver.yaml +++ b/hermit/agent/evolver/methods/continual_harness/evolver.yaml @@ -8,7 +8,7 @@ description: Continual Harness's Refiner (Karten et al. 2026, arXiv:2605.09998; score is optimised and no validation gate is applied - every pass is applied in place, as the paper's reset-free loop does; a pass whose result fails the template check is dropped, the others stand. class: evolver.py:ContinualHarnessEvolver -needs: [] +needs: [llm] # it calls the run's model (ctx.agent, the llm tool) params: components: [policy, subagents, skills, memory] # the passes to run, in this order feedback: true # show the judge's feedback to the Refiner (off: trajectory-only, as the paper's setting) diff --git a/hermit/agent/evolver/methods/evosafe/evolver.py b/hermit/agent/evolver/methods/evosafe/evolver.py index 021c88b4..1d5c6ff0 100644 --- a/hermit/agent/evolver/methods/evosafe/evolver.py +++ b/hermit/agent/evolver/methods/evosafe/evolver.py @@ -31,6 +31,9 @@ def step(self, ctx): proposer = role_backend(ctx.params) if proposer not in {"llm", "codex", "claude", "pi"}: return StepResult("failed", "proposer must be llm, codex, claude or pi") + if proposer == "pi" and not ctx.params.get("provider"): + return StepResult("failed", "proposer pi takes its model from evolver.base: pi and evolver.model (a " + "/ reference)") if proposer == "llm" and "llm" not in ctx.tools: return StepResult("failed", "configure the run's llm tool for defense proposals") search_mode = ctx.params.get("search_mode", "single") diff --git a/hermit/agent/evolver/methods/evosafe/evolver.yaml b/hermit/agent/evolver/methods/evosafe/evolver.yaml index 8eec840c..3b7e0f71 100644 --- a/hermit/agent/evolver/methods/evosafe/evolver.yaml +++ b/hermit/agent/evolver/methods/evosafe/evolver.yaml @@ -17,7 +17,7 @@ params: evidence_chars_per_case: 2000 # initial summaries; complete TRAIN observations available through role tools robustness_task_ids: [] # Prefer evolver.base/model/; these fields keep old configurations readable. - proposer: llm # llm | codex | claude | pi (a CLI with read-only TRAIN experience tools) + proposer: llm # llm | codex | claude (a CLI with read-only TRAIN experience tools); Pi: evolver.base: pi codex_bin: codex codex_model: gpt-6-sol codex_timeout_s: 600 diff --git a/hermit/agent/evolver/methods/gepa/evolver.yaml b/hermit/agent/evolver/methods/gepa/evolver.yaml index 62e79643..c08778d7 100644 --- a/hermit/agent/evolver/methods/gepa/evolver.yaml +++ b/hermit/agent/evolver/methods/gepa/evolver.yaml @@ -1,7 +1,7 @@ description: GEPA reflective prompt evolution (gepa-ai/gepa), one GEPA iteration per training step. Reflects with the run's `llm` tool and scores candidates with run_agent on the step's minibatch and the validation tasks. class: evolver.py:GEPAEvolver -needs: [validation_data] +needs: [validation_data, llm] # llm: it calls the run's model (ctx.agent, the llm tool) params: files: [ADAPTER.md] # learnable text files, updated in turn candidate_selection_strategy: pareto # pareto (GEPA's default) or current_best diff --git a/hermit/agent/evolver/methods/harness2_upstream/channel.py b/hermit/agent/evolver/methods/harness2_upstream/channel.py index 9e92748a..896fcc68 100644 --- a/hermit/agent/evolver/methods/harness2_upstream/channel.py +++ b/hermit/agent/evolver/methods/harness2_upstream/channel.py @@ -150,38 +150,37 @@ def _pi_cli(self, cwd: Path, mission: str, system: str, wall: int) -> tuple[str, """The session on Pi: the `pi` Base Agent on the bound model (its models.json provider), the mission on stdin, upstream's system text appended to Pi's own, Pi's own tools (read, bash, edit, write) inside the run's sandbox, no session kept.""" - from hermit.agent.base.cli import EFFORTS own = {k: str(v) for k, v in (self.params.get("env") or {}).items()} err = Path(cwd) / ".session.err" + key = (self.params.get("binding") or {}).get("api_key_env") # upstream drops Anthropic's for Claude settings = {"web_search": False, "bin": self.params.get("claude_bin") or "pi", "stdin": True, - "effort": EFFORTS.get(self.spec.effort, self.spec.effort), # Claude Code's max is Pi's xhigh + "effort": self.spec.effort, # Claude Code's levels are Pi's too "model": self.params.get("model") or self.spec.model, "binding": self.params.get("binding"), "provider": self.params.get("provider"), "image_input": self.params.get("image_input"), "price": self.params.get("price"), "args": self.params.get("args"), "append_system_prompt": system or None, "persist_session": False, "home": Path(cwd) / ".pi-home", "home_files": [], "log": Path(cwd) / ".session.out", - "stderr_log": err, "env": {**QUIET, **own}, "env_drop": sorted(_DROP_ENV), + "stderr_log": err, "env": {**QUIET, **own}, "env_drop": sorted(set(_DROP_ENV) - {key}), "isolation": "sandbox" if self.sandbox is not None else "none", "sandbox": self.sandbox, "writable": [Path(cwd)], "timeout_s": wall, "cancel": self.cancel} result = make("pi", {k: v for k, v in settings.items() if v is not None}).run(mission, workspace=Path(cwd)) return self._reply("pi", result, err, wall) def _reply(self, program: str, result, err: Path, wall: int) -> tuple[str, float, str]: - """(reply, cost, problem) of a Codex or Pi session, its usage kept for the step.""" + """(reply, cost, problem) of a Codex or Pi session. Its usage is kept for the step, a failed session's too; a + reply cut at the output limit is no reply.""" if result.extra["cancelled"]: raise RuntimeError("the session was stopped by the Trainer (budget or timeout)") if result.timed_out: raise subprocess.TimeoutExpired([program], wall) - if not result.extra["served"] or not result.reply.strip(): - tail = (_read_own(err) or result.extra.get("output_tail", ""))[-300:] - return "", 0.0, f"rc={result.exit_code}: {tail}" - cost = 0.0 + with self._usage_lock: + self.usages.extend(result.usage) + cost = sum(float(u.cost_usd or 0.0) for u in result.usage) + if not result.extra["served"] or not result.reply.strip() or result.finish_reason == "length": + tail = (_read_own(err) or result.extra.get("failure") or result.extra.get("output_tail", ""))[-300:] + return "", cost, f"rc={result.exit_code}: {tail}" with self._usage_lock: self.served += 1 - for usage in result.usage: - with self._usage_lock: - self.usages.append(usage) - cost += float(usage.cost_usd or 0.0) return result.reply, cost, "" def _harvest(self, tmp: Path, sub: str, label: str, cache_key: str = "") -> Path | None: diff --git a/hermit/agent/evolver/methods/harness2_upstream/evolver.yaml b/hermit/agent/evolver/methods/harness2_upstream/evolver.yaml index 6aed9b4e..3ddd3067 100644 --- a/hermit/agent/evolver/methods/harness2_upstream/evolver.yaml +++ b/hermit/agent/evolver/methods/harness2_upstream/evolver.yaml @@ -5,7 +5,7 @@ description: Harness² (Xu et al., arXiv:2610.14224) under the paper's own proto executed on the same task as the deliverable, and a reflection that adds the adopted harness and its lesson to a per-domain library, the only thing carried to the next task. The adapter is never changed. Editor sessions are upstream's claude_cli channel on the bound model or on a login, each in its own sandbox; executions go through - run_agent, with the run's acting agent (Codex or Claude Code). No judge score reaches any session. + run_agent, with the run's acting agent (Codex, Claude Code or Pi). No judge score reaches any session. class: evolver.py:Harness2UpstreamEvolver needs: [] params: @@ -19,7 +19,7 @@ params: session_timeout_s: 3600 # wall clock per session attempt (upstream's ChannelSpec default) tools: Read,Write,Edit,Glob,Grep,Bash # the session's tools: files and a shell inside its sandbox, no web claude_bin: null # the sessions' CLI binary to pin for the run; null: the versioned path of `claude` (or - # `codex`) at start + # `codex`, `pi`) at start login: null # the editors on the user's subscription, its plan's waits and holds (hermit.agent.base.login): # backend claude: claude (the token of `claude setup-token` in CLAUDE_CODE_OAUTH_TOKEN); # backend codex: chatgpt (the user's ChatGPT login) diff --git a/hermit/agent/evolver/methods/meta_harness_adapter/evolver.yaml b/hermit/agent/evolver/methods/meta_harness_adapter/evolver.yaml index 3f65f1dd..ec72065e 100644 --- a/hermit/agent/evolver/methods/meta_harness_adapter/evolver.yaml +++ b/hermit/agent/evolver/methods/meta_harness_adapter/evolver.yaml @@ -6,7 +6,7 @@ description: The outer loop of Meta-Harness (Lee et al., arXiv:2603.28052) on th class: evolver.py:MetaHarnessAdapterEvolver needs: [] params: - backend: codex # the proposer: codex, claude or pi (the paper: Claude Code) + backend: codex # the proposer: codex, claude, pi or opencode (the paper: Claude Code) prompt: PROPOSE.md # the round's prompt (placeholders filled per round) args: [] # extra arguments for the proposer's CLI, e.g. codex `-c model_reasoning_effort="medium"` model: null # the proposer's model, `/`; null: the agent's default diff --git a/hermit/agent/evolver/methods/mwm/evolver.py b/hermit/agent/evolver/methods/mwm/evolver.py index 6c26d3de..6b774c94 100644 --- a/hermit/agent/evolver/methods/mwm/evolver.py +++ b/hermit/agent/evolver/methods/mwm/evolver.py @@ -5,7 +5,7 @@ the native wrapper ran after a block: 1. maintenance on the adapter (journal roll, docket caps, gate advice, memory index; prompt.prepare_session); -2. one session of the learner's CLI (`backend`: codex, as natively, or claude) with the native session prompt +2. one session of the learner's CLI (`backend`: codex, as natively, claude or pi) with the native session prompt (prompt.build_prompt), started in the adapter directory with the native mounts (the world model at /w, read-only at /world-model; /evidence, /environment, /skills, /patterns), in its own network namespace (it reaches its model (the meter, or a login's hosts), the session's tool server with the venue's channels, the MW_TOOLSRV gate and @@ -30,9 +30,9 @@ (default task-info/mwm/; see deployment.py for what the method fixes itself). Parameters (evolver.params): - backend the learner's CLI: codex (default) or claude + backend the learner's CLI: codex (default), claude or pi model, args, home, price, as for the built-in codex and claude Evolvers (args carries Codex's provider and - login, effort, env reasoning settings; a binding's Claude Code provider settings come in env), with + login, effort, env reasoning settings; a binding's Claude Code provider settings come in env, Pi's in provider), with plan_dir, plan_max_wait_s, plan_rerun and usage_credits for a login's plan evidence the run's evidence store (required; must be among evolver_access.environment) deployment the venue's texts for MWM, relative to the run config (default: task-info/mwm) diff --git a/hermit/agent/evolver/methods/opro/evolver.yaml b/hermit/agent/evolver/methods/opro/evolver.yaml index 7c9a6906..87683e90 100644 --- a/hermit/agent/evolver/methods/opro/evolver.yaml +++ b/hermit/agent/evolver/methods/opro/evolver.yaml @@ -4,7 +4,7 @@ description: OPRO, Optimization by PROmpting (Yang et al., ICLR 2024, arXiv:2309 instructions; each is scored with run_agent on every training task and joins the history. Set data.step_size to the training split's size. finalize keeps the best on training, or the best on validation of the top_k on training. class: evolver.py:OPROEvolver -needs: [] +needs: [llm] # it calls the run's model (ctx.agent, the llm tool) params: n_candidates: 8 # new instructions per step, one optimizer call each (upstream: 8) max_num_instructions: 20 # old instructions shown, the best ones (upstream: 20) diff --git a/hermit/agent/evolver/methods/reharness/evolver.yaml b/hermit/agent/evolver/methods/reharness/evolver.yaml index ef67ae4c..eabbd76c 100644 --- a/hermit/agent/evolver/methods/reharness/evolver.yaml +++ b/hermit/agent/evolver/methods/reharness/evolver.yaml @@ -5,7 +5,7 @@ description: ReHarness (Xiao et al., arXiv:2610.12668), a recurrent harness for feedback (Eq. 2) and writes the instance's reflection with the revised ones as demonstrations (Eq. 3), through the run's `llm` tool, with the paper's prompts. No validation data, no replay. class: evolver.py:ReHarnessEvolver -needs: [] +needs: [llm] # it calls the run's model (ctx.agent, the llm tool) params: k: 5 # reflections retrieved per instance, and revised after it (the paper: 5) embedding: null # the embedding model, `/` (the paper: Qwen3-Embedding-8B, on diff --git a/hermit/agent/evolver/methods/rrsi_adapter/evolver.py b/hermit/agent/evolver/methods/rrsi_adapter/evolver.py index 6d4489f7..38a9f6f5 100644 --- a/hermit/agent/evolver/methods/rrsi_adapter/evolver.py +++ b/hermit/agent/evolver/methods/rrsi_adapter/evolver.py @@ -14,7 +14,7 @@ and its summaries (rrsi.history: L_t, T_t, U_t, sigma_t, E_t, g_t, B_t, the rendered rows), the component tags (rrsi.components.normalize), the scores (rrsi.evaluate), delta's calibration (rrsi.calibrate), the selection (rrsi.selection.select_round), the analyst with its digesters (rrsi.analyst.analyze) and the critic (rrsi.critic. -review), the last two with `generate` rebound to one session of the proposer's CLI Base Agent (`codex` or `claude`) +review), the last two with `generate` rebound to one session of the proposer's CLI Base Agent (`codex`, `claude` or `pi`) per call (roles.py). What is Hermit's: @@ -573,7 +573,7 @@ def _roles(self, ctx) -> Roles: provider = provider if list(base.get("args") or [])[:len(provider)] == provider else [] if role.get("model") is not None: # nor its provider arguments args = list(base.get("args") or [])[len(provider):] - base = {k: v for k, v in base.items() if k not in ("binding", "price", "args", "provider")} | ( + base = {k: v for k, v in base.items() if k not in ("binding", "price", "args")} | ( {"args": args} if args else {}) base["env"] = {k: v for k, v in (base.get("env") or {}).items() if k not in CLAUDE_ENV} provider = [] @@ -1017,7 +1017,7 @@ def _context(self, ctx, dom, t: int, vid: str, reserved: bool, bundle: dict, wor return cdir def _session(self, ctx, prompt: str, path: Path, work: Path, session: str | None, log: Path) -> StepResult: - """One proposer session (or a resumed one) of the `codex` or `claude` Base Agent, in the variant's working + """One proposer session (or a resumed one) of the `codex`, `claude` or `pi` Base Agent, in the variant's working directory (its candidate under adapter/, its context under context/) and the task description, nothing else the run keeps (a view of the run's sandbox), the Trainer's allowed tools, and its event log at `log`. Its home is the variant's own: a later variant never reads an earlier one's sessions.""" @@ -1070,7 +1070,7 @@ def _session(self, ctx, prompt: str, path: Path, work: Path, session: str | None # the model's plan held the session back past its wait, or refused it: not the proposer's doing, so # the variant is drafted again later, never recorded as a gate failure raise Stop(f"the model's plan did not serve a proposer session: {tail[-200:]}") - if result.exit_code == 0 or extra.get("served") or not extra.get("unavailable"): + if extra.get("served") or not extra.get("unavailable"): # Pi exits 0 when its provider failed ended = result.exit_code == 0 and not extra.get("failed") # exit 0 with no result is no finished edit return StepResult("done" if ended else "failed", f"{backend} session exited with {result.exit_code}", session=result.session, diff --git a/hermit/agent/evolver/methods/rrsi_adapter/roles.py b/hermit/agent/evolver/methods/rrsi_adapter/roles.py index 8de12a9f..ec04e616 100644 --- a/hermit/agent/evolver/methods/rrsi_adapter/roles.py +++ b/hermit/agent/evolver/methods/rrsi_adapter/roles.py @@ -32,6 +32,7 @@ import json import os from pathlib import Path +import shutil import subprocess import threading import time @@ -42,7 +43,14 @@ ROLE_MODULES = ("rrsi.analyst", "rrsi.digester", "rrsi.critic") DIGESTER_TOOLS = ["Read", "Grep", "Glob"] # Claude Code's tools that only read, as Codex's read-only sandbox allows -PI_DIGESTER_TOOLS = ["read", "grep", "find", "ls"] # Pi's own + + + +def pi_digester_tools() -> list[str]: + """Pi's tools that only read, of those that work here: its grep and find run rg and fd, which a Pi offline cannot + fetch, so they are given only where the machine has them on the system paths a sandbox shows.""" + found = {name: shutil.which(program) for name, program in (("grep", "rg"), ("find", "fd"))} + return ["read", *(n for n in ("grep", "find") if (found[n] or "").startswith(("/usr/", "/bin/"))), "ls"] LABELS = {"codex": "Codex", "claude": "Claude Code", "pi": "Pi"} @@ -193,7 +201,7 @@ def _session(self, system: str, prompt: str) -> Result: cwd = self.traces if digester else work settings = {**self.settings, "home": call / "home", "log": rec / "events.jsonl", "stdin": True, "cancel": self.ctx.cancel, - **({"allowed_tools": PI_DIGESTER_TOOLS if self.backend == "pi" else DIGESTER_TOOLS} + **({"allowed_tools": pi_digester_tools() if self.backend == "pi" else DIGESTER_TOOLS} if digester else {"text_only": True})} # Each session sees only its own call directory and, a digester, the round's traces: not the run's records, # the other calls' homes or the records in progress. diff --git a/hermit/agent/evolver/methods/skillopt/evolver.yaml b/hermit/agent/evolver/methods/skillopt/evolver.yaml index e58e5a32..1ce7d99e 100644 --- a/hermit/agent/evolver/methods/skillopt/evolver.yaml +++ b/hermit/agent/evolver/methods/skillopt/evolver.yaml @@ -1,7 +1,7 @@ description: SkillOpt bounded, validation-gated skill optimization (microsoft/SkillOpt), one SkillOpt step per training step, with its slow update and meta skill at the end of each epoch. Uses the run's `llm` tool and run_agent. class: evolver.py:SkillOptEvolver -needs: [validation_data] +needs: [validation_data, llm] # llm: it calls the run's model (ctx.agent, the llm tool) params: file: ADAPTER.md # the skill document minibatch_size: 8 # rollouts per reflection call diff --git a/hermit/agent/model/backends.py b/hermit/agent/model/backends.py index a4b68876..36f23e0e 100644 --- a/hermit/agent/model/backends.py +++ b/hermit/agent/model/backends.py @@ -325,6 +325,8 @@ def pi_provider(self) -> dict: model["contextWindow"] = int(self.backend.context_window) if self.backend.max_output_tokens: # else Pi's 16384: a model that reasons long is cut before it answers model["maxTokens"] = int(self.backend.max_output_tokens) + if self.extra_body and api in ("chat", "responses"): # sent with every request; the Messages API ignores them + model["samplingParams"] = dict(self.extra_body) if self.price: p = self.price model["cost"] = {"input": p.get("input", 0), "output": p.get("output", 0), diff --git a/hermit/config.py b/hermit/config.py index bacf7233..5c3595ee 100644 --- a/hermit/config.py +++ b/hermit/config.py @@ -110,13 +110,12 @@ def _model(params: dict, model, where: str, cli: bool = True) -> None: def _calls_the_runs_model(name, base: Path | None) -> bool: """Whether the Evolver `name` decides each step in its own code and calls the run's model (`ctx.agent`, the `llm` - tool): its manifest names no CLI of its own (no `backend`, no `proposer`).""" + tool): its manifest says so (`needs: [llm]`). Any other Evolver takes `evolver.base` as its own CLI.""" from hermit.agent.evolver.loader import find try: - params = find(str(name), base).params + return "llm" in find(str(name), base).needs except ValueError: # no such Evolver: said where the Evolver is loaded return False - return "backend" not in params and "proposer" not in params def layered(data: dict, base_dir: Path | None = None) -> None: diff --git a/tests/core/test_pi_agent.py b/tests/core/test_pi_agent.py index a662ae85..b31b96bc 100644 --- a/tests/core/test_pi_agent.py +++ b/tests/core/test_pi_agent.py @@ -89,6 +89,10 @@ def test_a_bound_model_is_pis_provider_with_its_key_as_a_variable_in_the_dialect long = bound(max_output_tokens=64000) assert long["provider"]["models"][0]["maxTokens"] == 64000 assert Binding.from_spec(long["binding"]).pi_provider()["models"][0]["maxTokens"] == 64000 # a role's own binding + # a backend's extra_body goes with every request to an OpenAI-compatible API; the Messages API takes none + assert bound(extra_body={"reasoning_effort": "low"})["provider"]["models"][0]["samplingParams"] == { + "reasoning_effort": "low"} + assert "samplingParams" not in bound(apis=["messages"], extra_body={"x": 1})["provider"]["models"][0] free = bound(api_key_env="NO_SUCH_KEY_VAR", key_required=False)["provider"] assert free["apiKey"] == "local" # a server that needs no key gets the placeholder @@ -324,15 +328,16 @@ def test_allowed_tools_are_pis_own_and_keep_the_calls_tools(fake): def test_pi_refuses_an_effort_it_does_not_take_and_keeps_no_session_when_told(fake): - """Pi warns about an unknown --thinking level and goes on at its default: refused, as for Claude Code.""" + """Pi 1.5.0 takes off, minimal, low, medium, high, xhigh and max (clamped to what the model supports); it warns + about any other --thinking level and goes on at its default: refused, as for Claude Code.""" work = fake / "work" work.mkdir() agent = make("pi", {**bound(), "web_search": False, "home": str(fake / "home")}) - with pytest.raises(Unsupported, match="Pi takes effort .*not 'max'"): - agent.configured(effort="max").run("go", workspace=work) - agent.configured(persist_session=False, effort="xhigh").run("go", workspace=work) + with pytest.raises(Unsupported, match="Pi takes effort .*not 'bogus'"): + agent.configured(effort="bogus").run("go", workspace=work) + agent.configured(persist_session=False, effort="max").run("go", workspace=work) args = seen(fake)[0]["args"] - assert "--no-session" in args and args[args.index("--thinking") + 1] == "xhigh" + assert "--no-session" in args and args[args.index("--thinking") + 1] == "max" def test_a_model_through_pi_answers_each_request_with_a_session_that_only_replies(fake, monkeypatch): @@ -348,11 +353,55 @@ def test_a_model_through_pi_answers_each_request_with_a_session_that_only_replie assert call["args"][call["args"].index("--append-system-prompt") + 1] == "Be exact." +def cut_stream(fake, text: bool = True): + """The recorded resume stream with its reply ended at the output limit, and with no text but its thinking.""" + lines = (STREAMS / "resume.jsonl").read_text().splitlines(keepends=True) + last = max(i for i, line in enumerate(lines) if '"type":"message_end"' in line and '"assistant"' in line) + event = json.loads(lines[last]) + event["message"]["stopReason"] = "length" + if not text: + event["message"]["content"] = [{"type": "thinking", "thinking": "a long thought"}] + lines[last] = json.dumps(event, separators=(",", ":")) + "\n" + (fake / "cut.jsonl").write_text("".join(lines)) + return str(fake / "cut.jsonl") + + +def test_a_reply_cut_at_the_output_limit_comes_back_through_the_chat_endpoint_marked_so(fake, monkeypatch): + """As from an API: the methods that call the run's model read `finish_reason: length` (GEPA, SkillOpt and ReHarness + discard or retry such a reply), and one with no text is no error to retry the same way.""" + from hermit.agent.base.endpoint import cli_answer + agent = make("pi", {**bound(), "web_search": False}) + request = {"messages": [{"role": "user", "content": "hello"}]} + for text, content in ((True, "the answer"), (False, "")): + monkeypatch.setenv("FAKE_PI_STREAM", cut_stream(fake, text)) + status, body, _ = cli_answer(agent, request) + choice = json.loads(body)["choices"][0] + assert status == 200 and choice["finish_reason"] == "length" and choice["message"]["content"] == content + work = fake / "work" + work.mkdir() + result = make("pi", {**bound(), "web_search": False, "home": str(fake / "home")}).run("go", workspace=work) + assert result.finish_reason == "length" and result.extra["failed"] + + +def test_a_requests_sampling_fields_reach_pis_model_where_its_api_takes_them(fake, monkeypatch): + """Pi sends a model's samplingParams to an OpenAI-compatible API: a request's temperature and top_p are applied + there, not refused; on the Messages API Pi would drop them, so there they are refused, as on the other CLIs.""" + from hermit.agent.base.endpoint import cli_answer + monkeypatch.setenv("FAKE_PI_STREAM", str(STREAMS / "resume.jsonl")) + request = {"messages": [{"role": "user", "content": "hello"}], "temperature": 0.3, "top_p": 0.9} + status, body, _ = cli_answer(make("pi", {**bound(extra_body={"seed": 1}), "web_search": False}), request) + [model] = json.loads(seen(fake)[0]["files"]["models.json"])["providers"]["hermit"]["models"] + assert status == 200 and "unapplied" not in json.loads(body) + assert model["samplingParams"] == {"seed": 1, "temperature": 0.3, "top_p": 0.9} + status, body, _ = cli_answer(make("pi", {**bound(apis=["messages"]), "web_search": False}), request) + assert status == 400 and "temperature" in json.loads(body)["error"]["message"] and len(seen(fake)) == 1 + + @pytest.mark.parametrize("spec, match", [({}, "needs a / reference"), ({"login": "chatgpt"}, "not login: chatgpt"), ({"binding": {"x": 1}, "isolation": "container"}, "needs isolation: sandbox"), ({"binding": {"x": 1}, "web_search": True}, "web_search cannot be on"), - ({"binding": {"x": 1}, "effort": "max"}, "takes effort off")]) + ({"binding": {"x": 1}, "effort": "bogus"}, "takes effort off")]) def test_what_a_model_through_pi_cannot_be_is_said_before_any_session(spec, match): from hermit.agent.base.endpoint import cli_problems assert any(match in problem for problem in cli_problems({"cli": "pi", **spec})) @@ -379,6 +428,48 @@ def test_evolver_base_pi_is_the_run_model_of_a_method_that_calls_it_and_the_lear assert data["evolver"]["params"]["backend"] == "pi" and data["llm"] is None, name with pytest.raises(ValueError, match="llm names it too"): layered({"agent": {}, "llm": "fake/m-1", "evolver": {"name": "opro", "base": "pi", "model": "fake/m-1", "params": {}}}) + data = {"agent": {}, "llm": None, "model": "fake/m-1", "evolver": {"name": "ace", "base": "pi", "params": {}}} + layered(data) # the run's default model, when evolver.model is not given + assert data["llm"] == {"cli": "pi", "model": "fake/m-1"} + data = {"agent": {}, "llm": None, "backends": {"anth": {"base_url": "http://127.0.0.1:9/v1", "api_key_env": "FAKE_KEY", + "apis": ["messages"]}}, + "evolver": {"name": "gepa", "base": "pi", "model": "anth/m-2", "params": {}}} + layered(data) + normalize_config(data) + [(_, _, dialect)] = bindings_of(data) # the dialect Pi speaks to this backend + assert dialect == "messages" and data["llm"]["provider"]["api"] == "anthropic-messages" + + +def test_a_custom_evolver_takes_evolver_base_pi_as_its_cli_unless_its_manifest_says_it_calls_the_runs_model(tmp_path, + monkeypatch): + """A launcher of the agent Evolver (docs/framework/custom-evolver.md) names no backend in its manifest: Pi is its + CLI, as before. One whose manifest says `needs: [llm]` calls the run's model, which becomes Pi; a relative name is + found beside the config.""" + import sys + sys.path.insert(0, str(ROOT / "tests")) + from toy_task import make_task + from hermit.config import Config + monkeypatch.setenv("FAKE_KEY", "sk-fake") + for name, needs in (("agentic", []), ("chatty", ["llm"])): + folder = tmp_path / name + folder.mkdir() + (folder / "evolver.yaml").write_text("class: hermit.agent.evolver.agent:AgentEvolver\n" + f"needs: {json.dumps(needs)}\nparams: {{prompt: START.md, web_search: false}}\n") + backends = {"fake": {"base_url": "http://127.0.0.1:9/v1", "api_key_env": "FAKE_KEY", "apis": ["chat"]}} + path = make_task(tmp_path, evolver={"name": "agentic", "base": "pi", "model": "fake/m-1"}, backends=backends) + agentic = Config.load(path).data + assert agentic["evolver"]["params"]["backend"] == "pi" and not agentic.get("llm") + chatty = Config.load(path, ["evolver.name=chatty"]).data + assert chatty["llm"]["cli"] == "pi" and "backend" not in chatty["evolver"]["params"] + + +def test_a_pipelines_model_through_pi_is_bound_as_the_learners_is(): + from hermit.agent.model.backends import normalize_config + data = {"agent": {"name": "react", "params": {"model": {"cli": "pi", "model": "fake/m-1"}}}, + "backends": {"fake": {"base_url": "http://127.0.0.1:9/v1", "api_key_env": "FAKE_KEY", "apis": ["chat"]}}} + normalize_config(data) + spec = data["agent"]["params"]["model"] + assert spec["cli"] == "pi" and spec["provider"]["apiKey"] == "$FAKE_KEY" and spec["model"] == "m-1" # ---------- the installed pi (integration) ---------- @@ -495,3 +586,27 @@ def script(body): finally: server.shutdown() assert result.extra["served"] and result.reply == "the answer" and asked == [offered] + + +@pytest.mark.integration +@pytest.mark.skipif(not shutil.which("pi"), reason="needs the pi CLI") +def test_with_the_pi_cli_a_requests_temperature_and_the_backends_extra_body_reach_the_model(tmp_path, monkeypatch): + """The installed Pi behind the chat endpoint: what it sends is what the method asked and the backend adds.""" + from hermit.agent.base.endpoint import cli_answer + bodies = [] + + def script(body): + bodies.append(body) + + server, url = serve_chat(script) + monkeypatch.setenv("MOCK_KEY", "sk-mock") + params = bind_agent_params({"model": "mock/m-1"}, "pi", registry({"mock": { + "base_url": url, "api_key_env": "MOCK_KEY", "apis": ["chat"], "extra_body": {"reasoning_effort": "low"}}})) + try: + status, body, _ = cli_answer(make("pi", {**params, "web_search": False, "home": str(tmp_path / "home"), + "timeout_s": 300}), + {"messages": [{"role": "user", "content": "hi"}], "temperature": 0.3}) + finally: + server.shutdown() + [sent] = bodies + assert status == 200 and sent["temperature"] == 0.3 and sent["reasoning_effort"] == "low" and not sent.get("tools") diff --git a/tests/methods/ahe/test_ahe_on_pi.py b/tests/methods/ahe/test_ahe_on_pi.py index 5c3e42d6..3d51478d 100644 --- a/tests/methods/ahe/test_ahe_on_pi.py +++ b/tests/methods/ahe/test_ahe_on_pi.py @@ -1,5 +1,5 @@ -"""The AHE Adapter's Evolve Agent and Agent Debugger on Pi (`evolver.base: pi`), against the stand-in `pi` -(tests/pi_stand.py).""" +"""The AHE Adapter's learners on Pi (`evolver.base: pi`): the Agent Debugger's session against the stand-in `pi` +(tests/pi_stand.py), on the Evolve Agent's settings, which the agent Evolver's own Pi route runs (tests/core).""" from dataclasses import fields import json @@ -15,7 +15,9 @@ def test_the_ahe_learners_run_on_pi_with_its_bound_model(pi_stand, tmp_path): # ctx = roles_ctx(tmp_path, {"login": None, "prompt": "START.md", "k": 1, **bound_params()}) evolver = AHEAdapterEvolver() evolver.setup(ctx) - runner = D.Runner(ctx, {"model": None}, evolver.settings(ctx, "pi"), tmp_path / "scratch") + base = evolver.settings(ctx, "pi") # the Evolve Agent's own + assert base["provider"]["apiKey"] == "$FAKE_KEY" and base["model"] == "m-1" + runner = D.Runner(ctx, {"model": None}, base, tmp_path / "scratch") job = D.Job.__new__(D.Job) for f in fields(D.Job): setattr(job, f.name, {"task": "t1"}.get(f.name) if f.name == "task" else None) @@ -32,6 +34,7 @@ def test_the_ahe_learners_run_on_pi_with_its_bound_model(pi_stand, tmp_path): # def test_an_effort_pi_does_not_take_is_refused_at_setup(tmp_path): from hermit.agent.evolver.methods.ahe_adapter.evolver import AHEAdapterEvolver - with pytest.raises(ValueError, match="evolver.params.effort is one of off, minimal.*for Pi, not 'max'"): - AHEAdapterEvolver().setup(roles_ctx(tmp_path, {"login": None, **bound_params(), "effort": "max"})) + with pytest.raises(ValueError, match="evolver.params.effort is one of off, minimal.*for Pi, not 'bogus'"): + AHEAdapterEvolver().setup(roles_ctx(tmp_path, {"login": None, **bound_params(), "effort": "bogus"})) + AHEAdapterEvolver().setup(roles_ctx(tmp_path, {"login": None, **bound_params(), "effort": "max"})) diff --git a/tests/methods/evosafe/test_evosafe_on_pi.py b/tests/methods/evosafe/test_evosafe_on_pi.py index db4ee664..52971564 100644 --- a/tests/methods/evosafe/test_evosafe_on_pi.py +++ b/tests/methods/evosafe/test_evosafe_on_pi.py @@ -1,9 +1,15 @@ -"""EvoSafeHarness's per-role sessions on Pi (`evolver.base: pi`), against the stand-in `pi` (tests/pi_stand.py).""" +"""EvoSafeHarness on Pi (`evolver.base: pi`): its per-role sessions against the stand-in `pi` (tests/pi_stand.py), its +dispatch of the proposer and the roles to them, and a whole training whose proposer is a stand-in for that role.""" import json +from pathlib import Path from types import SimpleNamespace as NS +import yaml + from pi_stand import bound_params, pi_stand # noqa: F401 (pi_stand: the fixture) +TEMPLATE = Path(__file__).resolve().parents[3] / "hermit" / "adapter" / "templates" / "evosafe" + def ctx_of(tmp_path): ws = NS(scratch=tmp_path / "scratch", output=tmp_path / "out") @@ -32,3 +38,67 @@ def test_a_reply_that_is_no_answer_fails_the_role(pi_stand, tmp_path): # noqa: response, _, error = pi_agent.call_role(ctx_of(tmp_path), [{"role": "user", "content": "x"}], {"type": "object", "required": ["verdict"]}, "trial-002-designer") assert response is None and error.startswith("pi role failed") + + +def test_a_legacy_proposer_pi_without_a_model_is_refused_with_how_to_give_it_one(tmp_path): + from hermit.agent.evolver.methods.evosafe.evolver import EvoSafeEvolver + ctx = NS(workspace=NS(), params={"proposer": "pi", "eval_task_ids": ["a", "b"]}, access=NS(validation=None), tools={}) + result = EvoSafeEvolver().step(ctx) + assert result.status == "failed" and "evolver.base: pi and evolver.model" in result.summary + + +def test_the_roles_go_to_pi_when_it_is_the_proposer(tmp_path, monkeypatch): + from hermit.agent.evolver.methods.evosafe import pi_agent, roles + asked = [] + + def call(ctx, messages, schema, name): + asked.append(name) + return {"content": json.dumps({"verdict": "ok"})}, [], None + monkeypatch.setattr(pi_agent, "call_role", call) + ws = NS(output=tmp_path, state=tmp_path) + ctx = NS(workspace=ws, params={"backend": "pi"}, cancel=None, tools={}) + schema = {"type": "object", "required": ["verdict"], "properties": {"verdict": {"type": "string"}}} + assert roles.invoke_role(ctx, "Review it.", {"case": 1}, schema, "trial-001-criticizer", []) == {"verdict": "ok"} + assert asked == ["trial-001-criticizer"] + + +def test_a_whole_training_proposes_on_pi_with_its_bound_model(tmp_path, monkeypatch): + """From `evolver.base: pi` through the Trainer: EvoSafe keeps its own proposer (it names one), bound to the model, + and its proposal is the Pi role's answer.""" + from hermit.agent.evolver.methods.evosafe import pi_agent + from hermit.config import Config + from hermit.trainer.trainer import Trainer + monkeypatch.setenv("FAKE_KEY", "sk-fake") + (tmp_path / "pipeline.py").write_text(''' +from hermit.task import RunOutput +def run(task, adapter): + improved = "tested revision" in (adapter / "ADAPTER.md").read_text() + return RunOutput(output={"kind": task["kind"], "utility": True, + "attack_success": None if task["kind"] == "clean" else not improved}, cost_usd=0.0, tokens=0) +''') + (tmp_path / "judge.py").write_text("from hermit.task import JudgeResult\n\ndef score(task, output):\n" + " return JudgeResult(score=1.0, extra={\"metrics\": output.output})\n") + rows = [{"id": f"{s}-{k}", "kind": k, **({"injection_task_id": "f"} if k == "injected" else {})} + for s in ("train", "val") for k in ("clean", "injected")] + (tmp_path / "tasks.jsonl").write_text("".join(json.dumps(r) + "\n" for r in rows)) + for split in ("train", "val"): + (tmp_path / f"{split}.txt").write_text(f"{split}-clean\n{split}-injected\n") + asked = [] + + def call(ctx, messages, schema, name): + asked.append(ctx.params) + files = {n: (ctx.workspace.adapter / n).read_text() for n in ("ADAPTER.md", "defense.py", "BUNDLE.md")} + files["ADAPTER.md"] += "\ntested revision\n" + return {"content": json.dumps({"summary": "on pi", "files": files})}, [], None + monkeypatch.setattr(pi_agent, "call_role", call) + config = {"data": {"tasks": "tasks.jsonl", "train": "train.txt", "val": "val.txt", "step_size": 2}, + "template": str(TEMPLATE), "agent": {"name": "pipeline.py:run", "concurrency": 1}, + "judge": {"path": "judge.py"}, "sandbox": {"enabled": False}, + "backends": {"fake": {"base_url": "http://127.0.0.1:9/v1", "api_key_env": "FAKE_KEY", "apis": ["chat"]}}, + "evolver": {"name": "evosafe", "base": "pi", "model": "fake/m-1"}, + "trainer": {"run_name": "on-pi", "output_dir": "runs", "epochs": 1}} + (tmp_path / "run.yaml").write_text(yaml.safe_dump(config)) + trainer = Trainer(Config.load(tmp_path / "run.yaml"), log=lambda *_: None) + trainer.train() + assert "tested revision" in (trainer.ws.adapter / "ADAPTER.md").read_text() + assert asked and all(p["backend"] == "pi" and p["provider"]["apiKey"] == "$FAKE_KEY" for p in asked) diff --git a/tests/methods/harness2/test_harness2_on_pi.py b/tests/methods/harness2/test_harness2_on_pi.py index 55f3f1f4..c2bb6874 100644 --- a/tests/methods/harness2/test_harness2_on_pi.py +++ b/tests/methods/harness2/test_harness2_on_pi.py @@ -23,7 +23,7 @@ def test_harness2s_session_on_pi_takes_its_bound_model_and_keeps_its_usage(pi_st assert call["stdin"] == "the mission" and "--no-session" in call["args"] assert call["args"][:6] == ["--mode", "json", "--provider", "hermit", "--model", "m-1"] assert call["args"][call["args"].index("--append-system-prompt") + 1] == "be brief" - assert call["args"][call["args"].index("--thinking") + 1] == "xhigh" # Claude Code's max is Pi's xhigh + assert call["args"][call["args"].index("--thinking") + 1] == "max" # Claude Code's levels are Pi's too def test_a_pi_session_that_failed_is_no_reply(pi_stand, tmp_path): # noqa: F811 @@ -35,6 +35,51 @@ def test_a_pi_session_that_failed_is_no_reply(pi_stand, tmp_path): # noqa: F811 assert text == "" and cost == 0.0 and problem.startswith("rc=0") and prop.served == 0 +def test_a_pi_reply_cut_at_its_limit_is_no_reply_and_what_it_spent_is_kept(pi_stand, tmp_path): # noqa: F811 + prop = proposer() + cwd = tmp_path / "session" + cwd.mkdir() + pi_stand.play(cut=True) + text, cost, problem = prop._claude_cli(cwd, "the mission", "", wall=60) + assert text == "" and "cut at its output limit" in problem and prop.served == 0 + assert cost == pytest.approx(prop.usages[0].cost_usd) and prop.usages[0].output_tokens == 20 + + +def test_a_session_on_pi_keeps_its_models_key_where_upstream_drops_anthropics(pi_stand, tmp_path, monkeypatch): # noqa: F811 + """Upstream drops ANTHROPIC_API_KEY for its Claude sessions; a Pi session bound to a backend whose key is in that + variable (the built-in anthropic backend's) needs it.""" + monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-fake") + prop = proposer(**bound_params(key_env="ANTHROPIC_API_KEY")) + cwd = tmp_path / "session" + cwd.mkdir() + prop._claude_cli(cwd, "the mission", "", wall=60) + [call] = pi_stand.seen() + assert "ANTHROPIC_API_KEY" in call["keys"] + + +def test_harness2_runs_its_editors_on_pi_and_pins_pis_binary(pi_stand, tmp_path): # noqa: F811 + pytest.importorskip("harness2") + from types import SimpleNamespace as NS + from hermit.agent.evolver.methods.harness2_upstream.evolver import Harness2UpstreamEvolver + Harness2UpstreamEvolver().setup(NS(params={"backend": "pi"})) + with pytest.raises(ValueError, match="not the sign-in of backend pi"): + Harness2UpstreamEvolver().setup(NS(params={"backend": "pi", "login": "claude", "model": "m"})) + ws = NS(state=tmp_path / "state") + ws.state.mkdir() + assert Harness2UpstreamEvolver()._claude(ws, "pi") == str((pi_stand.folder / "pi").resolve()) + + +def test_a_pi_acting_agents_trajectory_is_read_by_the_bench(tmp_path): + pytest.importorskip("harness2") + import shutil + from types import SimpleNamespace as NS + from hermit.agent.evolver.methods.harness2_upstream.bench import FrameworkBench + (tmp_path / "log").mkdir() + shutil.copy(STREAMS / "success.jsonl", tmp_path / "log" / "agent-pi.jsonl") + text = FrameworkBench.trajectory(NS(_run=lambda run_dir: {}), tmp_path, obs_trunc=1000) + assert "[ACTION] bash: echo hi && exit 3" in text + + def test_a_pi_trajectory_reads_in_upstreams_grammar(): from hermit.agent.evolver.methods.harness2_upstream.render import render_pi_events text = render_pi_events(STREAMS / "success.jsonl", obs_trunc=1000, max_chars=100000) diff --git a/tests/methods/rrsi_adapter/test_rrsi_adapter.py b/tests/methods/rrsi_adapter/test_rrsi_adapter.py index f2960531..c948f88c 100644 --- a/tests/methods/rrsi_adapter/test_rrsi_adapter.py +++ b/tests/methods/rrsi_adapter/test_rrsi_adapter.py @@ -649,6 +649,26 @@ def run(self, prompt, **kw): assert not (ws.state / "rrsi" / "r0" / "A" / "prep.json").exists() +def test_a_provider_outage_in_a_session_that_exits_zero_is_retried_and_never_a_gate_failure(tmp_path, monkeypatch): + """Pi's JSON mode exits 0 when its provider could not serve: the session is resumed after a pause, as Codex's and + Claude Code's are, and a provider that keeps failing stops the step without counting it toward max_failures.""" + ws = workspace(tmp_path) + dom = domain_files(tmp_path) + ev = evolver(monkeypatch, Script({})) + calls = [] + + class Down(CodexSession): + def run(self, prompt, **kw): + calls.append(prompt) + return Result(reply="", exit_code=0, extra={"served": False, "unavailable": True, "started": True, + "cancelled": False, "failed": True, "output_tail": "503: busy"}) + monkeypatch.setattr(E, "make", lambda name, settings=None, model=None: Down(settings)) + material(ws, 1, rows({"q1": [0, 1], "q2": [1, 0], "q3": [1, 1], "q4": [0, 0]})) + r = ev.step(context(ws, 1, dom, tmp_path, session_retries=1, session_retry_wait_s=0)) + assert r.status == "failed" and "kept failing a proposer session" in r.summary + assert len(calls) == 2 and state(ws)["failures"] == 0 + + def test_a_host_side_write_replaces_a_named_pipe_instead_of_waiting_on_it(tmp_path): import threading from hermit.agent.evolver.methods.rrsi_adapter.store import _write @@ -825,6 +845,10 @@ def test_setup_checks_what_every_step_needs(tmp_path): ev.setup(context(ws, 1, dom, tmp_path, backend=other)) with pytest.raises(ValueError, match="roles.model on Pi needs roles.binding"): ev.setup(context(ws, 1, dom, tmp_path, backend="pi", roles={"model": "m"})) + odd = {"backend": "x", "base_url": "http://x", "model": "m", "api_key_env": "K", "max_output_tokens": "64k"} + ev.setup(context(ws, 1, dom, tmp_path, roles={"binding": odd})) # a limit Codex's arguments never read + with pytest.raises(ValueError, match="roles.binding"): # Pi's provider does: read as Pi reads it + ev.setup(context(ws, 1, dom, tmp_path, backend="pi", roles={"binding": odd})) with pytest.raises(Exception): ev.setup(context(ws, 1, str(tmp_path / "dom" / "missing.py") + ":ToyDomain", tmp_path)) with pytest.raises(ValueError, match="roles.model"): diff --git a/tests/methods/rrsi_adapter/test_rrsi_on_pi.py b/tests/methods/rrsi_adapter/test_rrsi_on_pi.py index 9d27d292..5fef3e7d 100644 --- a/tests/methods/rrsi_adapter/test_rrsi_on_pi.py +++ b/tests/methods/rrsi_adapter/test_rrsi_on_pi.py @@ -18,8 +18,11 @@ def roles_of(tmp_path, **more): return evolver._roles(ctx) -def test_a_role_on_pi_has_no_tools_a_digester_only_those_that_read_and_each_its_bound_model(pi_stand, tmp_path): # noqa: F811 +def test_a_role_on_pi_has_no_tools_a_digester_only_those_that_read_and_each_its_bound_model(pi_stand, tmp_path, # noqa: F811 + monkeypatch): pytest.importorskip("rrsi") + from hermit.agent.evolver.methods.rrsi_adapter import roles as R + monkeypatch.setattr(R.shutil, "which", lambda program: f"/usr/bin/{program}") # rg and fd installed roles = roles_of(tmp_path) assert roles.backend == "pi" assert roles.generate("look at this", system="You are the analyst.") == "the answer" @@ -37,6 +40,17 @@ def test_a_role_on_pi_has_no_tools_a_digester_only_those_that_read_and_each_its_ assert "--no-tools" not in digester["args"] and digester["cwd"] == str(roles.traces.resolve()) +@pytest.mark.parametrize("found, tools", [(lambda p: None, ["read", "ls"]), + (lambda p: f"/home/u/.cargo/bin/{p}", ["read", "ls"]), + (lambda p: f"/usr/bin/{p}" if p == "rg" else None, ["read", "grep", "ls"])]) +def test_a_digester_on_pi_gets_grep_and_find_only_where_they_can_run(monkeypatch, found, tools): + """Pi's grep and find run rg and fd, which a Pi offline cannot fetch; a sandbox shows the system's programs only.""" + pytest.importorskip("rrsi") + from hermit.agent.evolver.methods.rrsi_adapter import roles as R + monkeypatch.setattr(R.shutil, "which", found) + assert R.pi_digester_tools() == tools + + def test_the_roles_own_binding_is_their_provider_on_pi(pi_stand, tmp_path): # noqa: F811 pytest.importorskip("rrsi") from hermit.agent.model.backends import Binding, as_binding, registry diff --git a/tests/pi_stand.py b/tests/pi_stand.py index aabc6eb6..f43da16c 100644 --- a/tests/pi_stand.py +++ b/tests/pi_stand.py @@ -22,7 +22,8 @@ here = Path(__file__).resolve().parent home = Path(os.environ["PI_CODING_AGENT_DIR"]) seen = {{"args": sys.argv[1:], "cwd": os.getcwd(), "stdin": sys.stdin.read(), - "files": {{p.name: p.read_text() for p in sorted(home.glob("*.json")) if p.is_file()}}}} + "files": {{p.name: p.read_text() for p in sorted(home.glob("*.json")) if p.is_file()}}, + "keys": sorted(k for k in os.environ if k.endswith("_KEY"))}} with open(here / "seen.jsonl", "a") as f: f.write(json.dumps(seen) + "\\n") for name, text in json.loads((here / "edits.json").read_text()).items(): @@ -36,10 +37,14 @@ class Stand: def __init__(self, folder: Path): self.folder = folder - def play(self, stream: str = "resume", reply: str | None = None, edits: dict | None = None) -> None: - """The next calls replay `stream` (a file of tests/fixtures/pi), `reply` as the final answer, and make `edits`. - `resume` has no tool calls, `success` has three.""" - text = (STREAMS / f"{stream}.jsonl").read_text() + def play(self, stream: str = "resume", reply: str | None = None, edits: dict | None = None, cut: bool = False) -> None: + """The next calls replay `stream` (a file of tests/fixtures/pi), `reply` as the final answer, and make `edits`; + with `cut`, the last reply ends at its output limit. `resume` has no tool calls, `success` has three.""" + lines = (STREAMS / f"{stream}.jsonl").read_text().splitlines(keepends=True) + if cut: + last = max(i for i, line in enumerate(lines) if '"type":"message_end"' in line and '"assistant"' in line) + lines[last] = lines[last].replace('"stopReason":"stop"', '"stopReason":"length"') + text = "".join(lines) (self.folder / "stream.jsonl").write_text( text if reply is None else text.replace("the answer", json.dumps(reply)[1:-1])) (self.folder / "edits.json").write_text(json.dumps(edits or {})) @@ -66,8 +71,9 @@ def pi_stand(tmp_path, monkeypatch): return stand -def bound_params(**more) -> dict: - """A learner's params with its model bound for Pi (`fake/m-1`), as the Evolver's loader binds them.""" - backends = registry({"fake": {"base_url": "http://127.0.0.1:9/v1", "api_key_env": "FAKE_KEY", "apis": ["chat"], +def bound_params(key_env: str = "FAKE_KEY", **more) -> dict: + """A learner's params with its model bound for Pi (`fake/m-1`, its key in `key_env`), as the Evolver's loader + binds them.""" + backends = registry({"fake": {"base_url": "http://127.0.0.1:9/v1", "api_key_env": key_env, "apis": ["chat"], "prices": {"m-1": {"input": 1.0, "cached_input": 0.1, "output": 2.0}}}}) return {**bind_agent_params({"model": "fake/m-1", "backend": "pi"}, "pi", backends), "web_search": False, **more} From 45acd88ce5c3cabea41711f8374b704a25279bb2 Mon Sep 17 00:00:00 2001 From: Albert Zhao Date: Tue, 10 Nov 2026 14:51:51 -0500 Subject: [PATCH 06/13] Pi: a bash command the model gives no time limit stops after command_timeout_s Pi's bash tool has no default time limit, so one command that never ends (an RRSI proposer's `grep -r ... /` in a real run) held the learner's session until the Trainer's call timeout, an hour, and the step was lost. The Pi Base Agent now writes a small extension into the session's home (where Pi finds its own) that gives a bash call without a limit command_timeout_s (600 s; 0 for none); a limit the model gives is kept. The home's extensions folder is Hermit's alone. Co-Authored-By: Claude Opus 5.5 --- docs/methods/agent.md | 4 ++- hermit/agent/base/cli.py | 28 +++++++++++++++-- tests/core/test_pi_agent.py | 62 +++++++++++++++++++++++++++++++++++++ 3 files changed, 90 insertions(+), 4 deletions(-) diff --git a/docs/methods/agent.md b/docs/methods/agent.md index 342c3ea3..d12b61eb 100644 --- a/docs/methods/agent.md +++ b/docs/methods/agent.md @@ -25,7 +25,9 @@ files its acting agent can read. Pi's `grep` and `find` tools run `rg` and `fd`, digesters get them only where the machine has them. Pi caps one reply at 16384 tokens unless the backend says otherwise: a reply cut there comes back with `finish_reason: length`, or fails the session that needed it whole. Where a long answer is due (EvoSafe's whole files) and the model reasons at length, give the backend a larger -[`max_output_tokens`](../guides/model-backends.md). +[`max_output_tokens`](../guides/model-backends.md). Pi's `bash` has no time limit of its own: a command the model +gives none stops after 600 seconds (the Pi Base Agent's `command_timeout_s`; `0` for none), so one command that never +ends costs that much of a step, not the whole call. ## Requirements and setup diff --git a/hermit/agent/base/cli.py b/hermit/agent/base/cli.py index 880995c0..511d39f5 100644 --- a/hermit/agent/base/cli.py +++ b/hermit/agent/base/cli.py @@ -1337,13 +1337,24 @@ def _final_turn(objects: list[dict]) -> str: PI_PROVIDER = "hermit" # the models.json provider a bound model is given under PI_SETTINGS = {"cacheWarming": "off", # no provider requests besides the session's own "enableInstallTelemetry": False} +PI_COMMAND_TIMEOUT_S = 600 # a bash command's limit when the model gives none (command_timeout_s; Pi's own: none) +PI_COMMAND_LIMIT = """\ +// Hermit's: a bash command the model gave no time limit stops after {seconds} s (Pi's own default is none). +export default function (pi) {{ + pi.on("tool_call", async (event) => {{ + if (event.toolName === "bash" && !(event.input.timeout > 0)) event.input.timeout = {seconds}; + }}); +}} +""" class Pi(CliAgent): """Pi (`pi --mode json`). Its home is its agent directory (PI_CODING_AGENT_DIR) and its HOME, offline (no catalog, update or download requests); a bound model is the models.json provider `hermit`, its key read by Pi from the backend's variable; the call's tools are an MCP server whose tools the model is offered directly. Pi reports a - failed request in its stream and exits 0: whether the session failed is read from the stream (`outcome`).""" + failed request in its stream and exits 0: whether the session failed is read from the stream (`outcome`). Pi's + bash has no time limit of its own: a command the model gives none stops after `command_timeout_s` (600 s; 0 for + none).""" name = backend = program = "pi" label = "Pi" home_var, user_folder = "PI_CODING_AGENT_DIR", ".pi/agent" @@ -1372,8 +1383,8 @@ def user_home(cls) -> Path: def prepare_home(self, home, roles, tools_url, tools_name): """models.json (the bound model), mcp.json (the call's tools, offered directly rather than through Pi's code - mode) and settings.json. No host path is written in them: a sandbox translates only the command, the - environment and the prompt.""" + mode), settings.json and the extension that limits a command's time. No host path is written in them: a + sandbox translates only the command, the environment and the prompt.""" if roles: raise Unsupported("pi has no sub-agents: it takes no roles") s = self.settings @@ -1396,6 +1407,17 @@ def prepare_home(self, home, roles, tools_url, tools_name): for name, data in (("mcp.json", {"mcpServers": servers}), ("settings.json", PI_SETTINGS)): _clear(home / name) (home / name).write_text(json.dumps(data, indent=1)) + # Pi's bash runs a command until it ends unless the model gives it a limit (Claude Code's Bash stops one + # after 2 minutes): an extension where Pi finds its own gives the others command_timeout_s, so one command + # that never ends (a search of the whole disk) costs that, not the caller's whole limit. The folder is + # Hermit's alone: what a session left in it is not loaded again. + limit = float(s.get("command_timeout_s", PI_COMMAND_TIMEOUT_S) or 0) # 0 or None: no limit + folder = home / "extensions" + _clear(folder) # a directory or a link + folder.unlink(missing_ok=True) # a file + if limit > 0: + folder.mkdir() + (folder / "hermit-command-limit.js").write_text(PI_COMMAND_LIMIT.format(seconds=format(limit, "g"))) @classmethod def web_search_args(cls, enabled: bool) -> list[str]: diff --git a/tests/core/test_pi_agent.py b/tests/core/test_pi_agent.py index b31b96bc..7275eaa1 100644 --- a/tests/core/test_pi_agent.py +++ b/tests/core/test_pi_agent.py @@ -34,6 +34,7 @@ files = {{p.name: p.read_text() for p in sorted(home.glob("*.json*")) if p.is_file()}} names = ("PI_CODING_AGENT_DIR", "HOME", "PI_OFFLINE", "PI_TELEMETRY", "PI_CODING_AGENT_SESSION_DIR", "FAKE_KEY") seen = {{"args": sys.argv[1:], "env": {{k: os.environ.get(k) for k in names}}, "files": files, + "extensions": {{p.name: p.read_text() for p in sorted(home.glob("extensions/*")) if p.is_file()}}, "stdin": sys.stdin.read()}} with open(os.environ["FAKE_PI_SEEN"], "a") as f: f.write(json.dumps(seen) + "\\n") @@ -340,6 +341,29 @@ def test_pi_refuses_an_effort_it_does_not_take_and_keeps_no_session_when_told(fa assert "--no-session" in args and args[args.index("--thinking") + 1] == "max" +def test_a_command_the_model_gives_no_time_limit_gets_the_sessions_and_only_hermits_extension_is_in_the_home(fake): + """Pi's bash runs a command until it ends unless the model gives it a limit: Hermit's extension in the session's + home gives the others `command_timeout_s` (600 s unless set; 0 for none). The home's extensions folder is + Hermit's alone, so what a session left there is gone before the next one.""" + work, home = fake / "work", fake / "home" + work.mkdir() + (home / "extensions").mkdir(parents=True) + (home / "extensions" / "left.js").write_text("export default function () {}\n") + agent = make("pi", {**bound(), "web_search": False, "home": str(home)}) + agent.run("go", workspace=work) + agent.configured(command_timeout_s=30).run("go", workspace=work) + agent.configured(command_timeout_s=0).run("go", workspace=work) + default, thirty, none = [c["extensions"] for c in seen(fake)] + assert list(default) == ["hermit-command-limit.js"] + assert 'event.toolName === "bash" && !(event.input.timeout > 0)) event.input.timeout = 600;' in \ + default["hermit-command-limit.js"] + assert "event.input.timeout = 30;" in thirty["hermit-command-limit.js"] + assert none == {} and not (home / "extensions").exists() + (home / "extensions").write_text("a file, not a folder") + agent.run("go", workspace=work) + assert list(seen(fake)[-1]["extensions"]) == ["hermit-command-limit.js"] + + def test_a_model_through_pi_answers_each_request_with_a_session_that_only_replies(fake, monkeypatch): from hermit.agent.base.endpoint import cli_answer monkeypatch.setenv("FAKE_PI_STREAM", str(STREAMS / "resume.jsonl")) @@ -588,6 +612,44 @@ def script(body): assert result.extra["served"] and result.reply == "the answer" and asked == [offered] +@pytest.mark.integration +@pytest.mark.skipif(not shutil.which("pi"), reason="needs the pi CLI") +@pytest.mark.parametrize("isolation", ["none", "sandbox"]) +def test_with_the_pi_cli_a_command_without_a_limit_stops_at_the_sessions_and_one_with_a_limit_keeps_it( + tmp_path, monkeypatch, isolation): + """The installed Pi, bound to a scripted model that runs two commands: one with a limit of its own, which it keeps, + and one without, which Hermit's extension stops after `command_timeout_s`; the session goes on to its answer.""" + import time + from hermit.sandbox import Sandbox + if isolation == "sandbox" and not _bwrap_works(): + pytest.skip("needs a working bubblewrap") + + def script(body): + done = sum(1 for m in body.get("messages") or [] if m.get("role") == "tool") + plan = [("bash", {"command": "sleep 3; echo kept", "timeout": 30}), ("bash", {"command": "sleep 60; echo late"})] + return plan[done] if done < len(plan) else None + + server, url = serve_chat(script) + monkeypatch.setenv("MOCK_KEY", "sk-mock") + params = bind_agent_params({"model": "mock/m-1"}, "pi", + registry({"mock": {"base_url": url, "api_key_env": "MOCK_KEY", "apis": ["chat"]}})) + work = tmp_path / "work" + work.mkdir() + settings = {**params, "web_search": False, "home": str(tmp_path / "home"), "isolation": isolation, + "timeout_s": 300, "command_timeout_s": 2} + if isolation == "sandbox": + settings["sandbox"] = Sandbox(network="isolated", env_allow=[], writable=[work], role="agent", + record_dir=tmp_path / "records") + start = time.monotonic() + try: + result = make("pi", settings).run("Do the task.", workspace=work) + finally: + server.shutdown() + assert result.extra["served"] and result.reply == "the answer" and time.monotonic() - start < 45 + kept, stopped = [s for s in result.trajectory if s.kind == "command"] + assert "kept" in kept.output and "late" not in stopped.output and "timed out" in stopped.output.lower() + + @pytest.mark.integration @pytest.mark.skipif(not shutil.which("pi"), reason="needs the pi CLI") def test_with_the_pi_cli_a_requests_temperature_and_the_backends_extra_body_reach_the_model(tmp_path, monkeypatch): From 8b67768186712e151b1fa5db9d3d9531752039b3 Mon Sep 17 00:00:00 2001 From: Albert Zhao Date: Tue, 10 Nov 2026 15:59:42 -0500 Subject: [PATCH 07/13] Test mwm on Pi with a model port a non-root sandbox can forward CI runs the suite as a non-root user. The sandbox forwards a loopback model's port into the session's network namespace, where only root may listen below 1024, so the fake backend at 127.0.0.1:9 failed every mwm step there ("prepare_failed": the relay's bind was refused). The test now uses port 59999 and its assertion names the steps' summaries. Co-Authored-By: Claude Opus 5.5 --- tests/methods/mwm/test_mwm_on_pi.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/methods/mwm/test_mwm_on_pi.py b/tests/methods/mwm/test_mwm_on_pi.py index c275a938..11841b6f 100644 --- a/tests/methods/mwm/test_mwm_on_pi.py +++ b/tests/methods/mwm/test_mwm_on_pi.py @@ -9,7 +9,8 @@ from hermit.config import Config NEEDS_BWRAP = pytest.mark.skipif(not shutil.which("bwrap"), reason="needs bubblewrap") -BACKENDS = {"fake": {"base_url": "http://127.0.0.1:9/v1", "api_key_env": "FAKE_KEY", "apis": ["chat"], +# The sandbox forwards a loopback model's port into the session's network, where only root may listen below 1024 +BACKENDS = {"fake": {"base_url": "http://127.0.0.1:59999/v1", "api_key_env": "FAKE_KEY", "apis": ["chat"], "prices": {"m-1": {"input": 1.0, "cached_input": 0.1, "output": 2.0}}}} FAKE_MWM_PI = r'''#!/usr/bin/env python3 @@ -47,7 +48,8 @@ def test_the_mwm_learner_runs_on_pi_with_its_bound_model(tmp_path, monkeypatch): Trainer(Config.load(path), log=lambda *_: None).train() run = tmp_path / "runs" / "mwm-test" steps = [json.loads(line) for line in (run / "steps.jsonl").read_text().splitlines()] - assert [s["evolver"]["status"] for s in steps] == ["done", "done", "done"] + assert [s["evolver"]["status"] for s in steps] == ["done", "done", "done"], \ + [s["evolver"].get("summary") for s in steps] sessions = json.loads((run / "step_0001" / "output" / "sessions.json").read_text()) assert sessions[0]["status"] == "adopted" and sessions[0]["tool_calls"] == 3 and sessions[0]["turns"] == 4 assert (run / "step_0001" / "output" / "review_0001.pi.jsonl").is_file() From 911561156d9c12c06f745befd093ec42ec15ac21 Mon Sep 17 00:00:00 2001 From: Albert Zhao Date: Tue, 10 Nov 2026 16:27:39 -0500 Subject: [PATCH 08/13] Pi: a session's effort is what the model is sent; Pi's settings reach every session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes from the post-PR audit of 45acd88: - command_timeout_s could not be set from a run config: the acting agent, the agent Evolver (pi, Meta-Harness, ASPIRE, RRSI, AHE), mwm, EvoSafe and Harness² each passed a fixed list of Pi's settings. They now share PI_PARAMS. - A backend's extra_body.reasoning_effort replaced the session's or the request's effort, since Pi applies samplingParams last. xhigh and max were sent as high, since a bound model has no thinkingLevelMap. The session's effort now outranks extra_body's; xhigh and max are mapped to themselves on an OpenAI-compatible API and refused on the Messages API, where Pi gives them high's thinking budget. extra_body goes with chat-completions requests only. - On the Messages API, Pi reports a provider's status as "503 {...}": that is an outage too. A 4xx that no retry can help is `rejected` (the chat endpoint's 400), not a 502 the client retries. - Harness² on Pi refuses at setup a run with no model reference or an effort Pi cannot send: upstream would take each failed session for the starting harness. - tests: no sys.path insert in test_pi_agent. Co-Authored-By: Claude Opus 5.5 --- docs/guides/model-backends.md | 2 +- docs/methods/agent.md | 13 +- hermit/agent/acting/workspace.py | 5 +- hermit/agent/base/cli.py | 66 +++++++--- hermit/agent/evolver/agent.py | 4 +- .../evolver/methods/evosafe/cli_roles.py | 3 +- .../methods/harness2_upstream/channel.py | 3 +- .../methods/harness2_upstream/evolver.py | 9 ++ hermit/agent/evolver/methods/mwm/evolver.py | 3 +- hermit/agent/model/backends.py | 4 +- tests/core/test_pi_agent.py | 116 +++++++++++++++++- tests/methods/evosafe/test_evosafe_on_pi.py | 7 ++ tests/methods/harness2/test_harness2_on_pi.py | 18 ++- tests/methods/mwm/test_mwm_on_pi.py | 6 +- tests/pi_stand.py | 7 +- 15 files changed, 228 insertions(+), 38 deletions(-) diff --git a/docs/guides/model-backends.md b/docs/guides/model-backends.md index 1c84ff38..7f8c79d6 100644 --- a/docs/guides/model-backends.md +++ b/docs/guides/model-backends.md @@ -96,7 +96,7 @@ lab-sglang: # a new one, like the built-in sglang at | `messages_url` | the root the Anthropic Messages API is under, when it is not `base_url` without its `/v1` | | `litellm` | the litellm route prefix, for task agents that call through litellm (`fireworks_ai`, `hosted_vllm`) | | `prices` | per model id, `{input, cached_input, output}` in USD per million tokens; a model without one has an unknown cost (never zero) | -| `extra_body` | fields added to every chat request, such as `reasoning_effort`; Pi sends them as its model's `samplingParams` to an OpenAI-compatible API | +| `extra_body` | fields added to every chat request, such as `reasoning_effort`; Pi sends them as its model's `samplingParams` with each chat-completions request, under a session's own effort | | `context_window` | tokens; Codex is told it as `model_context_window`, Claude Code as `CLAUDE_CODE_MAX_CONTEXT_TOKENS`, Pi as `contextWindow` | | `max_output_tokens` | tokens one request may answer with; Pi is told it as `maxTokens`, and otherwise uses its default of 16384: a model that reasons long can be cut before it answers, and that session fails | | `developer_role` | `keep` (default), or `system`: a relay in front of the backend renames the `developer` role Codex uses, for an endpoint that refuses it (the built-in `fireworks` sets it, as the examples always did; Qwen3.6's chat template refuses a `system` message after the first, so a local server keeps the role) | diff --git a/docs/methods/agent.md b/docs/methods/agent.md index d12b61eb..afdf6f7d 100644 --- a/docs/methods/agent.md +++ b/docs/methods/agent.md @@ -18,16 +18,19 @@ On the single-file prompt-only template, the Codex learner is the [prompt-only]( | GEPA, SkillOpt, ACE, OPRO, ReHarness, Continual Harness | They call the run's model, so that model becomes Pi: each call is one session with no tools (the same as `llm: {cli: pi, model: /}`) | Pi signs in only through the model reference and has no web search. Where the backend speaks an OpenAI-compatible API -(chat completions or the Responses API), a request's `temperature` and `top_p`, and the backend's `extra_body`, reach -the model as Pi's `samplingParams`; on the Messages API Pi ignores them, so there a request that asks for a -`temperature` is refused unless `evolver.pi.unapplied` names it. Pi has no sub-agents: an adapter's sub-agents stay +(chat completions or the Responses API), a request's `temperature` and `top_p` reach the model as Pi's +`samplingParams`; on the Messages API Pi ignores them, so there a request that asks for a `temperature` is refused +unless `evolver.pi.unapplied` names it. The backend's `extra_body` goes with each chat-completions request. A session's +`effort` is what the model is sent, over an `extra_body.reasoning_effort`; on the Messages API Pi gives `xhigh` and `max` +the same thinking budget as `high`, so there they are refused. Pi has no sub-agents: an adapter's sub-agents stay files its acting agent can read. Pi's `grep` and `find` tools run `rg` and `fd`, which an offline Pi cannot fetch: RRSI's digesters get them only where the machine has them. Pi caps one reply at 16384 tokens unless the backend says otherwise: a reply cut there comes back with `finish_reason: length`, or fails the session that needed it whole. Where a long answer is due (EvoSafe's whole files) and the model reasons at length, give the backend a larger [`max_output_tokens`](../guides/model-backends.md). Pi's `bash` has no time limit of its own: a command the model -gives none stops after 600 seconds (the Pi Base Agent's `command_timeout_s`; `0` for none), so one command that never -ends costs that much of a step, not the whole call. +gives none stops after 600 seconds, so one command that never ends costs that much of a step, not the whole call. +`command_timeout_s` in `evolver.pi` (the learner's sessions) or `agent.pi` (the acting agent's) changes it; `0` turns it +off. ## Requirements and setup diff --git a/hermit/agent/acting/workspace.py b/hermit/agent/acting/workspace.py index 214b9bb6..40e10ce0 100644 --- a/hermit/agent/acting/workspace.py +++ b/hermit/agent/acting/workspace.py @@ -321,10 +321,11 @@ def _check(backend: str, params: dict) -> str: def base_agent(backend: str, params: dict) -> BaseAgent: """The Base Agent (Layer 2) these params describe: the CLI and how it is run, nothing of the task.""" + from hermit.agent.base.cli import PI_PARAMS settings = {k: params[k] for k in ("model", "binding", "login", "plan_dir", "plan_max_wait_s", "usage_credits", "effort", "isolation", "container", "codex_sandbox", "shell_env", - "project_doc_max_bytes", "args", "env", "price", "provider", - "image_input", "model_class", "config", "step_limit") + "project_doc_max_bytes", "args", "env", "price", *PI_PARAMS, + "model_class", "config", "step_limit") if k in params and (params[k] is not None or k == "plan_max_wait_s")} if params.get("claude_permission_mode"): settings["permission_mode"] = params["claude_permission_mode"] diff --git a/hermit/agent/base/cli.py b/hermit/agent/base/cli.py index 511d39f5..9ae8561b 100644 --- a/hermit/agent/base/cli.py +++ b/hermit/agent/base/cli.py @@ -70,9 +70,12 @@ `login: claude` may draw the account's usage credits; default: a session that did holds the next ones back) Pi only: provider (its models.json entry for a bound model, from the binding: Binding.pi_provider), image_input (true: the bound model takes images, such as a tool's result; default: text only, Pi's default for a - model it does not know), append_system_prompt, effort (its --thinking level), allowed_tools (Pi's own tools by name, - its --tools: read, grep, find, ls, bash, edit, write; the call's tools stay; empty: none of its own), persist_session - (false: --no-session), sampling (fields for the bound model's samplingParams: a chat request's temperature, top_p). Pi takes no roles, has no web search and runs under isolation none or sandbox. + model it does not know), append_system_prompt, effort (its --thinking level, sent as named and over the backend's + extra_body; a bound model on the Messages API takes up to high), allowed_tools (Pi's own tools by name, its --tools: + read, grep, find, ls, bash, edit, write; the call's tools stay; empty: none of its own), persist_session (false: + --no-session), sampling (fields for the bound model's samplingParams: a chat request's temperature, top_p), + command_timeout_s (a bash command's limit when the model gives none; default 600, 0: none). Pi takes no roles, has no + web search and runs under isolation none or sandbox. mini-swe-agent only: model_class, config, step_limit (MiniSweAgent; hermit.agent.base.mini_swe_agent). It takes no roles, no session and no login, has no web search and runs under isolation none or sandbox. OpenCode only: provider (its config's provider for the bound model, from the binding: Binding.opencode_provider; @@ -120,7 +123,7 @@ UNAVAILABLE = re.compile(r"unexpected status (?:429|5\d\d)|exceeded retry limit|stream disconnected|" r"error sending request|too many requests|service unavailable|bad gateway|overloaded|" r"model is at capacity|" - r"^(?:429|5\d\d): |" # Pi's report of a provider's status + r"^(?:429|5\d\d)(?:: | \{)|" # Pi's report of a provider's status (two forms) r"error response from daemon|cannot connect to the docker daemon|" + re.escape(container.MISSING), re.I | re.M) CODEX_HOME_SETTINGS = ["features.shell_snapshot = false", # a snapshot would bring back the whole environment @@ -1346,6 +1349,10 @@ def _final_turn(objects: list[dict]) -> str: }}); }} """ +PI_PARAMS = ("provider", "image_input", "command_timeout_s") # a Pi session's settings a method passes on +# Pi's report of a provider's status no retry can help ("400: {...}" from an OpenAI-compatible API, "400 {...}" from +# the Messages API): not a timeout, a conflict or a rate limit +PI_REJECTED = re.compile(r"^4(?!08|09|29)\d\d(?::| \{)") class Pi(CliAgent): @@ -1370,6 +1377,19 @@ def applied_fields(self) -> tuple[str, ...]: api = (self.settings.get("provider") or {}).get("api") return self.sampling if api in ("openai-completions", "openai-responses") else () + @classmethod + def effort_problem(cls, effort, provider: dict | None) -> str | None: + """Why a session could not send `effort` as given, or None: a level --thinking does not take (the CLI would + warn and go on at its default), or xhigh or max for a bound model on the Messages API, which Pi gives high's + thinking budget. On an OpenAI-compatible API both are sent as named (prepare_home maps them).""" + if not effort: + return None + if effort not in cls.efforts: + return f"Pi takes effort {', '.join(cls.efforts)}, not {effort!r}" + if effort in ("xhigh", "max") and (provider or {}).get("api") == "anthropic-messages": + return f"Pi gives a model on the Messages API high's thinking budget for effort {effort}: take high or lower" + return None + def home_env(self, home): """Every variable Pi reads goes here, so that it passes the sandbox's filter: its agent directory, its HOME (Pi reads ~/.agents/skills), offline, no telemetry; a session directory of the caller's emptied, which Pi @@ -1392,15 +1412,27 @@ def prepare_home(self, home, roles, tools_url, tools_name): (home / "models.json").unlink(missing_ok=True) if s.get("provider"): provider = json.loads(json.dumps(s["provider"])) - if s.get("effort") and s["effort"] != "off": # --thinking applies to a reasoning model only - for model in provider.get("models") or []: + effort = s.get("effort") + problem = self.effort_problem(effort, provider) + if problem: + raise Unsupported(problem) + for model in provider.get("models") or []: + if effort and effort != "off": # --thinking applies to a reasoning model only model["reasoning"] = True - if s.get("image_input"): # else Pi sends the model no image (a text-only model refuses them) - for model in provider.get("models") or []: + if effort in ("xhigh", "max") and provider.get("api") in ("openai-completions", "openai-responses"): + # sent as named: a model with no map of its own, Pi takes either for high + model["thinkingLevelMap"] = {**(model.get("thinkingLevelMap") or {}), effort: effort} + if s.get("image_input"): # else Pi sends the model no image (a text-only model refuses them) model["input"] = ["text", "image"] - if s.get("sampling"): # a request's own (cli_answer), over the backend's extra_body - for model in provider.get("models") or []: - model["samplingParams"] = {**(model.get("samplingParams") or {}), **s["sampling"]} + # A request's own sampling (cli_answer) over the backend's extra_body; the session's effort over the + # extra_body's, as a call's fields win on the direct client (Pi applies samplingParams last) + sampling = {**(model.get("samplingParams") or {}), **(s.get("sampling") or {})} + if effort: + sampling.pop("reasoning_effort", None) + if sampling: + model["samplingParams"] = sampling + else: + model.pop("samplingParams", None) (home / "models.json").write_text(json.dumps({"providers": {PI_PROVIDER: provider}}, indent=1)) # A tool call may take minutes (a Trainer tool runs rollouts): Codex's tool_timeout_sec, not Pi's 60 s servers = {tools_name: {"url": tools_url, "exposure": "direct", "timeout": 1800}} if tools_url else {} @@ -1462,13 +1494,17 @@ def errors(cls, event): def outcome(self, raw, stream, last_file): """Pi's JSON mode exits 0 however the session ended: one that did not settle, aborted, or whose last request failed, was aborted or was cut at the output limit (Pi's text mode exits 1 for each) has failed, and so has a - session that was to have no tools and ran one.""" + session that was to have no tools and ran one. A provider's outage or rate limit is `unavailable` (retried); + a status no retry can help (a bad request, a key the provider refused) is `rejected`.""" notes, done = self.notices(raw), self.served(raw) - cut = self._last_assistant(raw).get("stopReason") == "length" + last = self._last_assistant(raw) + cut = last.get("stopReason") == "length" if self.settings.get("text_only") and any(e.get("type") == "tool_execution_start" for e in _objects(raw)[0]): notes, done = "the session was to have no tools, and it ran one", False - return {"reply": self.last_message(stream, last_file), "served": done, - "unavailable": bool(UNAVAILABLE.search(notes)), "refused": False, "failed": not done or cut, + unavailable = bool(UNAVAILABLE.search(notes)) + rejected = not done and not unavailable and bool(PI_REJECTED.match(str(last.get("errorMessage") or ""))) + return {"reply": self.last_message(stream, last_file), "served": done, "unavailable": unavailable, + "refused": False, "rejected": rejected, "failed": not done or cut, "finish_reason": "length" if cut else ("stop" if done else None), "failure": (notes or ("the reply was cut at its output limit" if cut else "the session did not settle") )[-600:]} diff --git a/hermit/agent/evolver/agent.py b/hermit/agent/evolver/agent.py index 4ddf1033..3075b51e 100644 --- a/hermit/agent/evolver/agent.py +++ b/hermit/agent/evolver/agent.py @@ -122,12 +122,12 @@ def settings(self, ctx: Context, backend: str) -> dict: clock (the Trainer stops the call). The framework is on PYTHONPATH, but the evolver sandbox shows the hermit package only to an Evolver that asks for it (`sandbox_framework`); the environment's other packages it shows to every Evolver.""" + from hermit.agent.base.cli import PI_PARAMS params = ctx.params env = {**(params.get("env") or {}), "PYTHONPATH": str(Path(__file__).resolve().parents[3]) + os.pathsep + os.environ.get("PYTHONPATH", "")} return {**{k: params[k] for k in ("model", "binding", "login", "login_root", "plan_dir", "plan_max_wait_s", - "plan_rerun", "usage_credits", "args", "price", "effort", "provider", - "image_input") + "plan_rerun", "usage_credits", "args", "price", "effort", *PI_PARAMS) if params.get(k) is not None or (k == "plan_max_wait_s" and k in params)}, # None: no limit "web_search": params["web_search"], "env": env, "isolation": "sandbox" if ctx.sandbox is not None else "none", "sandbox": ctx.sandbox, diff --git a/hermit/agent/evolver/methods/evosafe/cli_roles.py b/hermit/agent/evolver/methods/evosafe/cli_roles.py index 251ad1a9..d7ebdd3d 100644 --- a/hermit/agent/evolver/methods/evosafe/cli_roles.py +++ b/hermit/agent/evolver/methods/evosafe/cli_roles.py @@ -8,13 +8,14 @@ import json import re +from hermit.agent.base.cli import PI_PARAMS from hermit.agent.base.interface import Limits, LoginFailed, make from .experience import role_tools # The Layer 1/2 settings a configuration may give the role CLI; the rest are set per call below. CLI_SETTINGS = ("model", "binding", "login", "login_root", "plan_dir", "plan_max_wait_s", "plan_rerun", "usage_credits", "effort", "codex_sandbox", "permission_mode", "shell_env", "project_doc_max_bytes", - "home_files", "args", "env", "env_drop", "price", "timeout_s", "bin", "provider", "image_input") + "home_files", "args", "env", "env_drop", "price", "timeout_s", "bin", *PI_PARAMS) CLI_PROPOSERS = ("codex", "claude", "pi") # Provider messages that mean the role request itself was refused (stop, never retried). diff --git a/hermit/agent/evolver/methods/harness2_upstream/channel.py b/hermit/agent/evolver/methods/harness2_upstream/channel.py index 896fcc68..fe252fa5 100644 --- a/hermit/agent/evolver/methods/harness2_upstream/channel.py +++ b/hermit/agent/evolver/methods/harness2_upstream/channel.py @@ -22,6 +22,7 @@ from harness2.core.proposer import SYSTEM_ARG_MAX, Proposer, _DROP_ENV, _parse_json +from hermit.agent.base.cli import PI_PARAMS from hermit.agent.base.interface import LoginFailed, make from hermit.agent.base.records import price_usage from hermit.agent.evolver.base import Usage @@ -156,7 +157,7 @@ def _pi_cli(self, cwd: Path, mission: str, system: str, wall: int) -> tuple[str, settings = {"web_search": False, "bin": self.params.get("claude_bin") or "pi", "stdin": True, "effort": self.spec.effort, # Claude Code's levels are Pi's too "model": self.params.get("model") or self.spec.model, "binding": self.params.get("binding"), - "provider": self.params.get("provider"), "image_input": self.params.get("image_input"), + **{k: self.params.get(k) for k in PI_PARAMS}, # the bound model, images, command limit "price": self.params.get("price"), "args": self.params.get("args"), "append_system_prompt": system or None, "persist_session": False, "home": Path(cwd) / ".pi-home", "home_files": [], "log": Path(cwd) / ".session.out", diff --git a/hermit/agent/evolver/methods/harness2_upstream/evolver.py b/hermit/agent/evolver/methods/harness2_upstream/evolver.py index a203d067..2df2b09f 100644 --- a/hermit/agent/evolver/methods/harness2_upstream/evolver.py +++ b/hermit/agent/evolver/methods/harness2_upstream/evolver.py @@ -107,6 +107,15 @@ def setup(self, ctx) -> None: if named: # every session would refuse it (the Base Agent), each stage fall back raise ValueError(f"login: claude is the subscription; evolver.params.env names what would pay instead: " f"{named}") + if ctx.params.get("proposer") is None and ctx.params.get("backend") == "pi": + # refused here, not by every session: upstream turns a session's error into the starting harness + from hermit.agent.base.cli import Pi + if not ctx.params.get("provider"): + raise ValueError("harness2_upstream on Pi takes its model from evolver.base: pi and evolver.model (a " + "/ reference)") + problem = Pi.effort_problem(str(ctx.params.get("effort") or "medium"), ctx.params["provider"]) + if problem: + raise ValueError(f"evolver.params.effort: {problem}") if ctx.params.get("library_from"): _markers(context, ctx.params.get("verdict_markers")) self._import_library(_path(ctx.params["library_from"], ctx.base), ctx.workspace, ctx.params, ctx.base, diff --git a/hermit/agent/evolver/methods/mwm/evolver.py b/hermit/agent/evolver/methods/mwm/evolver.py index 6b774c94..2dd6da26 100644 --- a/hermit/agent/evolver/methods/mwm/evolver.py +++ b/hermit/agent/evolver/methods/mwm/evolver.py @@ -240,11 +240,12 @@ def _settings(self, ctx: StepContext, home: Path, log: Path, box) -> dict: variable for its commands, a fresh home, the session's clock), inside the native mounts, told /w as its working directory, the channels' JSON entrance as MW_TOOLSRV (the venue's shell client). `login` and `effort` are the model's; a binding's Claude Code provider settings come in `env`, Pi's in `provider`.""" + from hermit.agent.base.cli import PI_PARAMS params = ctx.params if not isinstance(params.get("web_search"), bool): raise ValueError("evolver.params.web_search must be set, true or false") return {**{k: params[k] for k in ("model", "binding", "args", "login", "login_root", "effort", "price", - "provider", "image_input", + *PI_PARAMS, "plan_dir", "plan_max_wait_s", "plan_rerun", "usage_credits") if params.get(k) is not None or (k == "plan_max_wait_s" and k in params)}, # None: no limit "web_search": params["web_search"], "isolation": "sandbox", "sandbox": box, diff --git a/hermit/agent/model/backends.py b/hermit/agent/model/backends.py index 36f23e0e..25e76bd4 100644 --- a/hermit/agent/model/backends.py +++ b/hermit/agent/model/backends.py @@ -325,8 +325,8 @@ def pi_provider(self) -> dict: model["contextWindow"] = int(self.backend.context_window) if self.backend.max_output_tokens: # else Pi's 16384: a model that reasons long is cut before it answers model["maxTokens"] = int(self.backend.max_output_tokens) - if self.extra_body and api in ("chat", "responses"): # sent with every request; the Messages API ignores them - model["samplingParams"] = dict(self.extra_body) + if self.extra_body and api == "chat": # sent with every chat request, as the direct client sends them; the + model["samplingParams"] = dict(self.extra_body) # Responses and Messages APIs take other fields if self.price: p = self.price model["cost"] = {"input": p.get("input", 0), "output": p.get("output", 0), diff --git a/tests/core/test_pi_agent.py b/tests/core/test_pi_agent.py index 7275eaa1..6c490e6a 100644 --- a/tests/core/test_pi_agent.py +++ b/tests/core/test_pi_agent.py @@ -339,6 +339,91 @@ def test_pi_refuses_an_effort_it_does_not_take_and_keeps_no_session_when_told(fa agent.configured(persist_session=False, effort="max").run("go", workspace=work) args = seen(fake)[0]["args"] assert "--no-session" in args and args[args.index("--thinking") + 1] == "max" + own = make("pi", {"model": "its-own", "web_search": False, "home": str(fake / "own"), "home_files": []}) + with pytest.raises(Unsupported, match="Pi takes effort .*not 'bogus'"): # a model of Pi's own catalog + own.configured(effort="bogus").run("go", workspace=work) + + +def test_the_sessions_effort_is_sent_as_named_and_over_the_backends_extra_body(fake): + """A session's effort is the call's: a backend's extra_body.reasoning_effort, which Pi applies last (its + samplingParams), no longer replaces it. xhigh and max, which Pi sends as high for a model with no map of its own, + are mapped to themselves on an OpenAI-compatible API; on the Messages API, where Pi gives either high's thinking + budget, they are refused. extra_body goes with a chat request only, and stands where no effort is given.""" + work = fake / "work" + work.mkdir() + + def model_of(call): + return json.loads(call["files"]["models.json"])["providers"]["hermit"]["models"][0] + + chat = bound(extra_body={"reasoning_effort": "low", "top_k": 20}) + for effort in (None, "high", "xhigh", "max", "off"): + make("pi", {**chat, "web_search": False, "home": str(fake / "home"), + **({"effort": effort} if effort else {})}).run("go", workspace=work) + plain, high, xhigh, top, off = [model_of(c) for c in seen(fake)] + assert plain["samplingParams"] == {"reasoning_effort": "low", "top_k": 20} and "thinkingLevelMap" not in plain + assert high["samplingParams"] == off["samplingParams"] == {"top_k": 20} and "thinkingLevelMap" not in high + assert xhigh["thinkingLevelMap"] == {"xhigh": "xhigh"} and top["thinkingLevelMap"] == {"max": "max"} + responses = bound(apis=["responses"], extra_body={"reasoning_effort": "low"}) + make("pi", {**responses, "web_search": False, "home": str(fake / "home"), "effort": "max"}).run("go", workspace=work) + model = model_of(seen(fake)[-1]) + assert "samplingParams" not in model and model["thinkingLevelMap"] == {"max": "max"} + messages = make("pi", {**bound(apis=["messages"]), "web_search": False, "home": str(fake / "home")}) + for effort in ("xhigh", "max"): + with pytest.raises(Unsupported, match=f"Messages API high's thinking budget for effort {effort}"): + messages.configured(effort=effort).run("go", workspace=work) + messages.configured(effort="high").run("go", workspace=work) + assert "thinkingLevelMap" not in model_of(seen(fake)[-1]) + + +@pytest.mark.parametrize("error, unavailable, rejected", [ + ('503: {"message":"busy"}', True, False), ('503 {"error":{"message":"busy"}}', True, False), + ('429 {"error":{"message":"slow down"}}', True, False), ('400: {"message":"no such field"}', False, True), + ('401 {"error":{"message":"bad key"}}', False, True), ('408: {"message":"too slow"}', False, False)], + ids=["outage", "outage, Messages API", "rate limit, Messages API", "bad request", "bad key, Messages API", + "request timeout"]) +def test_a_failed_requests_status_says_whether_a_retry_can_help(fake, monkeypatch, error, unavailable, rejected): + """Pi reports a provider's status as `503: {...}` from an OpenAI-compatible API and as `503 {...}` from the + Messages API. An outage or a rate limit is `unavailable` (retried; the chat endpoint's 503); a status no retry can + help is `rejected` (the chat endpoint's 400, which a client does not retry); a timeout or a conflict is neither.""" + from hermit.agent.base.endpoint import _no_reply + recorded = '503: {"message":"mock: service unavailable"}' + stream = (STREAMS / "failure.jsonl").read_text().replace(json.dumps(recorded)[1:-1], json.dumps(error)[1:-1]) + assert error in "".join(json.loads(line)["message"].get("errorMessage") or "" for line in stream.splitlines() + if isinstance(json.loads(line).get("message"), dict)) + (fake / "status.jsonl").write_text(stream) + monkeypatch.setenv("FAKE_PI_STREAM", str(fake / "status.jsonl")) + work = fake / "work" + work.mkdir() + agent = make("pi", {**bound(), "web_search": False, "home": str(fake / "home")}) + result = agent.run("go", workspace=work) + assert result.extra["failed"] and (result.extra["unavailable"], result.extra["rejected"]) == (unavailable, rejected) + assert _no_reply(agent, result)[0] == (503 if unavailable else 400 if rejected else 502) + + +def test_command_timeout_s_from_the_config_reaches_the_acting_agents_and_the_learners_sessions(fake): + """`agent.pi` and `evolver.pi` give Pi's settings (PI_PARAMS) to the acting agent's and the learner's sessions: + with command_timeout_s 0, neither session's home has Hermit's extension.""" + from types import SimpleNamespace as NS + from hermit.agent.acting.workspace import base_agent + from hermit.agent.evolver.loader import find, instantiate + from hermit.config import layered + data = {"agent": {"base": "pi", "model": "fake/m-1", "pi": {"command_timeout_s": 0}}, + "evolver": {"name": "pi", "base": "pi", "model": "fake/m-1", "pi": {"command_timeout_s": 0}}, "llm": None} + layered(data) + work = fake / "work" + work.mkdir() + acting = base_agent("pi", {**data["agent"]["params"], **bound(), "web_search": False}) + assert acting.settings["command_timeout_s"] == 0 + acting.configured(home=str(fake / "acting")).run("go", workspace=work) + evolver, params = instantiate(find("pi", ROOT), data["evolver"]["params"], default_model="fake/m-1", + backends=registry({"fake": {"base_url": "http://127.0.0.1:9/v1", + "api_key_env": "FAKE_KEY", "apis": ["chat"]}})) + ws = NS(state=fake / "state" / "now", output=fake / "out") + ws.output.mkdir() + settings = evolver.settings(NS(params=params, sandbox=None, workspace=ws, cancel=None), "pi") + assert settings["command_timeout_s"] == 0 + make("pi", settings).run("go", workspace=work) + assert [call["extensions"] for call in seen(fake)] == [{}, {}] def test_a_command_the_model_gives_no_time_limit_gets_the_sessions_and_only_hermits_extension_is_in_the_home(fake): @@ -469,8 +554,6 @@ def test_a_custom_evolver_takes_evolver_base_pi_as_its_cli_unless_its_manifest_s """A launcher of the agent Evolver (docs/framework/custom-evolver.md) names no backend in its manifest: Pi is its CLI, as before. One whose manifest says `needs: [llm]` calls the run's model, which becomes Pi; a relative name is found beside the config.""" - import sys - sys.path.insert(0, str(ROOT / "tests")) from toy_task import make_task from hermit.config import Config monkeypatch.setenv("FAKE_KEY", "sk-fake") @@ -672,3 +755,32 @@ def script(body): server.shutdown() [sent] = bodies assert status == 200 and sent["temperature"] == 0.3 and sent["reasoning_effort"] == "low" and not sent.get("tools") + + +@pytest.mark.integration +@pytest.mark.skipif(not shutil.which("pi"), reason="needs the pi CLI") +@pytest.mark.parametrize("asked, effort, sent", [("high", None, "high"), (None, "max", "max"), (None, "xhigh", "xhigh"), + (None, None, "low")], + ids=["the request's", "max", "xhigh", "the backend's"]) +def test_with_the_pi_cli_the_model_is_sent_the_calls_effort_over_the_backends(tmp_path, monkeypatch, asked, effort, + sent): + """The installed Pi behind the chat endpoint, its backend's extra_body asking for low: the request's or the + session's effort is what the model is sent, xhigh and max as named; with neither, the backend's.""" + from hermit.agent.base.endpoint import cli_answer + bodies = [] + + def script(body): + bodies.append(body) + + server, url = serve_chat(script) + monkeypatch.setenv("MOCK_KEY", "sk-mock") + params = bind_agent_params({"model": "mock/m-1"}, "pi", registry({"mock": { + "base_url": url, "api_key_env": "MOCK_KEY", "apis": ["chat"], "extra_body": {"reasoning_effort": "low"}}})) + agent = make("pi", {**params, "web_search": False, "home": str(tmp_path / "home"), "timeout_s": 300, + **({"effort": effort} if effort else {})}) + try: + status, _, _ = cli_answer(agent, {"messages": [{"role": "user", "content": "hi"}], + **({"reasoning_effort": asked} if asked else {})}) + finally: + server.shutdown() + assert status == 200 and [b.get("reasoning_effort") for b in bodies] == [sent] diff --git a/tests/methods/evosafe/test_evosafe_on_pi.py b/tests/methods/evosafe/test_evosafe_on_pi.py index 52971564..2c868dcf 100644 --- a/tests/methods/evosafe/test_evosafe_on_pi.py +++ b/tests/methods/evosafe/test_evosafe_on_pi.py @@ -31,6 +31,13 @@ def test_a_role_on_pi_has_none_of_its_own_tools_and_answers_the_schema(pi_stand, assert call["args"][:6] == ["--mode", "json", "--provider", "hermit", "--model", "m-1"] assert call["args"][call["args"].index("--append-system-prompt") + 1] == "Be exact." assert "the evidence" in call["stdin"] and "satisfies this JSON schema" in call["stdin"] + assert call["extensions"] == ["hermit-command-limit.js"] + zero = tmp_path / "zero" + zero.mkdir() + ctx = ctx_of(zero) + ctx.params["command_timeout_s"] = 0 # evolver.pi's, passed on (PI_PARAMS) + pi_agent.call_role(ctx, messages, schema, "trial-001-criticizer") + assert pi_stand.seen()[0]["extensions"] == [] def test_a_reply_that_is_no_answer_fails_the_role(pi_stand, tmp_path): # noqa: F811 diff --git a/tests/methods/harness2/test_harness2_on_pi.py b/tests/methods/harness2/test_harness2_on_pi.py index c2bb6874..7b87b1bb 100644 --- a/tests/methods/harness2/test_harness2_on_pi.py +++ b/tests/methods/harness2/test_harness2_on_pi.py @@ -1,5 +1,7 @@ """Harness²'s editors on Pi (`evolver.base: pi`), against the stand-in `pi` (tests/pi_stand.py), and a Pi acting agent's trajectory in upstream's grammar.""" +import json + import pytest from pi_stand import STREAMS, bound_params, pi_stand # noqa: F401 (pi_stand: the fixture) @@ -24,6 +26,11 @@ def test_harness2s_session_on_pi_takes_its_bound_model_and_keeps_its_usage(pi_st assert call["args"][:6] == ["--mode", "json", "--provider", "hermit", "--model", "m-1"] assert call["args"][call["args"].index("--append-system-prompt") + 1] == "be brief" assert call["args"][call["args"].index("--thinking") + 1] == "max" # Claude Code's levels are Pi's too + model = json.loads(call["files"]["models.json"])["providers"]["hermit"]["models"][0] + assert model["thinkingLevelMap"] == {"max": "max"} # sent as max, not Pi's high + assert call["extensions"] == ["hermit-command-limit.js"] + proposer(command_timeout_s=0)._claude_cli(cwd, "the mission", "", wall=60) # evolver.pi's, passed on + assert pi_stand.seen()[0]["extensions"] == [] def test_a_pi_session_that_failed_is_no_reply(pi_stand, tmp_path): # noqa: F811 @@ -61,7 +68,16 @@ def test_harness2_runs_its_editors_on_pi_and_pins_pis_binary(pi_stand, tmp_path) pytest.importorskip("harness2") from types import SimpleNamespace as NS from hermit.agent.evolver.methods.harness2_upstream.evolver import Harness2UpstreamEvolver - Harness2UpstreamEvolver().setup(NS(params={"backend": "pi"})) + Harness2UpstreamEvolver().setup(NS(params=bound_params())) + # refused at setup, not by each session: upstream would take a failed session for the starting harness + with pytest.raises(ValueError, match="takes its model from evolver.base: pi and evolver.model"): + Harness2UpstreamEvolver().setup(NS(params={"backend": "pi"})) + with pytest.raises(ValueError, match="Pi takes effort .*not 'huge'"): + Harness2UpstreamEvolver().setup(NS(params={**bound_params(), "effort": "huge"})) + messages = {**bound_params(), "effort": "max"} + messages["provider"] = {**messages["provider"], "api": "anthropic-messages"} + with pytest.raises(ValueError, match="Messages API high's thinking budget for effort max"): + Harness2UpstreamEvolver().setup(NS(params=messages)) with pytest.raises(ValueError, match="not the sign-in of backend pi"): Harness2UpstreamEvolver().setup(NS(params={"backend": "pi", "login": "claude", "model": "m"})) ws = NS(state=tmp_path / "state") diff --git a/tests/methods/mwm/test_mwm_on_pi.py b/tests/methods/mwm/test_mwm_on_pi.py index 11841b6f..fd4036e5 100644 --- a/tests/methods/mwm/test_mwm_on_pi.py +++ b/tests/methods/mwm/test_mwm_on_pi.py @@ -23,7 +23,8 @@ Path("memory", f"note{n}.md").write_text( f"last_confirmed_t: {n}\nscope: always\nderived_from: none (reasoning only)\nbrief: note {n}\n\nA fact.\n") Path("meta", "pi.json").write_text(json.dumps({"args": sys.argv[1:-1], "cwd": os.getcwd(), - "models": (home / "models.json").read_text()})) + "models": (home / "models.json").read_text(), + "extensions": sorted(p.name for p in home.glob("extensions/*"))})) sys.stdout.write(Path(__file__).with_name("stream.jsonl").read_text()) ''' @@ -38,7 +39,7 @@ def test_the_mwm_learner_runs_on_pi_with_its_bound_model(tmp_path, monkeypatch): monkeypatch.setenv("FAKE_KEY", "sk-fake") path = M.make(tmp_path, monkeypatch) data = yaml.safe_load(path.read_text()) - data["evolver"].update(base="pi", model="fake/m-1") + data["evolver"].update(base="pi", model="fake/m-1", pi={"command_timeout_s": 0}) data["backends"] = BACKENDS path.write_text(yaml.safe_dump(data)) fake = tmp_path / "fakebin" / "pi" @@ -56,3 +57,4 @@ def test_the_mwm_learner_runs_on_pi_with_its_bound_model(tmp_path, monkeypatch): saw = json.loads((run / "checkout" / "meta" / "pi.json").read_text()) assert saw["cwd"] == "/w" and saw["args"][:6] == ["--mode", "json", "--provider", "hermit", "--model", "m-1"] assert json.loads(saw["models"])["providers"]["hermit"]["apiKey"] == "$FAKE_KEY" + assert saw["extensions"] == [] # evolver.pi's command_timeout_s 0, passed on diff --git a/tests/pi_stand.py b/tests/pi_stand.py index f43da16c..e7da4c53 100644 --- a/tests/pi_stand.py +++ b/tests/pi_stand.py @@ -15,15 +15,16 @@ STREAMS = ROOT / "tests" / "fixtures" / "pi" SCRIPT = f'''#!{sys.executable} -"""A stand-in for `pi --mode json ...`: records its arguments, working directory, home files and stdin, makes the -edits in edits.json (relative to its working directory), then prints stream.jsonl.""" +"""A stand-in for `pi --mode json ...`: records its arguments, working directory, home files, extensions, the keys it +was given and stdin, makes the edits in edits.json (relative to its working directory), then prints stream.jsonl.""" import json, os, sys from pathlib import Path here = Path(__file__).resolve().parent home = Path(os.environ["PI_CODING_AGENT_DIR"]) seen = {{"args": sys.argv[1:], "cwd": os.getcwd(), "stdin": sys.stdin.read(), "files": {{p.name: p.read_text() for p in sorted(home.glob("*.json")) if p.is_file()}}, - "keys": sorted(k for k in os.environ if k.endswith("_KEY"))}} + "keys": sorted(k for k in os.environ if k.endswith("_KEY")), + "extensions": sorted(p.name for p in home.glob("extensions/*"))}} with open(here / "seen.jsonl", "a") as f: f.write(json.dumps(seen) + "\\n") for name, text in json.loads((here / "edits.json").read_text()).items(): From 9b8131b9eb4eed836e660c3931f41f0d72554f57 Mon Sep 17 00:00:00 2001 From: Albert Zhao Date: Tue, 10 Nov 2026 16:47:18 -0500 Subject: [PATCH 09/13] Test that a Responses API backend's extra_body stays out of Pi's samplingParams The test gave extra_body only a reasoning_effort, which a session's effort removes anyway, so sending extra_body on the Responses API went unnoticed (a mutation guard said so). It now holds a field of its own too. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_pi_agent.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/core/test_pi_agent.py b/tests/core/test_pi_agent.py index 6c490e6a..d96e393a 100644 --- a/tests/core/test_pi_agent.py +++ b/tests/core/test_pi_agent.py @@ -363,7 +363,7 @@ def model_of(call): assert plain["samplingParams"] == {"reasoning_effort": "low", "top_k": 20} and "thinkingLevelMap" not in plain assert high["samplingParams"] == off["samplingParams"] == {"top_k": 20} and "thinkingLevelMap" not in high assert xhigh["thinkingLevelMap"] == {"xhigh": "xhigh"} and top["thinkingLevelMap"] == {"max": "max"} - responses = bound(apis=["responses"], extra_body={"reasoning_effort": "low"}) + responses = bound(apis=["responses"], extra_body={"reasoning_effort": "low", "top_k": 20}) make("pi", {**responses, "web_search": False, "home": str(fake / "home"), "effort": "max"}).run("go", workspace=work) model = model_of(seen(fake)[-1]) assert "samplingParams" not in model and model["thinkingLevelMap"] == {"max": "max"} From 25833aa0c52ef405e8ec2c7d1bd251bb15b92ed5 Mon Sep 17 00:00:00 2001 From: Albert Zhao Date: Tue, 10 Nov 2026 18:56:59 -0500 Subject: [PATCH 10/13] Pi: the last request's status decides an outage, in each of Pi's error forms Fixes from the post-PR audit of ac43960. Pi reports a provider's status in more forms than the two the outage pattern knew: "503 status code (no body)", a proxy's "503 ...", the Responses API's " API error (503): ...", and no status at all for a dropped connection, which Pi retries itself and then gives up. Such an outage was a failure, not one to retry (RRSI's proposer counted it toward max_failures). The Pi Base Agent now reads the status of the last request's error: 429 or 5xx is unavailable; a 4xx no retry can help is rejected, also on the Responses API; with no status, an error Pi gave up retrying is unavailable. A 400 after retried 503s is rejected, not an outage. Also a test for a request's sampling on the Responses API. Co-Authored-By: Claude Opus 5.5 --- hermit/agent/base/cli.py | 17 +++++++++++------ tests/core/test_pi_agent.py | 29 ++++++++++++++++++++--------- 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/hermit/agent/base/cli.py b/hermit/agent/base/cli.py index 9ae8561b..098452fa 100644 --- a/hermit/agent/base/cli.py +++ b/hermit/agent/base/cli.py @@ -123,7 +123,6 @@ UNAVAILABLE = re.compile(r"unexpected status (?:429|5\d\d)|exceeded retry limit|stream disconnected|" r"error sending request|too many requests|service unavailable|bad gateway|overloaded|" r"model is at capacity|" - r"^(?:429|5\d\d)(?:: | \{)|" # Pi's report of a provider's status (two forms) r"error response from daemon|cannot connect to the docker daemon|" + re.escape(container.MISSING), re.I | re.M) CODEX_HOME_SETTINGS = ["features.shell_snapshot = false", # a snapshot would bring back the whole environment @@ -1350,9 +1349,9 @@ def _final_turn(objects: list[dict]) -> str: }} """ PI_PARAMS = ("provider", "image_input", "command_timeout_s") # a Pi session's settings a method passes on -# Pi's report of a provider's status no retry can help ("400: {...}" from an OpenAI-compatible API, "400 {...}" from -# the Messages API): not a timeout, a conflict or a rate limit -PI_REJECTED = re.compile(r"^4(?!08|09|29)\d\d(?::| \{)") +# The provider's status in Pi's report of a failed request: "503: {...}" or "503 status code (no body)" from chat +# completions, "503 {...}" from the Messages API, " API error (503): ..." from the Responses API +PI_STATUS = re.compile(r"^(\d{3})\b|API error \((\d{3})\)") class Pi(CliAgent): @@ -1501,8 +1500,14 @@ def outcome(self, raw, stream, last_file): cut = last.get("stopReason") == "length" if self.settings.get("text_only") and any(e.get("type") == "tool_execution_start" for e in _objects(raw)[0]): notes, done = "the session was to have no tools, and it ran one", False - unavailable = bool(UNAVAILABLE.search(notes)) - rejected = not done and not unavailable and bool(PI_REJECTED.match(str(last.get("errorMessage") or ""))) + found = PI_STATUS.search(str(last.get("errorMessage") or "")) + code = int(found.group(1) or found.group(2)) if found else None # the last request's: it decides + if code is not None: + unavailable = code == 429 or code >= 500 + else: # no status (a dropped connection): Pi retries what it takes to pass, and says when it gave up + unavailable = any(e.get("type") == "auto_retry_end" and not e.get("success") for e in _objects(raw)[0]) \ + or bool(UNAVAILABLE.search(notes)) + rejected = not done and code is not None and 400 <= code < 500 and code not in (408, 409, 429) return {"reply": self.last_message(stream, last_file), "served": done, "unavailable": unavailable, "refused": False, "rejected": rejected, "failed": not done or cut, "finish_reason": "length" if cut else ("stop" if done else None), diff --git a/tests/core/test_pi_agent.py b/tests/core/test_pi_agent.py index d96e393a..098e34f6 100644 --- a/tests/core/test_pi_agent.py +++ b/tests/core/test_pi_agent.py @@ -376,15 +376,23 @@ def model_of(call): @pytest.mark.parametrize("error, unavailable, rejected", [ - ('503: {"message":"busy"}', True, False), ('503 {"error":{"message":"busy"}}', True, False), - ('429 {"error":{"message":"slow down"}}', True, False), ('400: {"message":"no such field"}', False, True), - ('401 {"error":{"message":"bad key"}}', False, True), ('408: {"message":"too slow"}', False, False)], - ids=["outage", "outage, Messages API", "rate limit, Messages API", "bad request", "bad key, Messages API", - "request timeout"]) + ('503: {"message":"busy"}', True, False), ("503 status code (no body)", True, False), + ("503 Service Unavailable", True, False), + ('503 {"error":{"message":"busy"}}', True, False), + ('hermit API error (503): {"error":{"message":"busy"}}', True, False), + ('429 {"error":{"message":"slow down"}}', True, False), ("Connection error.", True, False), + ('400: {"message":"no such field"}', False, True), ('401 {"error":{"message":"bad key"}}', False, True), + ('hermit API error (404): {"error":{"message":"no such model"}}', False, True), + ('408: {"message":"too slow"}', False, False)], + ids=["outage", "outage, no body", "outage, a proxy's page", "outage, Messages API", "outage, Responses API", + "rate limit, Messages API", "no connection, retries given up", "bad request", "bad key, Messages API", + "no such model, Responses API", "request timeout"]) def test_a_failed_requests_status_says_whether_a_retry_can_help(fake, monkeypatch, error, unavailable, rejected): - """Pi reports a provider's status as `503: {...}` from an OpenAI-compatible API and as `503 {...}` from the - Messages API. An outage or a rate limit is `unavailable` (retried; the chat endpoint's 503); a status no retry can - help is `rejected` (the chat endpoint's 400, which a client does not retry); a timeout or a conflict is neither.""" + """Pi reports a provider's status in its own forms (those Pi 1.5.0 printed): `503: {...}` or `503 status code (no + body)` from chat completions, `503 {...}` from the Messages API, ` API error (503): ...` from the + Responses API. An outage or a rate limit is `unavailable` (retried; the chat endpoint's 503), and so is an error + with no status that Pi retried until it gave up (a dropped connection); a status no retry can help is `rejected` + (the chat endpoint's 400, which a client does not retry); a timeout or a conflict is neither.""" from hermit.agent.base.endpoint import _no_reply recorded = '503: {"message":"mock: service unavailable"}' stream = (STREAMS / "failure.jsonl").read_text().replace(json.dumps(recorded)[1:-1], json.dumps(error)[1:-1]) @@ -502,8 +510,11 @@ def test_a_requests_sampling_fields_reach_pis_model_where_its_api_takes_them(fak [model] = json.loads(seen(fake)[0]["files"]["models.json"])["providers"]["hermit"]["models"] assert status == 200 and "unapplied" not in json.loads(body) assert model["samplingParams"] == {"seed": 1, "temperature": 0.3, "top_p": 0.9} + status, body, _ = cli_answer(make("pi", {**bound(apis=["responses"]), "web_search": False}), request) + [model] = json.loads(seen(fake)[1]["files"]["models.json"])["providers"]["hermit"]["models"] + assert status == 200 and model["samplingParams"] == {"temperature": 0.3, "top_p": 0.9} status, body, _ = cli_answer(make("pi", {**bound(apis=["messages"]), "web_search": False}), request) - assert status == 400 and "temperature" in json.loads(body)["error"]["message"] and len(seen(fake)) == 1 + assert status == 400 and "temperature" in json.loads(body)["error"]["message"] and len(seen(fake)) == 2 @pytest.mark.parametrize("spec, match", [({}, "needs a / reference"), From e5490a4b951521b1c5faa9964e81f543632b713a Mon Sep 17 00:00:00 2001 From: Albert Zhao Date: Tue, 10 Nov 2026 19:54:46 -0500 Subject: [PATCH 11/13] Pi: an answer the provider declined is a refusal; the error tests replay what Pi sends From the post-PR audit of 25833aa (round 4): - A request whose answer the provider declined is `rejected` and `model_refusal`, as on Claude Code, and never `unavailable`: Pi's `rawStopReason` "refusal" or "sensitive" (Messages API), "content_filter" (chat completions) or "incomplete.content_filter" (Responses API). Such a request was answered and has no status; its words are the provider's. EvoSafe reads it as its safety refusal and does not try the role again. - An error with no status is `unavailable` only when Pi gave up its own retries (`auto_retry_end`, `success: false`); the shared UNAVAILABLE wording no longer decides. - The status tests replay the streams Pi 1.5.0 sends: a 4xx once with no retry event; a 429, a 5xx and a lost connection retried three times; outages that ended in a bad request, where the last request's status decides. New cases: 500, 529, 409, and 503, 503, then 400. - An integration test runs the installed Pi against a scripted model: 503, 503, then 400; a 409; a content filter. Co-Authored-By: Claude Opus 5.5 --- docs/methods/evosafe.md | 5 +- hermit/agent/base/cli.py | 20 ++- tests/core/test_pi_agent.py | 184 ++++++++++++++++---- tests/methods/evosafe/test_evosafe_on_pi.py | 14 ++ tests/pi_stand.py | 14 +- 5 files changed, 191 insertions(+), 46 deletions(-) diff --git a/docs/methods/evosafe.md b/docs/methods/evosafe.md index c394bf19..e7b5c49c 100644 --- a/docs/methods/evosafe.md +++ b/docs/methods/evosafe.md @@ -57,8 +57,9 @@ The Evolver keeps Designer/Criticizer/Analyzer orchestration and all selection g `make("claude" | "codex" | "pi", settings).run(...)` with read-only TRAIN archive tools and a fresh session. Base Agents own process cleanup, cancellation, timeouts, configuration, login-plan scheduling and usage. The role's JSON schema is given to Codex as `--output-schema` and to Claude and Pi in the prompt, all through the Base Agent's existing settings, -and the reply is validated against it in Layer 3; a refusal is read from the reply and the trajectory's error -steps. The normalized trajectory of each role is archived. Claude's built-in tools are disabled (`--tools ""`), and +and the reply is validated against it in Layer 3; a refusal is read from the Base Agent's own `model_refusal` (Claude +Code's and Pi's), else from the reply and the trajectory's error steps, and is never retried. The normalized +trajectory of each role is archived. Claude's built-in tools are disabled (`--tools ""`), and so are Pi's (`--no-builtin-tools`); Codex has web search disabled, a read-only sandbox by default, an ephemeral session, and instructions to use only the supplied TRAIN readers. Codex's read-only mode does not hide files; use the shared isolation settings for a filesystem boundary. `evolver.base`, `evolver.model` and `evolver.claude`/`evolver.codex`/`evolver.pi` are the preferred configuration. Legacy diff --git a/hermit/agent/base/cli.py b/hermit/agent/base/cli.py index 098452fa..4e2a1c27 100644 --- a/hermit/agent/base/cli.py +++ b/hermit/agent/base/cli.py @@ -1352,6 +1352,9 @@ def _final_turn(objects: list[dict]) -> str: # The provider's status in Pi's report of a failed request: "503: {...}" or "503 status code (no body)" from chat # completions, "503 {...}" from the Messages API, " API error (503): ..." from the Responses API PI_STATUS = re.compile(r"^(\d{3})\b|API error \((\d{3})\)") +# A provider's stop reason for an answer it declined, as Pi keeps it (rawStopReason): "refusal" or "sensitive" from the +# Messages API, "content_filter" from chat completions, "incomplete.content_filter" from the Responses API +PI_REFUSALS = ("refusal", "content_filter", "sensitive") class Pi(CliAgent): @@ -1494,22 +1497,25 @@ def outcome(self, raw, stream, last_file): """Pi's JSON mode exits 0 however the session ended: one that did not settle, aborted, or whose last request failed, was aborted or was cut at the output limit (Pi's text mode exits 1 for each) has failed, and so has a session that was to have no tools and ran one. A provider's outage or rate limit is `unavailable` (retried); - a status no retry can help (a bad request, a key the provider refused) is `rejected`.""" + a status no retry can help (a bad request, a key the provider refused) is `rejected`, and so is an answer the + model declined (a refusal, a content filter), which is also `model_refusal`, as on Claude Code.""" notes, done = self.notices(raw), self.served(raw) last = self._last_assistant(raw) cut = last.get("stopReason") == "length" if self.settings.get("text_only") and any(e.get("type") == "tool_execution_start" for e in _objects(raw)[0]): notes, done = "the session was to have no tools, and it ran one", False - found = PI_STATUS.search(str(last.get("errorMessage") or "")) + # the model declined: no retry helps, and the request, answered, has no status (its words are the provider's) + refusal = not done and str(last.get("rawStopReason") or "").split(".")[-1] in PI_REFUSALS + found = None if refusal else PI_STATUS.search(str(last.get("errorMessage") or "")) code = int(found.group(1) or found.group(2)) if found else None # the last request's: it decides if code is not None: unavailable = code == 429 or code >= 500 - else: # no status (a dropped connection): Pi retries what it takes to pass, and says when it gave up - unavailable = any(e.get("type") == "auto_retry_end" and not e.get("success") for e in _objects(raw)[0]) \ - or bool(UNAVAILABLE.search(notes)) - rejected = not done and code is not None and 400 <= code < 500 and code not in (408, 409, 429) + else: # no status: a refusal, or a dropped connection, which Pi retries until it passes or it gives up + unavailable = not refusal and any(e.get("type") == "auto_retry_end" and not e.get("success") + for e in _objects(raw)[0]) + rejected = not done and (refusal or code is not None and 400 <= code < 500 and code not in (408, 409, 429)) return {"reply": self.last_message(stream, last_file), "served": done, "unavailable": unavailable, - "refused": False, "rejected": rejected, "failed": not done or cut, + "refused": False, "rejected": rejected, "model_refusal": refusal, "failed": not done or cut, "finish_reason": "length" if cut else ("stop" if done else None), "failure": (notes or ("the reply was cut at its output limit" if cut else "the session did not settle") )[-600:]} diff --git a/tests/core/test_pi_agent.py b/tests/core/test_pi_agent.py index 098e34f6..37242cab 100644 --- a/tests/core/test_pi_agent.py +++ b/tests/core/test_pi_agent.py @@ -24,6 +24,7 @@ STREAMS = ROOT / "tests" / "fixtures" / "pi" FILE_ADAPTER = ROOT / "docs" / "_examples" / "file_adapter" SESSION = "01a1b44b-6699-759a-a7f2-22c02fcee4c5" # the recorded success stream's session +FAILED = '503: {"message":"mock: service unavailable"}' # the recorded failure stream's error, each request's FAKE_PI = f'''#!{sys.executable} """A stand-in for `pi --mode json ...`: records its arguments, Pi's variables, its home's files and its stdin, then @@ -375,37 +376,112 @@ def model_of(call): assert "thinkingLevelMap" not in model_of(seen(fake)[-1]) -@pytest.mark.parametrize("error, unavailable, rejected", [ - ('503: {"message":"busy"}', True, False), ("503 status code (no body)", True, False), - ("503 Service Unavailable", True, False), - ('503 {"error":{"message":"busy"}}', True, False), - ('hermit API error (503): {"error":{"message":"busy"}}', True, False), - ('429 {"error":{"message":"slow down"}}', True, False), ("Connection error.", True, False), - ('400: {"message":"no such field"}', False, True), ('401 {"error":{"message":"bad key"}}', False, True), - ('hermit API error (404): {"error":{"message":"no such model"}}', False, True), - ('408: {"message":"too slow"}', False, False)], +def ended(fake, name: str, **message) -> str: + """The recorded resume stream (one request) with these fields of the request's message (its `message_end`), one + given as None removed.""" + lines = (STREAMS / "resume.jsonl").read_text().splitlines(keepends=True) + last = max(i for i, line in enumerate(lines) if '"type":"message_end"' in line and '"assistant"' in line) + event = json.loads(lines[last]) + event["message"] = {k: v for k, v in {**event["message"], **message}.items() if v is not None} + lines[last] = json.dumps(event, separators=(",", ":")) + "\n" + (fake / name).write_text("".join(lines)) + return str(fake / name) + + +def retried(fake, error: str) -> str: + """An error Pi retries (a 429, a 5xx, a lost connection): the recorded failure stream with `error` for its 503, + each of its four requests failed, retried three times (`auto_retry_start`), then given up (`auto_retry_end`).""" + (fake / "retried.jsonl").write_text((STREAMS / "failure.jsonl").read_text().replace( + json.dumps(FAILED)[1:-1], json.dumps(error)[1:-1])) + return str(fake / "retried.jsonl") + + +def once(fake, error: str) -> str: + """An error Pi sends once (a 4xx but a 429): the resume stream's one request failed with `error`, with no retry + event and, no answer having come, no stop reason of the provider's.""" + return ended(fake, "once.jsonl", stopReason="error", errorMessage=error, rawStopReason=None, content=[]) + + +def given_up(fake, error: str, raw: str | None = None) -> str: + """Outages, then an error Pi does not retry: the recorded failure stream to its third request, which failed with + `error` (and `raw`, the provider's stop reason, for an answer it declined), the two 503s before it retried + (`auto_retry_start`), then given up (`auto_retry_end` with `error`).""" + lines = (STREAMS / "failure.jsonl").read_text().splitlines(keepends=True) + second, third = [i for i, line in enumerate(lines) if '"type":"auto_retry_start"' in line][1:] + events = [json.loads(line) for line in lines[second + 1:third]] + for event in events: + for message in [event.get("message"), *event.get("messages", [])]: + if isinstance(message, dict) and message.get("role") == "assistant": + message.update(errorMessage=error, **({"rawStopReason": raw} if raw else {})) + if event["type"] == "agent_end": + event["willRetry"] = False + events.append({"type": "auto_retry_end", "success": False, "attempt": 2, "finalError": error}) + (fake / "given-up.jsonl").write_text("".join([*lines[:second + 1], *(json.dumps(e, separators=(",", ":")) + "\n" + for e in events), lines[-1]])) + return str(fake / "given-up.jsonl") + + +@pytest.mark.parametrize("sent, error, unavailable, rejected", [ + (retried, '503: {"message":"busy"}', True, False), (retried, "503 status code (no body)", True, False), + (retried, "503 Service Unavailable", True, False), + (retried, '503 {"error":{"message":"busy"}}', True, False), + (retried, 'hermit API error (503): {"error":{"message":"busy"}}', True, False), + (retried, '500: {"message":"internal error"}', True, False), + (retried, '529 {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}', True, False), + (retried, '429 {"error":{"message":"slow down"}}', True, False), (retried, "Connection error.", True, False), + (once, '400: {"message":"no such field"}', False, True), (once, '401 {"error":{"message":"bad key"}}', False, True), + (once, 'hermit API error (404): {"error":{"message":"no such model"}}', False, True), + (once, '408: {"message":"too slow"}', False, False), (once, '409: {"message":"conflict"}', False, False), + (given_up, '400: {"message":"no such field"}', False, True)], ids=["outage", "outage, no body", "outage, a proxy's page", "outage, Messages API", "outage, Responses API", - "rate limit, Messages API", "no connection, retries given up", "bad request", "bad key, Messages API", - "no such model, Responses API", "request timeout"]) -def test_a_failed_requests_status_says_whether_a_retry_can_help(fake, monkeypatch, error, unavailable, rejected): + "server error", "overloaded, Messages API", "rate limit, Messages API", "no connection, retries given up", + "bad request", "bad key, Messages API", "no such model, Responses API", "request timeout", "conflict", + "outages, then a bad request"]) +def test_a_failed_requests_status_says_whether_a_retry_can_help(fake, monkeypatch, sent, error, unavailable, rejected): """Pi reports a provider's status in its own forms (those Pi 1.5.0 printed): `503: {...}` or `503 status code (no body)` from chat completions, `503 {...}` from the Messages API, ` API error (503): ...` from the - Responses API. An outage or a rate limit is `unavailable` (retried; the chat endpoint's 503), and so is an error - with no status that Pi retried until it gave up (a dropped connection); a status no retry can help is `rejected` - (the chat endpoint's 400, which a client does not retry); a timeout or a conflict is neither.""" + Responses API; it retries a 429, a 500 to 504, an overload and a lost connection, and sends a 4xx once. An outage + (any 5xx) or a rate limit is `unavailable` (retried; the chat endpoint's 503), and so is an error with no status + that Pi retried until it gave up (a dropped connection); a status no retry can help is `rejected` (the chat + endpoint's 400, which a client does not retry); a timeout or a conflict is neither. The last request's status + decides: outages that ended in a bad request are rejected.""" from hermit.agent.base.endpoint import _no_reply - recorded = '503: {"message":"mock: service unavailable"}' - stream = (STREAMS / "failure.jsonl").read_text().replace(json.dumps(recorded)[1:-1], json.dumps(error)[1:-1]) - assert error in "".join(json.loads(line)["message"].get("errorMessage") or "" for line in stream.splitlines() - if isinstance(json.loads(line).get("message"), dict)) - (fake / "status.jsonl").write_text(stream) - monkeypatch.setenv("FAKE_PI_STREAM", str(fake / "status.jsonl")) + monkeypatch.setenv("FAKE_PI_STREAM", sent(fake, error)) + raw = Path(os.environ["FAKE_PI_STREAM"]).read_text() + assert base_cli.Pi._last_assistant(raw)["errorMessage"] == error + assert ('"auto_retry_start"' in raw) == (sent is not once) work = fake / "work" work.mkdir() agent = make("pi", {**bound(), "web_search": False, "home": str(fake / "home")}) result = agent.run("go", workspace=work) assert result.extra["failed"] and (result.extra["unavailable"], result.extra["rejected"]) == (unavailable, rejected) - assert _no_reply(agent, result)[0] == (503 if unavailable else 400 if rejected else 502) + assert not result.extra["model_refusal"] and _no_reply(agent, result)[0] == ( + 503 if unavailable else 400 if rejected else 502) + + +@pytest.mark.parametrize("error, raw", [("The model refused to complete the request", "refusal"), + ("500 words of the answer are withheld by the usage policy", "refusal"), + ("Provider stopped with: sensitive", "sensitive"), + ("Provider finish_reason: content_filter", "content_filter"), + ("Response incomplete: content_filter", "incomplete.content_filter")], + ids=["refusal, Messages API", "refusal, explained with a number first", + "sensitive, Messages API", "content filter, chat completions", + "content filter, Responses API"]) +def test_an_answer_the_provider_declined_is_a_refusal_no_retry_can_help(fake, monkeypatch, error, raw): + """Pi 1.5.0 ends a request whose answer the provider stopped as an error, sent once, with the provider's stop + reason (`rawStopReason`) and its words (on the Messages API the refusal's explanation, when it gives one): + `rejected` and `model_refusal`, as on Claude Code, and never `unavailable` (the chat endpoint's 400), whatever + Pi retried before it and whatever number the words start with.""" + from hermit.agent.base.endpoint import _no_reply + work = fake / "work" + work.mkdir() + agent = make("pi", {**bound(), "web_search": False, "home": str(fake / "home")}) + for stream in (ended(fake, "declined.jsonl", stopReason="error", errorMessage=error, rawStopReason=raw), + given_up(fake, error, raw)): + monkeypatch.setenv("FAKE_PI_STREAM", stream) + result = agent.run("go", workspace=work) + assert result.extra["failed"] and result.extra["rejected"] and result.extra["model_refusal"] + assert not result.extra["unavailable"] and _no_reply(agent, result)[0] == 400 def test_command_timeout_s_from_the_config_reaches_the_acting_agents_and_the_learners_sessions(fake): @@ -472,15 +548,8 @@ def test_a_model_through_pi_answers_each_request_with_a_session_that_only_replie def cut_stream(fake, text: bool = True): """The recorded resume stream with its reply ended at the output limit, and with no text but its thinking.""" - lines = (STREAMS / "resume.jsonl").read_text().splitlines(keepends=True) - last = max(i for i, line in enumerate(lines) if '"type":"message_end"' in line and '"assistant"' in line) - event = json.loads(lines[last]) - event["message"]["stopReason"] = "length" - if not text: - event["message"]["content"] = [{"type": "thinking", "thinking": "a long thought"}] - lines[last] = json.dumps(event, separators=(",", ":")) + "\n" - (fake / "cut.jsonl").write_text("".join(lines)) - return str(fake / "cut.jsonl") + return ended(fake, "cut.jsonl", stopReason="length", + **({} if text else {"content": [{"type": "thinking", "thinking": "a long thought"}]})) def test_a_reply_cut_at_the_output_limit_comes_back_through_the_chat_endpoint_marked_so(fake, monkeypatch): @@ -594,7 +663,8 @@ def test_a_pipelines_model_through_pi_is_bound_as_the_learners_is(): def serve_chat(script): """A chat-completions model on the loopback: `script(request body) -> (tool call (name, arguments) | None)`; - None answers `the answer`. Every response is streamed, with usage.""" + None answers `the answer`, a status (an int) is an error with that status, and a finish reason (a str, such as + `content_filter`) ends an answer that has no text. Every answer is streamed, with usage.""" from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer def chunk(body): @@ -607,13 +677,22 @@ def log_message(self, *args): def do_POST(self): body = json.loads(self.rfile.read(int(self.headers.get("content-length") or 0)) or b"{}") call = script(body) + if isinstance(call, int): + error = json.dumps({"error": {"message": f"scripted {call}"}}).encode() + self.send_response(call) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(error))) + self.end_headers() + self.wfile.write(error) + return + tool = isinstance(call, tuple) delta = {"role": "assistant", "tool_calls": [{"index": 0, "id": "call_1", "type": "function", "function": {"name": call[0], "arguments": json.dumps(call[1])}}]} \ - if call else {"role": "assistant", "content": "the answer"} + if tool else {"role": "assistant", "content": "" if call else "the answer"} data = b"".join([chunk({"choices": [{"index": 0, "delta": delta, "finish_reason": None}]}), chunk({"choices": [{"index": 0, "delta": {}, "finish_reason": - "tool_calls" if call else "stop"}]}), + "tool_calls" if tool else call or "stop"}]}), chunk({"choices": [], "usage": {"prompt_tokens": 100, "completion_tokens": 5}}), b"data: [DONE]\n\n"]) self.send_response(200) @@ -795,3 +874,40 @@ def script(body): finally: server.shutdown() assert status == 200 and [b.get("reasoning_effort") for b in bodies] == [sent] + + +@pytest.mark.integration +@pytest.mark.skipif(not shutil.which("pi"), reason="needs the pi CLI") +@pytest.mark.parametrize("answers, retries, rejected, refusal, status", [ + ([503, 503, 400], ["auto_retry_start", "auto_retry_start", "auto_retry_end"], True, False, 400), + ([409], [], False, False, 502), (["content_filter"], [], True, True, 400)], + ids=["outages, then a bad request", "a conflict", "a content filter"]) +def test_with_the_pi_cli_the_last_requests_status_or_stop_reason_says_whether_a_retry_can_help( + tmp_path, monkeypatch, answers, retries, rejected, refusal, status): + """The installed Pi, bound to a scripted model that answers each request in turn: Pi retries a 503 (after 2 s, + then 4 s) and gives up at a 400, sends a 409 or a content filter once, and the session reads as the streams built + for test_a_failed_requests_status_says_whether_a_retry_can_help and the refusal test do.""" + from hermit.agent.base.endpoint import _no_reply + asked = [] + + def script(body): + asked.append(body) + return answers[min(len(asked), len(answers)) - 1] + + server, url = serve_chat(script) + monkeypatch.setenv("MOCK_KEY", "sk-mock") + params = bind_agent_params({"model": "mock/m-1"}, "pi", + registry({"mock": {"base_url": url, "api_key_env": "MOCK_KEY", "apis": ["chat"]}})) + work = tmp_path / "work" + work.mkdir() + agent = make("pi", {**params, "web_search": False, "home": str(tmp_path / "home"), "timeout_s": 300, + "log": str(tmp_path / "agent-pi.jsonl")}) + try: + result = agent.run("Do the task.", workspace=work) + finally: + server.shutdown() + events = [json.loads(line) for line in (tmp_path / "agent-pi.jsonl").read_text().splitlines() if line.strip()] + assert len(asked) == len(answers) and [e["type"] for e in events if e["type"].startswith("auto_retry")] == retries + assert result.extra["failed"] and not result.extra["unavailable"] + assert (result.extra["rejected"], result.extra["model_refusal"]) == (rejected, refusal) + assert _no_reply(agent, result)[0] == status diff --git a/tests/methods/evosafe/test_evosafe_on_pi.py b/tests/methods/evosafe/test_evosafe_on_pi.py index 2c868dcf..dc57acba 100644 --- a/tests/methods/evosafe/test_evosafe_on_pi.py +++ b/tests/methods/evosafe/test_evosafe_on_pi.py @@ -4,6 +4,7 @@ from pathlib import Path from types import SimpleNamespace as NS +import pytest import yaml from pi_stand import bound_params, pi_stand # noqa: F401 (pi_stand: the fixture) @@ -47,6 +48,19 @@ def test_a_reply_that_is_no_answer_fails_the_role(pi_stand, tmp_path): # noqa: assert response is None and error.startswith("pi role failed") +def test_a_role_the_provider_declines_is_the_safety_refusal_and_is_not_tried_again(pi_stand, tmp_path): # noqa: F811 + """As on Claude Code (test_evosafe_on_claude.py): Pi's `model_refusal` is EvoSafe's safety refusal, which ends + the role however many retries it has, not a role that failed.""" + from hermit.agent.evolver.methods.evosafe import roles + pi_stand.play(declined="content_filter") + ctx = ctx_of(tmp_path) + ctx.params["role_retries"] = 2 + schema = {"type": "object", "required": ["verdict"], "properties": {"verdict": {"type": "string"}}} + with pytest.raises(roles.RoleSafetyRefusal, match="SAFETY_REVIEW_REFUSAL"): + roles.invoke_role(ctx, "Review it.", {"case": 1}, schema, "trial-001-criticizer", []) + assert len(pi_stand.seen()) == 1 + + def test_a_legacy_proposer_pi_without_a_model_is_refused_with_how_to_give_it_one(tmp_path): from hermit.agent.evolver.methods.evosafe.evolver import EvoSafeEvolver ctx = NS(workspace=NS(), params={"proposer": "pi", "eval_task_ids": ["a", "b"]}, access=NS(validation=None), tools={}) diff --git a/tests/pi_stand.py b/tests/pi_stand.py index e7da4c53..724ac1b4 100644 --- a/tests/pi_stand.py +++ b/tests/pi_stand.py @@ -38,13 +38,21 @@ class Stand: def __init__(self, folder: Path): self.folder = folder - def play(self, stream: str = "resume", reply: str | None = None, edits: dict | None = None, cut: bool = False) -> None: + def play(self, stream: str = "resume", reply: str | None = None, edits: dict | None = None, cut: bool = False, + declined: str | None = None) -> None: """The next calls replay `stream` (a file of tests/fixtures/pi), `reply` as the final answer, and make `edits`; - with `cut`, the last reply ends at its output limit. `resume` has no tool calls, `success` has three.""" + with `cut`, the last reply ends at its output limit; with `declined`, the provider stopped it with that finish + reason (`content_filter`), which Pi 1.5.0 reports as an error. `resume` has no tool calls, `success` has + three.""" lines = (STREAMS / f"{stream}.jsonl").read_text().splitlines(keepends=True) + last = max(i for i, line in enumerate(lines) if '"type":"message_end"' in line and '"assistant"' in line) if cut: - last = max(i for i, line in enumerate(lines) if '"type":"message_end"' in line and '"assistant"' in line) lines[last] = lines[last].replace('"stopReason":"stop"', '"stopReason":"length"') + if declined: + event = json.loads(lines[last]) + event["message"].update(stopReason="error", rawStopReason=declined, + errorMessage=f"Provider finish_reason: {declined}") + lines[last] = json.dumps(event, separators=(",", ":")) + "\n" text = "".join(lines) (self.folder / "stream.jsonl").write_text( text if reply is None else text.replace("the answer", json.dumps(reply)[1:-1])) From 677b36c43a728036f59cf303941cd6d08ffa5c45 Mon Sep 17 00:00:00 2001 From: Albert Zhao Date: Tue, 10 Nov 2026 20:41:21 -0500 Subject: [PATCH 12/13] EvoSafe on Pi: a failed session is no answer, whatever its text From the post-PR audit of e5490a4 (round 5): - Pi exits 0 however a session ended, so EvoSafe's exit-code gate let a failed session's text through: a reply the provider declined, one cut at its output limit, or one the provider stopped, became the role's answer whenever it parsed as the schema's JSON, and a declined one never raised SAFETY_REVIEW_REFUSAL. A session the Base Agent marks `failed` is now no answer; Codex sets no `failed`, and Claude Code exits non-zero on the same sessions. - Tests: those three endings with a reply that is the schema's JSON (the Pi stand's `stopped` finish reason); a finish reason Pi sends once and that is no refusal is neither `unavailable` nor `rejected`; the refusal whose words start with a number now uses one Pi does not retry, so the stream is what Pi sends. - Docs: the RRSI row of docs/framework/evolver.md and EvoSafe's requirements name Pi. Co-Authored-By: Claude Opus 5.5 --- docs/framework/evolver.md | 2 +- docs/methods/index.md | 2 +- .../evolver/methods/evosafe/cli_roles.py | 4 +++- tests/core/test_pi_agent.py | 19 +++++++++++++------ tests/methods/evosafe/test_evosafe_on_pi.py | 16 +++++++++++++++- tests/pi_stand.py | 14 +++++++------- 6 files changed, 40 insertions(+), 17 deletions(-) diff --git a/docs/framework/evolver.md b/docs/framework/evolver.md index 17eed51f..5a3ccc2f 100644 --- a/docs/framework/evolver.md +++ b/docs/framework/evolver.md @@ -139,7 +139,7 @@ For selection guidance, setup, and the complete parameter defaults, use [Choose | `mwm` | MetaWorld Model, with `template: mwm`: one native MWM learner session per block (the step), under the MWM contract, with the task's evidence store mounted at `/evidence`, in its own network namespace. See `docs/methods/mwm.md`. | The Codex CLI, a task that keeps an MWM evidence store (`evolver_access.environment`), `task-info/mwm/`, `data.shuffle: false` | | `reharness` | [ReHarness](../methods/reharness.md), with `template: reharness`: one instance of the stream per step. It revises each reflection the acting agent retrieved, from that reflection's own source trajectory with the new trajectory as feedback, then writes the instance's reflection with the revised ones as demonstrations, through the run's `llm` tool with the paper's prompts; no validation data. | `llm`, `data.step_size: 1` and `data.shuffle: false`, an embedding endpoint (`evolver.params.embedding`, and `REHARNESS_EMBED_URL` for the acting side's reader; BM25 without) | | `meta_harness_adapter` | [Meta-Harness Adapter](../methods/meta_harness_adapter.md), with `template: meta-harness-adapter`: one candidate per step. Each step's rollouts evaluate the candidate handed back last; when none is waiting, a Codex, Claude Code, Pi or OpenCode proposer reads every earlier candidate's files, scores and trajectories and writes k new adapters, which pass `check_spec` before they are queued; no validation data. | The proposer CLI, `data.step_size` covering the training split (the search set) | -| `rrsi_adapter` | [RRSI Adapter](../methods/rrsi_adapter.md), with `template: rrsi-adapter`: one candidate per step. Each step's rollouts evaluate the candidate handed back last; when a round's candidates are all measured, upstream's selection decides it, upstream's analyst reads the incumbent's evaluation, and m Codex or Claude Code proposer sessions edit the incumbent under RRSI's edit budget, each diff screened by upstream's critic and a smoke before it is queued; no validation data. | The proposer CLI and the Codex CLI (the analyst, digesters and critic), `data.step_size` covering the training split with k rows per task, `evolver.params.domain`, `python -m pip install -e . --group rrsi` | +| `rrsi_adapter` | [RRSI Adapter](../methods/rrsi_adapter.md), with `template: rrsi-adapter`: one candidate per step. Each step's rollouts evaluate the candidate handed back last; when a round's candidates are all measured, upstream's selection decides it, upstream's analyst reads the incumbent's evaluation, and m Codex, Claude Code or Pi proposer sessions edit the incumbent under RRSI's edit budget, each diff screened by upstream's critic and a smoke before it is queued; no validation data. | The proposer CLI (Codex, Claude Code or Pi), which also runs the analyst, digesters and critic, `data.step_size` covering the training split with k rows per task, `evolver.params.domain`, `python -m pip install -e . --group rrsi` | Change a parameter with `evolver.params` in the run config; each Evolver's `evolver.yaml` under `hermit/agent/evolver/methods/` lists them with their defaults. For `gepa`, `data.step_size` is the reflection diff --git a/docs/methods/index.md b/docs/methods/index.md index 67cefd7e..4c2c0237 100644 --- a/docs/methods/index.md +++ b/docs/methods/index.md @@ -14,7 +14,7 @@ template–method combinations meaningful. | Refine a policy, sub-agents, skills and memory in place from each step's trajectories, without a gate | [Continual Harness](continual_harness.md) | `continual-harness@1.1` | Learner model endpoint, Codex | | Grow an itemised playbook by incremental deltas from reflections, keeping the best validation playbook | [ACE](ace.md) | `ace@1.0` | Learner model endpoint; optional validation split | | Evolve an agent's harness (prompt, middleware, scripts, skills, sub-agents, memory) from k rollouts per task, with each change attributed and reversible | [AHE Adapter](ahe_adapter.md) | `ahe@1.0` | An acting agent that runs hooks (Codex, Claude Code), a learner CLI (Codex, Claude Code or Pi), k rows per task | -| Search a dual-surface defense (prompt + tool hooks) for a frozen victim against frozen attack cases | [EvoSafeHarness](evosafe.md) | `evosafe@1.0` | Hook-bridge pipeline, utility/attack judge (verdicts in `JudgeResult.extra`), optional validation split, Claude Code or Codex | +| Search a dual-surface defense (prompt + tool hooks) for a frozen victim against frozen attack cases | [EvoSafeHarness](evosafe.md) | `evosafe@1.0` | Hook-bridge pipeline, utility/attack judge (verdicts in `JudgeResult.extra`), optional validation split, Claude Code, Codex or Pi | | Search instructions with a model that reads the best earlier instructions with their training scores | [OPRO](opro.md) | `prompt-only@1.0` | Learner model endpoint; validation split for `select: validation` | | Build a persistent world model from an ordered environment stream | [MWM](mwm.md) | `mwm` | Evidence store, deployment description, tools, Linux learner environment, a learner CLI (Codex, Claude Code or Pi) | | Learn a bank of reflections online, retrieved per instance of an ordered stream | [ReHarness](reharness.md) | `reharness` | The run's `llm`, an embedding endpoint (or BM25), an agent that reads the adapter through `Session.context(query, task)` | diff --git a/hermit/agent/evolver/methods/evosafe/cli_roles.py b/hermit/agent/evolver/methods/evosafe/cli_roles.py index d7ebdd3d..194f16c0 100644 --- a/hermit/agent/evolver/methods/evosafe/cli_roles.py +++ b/hermit/agent/evolver/methods/evosafe/cli_roles.py @@ -112,7 +112,9 @@ def call_role(ctx, messages, schema, name, backend): return None, result.usage, f"{backend} role cancelled" if result.timed_out: return None, result.usage, f"{backend} role timed out" - answer = parse_answer(result.reply, schema) if result.exit_code == 0 else None + # Pi exits 0 however a session ended: one that failed (a declined answer, a reply cut at its output limit, a last + # request that failed) is no answer, whatever its text says + answer = parse_answer(result.reply, schema) if result.exit_code == 0 and not result.extra.get("failed") else None if answer is None: # Only a failed answer is read for login errors: a valid one may quote such text. if authentication_failed(result): diff --git a/tests/core/test_pi_agent.py b/tests/core/test_pi_agent.py index 37242cab..0f058a0b 100644 --- a/tests/core/test_pi_agent.py +++ b/tests/core/test_pi_agent.py @@ -402,6 +402,12 @@ def once(fake, error: str) -> str: return ended(fake, "once.jsonl", stopReason="error", errorMessage=error, rawStopReason=None, content=[]) +def stopped(fake, error: str) -> str: + """A finish reason Pi does not retry and that is no refusal (DeepSeek's `insufficient_system_resource`): the resume + stream's one request stopped with it, sent once, with no status.""" + return ended(fake, "stopped.jsonl", stopReason="error", errorMessage=error, rawStopReason=error.split(": ")[-1]) + + def given_up(fake, error: str, raw: str | None = None) -> str: """Outages, then an error Pi does not retry: the recorded failure stream to its third request, which failed with `error` (and `raw`, the provider's stop reason, for an answer it declined), the two 503s before it retried @@ -432,24 +438,25 @@ def given_up(fake, error: str, raw: str | None = None) -> str: (once, '400: {"message":"no such field"}', False, True), (once, '401 {"error":{"message":"bad key"}}', False, True), (once, 'hermit API error (404): {"error":{"message":"no such model"}}', False, True), (once, '408: {"message":"too slow"}', False, False), (once, '409: {"message":"conflict"}', False, False), + (stopped, "Provider finish_reason: insufficient_system_resource", False, False), (given_up, '400: {"message":"no such field"}', False, True)], ids=["outage", "outage, no body", "outage, a proxy's page", "outage, Messages API", "outage, Responses API", "server error", "overloaded, Messages API", "rate limit, Messages API", "no connection, retries given up", "bad request", "bad key, Messages API", "no such model, Responses API", "request timeout", "conflict", - "outages, then a bad request"]) + "stopped by the provider, no status", "outages, then a bad request"]) def test_a_failed_requests_status_says_whether_a_retry_can_help(fake, monkeypatch, sent, error, unavailable, rejected): """Pi reports a provider's status in its own forms (those Pi 1.5.0 printed): `503: {...}` or `503 status code (no body)` from chat completions, `503 {...}` from the Messages API, ` API error (503): ...` from the Responses API; it retries a 429, a 500 to 504, an overload and a lost connection, and sends a 4xx once. An outage (any 5xx) or a rate limit is `unavailable` (retried; the chat endpoint's 503), and so is an error with no status - that Pi retried until it gave up (a dropped connection); a status no retry can help is `rejected` (the chat - endpoint's 400, which a client does not retry); a timeout or a conflict is neither. The last request's status - decides: outages that ended in a bad request are rejected.""" + that Pi retried until it gave up (a dropped connection), but not one it sent once (a finish reason); a status no + retry can help is `rejected` (the chat endpoint's 400, which a client does not retry); a timeout or a conflict is + neither. The last request's status decides: outages that ended in a bad request are rejected.""" from hermit.agent.base.endpoint import _no_reply monkeypatch.setenv("FAKE_PI_STREAM", sent(fake, error)) raw = Path(os.environ["FAKE_PI_STREAM"]).read_text() assert base_cli.Pi._last_assistant(raw)["errorMessage"] == error - assert ('"auto_retry_start"' in raw) == (sent is not once) + assert ('"auto_retry_start"' in raw) == (sent in (retried, given_up)) work = fake / "work" work.mkdir() agent = make("pi", {**bound(), "web_search": False, "home": str(fake / "home")}) @@ -460,7 +467,7 @@ def test_a_failed_requests_status_says_whether_a_retry_can_help(fake, monkeypatc @pytest.mark.parametrize("error, raw", [("The model refused to complete the request", "refusal"), - ("500 words of the answer are withheld by the usage policy", "refusal"), + ("501 words of the answer are withheld by the usage policy", "refusal"), ("Provider stopped with: sensitive", "sensitive"), ("Provider finish_reason: content_filter", "content_filter"), ("Response incomplete: content_filter", "incomplete.content_filter")], diff --git a/tests/methods/evosafe/test_evosafe_on_pi.py b/tests/methods/evosafe/test_evosafe_on_pi.py index dc57acba..41df15ad 100644 --- a/tests/methods/evosafe/test_evosafe_on_pi.py +++ b/tests/methods/evosafe/test_evosafe_on_pi.py @@ -52,7 +52,7 @@ def test_a_role_the_provider_declines_is_the_safety_refusal_and_is_not_tried_aga """As on Claude Code (test_evosafe_on_claude.py): Pi's `model_refusal` is EvoSafe's safety refusal, which ends the role however many retries it has, not a role that failed.""" from hermit.agent.evolver.methods.evosafe import roles - pi_stand.play(declined="content_filter") + pi_stand.play(stopped="content_filter") ctx = ctx_of(tmp_path) ctx.params["role_retries"] = 2 schema = {"type": "object", "required": ["verdict"], "properties": {"verdict": {"type": "string"}}} @@ -61,6 +61,20 @@ def test_a_role_the_provider_declines_is_the_safety_refusal_and_is_not_tried_aga assert len(pi_stand.seen()) == 1 +@pytest.mark.parametrize("ending, error", [({"stopped": "content_filter"}, "SAFETY_REVIEW_REFUSAL"), + ({"cut": True}, "pi role failed"), + ({"stopped": "insufficient_system_resource"}, "pi role failed")], + ids=["declined", "cut at the output limit", "stopped by the provider"]) +def test_a_failed_session_is_no_answer_even_when_its_text_is_one(pi_stand, tmp_path, ending, error): # noqa: F811 + """Pi exits 0 however a session ended: a role whose session failed after its text came is not answered by that + text, even when it is the schema's JSON.""" + from hermit.agent.evolver.methods.evosafe import pi_agent + pi_stand.play(reply='{"verdict": "ok"}', **ending) + response, _, said = pi_agent.call_role(ctx_of(tmp_path), [{"role": "user", "content": "x"}], + {"type": "object", "required": ["verdict"]}, "trial-003-designer") + assert response is None and said.startswith(error) + + def test_a_legacy_proposer_pi_without_a_model_is_refused_with_how_to_give_it_one(tmp_path): from hermit.agent.evolver.methods.evosafe.evolver import EvoSafeEvolver ctx = NS(workspace=NS(), params={"proposer": "pi", "eval_task_ids": ["a", "b"]}, access=NS(validation=None), tools={}) diff --git a/tests/pi_stand.py b/tests/pi_stand.py index 724ac1b4..2d0e8650 100644 --- a/tests/pi_stand.py +++ b/tests/pi_stand.py @@ -39,19 +39,19 @@ def __init__(self, folder: Path): self.folder = folder def play(self, stream: str = "resume", reply: str | None = None, edits: dict | None = None, cut: bool = False, - declined: str | None = None) -> None: + stopped: str | None = None) -> None: """The next calls replay `stream` (a file of tests/fixtures/pi), `reply` as the final answer, and make `edits`; - with `cut`, the last reply ends at its output limit; with `declined`, the provider stopped it with that finish - reason (`content_filter`), which Pi 1.5.0 reports as an error. `resume` has no tool calls, `success` has - three.""" + with `cut`, the last reply ends at its output limit; with `stopped`, the provider stopped it after its text with + that finish reason (`content_filter`, a refusal, or `insufficient_system_resource`), which Pi 1.5.0 reports as + an error, sent once. `resume` has no tool calls, `success` has three.""" lines = (STREAMS / f"{stream}.jsonl").read_text().splitlines(keepends=True) last = max(i for i, line in enumerate(lines) if '"type":"message_end"' in line and '"assistant"' in line) if cut: lines[last] = lines[last].replace('"stopReason":"stop"', '"stopReason":"length"') - if declined: + if stopped: event = json.loads(lines[last]) - event["message"].update(stopReason="error", rawStopReason=declined, - errorMessage=f"Provider finish_reason: {declined}") + event["message"].update(stopReason="error", rawStopReason=stopped, + errorMessage=f"Provider finish_reason: {stopped}") lines[last] = json.dumps(event, separators=(",", ":")) + "\n" text = "".join(lines) (self.folder / "stream.jsonl").write_text( From e3df1259f58e53e22c0d94202a09a95a2dedf49b Mon Sep 17 00:00:00 2001 From: Haizhong Zheng Date: Wed, 11 Nov 2026 01:47:37 -0500 Subject: [PATCH 13/13] =?UTF-8?q?Review=20fixes:=20Harness=C2=B2=20usage?= =?UTF-8?q?=20and=20Pi=20trajectories,=20claude-code,=20model=20mappings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Harness²: a Codex or Pi editor session that times out or is stopped keeps its usage - Harness²: a Pi trajectory is rendered from Pi's events, every tool's result kept and a failed one marked [OBSERVATION ERROR] - mwm and RRSI accept backend claude-code again, as before their new checks - evolver.model: {ref, extra_body} binds on the Pi llm route Co-Authored-By: Claude Opus 5.5 --- .../methods/harness2_upstream/channel.py | 8 ++-- .../methods/harness2_upstream/render.py | 44 +++++++++++-------- hermit/agent/evolver/methods/mwm/evolver.py | 2 +- .../evolver/methods/rrsi_adapter/evolver.py | 2 +- hermit/agent/model/backends.py | 2 +- tests/core/test_pi_agent.py | 7 +++ tests/methods/harness2/test_harness2_on_pi.py | 44 ++++++++++++++++++- tests/methods/mwm/test_mwm_evolver.py | 9 ++++ .../methods/rrsi_adapter/test_rrsi_adapter.py | 1 + 9 files changed, 93 insertions(+), 26 deletions(-) diff --git a/hermit/agent/evolver/methods/harness2_upstream/channel.py b/hermit/agent/evolver/methods/harness2_upstream/channel.py index fe252fa5..05dafd2d 100644 --- a/hermit/agent/evolver/methods/harness2_upstream/channel.py +++ b/hermit/agent/evolver/methods/harness2_upstream/channel.py @@ -168,14 +168,14 @@ def _pi_cli(self, cwd: Path, mission: str, system: str, wall: int) -> tuple[str, return self._reply("pi", result, err, wall) def _reply(self, program: str, result, err: Path, wall: int) -> tuple[str, float, str]: - """(reply, cost, problem) of a Codex or Pi session. Its usage is kept for the step, a failed session's too; a - reply cut at the output limit is no reply.""" + """(reply, cost, problem) of a Codex or Pi session. Its usage is kept for the step, a failed, stopped or timed + out session's too; a reply cut at the output limit is no reply.""" + with self._usage_lock: + self.usages.extend(result.usage) if result.extra["cancelled"]: raise RuntimeError("the session was stopped by the Trainer (budget or timeout)") if result.timed_out: raise subprocess.TimeoutExpired([program], wall) - with self._usage_lock: - self.usages.extend(result.usage) cost = sum(float(u.cost_usd or 0.0) for u in result.usage) if not result.extra["served"] or not result.reply.strip() or result.finish_reason == "length": tail = (_read_own(err) or result.extra.get("failure") or result.extra.get("output_tail", ""))[-300:] diff --git a/hermit/agent/evolver/methods/harness2_upstream/render.py b/hermit/agent/evolver/methods/harness2_upstream/render.py index e39a2965..ac6c2d88 100644 --- a/hermit/agent/evolver/methods/harness2_upstream/render.py +++ b/hermit/agent/evolver/methods/harness2_upstream/render.py @@ -150,28 +150,36 @@ def emit(line: str) -> None: def render_pi_events(path: Path, *, obs_trunc: int, max_chars: int, args_trunc: int = 2000) -> str: - """Render a Pi `--mode json` stream into upstream's shared grammar, from its standard steps.""" - from hermit.agent.base.trajectory import events, pi_steps + """Render a Pi `--mode json` stream into upstream's shared grammar: each assistant message's text, thinking and + tool calls, and each call's result as Pi reported it (a failed one, an edit's or a read's too, as an error).""" + from hermit.agent.base.trajectory import events try: - steps = pi_steps(events(path)) + stream = events(path) except OSError as exc: return f"(failed to read trajectory: {exc})" lines: list[str] = [] - for step in steps: - if step.kind == "message": - lines.append(f"[ASSISTANT] {clip(step.text, obs_trunc)}") - elif step.kind == "reasoning": - lines.append(f"[REASONING] {clip(step.text, obs_trunc)}") - elif step.kind == "command": - lines.append(f"[ACTION] bash: {clip(step.command, args_trunc)}") - tag = "OBSERVATION" if step.exit_code == 0 else "OBSERVATION ERROR" - lines.append(f"[{tag}] {clip(step.output, obs_trunc)}") - elif step.kind == "error": - lines.append(f"[ERROR] {clip(step.text, 1000)}") - else: # a file change or a tool call: its summary, then its result - lines.append(f"[ACTION] {clip(step.text, args_trunc)}") - if step.output: - lines.append(f"[OBSERVATION] {clip(step.output, obs_trunc)}") + for event in stream: + kind = event.get("type") + message = event.get("message") if isinstance(event.get("message"), dict) else {} + if kind == "message_end" and message.get("role") == "assistant": + for block in _blocks(message.get("content")): + btype = block.get("type") + if btype == "text" and str(block.get("text") or "").strip(): + lines.append(f"[ASSISTANT] {clip(block['text'], obs_trunc)}") + elif btype == "thinking" and str(block.get("thinking") or "").strip(): + lines.append(f"[REASONING] {clip(block['thinking'], obs_trunc)}") + elif btype == "toolCall": + name, args = str(block.get("name") or "tool"), block.get("arguments") or {} + lines.append(f"[ACTION] {name}: {_action('Bash' if name == 'bash' else name, args, args_trunc)}") + if message.get("stopReason") in ("error", "aborted"): + lines.append(f"[ERROR] {clip(message.get('errorMessage') or 'request ' + message['stopReason'], 1000)}") + elif kind == "tool_execution_end": + result = event.get("result") if isinstance(event.get("result"), dict) else {} + structured = result.get("structuredContent") if isinstance(result.get("structuredContent"), dict) else {} + said = str(structured["output"]) if event.get("toolName") == "bash" and "output" in structured \ + else _result_text(result.get("content")) + tag = "OBSERVATION ERROR" if event.get("isError") else "OBSERVATION" + lines.append(f"[{tag}] {clip(said, obs_trunc)}") rendered = "\n".join(lines).strip() if not rendered: return "(no parseable events in trajectory)" diff --git a/hermit/agent/evolver/methods/mwm/evolver.py b/hermit/agent/evolver/methods/mwm/evolver.py index 2dd6da26..6b2e5f8c 100644 --- a/hermit/agent/evolver/methods/mwm/evolver.py +++ b/hermit/agent/evolver/methods/mwm/evolver.py @@ -458,7 +458,7 @@ def _notes(admission: dict | None) -> str: # ------------------------------------------------------------------ steps def setup(self, ctx: Context) -> None: - if ctx.params.get("backend", "codex") not in ("codex", "claude", "pi"): # the CLIs its sessions are set up for + if ctx.params.get("backend", "codex") not in ("codex", "claude", "claude-code", "pi"): # its sessions' CLIs raise ValueError("the mwm Evolver's learner is a Codex, Claude Code or Pi session: evolver.params.backend " f"is codex, claude or pi, not {ctx.params.get('backend')!r}") if "network_isolation" in ctx.params: diff --git a/hermit/agent/evolver/methods/rrsi_adapter/evolver.py b/hermit/agent/evolver/methods/rrsi_adapter/evolver.py index 38a9f6f5..d3d00dd0 100644 --- a/hermit/agent/evolver/methods/rrsi_adapter/evolver.py +++ b/hermit/agent/evolver/methods/rrsi_adapter/evolver.py @@ -417,7 +417,7 @@ def setup(self, ctx) -> None: """What every step needs, checked once: a broken hyperparameter file or domain, or an unset web_search, stops the run here rather than failing each step.""" _require_rrsi() - if ctx.params.get("backend", "codex") not in ("codex", "claude", "pi"): # what keeps its roles read-only + if ctx.params.get("backend", "codex") not in ("codex", "claude", "claude-code", "pi"): # roles kept read-only raise ValueError("the RRSI Adapter's proposer and roles are Codex, Claude Code or Pi sessions: " f"evolver.params.backend is codex, claude or pi, not {ctx.params.get('backend')!r}") if not isinstance(ctx.params.get("web_search"), bool): diff --git a/hermit/agent/model/backends.py b/hermit/agent/model/backends.py index b0a7f3e4..dad45d7d 100644 --- a/hermit/agent/model/backends.py +++ b/hermit/agent/model/backends.py @@ -547,7 +547,7 @@ def _cli_model(spec: dict, backends: dict[str, Backend], where: str) -> dict: if cli not in ("codex", "claude", "pi"): raise ValueError(f"{where}.cli must be codex, claude or pi, not {spec['cli']!r}") spec = {**spec, "cli": cli} - return bind_agent_params(spec, cli, backends) if is_ref(spec.get("model"), backends) else spec + return bind_agent_params(spec, cli, backends) if as_binding(spec.get("model"), backends) else spec def _split(ref: str) -> dict: diff --git a/tests/core/test_pi_agent.py b/tests/core/test_pi_agent.py index 0f058a0b..fb9eb50d 100644 --- a/tests/core/test_pi_agent.py +++ b/tests/core/test_pi_agent.py @@ -618,6 +618,13 @@ def test_evolver_base_pi_is_the_run_model_of_a_method_that_calls_it_and_the_lear assert "backend" not in data["evolver"]["params"] [(who, _, dialect)] = bindings_of(data) assert who == "llm tool through pi" and dialect == "chat" + data = {"agent": {}, "llm": None, "backends": {"fake": fake_backend}, # a model mapping binds the same way + "evolver": {"name": "ace", "base": "pi", "model": {"ref": "fake/m-1", "extra_body": {"top_k": 20}}, + "params": {}}} + layered(data) + normalize_config(data) + assert data["llm"]["model"] == "m-1" and data["llm"]["provider"]["apiKey"] == "$FAKE_KEY" + assert data["llm"]["provider"]["models"][0]["samplingParams"] == {"top_k": 20} for name in ("mwm", "evosafe", "rrsi_adapter", "ahe_adapter", "harness2_upstream", "meta_harness_adapter", "aspire"): data = {"agent": {}, "llm": None, "evolver": {"name": name, "base": "pi", "model": "fake/m-1", "params": {}}} layered(data) diff --git a/tests/methods/harness2/test_harness2_on_pi.py b/tests/methods/harness2/test_harness2_on_pi.py index 7b87b1bb..fcfa8f5c 100644 --- a/tests/methods/harness2/test_harness2_on_pi.py +++ b/tests/methods/harness2/test_harness2_on_pi.py @@ -52,6 +52,28 @@ def test_a_pi_reply_cut_at_its_limit_is_no_reply_and_what_it_spent_is_kept(pi_st assert cost == pytest.approx(prop.usages[0].cost_usd) and prop.usages[0].output_tokens == 20 +@pytest.mark.parametrize("ending", ["timed_out", "cancelled"]) +def test_what_a_pi_session_spent_is_kept_when_it_times_out_or_is_stopped(tmp_path, monkeypatch, ending): + """Upstream retries a session that timed out: the attempt's spending is the step's all the same.""" + import subprocess + from hermit.agent.base.interface import Result + from hermit.agent.evolver.base import Usage + from hermit.agent.evolver.methods.harness2_upstream import channel + spent = Usage(model="m-1", input_tokens=900, output_tokens=40, calls=3, cost_usd=0.02) + + class Stopped: + def run(self, prompt, workspace): + return Result(reply="", usage=[spent], timed_out=ending == "timed_out", + extra={"cancelled": ending == "cancelled", "served": False}) + monkeypatch.setattr(channel, "make", lambda backend, settings: Stopped()) + prop = proposer() + cwd = tmp_path / "session" + cwd.mkdir() + with pytest.raises(subprocess.TimeoutExpired if ending == "timed_out" else RuntimeError): + prop._claude_cli(cwd, "the mission", "", wall=60) + assert prop.usages == [spent] and prop.served == 0 + + def test_a_session_on_pi_keeps_its_models_key_where_upstream_drops_anthropics(pi_stand, tmp_path, monkeypatch): # noqa: F811 """Upstream drops ANTHROPIC_API_KEY for its Claude sessions; a Pi session bound to a backend whose key is in that variable (the built-in anthropic backend's) needs it.""" @@ -100,4 +122,24 @@ def test_a_pi_trajectory_reads_in_upstreams_grammar(): from hermit.agent.evolver.methods.harness2_upstream.render import render_pi_events text = render_pi_events(STREAMS / "success.jsonl", obs_trunc=1000, max_chars=100000) assert "[ACTION] bash: echo hi && exit 3" in text and "[OBSERVATION ERROR] hi" in text - assert '"tool": "echo"' in text and text.rstrip().endswith("[ASSISTANT] the answer") + assert '[ACTION] mcp__hermit_tools__echo: {"text": "from pi"}' in text + assert '[OBSERVATION] {"echoed": "from pi"}' in text + assert "[OBSERVATION] Successfully wrote to note.txt" in text and text.rstrip().endswith("[ASSISTANT] the answer") + + +def test_a_pi_tool_that_failed_reads_as_an_error_whatever_the_tool(tmp_path): + """An edit that did not apply and a read of a missing file are what the editors learn from, as on Claude Code.""" + from hermit.agent.evolver.methods.harness2_upstream.render import render_pi_events + calls = [("edit", {"path": "a.py", "oldText": "x", "newText": "y"}, "Could not find the exact text in a.py"), + ("read", {"path": "gone.txt"}, "ENOENT: no such file or directory, open 'gone.txt'")] + lines = [] + for i, (name, args, said) in enumerate(calls): + lines += [{"type": "message_end", "message": {"role": "assistant", "stopReason": "toolUse", "content": [ + {"type": "toolCall", "id": f"c{i}", "name": name, "arguments": args}]}}, + {"type": "tool_execution_end", "toolCallId": f"c{i}", "toolName": name, "isError": True, + "result": {"content": [{"type": "text", "text": said}]}}] + (tmp_path / "agent-pi.jsonl").write_text("".join(json.dumps(e) + "\n" for e in lines)) + text = render_pi_events(tmp_path / "agent-pi.jsonl", obs_trunc=1000, max_chars=100000) + assert '[ACTION] edit: {"path": "a.py"' in text + assert "[OBSERVATION ERROR] Could not find the exact text in a.py" in text + assert "[OBSERVATION ERROR] ENOENT: no such file or directory" in text diff --git a/tests/methods/mwm/test_mwm_evolver.py b/tests/methods/mwm/test_mwm_evolver.py index 5a73696d..79c85b9c 100644 --- a/tests/methods/mwm/test_mwm_evolver.py +++ b/tests/methods/mwm/test_mwm_evolver.py @@ -148,6 +148,15 @@ def make(tmp: Path, monkeypatch, steps: int = 2, deployment_param: bool = False) return path +@pytest.mark.parametrize("name", ["codex", "claude", "claude-code", "pi"]) +def test_a_learner_on_a_cli_mwm_is_set_up_for_passes_the_backend_check(name): + """Claude Code's other name too, as before the check: setup goes on to its next check.""" + from types import SimpleNamespace + from hermit.agent.evolver.methods.mwm.evolver import MwmEvolver + with pytest.raises(ValueError, match="network_isolation was removed"): + MwmEvolver().setup(SimpleNamespace(params={"backend": name, "network_isolation": True})) + + @pytest.mark.parametrize("name", ["react", "mini-swe-agent", "dsh"]) def test_a_learner_on_a_cli_mwm_is_not_set_up_for_is_refused_at_setup(tmp_path, monkeypatch, name): """From the config through the Trainer: mwm's sessions are set up for Codex, Claude Code and Pi (each one's way to its diff --git a/tests/methods/rrsi_adapter/test_rrsi_adapter.py b/tests/methods/rrsi_adapter/test_rrsi_adapter.py index 9de654bf..60a387cf 100644 --- a/tests/methods/rrsi_adapter/test_rrsi_adapter.py +++ b/tests/methods/rrsi_adapter/test_rrsi_adapter.py @@ -839,6 +839,7 @@ def test_setup_checks_what_every_step_needs(tmp_path): with pytest.raises(ValueError, match="web_search"): ev.setup(context(ws, 1, dom, tmp_path, web_search=None)) ev.setup(context(ws, 1, dom, tmp_path, backend="claude")) + ev.setup(context(ws, 1, dom, tmp_path, backend="claude-code")) # Claude Code's other name, as before ev.setup(context(ws, 1, dom, tmp_path, backend="pi")) for other in ("react", "mini-swe-agent", "dsh"): # no way to keep its roles read-only with pytest.raises(ValueError, match=f"backend is codex, claude or pi, not '{other}'"):