diff --git a/CHANGELOG.md b/CHANGELOG.md index ad973dc2..6931d655 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -143,6 +143,14 @@ Changes are grouped by software version. Entries under Unreleased describe work ### Added +- CaP-Agent0 (CaP-X, arXiv:2603.22435; capgym/cap-x at acac62f): the `cap-agent0@1.0` template (the skill + library, `skill_library.py`, rendered by its context tool and checked against the cap-harness engine's program + rules), the acting agent `hermit.agent.evolver.methods.cap_agent0.actor:CapAgent0Actor` (cap-x's trial loop on the + engine: the multi-turn loop replayed per turn, the Visual Differencing Module, the parallel ensemble; every call one + `Direct` call), and the `cap_agent0` Evolver (cap-x's library compile, `setting: paper` for the paper's single + pass, `setting: continual` for a synthesis after every step with validation-based selection), with cap-x's pure + functions and prompts copied verbatim. `examples/libero/cap_agent0/`: one task row per trial on LIBERO-Pro + (`rows.py`), the paper's pipeline (`paper.yaml`) and the continual setting (`continual.yaml`), smoke configs. - `examples/officeqa_harbor/`: OfficeQA as Harbor's task set (harbor-datasets' `datasets/officeqa`, pinned) in the OfficeQA paper's evaluation: each question in its own Harbor environment, the paper's agent prompt, the final message's `` scored by the paper's `reward.py` (the OfficeQA repository's at its commit) at a 0.0% diff --git a/docs/index.md b/docs/index.md index 705a1706..90a62860 100644 --- a/docs/index.md +++ b/docs/index.md @@ -76,6 +76,7 @@ methods/harness2 methods/continual_harness methods/reharness methods/aspire +methods/cap_agent0 methods/meta_harness_adapter methods/ace methods/ahe_adapter diff --git a/docs/methods/cap_agent0.md b/docs/methods/cap_agent0.md new file mode 100644 index 00000000..7b589b18 --- /dev/null +++ b/docs/methods/cap_agent0.md @@ -0,0 +1,252 @@ +# CaP-Agent0 + +CaP-Agent0 (CaP-X, Fu et al., [arXiv:2603.22435](https://arxiv.org/abs/2603.22435), §4.1; +[project](https://capgym.github.io/), [code](https://github.com/capgym/cap-x)) is a training-free coding agent for +robot control. It writes a program against low-level perception and control primitives, runs it, and over several +turns reads the program's output and a vision–language model's description of how the scene changed (the Visual +Differencing Module, VDM), regenerating the code until it answers FINISH. A parallel ensemble of requests at several +temperatures, merged by a synthesis request, writes every program. The one thing CaP-Agent0 learns is its skill +library: helper functions that recur in successful programs, curated by a model and offered to later programs as part +of the API. Here the acting harness is cap-x's, ported onto the +[cap-harness engine](https://github.com/Infini-AI-Lab/hermit/tree/main/examples/cap_harness) (ASPIRE's robot +harness), and the library is the adapter. The paper synthesizes it once; the `continual` setting, which the paper does +not run, synthesizes it again after every step. + +CaP-Bench, CaP-Gym and CaP-RL, the paper's benchmark, environment suite and RL training, are not part of this port. + +## Setup + +```yaml +template: cap-agent0@1.0 # the skill library: skill_library.py +data: # one row per trial (rows.py): a task and one seed + {tasks: tasks, train: splits/train.txt, val: splits/val.txt, test: splits/test.txt, step_size: 50} +agent: + name: hermit.agent.evolver.methods.cap_agent0.actor:CapAgent0Actor + params: + engine: ../../cap_harness/utils/agent/sim.py # the engine the programs run on + model: fireworks/accounts/fireworks/models/glm-5p3-flash + multi_turn: true # cap-x's multi-turn loop, at most 10 regenerations + vdm: true # the Visual Differencing Module + ensemble: single # nine temperatures and a synthesis request +judge: {path: judge.py} # the engine's judge: the final program once more on the row's seed +evolver: + name: cap_agent0 + base: direct # the curation: one call of the run's model + model: {ref: fireworks/accounts/fireworks/models/glm-5p3-flash, effort: medium} + params: {setting: continual} # or paper +environment: {runner: host} # the actor starts the GPU simulator; every program runs in its sandbox +sandbox: {enabled: true, enforce: required} +``` + +The template is the library as cap-x's API module carries it: one Python file, `skill_library.py`, of top-level +functions with docstrings. The acting agent receives it through the template's context tool (`library`): the +functions' signatures and docstrings in cap-x's API documentation format (`ApiBase.combined_doc`), which follow the +engine's API reference in the prompt, as cap-x lists its synthesized functions among the API's +(`FrankaLiberoApiReducedSkillLibrary`); and their code, which runs before every program. The template has no +`ADAPTER.md`: the prompt is cap-x's. The engine prepends the library to every program, so the template's check refuses +what would stop them all: anything at the top level but functions (a docstring and `import math` first), a function the +engine's validator would refuse (only `import math`; no classes, `with`, `global`, `nonlocal`, `del`, `async`, or names +starting with `_`), code the engine's compile would refuse (`break` outside a loop, a repeated keyword argument; as +Python 3.10, the oldest ASPIRE runs on, so far as Hermit's parser tells newer grammar: not a 3.12 f-string that reuses +its quote or holds a backslash, nor `a[*b]`, which the Evolver leaves to the engine's own validator), a decorator or a +default that is not a literal (they run when the library is defined), a name the function neither binds nor finds in the +engine or the library, a name the engine owns, a missing docstring, privileged access, and a file past 60,000 bytes. No +existing template fits: `prompt-only` and `ace` are text the agent reads, `aspire`'s library is Markdown entries, and +none runs its content as code before the agent's own. + +## One trial + +The acting agent, `CapAgent0Actor`, is one trial of cap-x's `_run_single_trial` (capx/envs/trial.py) on one row (a +LIBERO-Pro task and a seed). It runs on the host (`environment.runner: host`): the engine needs the GPU, and runs each +program confined (its `sim.py` `confine`). Every model call is one `Direct` call. + +```{mermaid} +flowchart TD + P[probe program on the seed: the task's language, the reset frame] --> D{vdm} + D -->|yes| V0[VDM: describe the initial frame] + D -->|no| G + V0 --> G[initial program: one request, or the ensemble and its synthesis] + G --> X[turn k: the library and blocks 0..k replayed from the reset, each block in its own try] + X --> T{episode over, or single-turn} + T -->|yes| E[final program: the last turn's] + T -->|no| V[VDM: how the turn's last frame differs from the one before] + V --> Q[decision request: executed code, the block's stdout and stderr, the VDM's text] + Q -->|REGENERATE, under the limit| X + Q -->|FINISH, or the limit| E + E --> J[judge on the host: the final program once more on the seed] +``` + +1. **The initial frame.** A probe program reads the task's language (`get_task_context()`, the instruction cap-x + formats into `{libero_environment_goal}`) and opens the gripper once, so that the engine records the frame before + the first motion, which is the reset scene. +2. **The prompt.** cap-x's system message and LIBERO task prompt (env_configs/libero/franka_libero_cap_agent0.yaml), + then `APIs:` with the engine's API reference (its generated-program part) and the library's functions. With the + VDM, its description of the initial frame is appended to the first request. +3. **The initial program.** One request, or the parallel ensemble (`query_single_model_ensemble`, + `query_model_ensemble`): the candidates in parallel, failed ones left out, a synthesis request at temperature 0.2. + The code is the reply's fenced block (`_extract_code`). +4. **The turns.** The engine runs one program per episode, so turn k replays: the library and blocks 0..k from the reset + on the trial's seed (`--init-mode seeded`: a seed is one scene). Each block runs inside a `try` of its own, so that + an exception ends that block only, as each cap-x turn is one `exec` of its block in the episode's namespace. Markers + split the run's stdout into each block's. A block the engine's validator refuses, or that does not compile (a + `return` outside a function), is left out and the refusal is its stderr. After each turn the model reads cap-x's + multi-turn prompt (the executed code, the newest block's stdout and stderr), the VDM's description of the difference + between the newest two frames, and cap-x's decision instructions (`_build_multi_turn_decision_prompt`), and answers + REGENERATE with new code or FINISH (`_parse_multi_turn_decision`), at most ten regenerations after the first block + (`MULTITURN_LIMIT`). A turn whose episode ended (the task done, the environment terminated or truncated, the step + limit) ends the loop, as cap-x's "terminated episode" does. +5. **The score.** The final program (the library and the executed blocks) is the one the engine's judge runs once + more on the row's seed. The model never sees that score. A rerun that ran no episode (an infrastructure end: no + termination reason, `harness_error`, `user_interrupt`), or a refusal of the program the trial itself ran, is the + judge's failure and the row a judge error (`judge_error`), not a 0: the engine's judge counts `task_success` alone + (examples/libero/cap_agent0/judge.py). The program runs inside cap-harness's own process, so the engine's caveat + holds: one that escaped ASPIRE's validator could write its own run's outcome, and its sandbox keeps it from + anything else ([the engine](https://github.com/Infini-AI-Lab/hermit/tree/main/examples/cap_harness)). The actor's + own last run is its `output`; each turn records whether its replay reached the previous turn's last frame unchanged + (`replay_matches`; null when there was no frame to compare), which a perception or planning service that is not + deterministic can break. + +## The step + +The Evolver is cap-x's library compile (scripts/skill_library_compilation/) at each synthesis. + +```{mermaid} +flowchart TD + R[the step's trial records: code and judge score] --> C[pool: each successful trial's code, by experiment] + C --> S{paper: the epoch's last step? continual: every step} + S -->|no| K0[library unchanged] + S -->|yes| F[functions.txt per experiment: compile_successful_functions] + F --> A[pooled by name, filtered: parse_functions_file, filter_functions, min_occurrences] + A -->|none recurs| K0 + A --> M[run's model: SKILL_LIBRARY_PROMPT with the list, then the engine's rules] + M --> L[the reply's python functions, each kept if the template's check takes it with the others] + L --> W[skill_library.py, check_spec] + W -->|continual| V[run_agent on the validation trials] + V --> B[finalize: the best validation mean, the starting library included] + W -->|paper| Z[finalize: the library] +``` + +1. The step's records go into the pool in the Training State (`state/cap_agent0.json`): each trial the judge scored at + `success_score` or above, its code (`_annotate_code_blocks`, every generated block) under its experiment (the acting + model on one task, as cap-x's outputs///). +2. A synthesis writes each experiment's `functions.txt` (`compile_successful_functions`: the top-level `def`s the + regular expression finds in the successful trials' code), reads them back and pools them by name + (`parse_functions_file`, `collect_all_functions`'s loop), and filters them (`filter_functions`: at least + `min_occurrences` trials, three lines, no task-specific name). With nothing left the library stays, as cap-x's + compile stops there. +3. The run's model gets `SKILL_LIBRARY_PROMPT` with the list (`format_functions_for_prompt`, most frequent first), and + after it the engine's rules (`prompts.ENGINE_RULES`, ours), with `max_tokens` 20,480 (cap-x sends none). Every + top-level function of the reply's Python blocks (` ```python `, ` ```py ` or bare), the first of each name, as + written (its decorators, which the check refuses, and its type hints, which it does not: the engine compiles a + program with `from __future__ import annotations` and never evaluates one), is kept if the template's check accepts + it together with the others (a function that calls one left out goes too), in the reply's order, as long as the + library stays within 60,000 bytes (past them the last function goes, and the rest are checked again), and, with + `params.engine` named (the configs name the engine's `sim.py`, and `aspire_root`), as long as the engine's own + validator takes it, on the benchmark venv's Python (it is asked about each function when it refuses the library, and + those it refuses go): ASPIRE runs on Python 3.10 to 3.12, and the template's check, on Hermit's, cannot tell all that + 3.10 refuses. A curation is tried once more when its call fails, its reply was cut off (`finish_reason` `length`, or + a last block left open) or none of its functions is kept; a second failure fails the step and the library stays as it + was. The released code stops at the curated text (the paper calls the pipeline automated, and the API module of nine + functions is not made by the code); this step is ours. +4. `skill_library.py` is written whole and checked with `check_spec`; a library that fails it is not kept. +5. `continual`: the library is scored on the validation trials (`run_agent`; the starting library once, at the first + step), and `finalize` keeps the best validation mean (a tie: the later library). `paper`: the synthesis runs once, + at the epoch's last step, and `finalize` keeps it. + +## The two settings + +| | `paper` (the paper's pipeline) | `continual` (ours) | +|---|---|---| +| Training rollouts | the collection: the single-turn, low-level tier with no VDM, no ensemble and no library (the paper names its S3 rollouts, whose documentation adds usage examples; cap-x's compile pools the S3 and S4 experiments; the engine's API reference has no usage examples, as S4); each collection row sets `multi_turn: false`, `vdm: false`, `ensemble: none` itself | CaP-Agent0 with the library as it stands | +| Syntheses | one, at the epoch's last step, over every collected success | one after every step, over every success so far | +| Selection | none | the best validation mean among the starting library and every step's | +| Test | `eval --adapter final`: CaP-Agent0 with the library, frozen | the same | + +Both are train / test splits: the library is learned on the training trials and evaluated frozen on test trials whose +seeds no training or validation trial uses ([the splits](https://github.com/Infini-AI-Lab/hermit/tree/main/examples/libero/cap_agent0#the-splits)). +What the learner sees is the successful trials' code, as cap-x's compile reads it; whether a trial succeeded is the +judge's score on its own seed, the label cap-x's `task_completed` is. + +## Parameters + +```{literalinclude} ../../hermit/agent/evolver/methods/cap_agent0/evolver.yaml +:language: yaml +``` + +The actor's settings (`agent.params`): `engine` (the engine's `sim.py`), `aspire_root` (an ASPIRE checkout with the +benchmark's venv), `sim_env` (default the launcher's `ASPIRE_SIM_ENV`), `model`, `effort`, `temperature` (1.0), +`max_tokens` (20,480: cap-x's defaults), `multi_turn`, `multiturn_limit` (10), `vdm`, `vdm_model` and `vdm_effort` +(default the acting model's), `ensemble` (`none`, `single`: `ensemble_temperatures`, default 0.1 to 0.9; `multi`: +`ensemble_models`, a list of `{model, temperatures}`, and `synthesis_model`), `synthesis_temperature` (0.2), +`decision_prompt` (`upstream` or `initial`, below), `max_steps` (8,000), `run_timeout_s`, `unserved_retries`, +`stdout_chars`, `keep_runs`, `keep_images` (default true: a trial's initial frame and each turn's last, which the VDM +compares when it is on, stay in its log; false removes them when the trial ends, as `paper.yaml` and `continual.yaml` +set it), `scratch` and `logs`. A row's own `multi_turn`, `vdm` and `ensemble` win +over them. + +## The authors' implementation against this one + +The robot code of cap-x cannot be imported: its trial loop's modules import torch, SAM 3, Ray, Open3D and JAX at +package import, `capx/utils/launch_utils.py` sets the process-wide multiprocessing start method when imported, its +client retries a failed request without end, and the library compile is a script outside the installed package. The +pure functions the port calls are copied verbatim, pinned to acac62f +([upstream/](https://github.com/Infini-AI-Lab/hermit/tree/main/hermit/agent/evolver/methods/cap_agent0/upstream), +MIT): `_extract_code`, `_build_multi_turn_decision_prompt`, `_parse_multi_turn_decision`, +`collapse_text_image_inputs`, `_annotate_code_blocks`, the compile's regular expressions, +`compile_successful_functions`, `parse_functions_file`, `filter_functions`, `format_functions_for_prompt`, +`SKILL_LIBRARY_PROMPT`. The prompt texts are verbatim in `prompts.py`, each with its source; the tests compare them, +and the copies, with a cap-x checkout. + +| Dimension | CaP-Agent0 (the paper; capgym/cap-x at acac62f) | This port | Why | +|---|---|---|---| +| Robot environment | CaP-Gym's LIBERO-PRO (`FrankaLiberoEnv`), cap-x's API classes and servers | the cap-harness engine with LIBERO-Pro (ASPIRE's harness at fa00f0e): its API, its SAM3, Contact-GraspNet, PyRoki and cuRobo services, each program in a bubblewrap sandbox | forced by the task: the existing robot environment | +| The API | `FrankaLiberoApiReducedSkillLibrary`: the reduced low-level API and the nine synthesized functions (numpy) | the engine's API reference (its generated-program tools, LIBERO's extension, the constructors) and the learned library, in cap-x's `combined_doc` format | forced by the environment; the nine functions use numpy | +| Program rules | any Python, numpy imported explicitly | the engine's validator: only `import math`, no classes, `with`, `global`, `nonlocal`, `del`, `async` or `_` names; the task prompt's last line says so instead of cap-x's numpy line | forced; the one adapted line of the acting prompt | +| Initial state | trial t is LIBERO's saved initial state t − 1 | seed s is a scene LIBERO samples (`--init-mode seeded`) | forced: the engine's saved mode fails at its pinned commit (NVlabs/ASPIRE#31) | +| Turns | one persistent episode and namespace, one `exec` per block | a replay of the library and blocks 0..k from the reset per turn, each block in its own `try`; a refused block left out, its refusal as stderr | forced: the engine runs one program per episode | +| stdout and stderr | the block's stdout and traceback | the block's stdout (its last `stdout_chars`) and its exception as a traceback's last line names it | the engine gives a program no traceback | +| The loop's end | "terminated episode" in stderr | a turn whose episode ended: the task done, terminated, truncated, the step limit | the engine reports it as the run's termination reason | +| The VDM's frames | `env.render()` after the reset and after each turn | the engine's keyframes of `agentview`: the probe's first frame, each turn's last one (a motion that raised, or that the step limit cut, recorded only its `before-` frame: the VDM then sees the scene from before it) | the engine records keyframes around motion calls | +| Decision requests | built from the environment's own prompt: `{libero_environment_goal}` unformatted, no initial description | the same (`decision_prompt: upstream`); `initial` starts them from the first request instead | upstream's behaviour kept; the option is ours | +| The goal | formatted into the whole first text | into the task prompt alone | the engine's API reference holds braces | +| Ensemble | the paper's +3M: Gemini-3-Pro, GPT-5.2, Claude Opus × three temperatures; the code's `ENSEMBLE_CONFIGS`: gpt-5.4 × 0.1, 0.5, 0.9, synthesis gpt-5.4; single-model: nine temperatures | `single` (nine temperatures of the acting model, which also synthesizes) by default; `multi` with `ensemble_models`; candidates in their configured order, not their completion order | a decision: one model on the first evaluation's row | +| VDM model | Gemini-3-Pro (paper), gemini-3.1-pro-preview (code) | `vdm_model`, default the acting model | the first evaluation's row | +| Acting model | the paper's models; temperature 1.0, 20,480 tokens, effort medium (cap-x's defaults) | GLM 5.3 Flash with cap-x's defaults | the first evaluation's row | +| Reasoning effort | `reasoning_effort` sent to GPT models only (medium by default); other models get none | `effort` (medium) sent to the run's model, GLM 5.3 Flash included, on every call (code, VDM, ensemble, curation) | one setting for every call of the first evaluation's row | +| Failed requests | retried without end | the client's retries, then `unserved_retries` with pauses, then the trial fails: an error row, which `hermit eval` counts in `errors` and as 0 in `mean_score` | an outage must not stall a run | +| Score | the trial's own `task_completed` | the engine's judge: the final program once more on the seed; a rerun that ran no episode, or that refused the program the trial ran, is a judge error, not a 0; the actor's own success is `output` | the existing environment's judge | +| Synthesis input | the paper: successful S3 rollouts (the low-level API with usage examples) of 12 models on 7 Robosuite tasks; the code (`is_reduced_api_experiment`) and its shipped LIBERO library: the S3 and S4 experiments (`_reduced_api`, `_reduced_api_exampleless`) | the successful trials of one acting model on LIBERO's four suites: the single-turn, low-level tier on the engine's API reference, which has no usage examples (as S4; `paper`), or CaP-Agent0 (`continual`) | the request: training on LIBERO-Pro; examples for the engine's API would be ours | +| Extraction | each trial's summary.txt (its code and its log) | each trial's annotated code alone | a log's text is not code | +| Curation | `SKILL_LIBRARY_PROMPT` to Gemini-3.1-Pro (no `max_tokens`); the released code stops at the curated text | the prompt verbatim with the engine's rules after it, to the run's model with `max_tokens` 20,480; the reply's functions, as written and checked, become the library; a reply cut off or with none kept is tried once more | the step from the text to a module is not in the code; the rules are the engine's; an endpoint's default may cut the reply short | +| When learning happens | one synthesis pass ("inherently iterative") | `paper`: once, at the epoch's end; `continual`: after every step of fifty trials | `continual` is the setting the request adds | +| The update | a new library | the library rewritten whole; the template's check per function and `check_spec` on the result | — | +| Selection | none | `paper`: none; `continual`: the best validation mean (sixty trials) of the starting and every step's library | ours | +| Not ported | — | CaP-Bench, CaP-Gym, CaP-RL; video differencing, the wrist camera and images in the decision request (off in the CaP-Agent0 config); `evolve_skill_library` (capx/skills/: functions recorded from successful trials, which nothing at acac62f reads back into a prompt); the web UI | the request's scope; off in the authors' configuration | + +## The first evaluation + +Pending: the configs are written and the smoke is the next step. The row, on the trials above: + +| Setting | Value | +|---|---| +| Acting model | GLM 5.3 Flash (`fireworks/accounts/fireworks/models/glm-5p3-flash`), effort medium; also the VDM and the ensemble's synthesis | +| Learning model | GLM 5.3 Flash, effort medium | +| Harness | `CapAgent0Actor` on the cap-harness engine (ASPIRE fa00f0e), LIBERO-Pro, `--init-mode seeded`, 8,000 steps | +| Starting adapter | the empty library | +| Data | `collect` or `train` 200 trials, `val` 60, `test` 3,000 (`test_sample` 300) | +| Evaluation | the test split, one pass; the judge's success rate: `mean_score` with `errors` beside it (rows the agent or the judge failed, which `mean_score` counts as 0), and the rate over the scored rows | +| Baselines | `--adapter root` (CaP-Agent0 without a library), the single-turn tier (`agent.params.multi_turn=false agent.params.vdm=false agent.params.ensemble=none`) | + +## What it is not + +The scores are not Table 2's: the trials are seeded scenes, not LIBERO's saved states, the model is not the paper's, +and the library is learned on LIBERO's own suites, where the paper's came from CaP-Bench's Robosuite tasks. The +acting harness is fixed: VDM, ensemble and multi-turn loop are cap-x's and nothing learns them. A replayed turn +reaches the state the model saw only where the engine's services are deterministic; `replay_matches` says where they +were not. In `continual` the library is selected on the test's own sixty tasks (at a seed of their own) by the best +of several means, so its test score is optimistic beside `paper`'s one library. + +## Example + +[`examples/libero/cap_agent0/`](https://github.com/Infini-AI-Lab/hermit/tree/main/examples/libero/cap_agent0): +LIBERO-Pro, both settings, their splits and smoke configs. diff --git a/docs/methods/index.md b/docs/methods/index.md index 9bc3f910..83a0122c 100644 --- a/docs/methods/index.md +++ b/docs/methods/index.md @@ -23,6 +23,7 @@ template–method combinations meaningful. | 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, Claude Code or Pi), verifier task rows in `data.val`, an acting agent that delivers the adapter | +| Synthesize a library of helper functions from the functions that recur in successful robot programs, for a multi-turn coding agent with visual differencing and a parallel ensemble | [CaP-Agent0](cap_agent0.md) | `cap-agent0@1.0` | The run's `llm`, the cap-harness engine on the host, one task row per trial; validation trials for the `continual` setting | 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. @@ -48,6 +49,7 @@ task-specific service overhead. Call counts vary with evidence, candidates, and | ReHarness | Per instance, one reflection call, one revision call per retrieved reflection (up to k) and one embedding call; no candidate rollouts or validation | Reflection bank in the adapter; source trajectories and per-instance retrieval and revision records in `state/` | Current adapter: the bank after the last instance | | Meta-Harness Adapter | One proposer session per round writing k candidates; each candidate is a full rollout of the search set, one step per candidate | Every candidate's files, hypothesis, base and per-task scores in `state/` | Best mean on the search set | | ASPIRE | Per task, one coordinator session and, when it proposes entries, a verifier rollout (a fresh actor on the task's verifier row) | The coordinator's curriculum and changelog notes in `state/` | Current adapter: the library after the last task | +| CaP-Agent0 | Per synthesis (`paper`: once, at the epoch's end; `continual`: every step), one curation call; `continual` also runs the new library on every validation trial | `state/cap_agent0.json` (the pool of successful trials' code, each synthesis's record) and every library in `state/libraries/` | `paper`: the library; `continual`: the best validation mean, the starting library included | | RRSI Adapter | Per round: the analyst with a digester per rendered trace (a session per turn), m proposer sessions with the critic's review and repairs, a smoke on the domain's smoke tasks per screened candidate; each candidate is a full rollout of the evolve set (k rows per task), one step per candidate | Every candidate's files and digest, the edit history, the attribution and the frontier in `state/` (upstream's files under `state/rrsi/`) | The incumbent H_T, admitted above the noise floor and within the cost rule | `use_gate: false` in SkillOpt removes the ordinary improvement requirement, **not** the validation calls. diff --git a/examples/libero/.gitignore b/examples/libero/.gitignore index 62859799..61f7fad0 100644 --- a/examples/libero/.gitignore +++ b/examples/libero/.gitignore @@ -2,3 +2,6 @@ runs/ # ASPIRE's tasks and splits, written by aspire/tasks.sh at launch aspire/tasks/ aspire/splits/ +# CaP-Agent0's trial rows and splits, written by cap_agent0/tasks.sh at launch +cap_agent0/tasks/ +cap_agent0/splits/ diff --git a/examples/libero/README.md b/examples/libero/README.md index 64f8f7dd..7becdae4 100644 --- a/examples/libero/README.md +++ b/examples/libero/README.md @@ -17,6 +17,7 @@ on held-out seeds by the task's own success check. | `utils/launch.sh` | Starts a method folder's run: the simulator service and hermit | | [`aspire/`](aspire/) | The ASPIRE method (its session's task functions, verifier and coordinator are ASPIRE's own; `tasks.sh` adds its verifiers to the tasks). `run.yaml` (Object, Spatial, Goal, Long: 40 tasks), `run_90.yaml` (LIBERO-90), `run_pro.yaml` (LIBERO-Pro: 80), `run_pro_long.yaml` (LIBERO-Long-Pro), `run_luna.yaml` (`run.yaml` on Luna), `run_sample_luna.yaml` (six of the forty on Luna, for a run of a day or two), `smoke*.yaml`, `launch.sh` | | [`prompt_only/`](prompt_only/) | The prompt-only template: one `ADAPTER.md` the built-in Codex Evolver revises after each task, with the method-neutral prompt. `run.yaml`, `run_pro.yaml`, `smoke.yaml`, `smoke_luna.yaml`, `launch.sh` | +| [`cap_agent0/`](cap_agent0/) | CaP-Agent0 (CaP-X): its own acting agent on the engine (the multi-turn loop with visual differencing and the parallel ensemble) and the `cap_agent0` Evolver's skill library; one task row per trial (`rows.py`). `paper.yaml` (the paper's pipeline: the single-turn collection, one synthesis, CaP-Agent0 on the test), `continual.yaml` (ours: a synthesis after every step, validation-based selection), `smoke_*.yaml`, `launch.sh` | The `*_luna.yaml` configs run GPT-5.6-Luna on the machine's ChatGPT login; the others GLM 5.3 Flash on Fireworks. diff --git a/examples/libero/cap_agent0/README.md b/examples/libero/cap_agent0/README.md new file mode 100644 index 00000000..313559bb --- /dev/null +++ b/examples/libero/cap_agent0/README.md @@ -0,0 +1,100 @@ +# LIBERO-Pro with CaP-Agent0 + +[CaP-Agent0](https://capgym.github.io/) (CaP-X, Fu et al., [arXiv:2603.22435](https://arxiv.org/abs/2603.22435); +[code](https://github.com/capgym/cap-x)), the paper's training-free coding agent for robot control, on LIBERO-Pro in +the [cap-harness engine](../../cap_harness/): multi-turn code generation with the Visual Differencing Module (VDM), +the parallel ensemble, and the automatically synthesized skill library, which the +[`cap_agent0`](../../../docs/methods/cap_agent0.md) Evolver writes. One task row is one trial: a task and one seed. + +Two settings, on the same trials: + +| | `paper.yaml`: the paper's pipeline | `continual.yaml`: our continual setting | +|---|---|---| +| Training rollouts | the collection (`splits/collect.txt`): the single-turn, low-level tier, no VDM, no ensemble, no library (the paper names its S3 rollouts, with usage examples in the API's documentation, and cap-x's compile pools S3 and S4; the engine's has no examples, as S4) | CaP-Agent0 with the library as it stands (`splits/train.txt`) | +| The library | synthesized once, at the epoch's end, from the collection's successful trials | synthesized again after every step of fifty trials, from every successful trial so far | +| Selection | none: the one library | the best validation mean of every step's library and the starting one (`splits/val.txt`, run only by the Evolver) | +| Test | `eval --adapter final`: CaP-Agent0 with the library, frozen (`splits/test.txt`) | the same | + +The library is frozen at test time in both. The paper synthesizes its library once from S3 rollouts (cap-x's compile +takes S3 and S4) on CaP-Bench's Robosuite tasks, pooled across twelve models, and calls the process "inherently +iterative"; the continual setting is that iteration, and is ours. A trial the agent or the judge failed (an outage, a +rerun that ran no episode) is an error row, never pooled and run again in validation; `hermit eval` counts it in +`errors` and as 0 in `mean_score`. + +## The splits + +`rows.py` (run by `tasks.sh` before every launch) writes one row per trial from the benchmark's tasks +(`../utils/benchmark/prepare.py`). The seed sets never meet: a test seed is never run before the test. + +| Split | Trials | Suites | Seeds | Run by | +|---|---|---|---|---| +| `collect` | 200 | `libero_object`, `libero_spatial`, `libero_goal`, `libero_10` (unperturbed; 40 tasks) | 51-55 | `paper.yaml`'s training rollouts (the rows carry the single-turn tier) | +| `train` | 200 | the same 40 tasks | 51-55 | `continual.yaml`'s training rollouts | +| `val` | 60 | the six test suites (60 tasks) | 66 | `continual.yaml`'s Evolver | +| `test` | 3,000 | `libero_{object,spatial,goal}_{swap,task}`: Table 2's Pos and Task perturbations of Object, Spatial and Goal (60 tasks) | 1-50 | `eval` | +| `test_sample` | 300 | the same 60 tasks | 1-5 | `eval`, a cheaper look (rows of `test`) | +| `test_long` | 1,000 | `libero_10_swap`, `libero_10_task` (LIBERO-Long-Pro, beyond Table 2) | 1-50 | `eval` | + +The `*_smoke` splits are two collection and two training trials (`libero_object` and `libero_spatial` task 0, seed +51), one validation trial (`libero_object_swap` task 0, seed 66) and two test trials (`libero_object_swap` and +`libero_object_task` task 0, seed 1). + +The validation trials are the test's 60 tasks on a seed of their own (66): `continual.yaml` selects its library on +the perturbations it is tested on, never on a test trial, and the Evolver sees only their scores, not their +trajectories. + +The seeds are `rows.py`'s own (`--train-seeds`, `--val-seeds`, `--test-seeds`, `--sample-seeds`; `tasks.sh` passes +none, so the ones above), and it refuses sets that meet. `ASPIRE_SEEDS` and `ASPIRE_EVAL_SEEDS` change only the +benchmark's own task rows, which these trials do not read. + +A seed is a scene LIBERO samples (the engine's `--init-mode seeded`), not one of the fifty saved initial states the +paper's trials use (cap-x maps trial `t` to saved state `t - 1`), so a success rate here is not comparable with +Table 2's; [the engine and the protocol](../README.md#the-engine-and-the-protocol) say why. The judge runs each trial's +final program once more on its seed; the actor's own last run is its `output`, and the two can differ where a +perception or planning service is not deterministic (each turn records `replay_matches`). + +## Run + +As [ASPIRE's](../README.md#setup): an ASPIRE checkout at the pinned commit with `.venv-libero`, its SAM3, PyRoki, +cuRobo and Contact-GraspNet services up, and `FIREWORKS_API_KEY` for GLM 5.3 Flash. From this folder: + +```bash +export ASPIRE_ROOT=/path/to/ASPIRE FIREWORKS_API_KEY=... ASPIRE_SIM_GPU=0 +ASPIRE_CONFIG=smoke_paper.yaml ./launch.sh # the paper's pipeline, two trials +ASPIRE_CONFIG=smoke_paper.yaml ./launch.sh eval --adapter final # its two test trials +ASPIRE_CONFIG=smoke_continual.yaml ./launch.sh # ours, two trials and one validation trial + +ASPIRE_CONFIG=paper.yaml ./launch.sh # collect, then synthesize once +ASPIRE_CONFIG=paper.yaml ./launch.sh eval --adapter final # CaP-Agent0 with the library on the test split +ASPIRE_CONFIG=paper.yaml ./launch.sh eval --adapter root # the same without a library +ASPIRE_CONFIG=continual.yaml ./launch.sh # ours +ASPIRE_CONFIG=continual.yaml ./launch.sh eval --adapter final +ASPIRE_CONFIG=paper.yaml ./launch.sh eval --adapter final data.test=splits/test_sample.txt # seeds 1-5 only +``` + +`ASPIRE_OUT` puts the runs on a large disk (default `../runs`). The two settings' runs are apart +(`trainer.run_name`, and the launcher's tree per config). The smoke configs use three ensemble temperatures, two +regenerations and `min_occurrences: 1`; the code path is the run's. + +A trial is a probe episode, one episode per turn (a turn replays the blocks before it) and the judge's episode; +CaP-Agent0's default ensemble sends nine candidate requests and a synthesis per turn, with the VDM's one image +request. A run's `budget` bounds its training and validation; `eval` has none of its own. + +## What to read after the smoke + +In `$ASPIRE_OUT/actor-logs/-/` (also each step's `trajectories/` in the learning material): + +- `prompt.json`: the first request (the task prompt, the engine's API reference and the library's functions, then + the VDM's description of the initial frame) and the text the decision requests start from; +- `trial.json`: each turn's stdout and stderr, termination reason, `replay_matches` and decision, the VDM's + descriptions, and every ensemble candidate; +- `programs/turnNN.py`: what each turn ran (the library, then each block in its `try`); `code.py`: the blocks as + the synthesis reads them; +- `images/`: the initial frame and each turn's last frame (up to twelve a trial; the VDM compares them when it is on). + The smokes keep them; `paper.yaml` and `continual.yaml` set `agent.params.keep_images: false`, which removes them + when the trial ends (a test split is thousands of trials); `agent.params.keep_images=true` keeps them. + +In the run's step directories: `output/skill_library_raw.txt` (the pooled, filtered functions), `output/prompt.md` +(the curation request), `output/skill_library.attemptN.txt` (each reply) and `output/skill_library.txt` (the one +kept), the step's `extra.record` (what was kept, why the others were left out, each attempt) and the adapter's +`skill_library.py`. diff --git a/examples/libero/cap_agent0/continual.yaml b/examples/libero/cap_agent0/continual.yaml new file mode 100644 index 00000000..6c749855 --- /dev/null +++ b/examples/libero/cap_agent0/continual.yaml @@ -0,0 +1,60 @@ +# CaP-Agent0 on LIBERO-Pro in our continual setting (not the paper's): CaP-Agent0 (multi-turn with the VDM and the +# parallel ensemble) acts on the four LIBERO suites, seeds 51-55 (splits/train.txt), fifty trials a step in a +# shuffled order; after every step the library is synthesized again from every successful trial so far and scored on +# the validation trials (splits/val.txt: the six test suites on seed 66, run only by the Evolver), and the run keeps +# the library that scored best there (the starting, empty one included). `./launch.sh eval --adapter final` then +# runs it, frozen, on the paper's LIBERO-PRO set (splits/test.txt, seeds 1-50), as paper.yaml's eval does. +# Started by launch.sh: ASPIRE_CONFIG=continual.yaml ./launch.sh. +data: + tasks: tasks # CaP-Agent0's trial rows (tasks.sh, rows.py) + view: ../../cap_harness/utils/agent/fields.py:task_row # each task as the row it always was + train: splits/train.txt + val: splits/val.txt + test: splits/test.txt + step_size: 50 # four steps, four syntheses + shuffle: true # the suites mixed in every step + shuffle_seed: 0 +task_info: ../utils/benchmark/task-info +agent: + name: hermit.agent.evolver.methods.cap_agent0.actor:CapAgent0Actor + concurrency: 4 # trials at a time, each one simulator episode after the other + params: + engine: ../../cap_harness/utils/agent/sim.py # the engine the programs run on (ASPIRE's harness) + aspire_root: $ASPIRE_ROOT # an ASPIRE checkout with .venv-libero (launch.sh) + model: fireworks/accounts/fireworks/models/glm-5p3-flash + effort: medium # cap-x's reasoning_effort default + temperature: 1.0 # cap-x's default for a single request and the VDM + max_tokens: 20480 # cap-x's default + multi_turn: true + multiturn_limit: 10 # cap-x MULTITURN_LIMIT + vdm: true + vdm_model: null # null: the acting model (the paper's VDM is Gemini-3-Pro) + ensemble: single # nine temperatures of the acting model and a synthesis (the paper's +1M) + decision_prompt: upstream # the decision requests as cap-x builds them (docs/methods/cap_agent0.md) + max_steps: 8000 # cap-x's LIBERO CaP-Agent0 config + keep_images: false # a test split is thousands of trials: each one's frames go when it ends +judge: + path: judge.py # the engine's judge on the row's seed, its images pruned +template: cap-agent0@1.0 +evolver: + name: cap_agent0 + base: direct # the curation: one call of the run's model + model: {ref: fireworks/accounts/fireworks/models/glm-5p3-flash, effort: medium} + params: + setting: continual + engine: ../../cap_harness/utils/agent/sim.py # each library checked by the engine's own validator + aspire_root: $ASPIRE_ROOT # on its venv's Python (ASPIRE runs on 3.10 to 3.12) + select: validation +environment: + runner: host # the actor starts the GPU simulator itself; each program runs in its sandbox +sandbox: + enabled: true + enforce: required +trainer: + run_name: cap-agent0-continual + epochs: 1 + call_timeout_min: 1440 # a step: the curation and sixty validation trials (step 1: also the starting + # library's sixty) + budget: {usd: 600, hours: 240} +eval: + repeats: 1 diff --git a/examples/libero/cap_agent0/judge.py b/examples/libero/cap_agent0/judge.py new file mode 100644 index 00000000..74df60ea --- /dev/null +++ b/examples/libero/cap_agent0/judge.py @@ -0,0 +1,104 @@ +"""The engine's judge (../../cap_harness/utils/benchmark/judge.py) for CaP-Agent0's trial rows: its score, unless its +rerun did not judge the program, and each scored run's images removed afterwards. + +- A rerun that ran no episode (an infrastructure end, the actor's INFRA: no termination reason, `harness_error`, + `user_interrupt`, or no run directory), or a refusal of the program the trial itself ran (the trial's turns ran it + in the same engine), is the judge's failure, not the program's: it raises, and the Trainer records the row as a + judge error (`judge_error`) instead of a score of 0. The engine's judge counts only `task_success` and would score + such a rerun 0 with status ok: a successful trial would then leave the paper setting's pool, and a validation + run would count as a real 0 rather than be run again. +- A row is one episode and a test split thousands of them, and an episode's keyframes are tens of megabytes: the + scores, the records and the traces stay, and each run's `media/` goes: every run folder of the rerun (ASPIRE writes + a run as ///, and leaves the folder of a run it lost with no record) and every run + directory its stage2.json records. Only a real directory inside the rerun's own folder is removed, reached through + no link: the confined program could write links there, and the engine's removal of them may have failed (the + judge then raised, with no stage2.json written). CAP_AGENT0_KEEP_MEDIA=1 keeps the images.""" +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import shutil + +ENGINE_JUDGE = Path(__file__).resolve().parents[2] / "cap_harness" / "utils" / "benchmark" / "judge.py" +_spec = importlib.util.spec_from_file_location("_cap_engine_judge", ENGINE_JUDGE) +engine_judge = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(engine_judge) + +INFRA = (None, "harness_error", "user_interrupt") # hermit/agent/evolver/methods/cap_agent0/actor.py INFRA + + +def score(task: dict, output) -> dict: + stage2 = Path(os.environ.get("ASPIRE_OUT", ".")).resolve() / "stage2" + try: + result = engine_judge.score(task, output) + why = not_judged(task, output, stage2) + if why: + raise RuntimeError(why) + return result + finally: + if os.environ.get("CAP_AGENT0_KEEP_MEDIA") != "1": + prune(task, output, stage2) + + +def rerun_folder(task: dict, output, stage2: Path) -> Path | None: + """Where the engine judge reran the trial's program (its stage2/-/), or None when it reran + nothing.""" + facts = (output.extra or {}).get("task") or {} + program = facts.get("fix_code") + if facts.get("not_scored") or not program or not engine_judge.sim.seeds_of(task.get("eval_seeds")): + return None # nothing was rerun: the engine judge's own 0 + return stage2 / f"{task['id']}-{hashlib.sha256(program.encode()).hexdigest()[:12]}" + + +def prune(task: dict, output, stage2: Path) -> None: + """The images of the rerun's runs: the `media/` of every run folder in its runs/// (links left + out) and of each run directory its stage2.json records, each one only if it is a real directory whose real path + is inside the rerun's folder.""" + folder = rerun_folder(task, output, stage2) + if folder is None: + return + inside = folder.resolve() + runs = [run for seed in _real_dirs(folder / "runs") for run in _real_dirs(seed)] + try: + records = json.loads((folder / "stage2.json").read_text()).get("records") or [] + runs += [Path(r["run_dir"]) for r in records if r.get("run_dir")] + except (OSError, ValueError, AttributeError, TypeError): + pass # no record (the judge raised first): the run folders alone + for media in dict.fromkeys(run / "media" for run in runs): + try: # a folder the program made unreadable is passed over + real = not media.is_symlink() and media.is_dir() and media.resolve().is_relative_to(inside) + except OSError: + continue + if real: + shutil.rmtree(media, ignore_errors=True) + + +def _real_dirs(path: Path) -> list[Path]: + """The directories in `path`, without following a link.""" + try: + with os.scandir(path) as entries: + return [Path(e.path) for e in entries if e.is_dir(follow_symlinks=False)] + except OSError: + return [] + + +def not_judged(task: dict, output, stage2: Path) -> str | None: + """Why the engine judge's rerun of the trial's program (its stage2.json) is no verdict on it, or None.""" + folder = rerun_folder(task, output, stage2) + if folder is None: + return None + try: + rerun = json.loads((folder / "stage2.json").read_text()) + except (OSError, ValueError) as exc: + return f"the judge's rerun left no record ({folder / 'stage2.json'}): {exc}" + if rerun.get("refused"): + return f"the engine refused, at judging, the program the trial ran: {str(rerun['refused'])[-600:]}" + failed = [r for r in rerun.get("records") or [] if r.get("termination_reason") in INFRA or not r.get("run_dir")] + if failed: + first = failed[0] + return (f"the judge's rerun ran no episode on seed {first.get('seed')} " + f"({first.get('termination_reason') or 'no termination reason'}): {str(first.get('error'))[-600:]}") + return None diff --git a/examples/libero/cap_agent0/launch.sh b/examples/libero/cap_agent0/launch.sh new file mode 100755 index 00000000..f23ff898 --- /dev/null +++ b/examples/libero/cap_agent0/launch.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# Train, or evaluate, CaP-Agent0 on LIBERO-Pro: ../utils/launch.sh with this folder's configs (its header gives the +# commands and variables). Name the config: the paper's pipeline (paper.yaml) or ours (continual.yaml), e.g. +# ASPIRE_ROOT=/path/to/ASPIRE ASPIRE_CONFIG=paper.yaml ./launch.sh +# ASPIRE_ROOT=/path/to/ASPIRE ASPIRE_CONFIG=paper.yaml ./launch.sh eval --adapter final +: "${ASPIRE_CONFIG:?set ASPIRE_CONFIG: paper.yaml, continual.yaml, smoke_paper.yaml or smoke_continual.yaml}" +export ASPIRE_CONFIG +exec "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/../utils/launch.sh" cap_agent0 "$@" diff --git a/examples/libero/cap_agent0/paper.yaml b/examples/libero/cap_agent0/paper.yaml new file mode 100644 index 00000000..d8ff7160 --- /dev/null +++ b/examples/libero/cap_agent0/paper.yaml @@ -0,0 +1,59 @@ +# CaP-Agent0 on LIBERO-Pro in the paper's own pipeline (CaP-X, arXiv:2603.22435, §4.1 and Table 2), in one run: +# 1. the collection: the single-turn, low-level tier (no VDM, no ensemble, no library; the paper's S3 rollouts, whose +# API documentation adds usage examples the engine's lacks, as cap-x's S4) on the four LIBERO suites, seeds 51-55 +# (splits/collect.txt; each row says the tier it runs); +# 2. one synthesis pass at the epoch's end over the collection's successful trials (evolver setting: paper); +# 3. `./launch.sh eval --adapter final`: CaP-Agent0 (multi-turn with the VDM and the parallel ensemble) with that +# library, frozen, on the paper's LIBERO-PRO set (splits/test.txt: Object, Spatial, Goal x Pos, Task; ten tasks +# each; seeds 1-50). `--adapter root` is the same without a library. +# GLM 5.3 Flash acts, describes and curates (the authors: Gemini-3-Pro and others; see docs/methods/cap_agent0.md). +# Started by launch.sh: ASPIRE_CONFIG=paper.yaml ./launch.sh. +data: + tasks: tasks # CaP-Agent0's trial rows (tasks.sh, rows.py) + view: ../../cap_harness/utils/agent/fields.py:task_row # each task as the row it always was + train: splits/collect.txt + test: splits/test.txt + step_size: 50 # the collection in four steps; the library is synthesized at the epoch's end + shuffle: false +task_info: ../utils/benchmark/task-info +agent: + name: hermit.agent.evolver.methods.cap_agent0.actor:CapAgent0Actor + concurrency: 4 # trials at a time, each one simulator episode after the other + params: + engine: ../../cap_harness/utils/agent/sim.py # the engine the programs run on (ASPIRE's harness) + aspire_root: $ASPIRE_ROOT # an ASPIRE checkout with .venv-libero (launch.sh) + model: fireworks/accounts/fireworks/models/glm-5p3-flash + effort: medium # cap-x's reasoning_effort default + temperature: 1.0 # cap-x's default for a single request and the VDM + max_tokens: 20480 # cap-x's default + multi_turn: true # CaP-Agent0: the test rows; a collection row sets the single-turn tier itself + multiturn_limit: 10 # cap-x MULTITURN_LIMIT + vdm: true + vdm_model: null # null: the acting model (the paper's VDM is Gemini-3-Pro) + ensemble: single # nine temperatures of the acting model and a synthesis (the paper's +1M) + decision_prompt: upstream # the decision requests as cap-x builds them (docs/methods/cap_agent0.md) + max_steps: 8000 # cap-x's LIBERO CaP-Agent0 config + keep_images: false # a test split is thousands of trials: each one's frames go when it ends +judge: + path: judge.py # the engine's judge on the row's seed, its images pruned +template: cap-agent0@1.0 +evolver: + name: cap_agent0 + base: direct # the curation: one call of the run's model + model: {ref: fireworks/accounts/fireworks/models/glm-5p3-flash, effort: medium} + params: + setting: paper + engine: ../../cap_harness/utils/agent/sim.py # each library checked by the engine's own validator + aspire_root: $ASPIRE_ROOT # on its venv's Python (ASPIRE runs on 3.10 to 3.12) +environment: + runner: host # the actor starts the GPU simulator itself; each program runs in its sandbox +sandbox: + enabled: true + enforce: required +trainer: + run_name: cap-agent0-paper + epochs: 1 # one collection, one synthesis + call_timeout_min: 60 # a synthesis: one curation call + budget: {usd: 100, hours: 72} +eval: + repeats: 1 diff --git a/examples/libero/cap_agent0/rows.py b/examples/libero/cap_agent0/rows.py new file mode 100644 index 00000000..3c411c7f --- /dev/null +++ b/examples/libero/cap_agent0/rows.py @@ -0,0 +1,120 @@ +"""CaP-Agent0's task rows on LIBERO-Pro: one row per trial (a task and one seed), from the benchmark's prepared tasks +(../utils/benchmark/prepare.py, which the engine's launcher runs first), written as task directories by the engine's +task writer (../../cap_harness/utils/benchmark/tasks.py) into tasks/ and splits/ here, which this folder's configs +read. tasks.sh runs it: + + python rows.py --benchmark ../utils/benchmark --out . + +A CaP-Agent0 trial is one episode on one seed (cap-x runs 50 trials per task, trial t on LIBERO's saved state t - 1): +the actor's multi-turn loop runs on the row's `seed`, and the judge runs the final program once more on that seed +(`eval_seeds`). The engine runs LIBERO-Pro with `--init-mode seeded`, so a seed is a scene LIBERO samples, not one of +LIBERO's fifty saved states (see ../README.md, "The engine and the protocol"). + +The splits (each set of seeds apart from the others: tasks a training row ran are never test rows): + +| split | rows | suites | seeds | runs it | +|---|---|---|---|---| +| collect | 200 | libero_object, _spatial, _goal, libero_10 (40 tasks) | 51-55 | paper.yaml: the single-turn tier | +| train | 200 | the same 40 tasks | 51-55 | continual.yaml: CaP-Agent0 | +| val | 60 | the six test suites (60 tasks) | 66 | continual.yaml's Evolver (run_agent) | +| test | 3000 | libero_{object,spatial,goal}_{swap,task} (Table 2) | 1-50 | eval | +| test_sample | 300 | the same 60 tasks | 1-5 | eval, a cheaper look (rows of test) | +| test_long | 1000 | libero_10_swap, libero_10_task (beyond Table 2) | 1-50 | eval: LIBERO-Long-Pro | + +and the smoke's: collect_smoke and train_smoke (libero_object and libero_spatial task 0, seed 51), val_smoke +(libero_object_swap task 0, seed 66), test_smoke (libero_object_swap and libero_object_task task 0, seed 1). + +A row: {id, benchmark, suite, task_id, seed, eval_seeds, score_label, role} and, for a collection row, the actor's +settings it runs with (multi_turn, vdm, ensemble), which win over agent.params. +""" +from __future__ import annotations + +import argparse +from pathlib import Path +import shutil +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[1] / "cap_harness" / "utils" / "benchmark")) +from tasks import rows as task_rows, write_task # noqa: E402 +sys.path.insert(0, str(HERE.parents[1] / "cap_harness" / "utils" / "agent")) +from sim import seeds_of # noqa: E402 + +TRAIN_SUITES = ("libero_object", "libero_spatial", "libero_goal", "libero_10") +TEST_SUITES = tuple(f"libero_{family}_{kind}" for family in ("object", "spatial", "goal") for kind in ("swap", "task")) +LONG_SUITES = ("libero_10_swap", "libero_10_task") +# The single-turn, low-level tier the paper's library was synthesized from (its S3, by the paper; S3 and S4 in cap-x's +# compile; the engine's API reference has no usage examples, as S4): no VDM, no ensemble, no library +COLLECT = {"multi_turn": False, "vdm": False, "ensemble": "none"} +DEFAULTS = {"train": "51-55", "val": "66", "test": "1-50", "sample": "1-5"} + + +def trial(task: dict, seed: int, *, prefix: str = "", role: str, **settings) -> dict: + return {"id": f"{prefix}{task['id']}-s{seed:03d}", "benchmark": task.get("benchmark") or "libero-pro", + "suite": task["suite"], "task_id": int(task["task_id"]), "seed": seed, "eval_seeds": str(seed), + "score_label": "trial", "role": role, **settings} + + +def text(row: dict) -> str: + how = "the single-turn tier (the paper's collection)" if row.get("multi_turn") is False else "CaP-Agent0" + return (f"One CaP-Agent0 trial, {how}: libero-pro suite `{row['suite']}`, task id {row['task_id']}, " + f"seed {row['seed']}.") + + +def main(argv=None) -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--benchmark", type=Path, required=True, help="the benchmark's utils/benchmark (prepared)") + ap.add_argument("--out", type=Path, required=True) + for name, value in DEFAULTS.items(): + ap.add_argument(f"--{name}-seeds", default=value) + a = ap.parse_args(argv) + seeds = {name: seeds_of(getattr(a, f"{name}_seeds")) for name in DEFAULTS} + for one, other in (("train", "val"), ("train", "test"), ("val", "test")): + if set(seeds[one]) & set(seeds[other]): + ap.error(f"the {one} and {other} seeds overlap: {sorted(set(seeds[one]) & set(seeds[other]))[:10]}") + if not set(seeds["sample"]) <= set(seeds["test"]): + ap.error(f"the sample's seeds must be test seeds: {sorted(set(seeds['sample']) - set(seeds['test']))[:10]}") + benchmark = task_rows(a.benchmark / "tasks") + of = lambda *suites: [t for t in benchmark.values() if t["suite"] in suites and not t.get("rerun_of")] + missing = [s for s in (*TRAIN_SUITES, *TEST_SUITES, *LONG_SUITES) if not of(s)] + if missing: + raise SystemExit(f"{a.benchmark / 'tasks'} has no task of {', '.join(missing)}: run its prepare.py first") + order = lambda tasks: sorted(tasks, key=lambda t: (t["suite"], int(t["task_id"]))) + train_tasks = sorted(of(*TRAIN_SUITES), key=lambda t: (TRAIN_SUITES.index(t["suite"]), int(t["task_id"]))) + test_tasks = order(of(*TEST_SUITES)) + long_tasks = order(of(*LONG_SUITES)) + splits = { + "collect": [trial(t, s, prefix="collect-", role="collect", **COLLECT) for t in train_tasks + for s in seeds["train"]], + "train": [trial(t, s, role="train") for t in train_tasks for s in seeds["train"]], + "val": [trial(t, s, role="val") for t in test_tasks for s in seeds["val"]], + "test": [trial(t, s, role="test") for t in test_tasks for s in seeds["test"]], + "test_long": [trial(t, s, role="test") for t in long_tasks for s in seeds["test"]], + } + splits["test_sample"] = [r for r in splits["test"] if r["seed"] in set(seeds["sample"])] + first = lambda suite: next(t for t in train_tasks + test_tasks if t["suite"] == suite and int(t["task_id"]) == 0) + smoke_train = [first("libero_object"), first("libero_spatial")] + splits.update(collect_smoke=[trial(t, 51, prefix="collect-", role="collect", **COLLECT) for t in smoke_train], + train_smoke=[trial(t, 51, role="train") for t in smoke_train], + val_smoke=[trial(first("libero_object_swap"), 66, role="val")], + test_smoke=[trial(first(s), 1, role="test") for s in ("libero_object_swap", "libero_object_task")]) + rows = {r["id"]: r for split in splits.values() for r in split} + for name, one in (("collect", "train"), ("train", "val")): # ids are their split's alone, but test_sample + assert not {r["id"] for r in splits[name]} & {r["id"] for r in splits[one]} + tasks = a.out / "tasks" + if tasks.exists(): # this script's own output: rewritten whole + shutil.rmtree(tasks) + for row in rows.values(): + write_task(tasks, row, text(row)) + out = a.out / "splits" + if out.exists(): + shutil.rmtree(out) + out.mkdir(parents=True) + for name, split in splits.items(): + (out / f"{name}.txt").write_text("".join(f"{r['id']}\n" for r in split)) + print(f"{len(rows)} CaP-Agent0 trials -> {tasks}; splits: " + + ", ".join(f"{name} {len(split)}" for name, split in splits.items())) + + +if __name__ == "__main__": + main() diff --git a/examples/libero/cap_agent0/smoke_continual.yaml b/examples/libero/cap_agent0/smoke_continual.yaml new file mode 100644 index 00000000..f29c97f5 --- /dev/null +++ b/examples/libero/cap_agent0/smoke_continual.yaml @@ -0,0 +1,57 @@ +# The smoke of continual.yaml: two training trials (libero_object and libero_spatial task 0, seed 51) in one step, +# one validation trial (libero_object_swap task 0, seed 66), then `./launch.sh eval --adapter final` on two test +# trials (libero_object_swap and libero_object_task task 0, seed 1). Fewer temperatures and turns than the run's, to +# be cheap: the code path is the same. Started by launch.sh: ASPIRE_CONFIG=smoke_continual.yaml ./launch.sh. +data: + tasks: tasks # CaP-Agent0's trial rows (tasks.sh, rows.py) + view: ../../cap_harness/utils/agent/fields.py:task_row # each task as the row it always was + train: splits/train_smoke.txt + val: splits/val_smoke.txt + test: splits/test_smoke.txt + step_size: 2 + shuffle: true # the suites mixed in every step + shuffle_seed: 0 +task_info: ../utils/benchmark/task-info +agent: + name: hermit.agent.evolver.methods.cap_agent0.actor:CapAgent0Actor + concurrency: 1 + params: + engine: ../../cap_harness/utils/agent/sim.py # the engine the programs run on (ASPIRE's harness) + aspire_root: $ASPIRE_ROOT # an ASPIRE checkout with .venv-libero (launch.sh) + model: fireworks/accounts/fireworks/models/glm-5p3-flash + effort: medium # cap-x's reasoning_effort default + temperature: 1.0 # cap-x's default for a single request and the VDM + max_tokens: 20480 # cap-x's default + multi_turn: true + multiturn_limit: 2 # the run's: 10 + vdm: true + vdm_model: null # null: the acting model (the paper's VDM is Gemini-3-Pro) + ensemble: single + ensemble_temperatures: [0.1, 0.5, 0.9] # the run's: nine + decision_prompt: upstream # the decision requests as cap-x builds them (docs/methods/cap_agent0.md) + max_steps: 8000 # cap-x's LIBERO CaP-Agent0 config +judge: + path: judge.py # the engine's judge on the row's seed, its images pruned +template: cap-agent0@1.0 +evolver: + name: cap_agent0 + base: direct # the curation: one call of the run's model + model: {ref: fireworks/accounts/fireworks/models/glm-5p3-flash, effort: medium} + params: + setting: continual + engine: ../../cap_harness/utils/agent/sim.py # each library checked by the engine's own validator + aspire_root: $ASPIRE_ROOT # on its venv's Python (ASPIRE runs on 3.10 to 3.12) + select: validation + min_occurrences: 1 # the run's: 2 (two trials rarely share a function) +environment: + runner: host # the actor starts the GPU simulator itself; each program runs in its sandbox +sandbox: + enabled: true + enforce: required +trainer: + run_name: cap-agent0-smoke-continual + epochs: 1 + call_timeout_min: 120 + budget: {usd: 10, hours: 6} +eval: + repeats: 1 diff --git a/examples/libero/cap_agent0/smoke_paper.yaml b/examples/libero/cap_agent0/smoke_paper.yaml new file mode 100644 index 00000000..0520c2d9 --- /dev/null +++ b/examples/libero/cap_agent0/smoke_paper.yaml @@ -0,0 +1,54 @@ +# The smoke of paper.yaml: two collection trials (libero_object and libero_spatial task 0, seed 51), the synthesis, +# then `./launch.sh eval --adapter final` on two test trials (libero_object_swap and libero_object_task task 0, seed +# 1). Fewer temperatures and turns than the run's, to be cheap: the code path is the same. +# Started by launch.sh: ASPIRE_CONFIG=smoke_paper.yaml ./launch.sh. +data: + tasks: tasks # CaP-Agent0's trial rows (tasks.sh, rows.py) + view: ../../cap_harness/utils/agent/fields.py:task_row # each task as the row it always was + train: splits/collect_smoke.txt + test: splits/test_smoke.txt + step_size: 50 # the two collection trials in one step; the library is synthesized then + shuffle: false +task_info: ../utils/benchmark/task-info +agent: + name: hermit.agent.evolver.methods.cap_agent0.actor:CapAgent0Actor + concurrency: 1 + params: + engine: ../../cap_harness/utils/agent/sim.py # the engine the programs run on (ASPIRE's harness) + aspire_root: $ASPIRE_ROOT # an ASPIRE checkout with .venv-libero (launch.sh) + model: fireworks/accounts/fireworks/models/glm-5p3-flash + effort: medium # cap-x's reasoning_effort default + temperature: 1.0 # cap-x's default for a single request and the VDM + max_tokens: 20480 # cap-x's default + multi_turn: true # CaP-Agent0: the test rows; a collection row sets the single-turn tier itself + multiturn_limit: 2 # the run's: 10 + vdm: true + vdm_model: null # null: the acting model (the paper's VDM is Gemini-3-Pro) + ensemble: single + ensemble_temperatures: [0.1, 0.5, 0.9] # the run's: nine + decision_prompt: upstream # the decision requests as cap-x builds them (docs/methods/cap_agent0.md) + max_steps: 8000 # cap-x's LIBERO CaP-Agent0 config +judge: + path: judge.py # the engine's judge on the row's seed, its images pruned +template: cap-agent0@1.0 +evolver: + name: cap_agent0 + base: direct # the curation: one call of the run's model + model: {ref: fireworks/accounts/fireworks/models/glm-5p3-flash, effort: medium} + params: + setting: paper + engine: ../../cap_harness/utils/agent/sim.py # each library checked by the engine's own validator + aspire_root: $ASPIRE_ROOT # on its venv's Python (ASPIRE runs on 3.10 to 3.12) + min_occurrences: 1 # the run's: 2 (two trials rarely share a function) +environment: + runner: host # the actor starts the GPU simulator itself; each program runs in its sandbox +sandbox: + enabled: true + enforce: required +trainer: + run_name: cap-agent0-smoke-paper + epochs: 1 # one collection, one synthesis + call_timeout_min: 60 # a synthesis: one curation call + budget: {usd: 10, hours: 6} +eval: + repeats: 1 diff --git a/examples/libero/cap_agent0/tasks.sh b/examples/libero/cap_agent0/tasks.sh new file mode 100644 index 00000000..848613a4 --- /dev/null +++ b/examples/libero/cap_agent0/tasks.sh @@ -0,0 +1,5 @@ +# Sourced by the engine's launcher (../../cap_harness/launch.sh) in this folder, after the benchmark's prepare.py: +# CaP-Agent0's trial rows (rows.py: one row per task and seed, and the splits) in tasks/ and splits/ here, which this +# folder's configs read. +"$HERMIT" rows.py --benchmark ../utils/benchmark --out . +TASKS="$PWD/tasks" diff --git a/hermit/adapter/templates/cap_agent0/.hermit/EVOLVER.md b/hermit/adapter/templates/cap_agent0/.hermit/EVOLVER.md new file mode 100644 index 00000000..25e9ba5c --- /dev/null +++ b/hermit/adapter/templates/cap_agent0/.hermit/EVOLVER.md @@ -0,0 +1,20 @@ +# CaP-Agent0 adapter: structure + +The adapter is CaP-Agent0's skill library (CaP-X, arXiv:2603.22435, §4.1): Python functions that the coding agent's +programs call. The acting agent reads each function's signature and docstring after the API documentation (the +reader `library` in `interface.py`), and the engine runs the library's code before every program. + +| path | what it is | +|---|---| +| `skill_library.py` | the library: a module docstring, optionally `import math`, then top-level functions (at most 60,000 bytes) | + +- The library runs before every program, so a function the engine would refuse, or one that fails while it is + defined, stops every program: only `import math`, no classes, `with`, `global`, `nonlocal`, `del`, `async`, + decorators or names starting with `_`; literal defaults; names from the function itself, the engine (its builtins, + tools, constructors, `math`) or the library's other functions (type hints aside: the engine never evaluates + them); a docstring each; no engine name taken; code that compiles as the engine compiles it, as Python 3.10 too + (`break` outside a loop or a repeated keyword argument stops every program, and on a 3.10 venv so does an f-string + that reuses its quote). `.hermit/check.py` checks all of it, the grammar as far as Hermit's Python tells (not that + f-string: the CaP-Agent0 Evolver asks the engine's own validator). +- No other statement at the top level: it would run before every program. +- Fixed: `.hermit/`, `exports.yaml`, `interface.py`, `README.md`. diff --git a/hermit/adapter/templates/cap_agent0/.hermit/adapter.yaml b/hermit/adapter/templates/cap_agent0/.hermit/adapter.yaml new file mode 100644 index 00000000..cd9cdb7c --- /dev/null +++ b/hermit/adapter/templates/cap_agent0/.hermit/adapter.yaml @@ -0,0 +1,21 @@ +# The CaP-Agent0 adapter (CaP-X, arXiv:2603.22435, §4.1; capgym/cap-x): the auto-synthesized skill library, Python +# functions the coding agent's programs call. The acting agent reads the functions' signatures and docstrings with +# the API documentation and runs their code before each program; only the Evolver writes them, from the functions +# that recur in successful programs. +template: + id: cap-agent0 + version: "1.0" + contract: "2" + name: CaP-Agent0 skill library +structure: + learnable: + - path: skill_library.py # the library: top-level functions with docstrings, under the engine's rules + format: {text: true, max_bytes: 60000} + fixed: + - exports.yaml # the reader's wiring: the context tool must stay + - interface.py + - README.md +check: .hermit/check.py:check +# The reader renders the library per task, before the actor's first model call; `hermit deploy` has no such moment, +# and the library runs only in the cap-harness engine's programs. +plugin-portable: false diff --git a/hermit/adapter/templates/cap_agent0/.hermit/check.py b/hermit/adapter/templates/cap_agent0/.hermit/check.py new file mode 100644 index 00000000..a7b79a22 --- /dev/null +++ b/hermit/adapter/templates/cap_agent0/.hermit/check.py @@ -0,0 +1,229 @@ +"""Template check for `cap-agent0` adapters: the skill library is Python the cap-harness engine runs before every +program the coding agent writes, so a library the engine would refuse, or that fails while it is defined, stops every +program of every task. + +The surface: `skill_library.py`, top-level function definitions only (a module docstring and `import math` may come +first), and nothing else beside the fixed files. Each function: + +- runs under the engine's program rules (ASPIRE cap_harness/runtime.py `_ProgramValidator`): only `import math`, no + names or attributes starting with `_`, no class, with, global, nonlocal, del, async or await; +- compiles as the engine compiles a program (runtime.py `execute_program`, with its `from __future__ import + annotations`): some errors only compiling finds (`break` outside a loop, a repeated keyword argument or parameter); + and parses as Python 3.10, the oldest ASPIRE runs on (its requires-python), so far as this parser tells newer + grammar (`except*`, type parameters; not a 3.12 f-string that reuses its quote or holds a backslash, nor `a[*b]`: + only the engine's own Python tells those, and the CaP-Agent0 Evolver asks its validator); +- has a docstring (the acting agent reads the library as each function's signature and docstring), no decorator, + and literal defaults (a default runs when the library is defined, in every program); +- uses only its own names, the engine's builtins, tools and constructors, a benchmark's namespace, the library's + other functions, and `math` when the library imports it; its type hints are not checked, for the engine never + evaluates them (ASPIRE's runtime.py compiles a program with its own `from __future__ import annotations`); +- names no privileged access, and does not take a name that starts with `_` (a program may not call it) or the name + of a builtin, an engine tool or constructor, `math` or `result` (the program's output); +- is defined once. + +The names are those of ASPIRE at fa00f0e, the engine's pinned commit (runtime.py `_SAFE_BUILTINS` and +`_SAFE_CONSTRUCTORS`, api.py `register_tools`); tests/methods/cap_agent0 compares them with a checkout when one is +named. +""" +from __future__ import annotations + +import __future__ +import ast +from pathlib import Path +import re + +LIBRARY = "skill_library.py" +OWN = frozenset({"exports.yaml", "README.md", "interface.py", LIBRARY}) +LIBRARY_MAX = 60_000 # bytes: the library goes into every prompt and every program + +BUILTINS = frozenset({"Exception", "ValueError", "TypeError", "abs", "all", "any", "bool", "dict", "enumerate", + "float", "int", "len", "list", "max", "min", "print", "range", "reversed", "round", "set", + "sorted", "str", "sum", "tuple", "zip"}) +CONSTRUCTORS = frozenset({"ArmCommand", "MotionStrategy", "Pose", "RobotAction", "SynchronizedTrajectory", + "Trajectory"}) +TOOLS = frozenset({"get_task_context", "get_observation", "get_robot_state", "segment_text", "segment_points", + "mask_to_point_cloud", "crop_point_cloud", "estimate_geometry", "generate_grasps", "solve_ik", + "plan_motion", "plan_synchronized_motion", "step", "execute_trajectory", "set_gripper", + "set_grippers", "localize_object", "select_grasp", "move_to_joints", "move_to_pose", + "move_synchronized", "open_gripper", "close_gripper", "go_home"}) +EXTENSIONS = frozenset({"libero", "robosuite", "behavior"}) # each run injects its benchmark's namespace +ENGINE = BUILTINS | CONSTRUCTORS | TOOLS | EXTENSIONS # what the engine puts in a program's namespace +RESERVED = ENGINE | {"math", "result"} +FORBIDDEN = (ast.AsyncFunctionDef, ast.Await, ast.ClassDef, ast.Delete, ast.Global, ast.ImportFrom, ast.Nonlocal, + ast.With) +# Privileged access a generated program must never use (ASPIRE's provenance rule, as its aspire template checks it) +PRIVILEGED = re.compile(r"\b(?:env\.sim|sim\.(?:data|model)|sim\.forward|check_success|get_reward|" + r"native_env|handle\.env|parsed_problem|eval_predicate|obj_body_id|getattr|setattr)\b") +LITERALS = (ast.Constant, ast.Tuple, ast.List, ast.UnaryOp) +OLDEST_PYTHON = (3, 10) # ASPIRE's requires-python (>=3.10,<3.13): its venv may be the oldest + + +def program_problem(src: str) -> str | None: + """Why the engine would refuse `src`, or None (the rules of ASPIRE's _ProgramValidator).""" + try: + tree = ast.parse(src) + except SyntaxError as exc: + return f"does not parse: {exc.msg} (line {exc.lineno})" + for node in ast.walk(tree): + if isinstance(node, FORBIDDEN): + return f"{type(node).__name__} is not allowed in generated programs" + if isinstance(node, ast.Import) and any(a.name != "math" or a.asname for a in node.names): + return "only `import math` is allowed, without aliasing" + if isinstance(node, ast.Attribute) and node.attr.startswith("_"): + return "private and dunder attribute access is not allowed" + if isinstance(node, ast.Name) and node.id.startswith("_"): + return "private and dunder names are not allowed" + return None + + +def compile_problem(src: str) -> str | None: + """Why the engine's Python would not compile `src`, or None: the validator only parses, and ASPIRE compiles a + program after it (with `from __future__ import annotations`), on Python 3.10 to 3.12.""" + try: + ast.parse(src, feature_version=OLDEST_PYTHON) + compile(src, "", "exec", flags=__future__.annotations.compiler_flag, dont_inherit=True) + except (SyntaxError, ValueError) as exc: + return f"{getattr(exc, 'msg', None) or exc} (line {getattr(exc, 'lineno', None)})" + return None + + +def _literal(node) -> bool: + if isinstance(node, ast.Constant): + return True + if isinstance(node, ast.UnaryOp): + return isinstance(node.op, (ast.USub, ast.UAdd)) and isinstance(node.operand, ast.Constant) + if isinstance(node, (ast.Tuple, ast.List)): + return all(_literal(e) for e in node.elts) + return False + + +def code_nodes(fn: ast.FunctionDef) -> list[ast.AST]: + """Every node of `fn` but those of its type hints (its own, a nested function's, a variable's): the engine + compiles a program with `from __future__ import annotations` (ASPIRE runtime.py, whose flag the program + inherits), so a hint is text it never evaluates.""" + hints: set[int] = set() + for node in ast.walk(fn): + for hint in ([node.annotation] if isinstance(node, (ast.arg, ast.AnnAssign)) else + [node.returns] if isinstance(node, ast.FunctionDef) else []): + if hint is not None: + hints.update(id(n) for n in ast.walk(hint)) + return [n for n in ast.walk(fn) if id(n) not in hints] + + +def free_names(fn: ast.FunctionDef) -> set[str]: + """The names `fn` reads that it never binds (its parameters, assignments, loop and comprehension targets, + except-as names, match captures, nested functions and lambdas), but in its type hints: what must come from the + engine or the library.""" + nodes = code_nodes(fn) + bound: set[str] = set() + for node in nodes: + if isinstance(node, ast.arg): + bound.add(node.arg) + elif isinstance(node, ast.Name) and not isinstance(node.ctx, ast.Load): + bound.add(node.id) + elif isinstance(node, ast.FunctionDef) and node is not fn: + bound.add(node.name) + elif isinstance(node, ast.ExceptHandler) and node.name: + bound.add(node.name) + elif isinstance(node, ast.alias): + bound.add(node.asname or node.name.split(".")[0]) + elif isinstance(node, (ast.MatchAs, ast.MatchStar)) and node.name: + bound.add(node.name) # `case (a, b):`, `case [x, *rest]:` + elif isinstance(node, ast.MatchMapping) and node.rest: + bound.add(node.rest) # `case {"k": v, **rest}:` + loads = {n.id for n in nodes if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load)} + return loads - bound + + +def function_problems(fn: ast.FunctionDef, src: str, library: set[str]) -> list[str]: + """Why the function `fn` (whose text is `src`) cannot be in the library, beside the names the library defines + (`library`: its functions, and `math` when it imports it).""" + out = [] + why = program_problem(src) + if why: + out.append(f"the engine would refuse it: {why}") + elif why := compile_problem(src): + out.append(f"the engine would not compile it: {why}") + if fn.name.startswith("_"): + out.append("a name that starts with `_`: a program may not call it") + if fn.name in RESERVED: + out.append(f"`{fn.name}` is the engine's name (a builtin, a tool, a constructor, `math` or `result`)") + if fn.decorator_list: + out.append("a decorator runs when the library is defined: none is allowed") + if not ast.get_docstring(fn): + out.append("no docstring: the acting agent reads the library as signatures and docstrings") + defaults = [*fn.args.defaults, *[d for d in fn.args.kw_defaults if d is not None]] + if any(not _literal(d) for d in defaults): + out.append("a default that is not a literal runs when the library is defined") + found = PRIVILEGED.search(src) + if found: + out.append(f"it uses privileged access ({found.group(0)})") + unknown = sorted(free_names(fn) - ENGINE - library) + if unknown: + out.append(f"it uses names neither the engine nor the library defines: {', '.join(unknown)}") + return out + + +def library_problems(text: str) -> list[str]: + """Every reason the library `text` cannot be prepended to a program, each naming its function.""" + try: + tree = ast.parse(text) + except SyntaxError as exc: + return [f"{LIBRARY} does not parse: {exc.msg} (line {exc.lineno})"] + out = [] + names = {n.name for n in tree.body if isinstance(n, ast.FunctionDef)} + if any(isinstance(n, ast.Import) and [(a.name, a.asname) for a in n.names] == [("math", None)] + for n in tree.body): + names.add("math") + for i, node in enumerate(tree.body): + if isinstance(node, ast.FunctionDef): + continue + if i == 0 and isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) \ + and isinstance(node.value.value, str): + continue # the module docstring + if isinstance(node, ast.Import) and [(a.name, a.asname) for a in node.names] == [("math", None)]: + continue + out.append(f"line {node.lineno}: only function definitions (after a docstring and `import math`) may be " + f"at the top level: a statement there runs before every program") + seen = set() + for node in tree.body: + if not isinstance(node, ast.FunctionDef): + continue + if node.name in seen: + out.append(f"`{node.name}` is defined twice") + seen.add(node.name) + src = ast.get_source_segment(text, node) or "" + out += [f"`{node.name}`: {p}" for p in function_problems(node, src, names)] + why = program_problem(text) + if why is None and (error := compile_problem(text)): + why = f"it would not compile: {error}" + if why and not out: + out.append(f"the engine would refuse the library: {why}") + return out + + +def check(adapter_path: str) -> list[dict]: + adapter = Path(adapter_path).resolve() + if not (adapter / "exports.yaml").is_file(): + # Never pass an adapter this check cannot see (under bubblewrap, /tmp is an empty tmpfs). + return [{"path": LIBRARY, "problem": f"no cap-agent0 adapter at {adapter} (exports.yaml missing or not " + f"visible)"}] + issues = [] + for p in sorted(adapter.rglob("*")): + if not p.is_file() or "__pycache__" in p.parts or ".git" in p.parts: + continue + rel = p.relative_to(adapter).as_posix() + if rel in OWN or rel.startswith(".hermit/"): + continue + issues.append({"path": rel, "problem": f"{rel} is off the adapter's surface: the skill library is " + f"{LIBRARY} alone"}) + path = adapter / LIBRARY + if not path.is_file(): + return issues + [{"path": LIBRARY, "problem": f"{LIBRARY} is missing: it is the skill library (a docstring " + f"alone is the empty library)"}] + if path.stat().st_size > LIBRARY_MAX: + issues.append({"path": LIBRARY, "problem": f"{LIBRARY} is {path.stat().st_size} bytes, past {LIBRARY_MAX}: " + f"it goes into every prompt and every program"}) + issues += [{"path": LIBRARY, "problem": p} for p in library_problems(path.read_text(encoding="utf-8", + errors="replace"))] + return issues diff --git a/hermit/adapter/templates/cap_agent0/README.md b/hermit/adapter/templates/cap_agent0/README.md new file mode 100644 index 00000000..cc29e318 --- /dev/null +++ b/hermit/adapter/templates/cap_agent0/README.md @@ -0,0 +1,9 @@ +# CaP-Agent0 skill library + +The adapter of CaP-Agent0, the agentic harness of CaP-X (arXiv:2603.22435, §4.1; +[capgym/cap-x](https://github.com/capgym/cap-x)): its automatically synthesized skill library, Python functions the +coding agent's programs call. The acting agent (`hermit.agent.evolver.methods.cap_agent0.actor:CapAgent0Actor`) lists +the functions' signatures and docstrings after the API documentation of its prompt, as cap-x lists its synthesized +skills among the API's functions, and runs their code before every program in the cap-harness engine. The `cap_agent0` +Evolver writes the library: the functions that recur in successful programs, curated by the run's model with cap-x's +skill-library prompt. See docs/methods/cap_agent0.md. diff --git a/hermit/adapter/templates/cap_agent0/exports.yaml b/hermit/adapter/templates/cap_agent0/exports.yaml new file mode 100644 index 00000000..5a8107e7 --- /dev/null +++ b/hermit/adapter/templates/cap_agent0/exports.yaml @@ -0,0 +1,30 @@ +# What the acting agent receives: no ADAPTER.md (CaP-Agent0's prompt is cap-x's), and the skill library as the reader +# `library` renders it (context_tool: the harness calls it once per task, never the agent): its documentation goes +# after the engine's API documentation in the prompt, its code before every program. +context: ADAPTER.md +tools: + - name: library + description: >- + The skill library for the acting agent: its functions documented as cap-x documents an API (text), and its + code (source). Called by the harness once per task (context_tool in exports.yaml), never by the agent. + entrypoint: interface.py:library + input_schema: + type: object + properties: + query: {type: string} + task: {type: object} + additionalProperties: false + output_schema: + type: object + properties: + text: {type: string} + source: {type: string} + functions: {type: array, items: {type: string}} + required: [text, source, functions] + annotations: + readOnlyHint: true + destructiveHint: false + idempotentHint: true + openWorldHint: false +context_tool: library +internal: [interface.py, skill_library.py] diff --git a/hermit/adapter/templates/cap_agent0/interface.py b/hermit/adapter/templates/cap_agent0/interface.py new file mode 100644 index 00000000..818b8834 --- /dev/null +++ b/hermit/adapter/templates/cap_agent0/interface.py @@ -0,0 +1,73 @@ +"""The reader of a `cap-agent0` adapter: the skill library as the acting agent sees it, and as the engine runs it. + +`library(query, task)` is the adapter's context tool (exports.yaml): the harness calls it once per task, before the +agent's first model call. Its `text` is the library's documentation in the format cap-x documents an API +(capx/integrations/base_api.py `ApiBase.combined_doc`: each function's name and signature, then its docstring under +" Doc:"), which the acting agent appends to the API documentation of its prompt (cap-x lists its synthesized skills +as functions of the API, FrankaLiberoApiReducedSkillLibrary). Its `source` is the library's code, which the agent puts +before every program it runs. The library is parsed, never run, here. +""" +from __future__ import annotations + +import ast +from pathlib import Path + +HERE = Path(__file__).resolve().parent +LIBRARY = "skill_library.py" + + +def _annotation(node) -> str: + return ast.unparse(node) if node is not None else "" + + +def _param(arg: ast.arg, default) -> str: + """One parameter as inspect.Signature prints it: `name: annotation = default`, or `name=default`.""" + text = arg.arg + if arg.annotation is not None: + text += f": {_annotation(arg.annotation)}" + if default is not None: + text += (" = " if arg.annotation is not None else "=") + ast.unparse(default) + return text + + +def signature(fn: ast.FunctionDef) -> str: + """`(a, b: float = 0.1, *, c=2) -> list`, as str(inspect.signature(fn)) gives it.""" + a = fn.args + positional = [*a.posonlyargs, *a.args] + defaults = [None] * (len(positional) - len(a.defaults)) + list(a.defaults) + parts = [_param(arg, d) for arg, d in zip(positional, defaults)] + if a.posonlyargs: + parts.insert(len(a.posonlyargs), "/") + if a.vararg is not None: + parts.append("*" + _param(a.vararg, None)) + elif a.kwonlyargs: + parts.append("*") + parts += [_param(arg, d) for arg, d in zip(a.kwonlyargs, a.kw_defaults)] + if a.kwarg is not None: + parts.append("**" + _param(a.kwarg, None)) + returns = f" -> {_annotation(fn.returns)}" if fn.returns is not None else "" + return f"({', '.join(parts)}){returns}" + + +def functions(source: str) -> list[ast.FunctionDef]: + return [node for node in ast.parse(source).body if isinstance(node, ast.FunctionDef)] + + +def combined_doc(source: str) -> str: + """The library's functions in cap-x's combined_doc format, in the file's order.""" + lines: list[str] = [] + for fn in functions(source): + doc = ast.get_docstring(fn) or "" # cleaned as inspect.getdoc cleans it + lines.append(f"{fn.name}{signature(fn)}") + if doc: + lines.append(" Doc:") + lines.extend(f" {ln}" for ln in doc.splitlines()) + lines.append("") + return "\n".join(lines).strip() + + +def library(query: str = "", task: dict | None = None) -> dict: + path = HERE / LIBRARY + source = path.read_text(encoding="utf-8") if path.is_file() else "" + names = [fn.name for fn in functions(source)] if source.strip() else [] + return {"text": combined_doc(source) if names else "", "source": source if names else "", "functions": names} diff --git a/hermit/adapter/templates/cap_agent0/skill_library.py b/hermit/adapter/templates/cap_agent0/skill_library.py new file mode 100644 index 00000000..33f65427 --- /dev/null +++ b/hermit/adapter/templates/cap_agent0/skill_library.py @@ -0,0 +1,2 @@ +"""CaP-Agent0's skill library: the functions the coding agent's programs may call, synthesized from the functions that +recur in successful programs. Empty at the start.""" diff --git a/hermit/agent/evolver/methods/cap_agent0/NOTICE b/hermit/agent/evolver/methods/cap_agent0/NOTICE new file mode 100644 index 00000000..be1d74dc --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/NOTICE @@ -0,0 +1,13 @@ +upstream/ holds verbatim excerpts of cap-x (https://github.com/capgym/cap-x, commit +acac62fcb1b6f9e02975004a2c729a65e11bffed): capx/envs/trial.py (_annotate_code_blocks), capx/llm/client.py +(collapse_text_image_inputs), capx/utils/launch_utils.py (_extract_code, _build_multi_turn_decision_prompt, +_parse_multi_turn_decision), scripts/skill_library_compilation/parse_outputs.py (FUNCTION_DEF_PATTERN, +FUNCTION_SIG_PATTERN, extract_functions_from_code, compile_successful_functions) and +scripts/skill_library_compilation/compile_skill_library.py (EXCLUDED_FUNCTION_NAMES, SKILL_LIBRARY_PROMPT, +FunctionInfo, AggregatedFunction, parse_functions_file, filter_functions, format_functions_for_prompt). prompts.py +copies cap-x's prompt texts (env_configs/libero/franka_libero_cap_agent0.yaml, capx/envs/tasks/base.py, +capx/envs/trial.py, capx/llm/client.py). actor.py follows capx/envs/trial.py (_run_single_trial, +_capture_initial_visual_feedback, _describe_initial_scene, _get_visual_differencing_feedback, _query_initial_code, +_handle_multi_turn_step) and capx/llm/client.py (query_model_ensemble, query_single_model_ensemble); evolver.py +follows scripts/skill_library_compilation/compile_skill_library.py (collect_all_functions, main). +cap-x is Copyright (c) 2026 Max Fu, licensed under the MIT License (upstream/LICENSE). diff --git a/hermit/agent/evolver/methods/cap_agent0/__init__.py b/hermit/agent/evolver/methods/cap_agent0/__init__.py new file mode 100644 index 00000000..e2d68fc1 --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/__init__.py @@ -0,0 +1,4 @@ +"""CaP-Agent0 (CaP-X, Fu et al., arXiv:2603.22435; capgym/cap-x) on the cap-harness engine: its acting agent +(actor.py: the multi-turn loop with the Visual Differencing Module and the parallel ensemble), its skill-library +synthesis as an Evolver (evolver.py), the prompt texts (prompts.py) and the verbatim upstream code it calls +(upstream/).""" diff --git a/hermit/agent/evolver/methods/cap_agent0/actor.py b/hermit/agent/evolver/methods/cap_agent0/actor.py new file mode 100644 index 00000000..eacb7f98 --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/actor.py @@ -0,0 +1,618 @@ +"""CaP-Agent0's acting agent (CaP-X, arXiv:2603.22435, §4.1; capgym/cap-x at acac62f) on one task row of the +cap-harness engine: one trial of cap-x's trial loop (capx/envs/trial.py `_run_single_trial`), run against the +engine's robot (ASPIRE's harness; examples/cap_harness) instead of cap-x's CaP-Gym. + +The trial, as cap-x runs it, with the engine in place of cap-x's environment: + +1. the initial frame: a probe program on the trial's seed reads the task's language (`get_task_context()`, the + LIBERO instruction cap-x formats into `{libero_environment_goal}`) and opens the gripper once, so the engine + records the frame before the first motion: the reset scene (cap-x renders it after `env.reset`); +2. the prompt: cap-x's (prompts.py) with the engine's API reference as the API documentation and, after it, the + skill library's functions (the adapter's context tool), as cap-x lists its synthesized skills among the API's + functions (`FrankaLiberoApiReducedSkillLibrary`); +3. with `vdm`, the Visual Differencing Module describes the initial frame, and the description is appended to the + first request (`_capture_initial_visual_feedback`, `_describe_initial_scene`); +4. the initial program: one request, or the parallel ensemble (`ensemble`: `single`, nine temperatures of the acting + model; `multi`, each model of `ensemble_models` at its temperatures) and a synthesis request + (`query_single_model_ensemble`, `query_model_ensemble`); the code is the reply's fenced block (`_extract_code`); +5. the multi-turn loop (`multi_turn`), at most `multiturn_limit` regenerations after the first block, as cap-x's + `while code_block_idx < len(code_blocks) and code_block_idx <= MULTITURN_LIMIT`: each code block runs, and the + model sees the executed code, the block's stdout and stderr and, with `vdm`, the VDM's description of how the + newest frame differs from the one before (`_handle_multi_turn_step`, `_build_multi_turn_decision_prompt`), then + answers REGENERATE with new code or FINISH (`_parse_multi_turn_decision`). An episode that ended (the task done, + the environment terminated or truncated, the step limit) ends the loop, as cap-x's "terminated episode" does. + +The engine runs one program per episode, so a turn replays: turn k runs the library and blocks 0..k from the reset +on the trial's seed (the engine's `--init-mode seeded`: a seed is one scene), each block inside a `try` of its own, +so an exception ends that block only, as each cap-x turn is one `exec` of its block in the episode's namespace. A +block that does not compile, or that the engine refuses, is left out of the program and its refusal is the block's +stderr. The frames are the engine's keyframes (before and after each motion call): the last one of a turn's run is +the newest it recorded, the state after the last motion that returned (a motion that raised, or that the step limit +cut, recorded its `before-` frame only, so the VDM then sees the scene from before that motion). +Each turn records whether its replay reached the previous turn's last frame unchanged (`replay_matches`; None when +no turn before it moved and it did not either: nothing to compare): a perception or planning service that is not +deterministic makes a replay differ from the run the model saw. + +The score is the engine's judge (utils/benchmark/judge.py), which runs the final program (`fix_code`: the library +and the executed blocks) once more on the row's seed (`eval_seeds`); the model never sees it. `output` is the +actor's own last run's success. + +Every model call is one Direct call (Layer 1); the loop is this file's. The engine runs on the host's GPU and every +program in its sandbox (sim.py `confine`), so the configs run this actor in the run's process +(environment.runner: host). +""" +from __future__ import annotations + +import __future__ +import ast +from concurrent.futures import ThreadPoolExecutor +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import sys +import threading +import time + +from hermit.agent.acting import Agent +from hermit.common import RunOutput + +from hermit.agent.evolver.methods.cap_agent0 import prompts as P +from hermit.agent.evolver.methods.cap_agent0.upstream.launch_utils import (_build_multi_turn_decision_prompt, + _extract_code, _parse_multi_turn_decision) +from hermit.agent.evolver.methods.cap_agent0.upstream.trial import _annotate_code_blocks + +DEFAULT_MODEL = "fireworks/accounts/fireworks/models/glm-5p3-flash" +API_SECTIONS_END = "## Host-only adapter and provider interfaces" # what a generated program never sees +UNAVAILABLE = "acting model unavailable" +_UNSERVED = re.compile(r"chat/completions (?:HTTP (?:408|409|429|5\d\d)|failed)") +# What a task row may set over agent.params: the paper's collection rows run the single-turn tier +ROW_KEYS = ("multi_turn", "vdm", "ensemble") +ENSEMBLES = ("none", "single", "multi") +MULTITURN_LIMIT = 10 # capx/envs/trial.py MULTITURN_LIMIT +SINGLE_TEMPERATURES = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] # query_single_model_ensemble +MULTI_MODELS = [{"model": None, "temperatures": [0.1, 0.5, 0.9]}] # ENSEMBLE_CONFIGS's shape at acac62f +DECISION_PROMPTS = ("upstream", "initial") +# The engine's termination reasons of an episode that is over (cap-harness run.py); any other ends with the program +TERMINAL = ("task_succeeded", "environment_terminated", "environment_truncated", "step_limit") +INFRA = (None, "harness_error", "user_interrupt") +PROBE = ('context = get_task_context()\n' + 'result = {"language": context.language, "task_name": context.task_name}\n' + 'open_gripper()\n') +_WRAP = ('print("<<>>")\n' + 'try:\n' + ' pass\n' + 'except Exception as cap_agent0_error:\n' + ' print("<<>>" + f"{{cap_agent0_error!r}}" + "<<>>" + ' + 'str(cap_agent0_error) + "<<>>")\n') + + +_ENGINE_LOAD = threading.Lock() + + +def compile_error(source: str) -> str | None: + """`SyntaxError: ...` when the engine's compile refuses `source` (ASPIRE runtime.py compiles a program, after its + validator, with its own `from __future__ import annotations`), or None.""" + try: + compile(source, "", "exec", flags=__future__.annotations.compiler_flag, dont_inherit=True) + except SyntaxError as exc: + return f"SyntaxError: {exc}" + return None + + +def engine_module(path: Path): + """The engine's sim.py (agent.params.engine), loaded from its own folder once. Concurrent trials wait for the one + that loads it (a module seen in sys.modules while it still runs has no Engine yet), and a load that fails leaves + nothing behind for the next trial to take as loaded.""" + path = Path(path).resolve() + name = f"_cap_sim_{abs(hash(str(path)))}" + with _ENGINE_LOAD: + if name not in sys.modules: + if str(path.parent) not in sys.path: + sys.path.insert(0, str(path.parent)) + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module # as an import does: the module may look itself up while it runs + try: + spec.loader.exec_module(module) + except BaseException: + sys.modules.pop(name, None) + raise + return sys.modules[name] + + +def wrap(i: int, block: str) -> str: + """Block i of a turn's program: its code inside a `try`, between the markers that split the run's stdout into + each block's stdout and its exception. The code is printed again from its syntax tree (the same program: a + string's lines are never indented again), without its comments; the trial's `code` keeps the block as written.""" + tree = ast.parse(_WRAP.format(i=i)) + tree.body[1].body = ast.parse(block).body or [ast.Pass()] + return ast.unparse(ast.fix_missing_locations(tree)) + "\n" + + +def program(library: str, blocks: list[str | None]) -> str: + """The library, then each block wrapped; a refused block (None) keeps only its marker.""" + parts = [library.rstrip() + "\n"] if library.strip() else [] + for i, block in enumerate(blocks): + parts.append(wrap(i, block) if block is not None else f'print("<<>>")\n') + return "\n".join(parts) + + +def block_output(stdout: str, i: int) -> tuple[str, str]: + """Block i's stdout, and its exception as a traceback's last line names it ("" when the block ended normally).""" + start = f"<<>>\n" + at = stdout.find(start) + if at < 0: + return "", "" + rest = stdout[at + len(start):] + following = rest.find(f"<<>>\n") + if following >= 0: + rest = rest[:following] + mark = f"<<>>" + if mark not in rest: + return rest, "" + text, _, tail = rest.partition(mark) + shown, _, tail = tail.partition("<<>>") + message = tail.partition("<<>>")[0] + name = re.match(r"([A-Za-z_][\w.]*)\(", shown) + if not name: + return text, shown + return text, f"{name.group(1)}: {message}" if message else name.group(1) + + +def frames_of(run_dir, camera: str = "agentview") -> list[Path]: + """A run's keyframes of `camera`, in the order the engine recorded them.""" + root = Path(run_dir) / "media" / "keyframes" if run_dir else None + if root is None or not root.is_dir(): + return [] + return [p / f"{camera}.png" for p in sorted(root.iterdir()) if (p / f"{camera}.png").is_file()] + + +def _digest(path: Path) -> str: + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +class CapAgent0Actor(Agent): + """`agent.name: hermit.agent.evolver.methods.cap_agent0.actor:CapAgent0Actor` + + params: engine (the engine's sim.py, relative to the config), aspire_root (an ASPIRE checkout with the + benchmark's venv; default ASPIRE_ROOT), sim_env (the simulator's environment; default ASPIRE_SIM_ENV, the + launcher's), model, effort, max_tokens, temperature, multi_turn, multiturn_limit, vdm, vdm_model, vdm_effort, + ensemble (none | single | multi), ensemble_temperatures (single), ensemble_models (multi: [{model, temperatures}], + a null model being the acting model), synthesis_model (multi; null: the acting model), synthesis_temperature, + decision_prompt (upstream | initial), max_steps, run_timeout_s, unserved_retries, stdout_chars, keep_runs, + keep_images (default true), scratch, logs. A task row's multi_turn, vdm and ensemble win over these. + """ + supports = ("context", "context_tool") # the skill library, through the adapter's context tool + + def __init__(self, params=None, base=None): + super().__init__(params, base) + self._lock = threading.Lock() + self._agents: dict[str, object] = {} + + # --- the models --------------------------------------------------------------------------------------------- + def model_name(self, model=None) -> str: + model = model or self.params.get("model") or DEFAULT_MODEL + return str(model.get("model") if isinstance(model, dict) else model) + + def direct(self, model=None, effort=None): + """The Direct agent of `model` (the acting model when None), one per model, with `effort` in its request.""" + model = model or self.params.get("model") or DEFAULT_MODEL + effort = effort or self.params.get("effort") or "medium" + key = json.dumps([model, effort], sort_keys=True, default=str) + with self._lock: + if key not in self._agents: + from hermit.agent.model.backends import registry, resolve + from hermit.agent.model.direct import Direct + from hermit.agent.model.llm import ChatClient + # a spec as given (its timeout, its request fields), the effort added to its extra_body + base = dict(model) if isinstance(model, dict) else resolve(model, registry()).spec() + extra = dict(base.get("extra_body") or {}) + extra["reasoning_effort"] = effort + spec = {**base, "extra_body": extra} + self._agents[key] = Direct({"max_tokens": int(self.params.get("max_tokens", 20480))}, + ChatClient.from_spec(spec, max_retries=4, retry_wait=4.0, + retry_wait_max=60.0)) + return self._agents[key] + + def ask(self, trial: "_Trial", agent, messages: list[dict], stage: str, temperature: float) -> dict: + """One model call ({content, reasoning}, as cap-x's query_model returns it). A request the endpoint did not + serve (after the client's own retries) is tried again after a pause, `unserved_retries` times, before it + fails: one outage must not cost a trial. cap-x's client retries without end.""" + retries = int(self.params.get("unserved_retries", 3)) + for attempt in range(retries + 1): + try: + result = agent.configured(temperature=temperature).run(messages) + break + except RuntimeError as exc: + if not _UNSERVED.match(str(exc)): + raise + if attempt == retries: + raise RuntimeError(f"{UNAVAILABLE}: {exc}") from None + time.sleep(60.0 * (attempt + 1)) + trial.account(result.usage, stage, result.reply, result.reasoning, result.finish_reason) + return {"content": result.reply or "", "reasoning": result.reasoning} + + # --- one task ----------------------------------------------------------------------------------------------- + def settings(self, task: dict) -> dict: + """agent.params with the row's own settings over them, checked.""" + p = {**self.params, **{k: task[k] for k in ROW_KEYS if k in task}} + if str(p.get("ensemble", "single")) not in ENSEMBLES: + raise ValueError(f"ensemble is one of {', '.join(ENSEMBLES)}, not {p.get('ensemble')!r}") + if str(p.get("decision_prompt", "upstream")) not in DECISION_PROMPTS: + raise ValueError(f"decision_prompt is one of {', '.join(DECISION_PROMPTS)}") + return p + + def run(self, task: dict, adapter: Path | None) -> RunOutput: + started = time.time() + p = self.settings(task) + root = p.get("aspire_root") or os.environ.get("ASPIRE_ROOT") + if not root: + raise ValueError("agent.params.aspire_root (or ASPIRE_ROOT): an ASPIRE checkout") + if not p.get("engine"): + raise ValueError("agent.params.engine: the engine's sim.py (e.g. ../../cap_harness/utils/agent/sim.py)") + sim = engine_module(self.path(os.path.expandvars(str(p["engine"])))) + env = p.get("sim_env") + if env is None: # the launcher's, as the judge reads it + env = os.environ.get("ASPIRE_SIM_ENV") or "{}" + env = json.loads(env) if isinstance(env, str) else dict(env) + engine = sim.Engine(self.path(os.path.expandvars(str(root))), env=env, workers=1, + max_steps=p.get("max_steps", 8000), timeout_s=float(p.get("run_timeout_s", 3600)), + benchmark=task.get("benchmark") or "libero-pro") + seeds = sim.seeds_of(task.get("seed") if task.get("seed") is not None else task.get("eval_seeds")) + if len(seeds) != 1: + raise ValueError(f"{task['id']}: a CaP-Agent0 row is one trial: one seed (`seed`), not {seeds}") + stamp = time.strftime("%Y%m%dT%H%M%S") + f"-{time.time_ns() % 10**6:06d}" + log = self.log_dir() / f"{task['id']}-{stamp}" + scratch = self.path(p.get("scratch") or (self.log_dir() / "scratch")) / f"{task['id']}-{stamp}" + trial = _Trial(self, sim, engine, task, seeds[0], log, scratch, p) + try: + trial.library = self.library(adapter, task) + trial.run() + except Exception as exc: # a failed trial (an outage past the retries): what it spent still counts + trial.save(error=f"{type(exc).__name__}: {exc}") + trial.clean() + from hermit.agent.base.interface import login_failure + if login_failure(exc) is not None: # a lost sign-in stops the run (run_one), not this one task + raise + return RunOutput(output=None, log=log, wall_s=time.time() - started, **trial.spent(), + messages=trial.transcript_messages(), + extra={"session_failed": f"{type(exc).__name__}: {exc}"[:600], "usage": trial.totals, + "trial": trial.summary()}) + trial.save() + trial.clean() + # the facts the engine's judge reads (judge.py): the program it runs on the row's seed, the steps it may take + facts = {"role": "trial", "suite": task["suite"], "fix_code": trial.program, + "max_steps": p.get("max_steps", 8000), "unseen": None, "findings": None} + return RunOutput(output=1.0 if trial.success else 0.0, log=log, wall_s=time.time() - started, **trial.spent(), + messages=trial.transcript_messages(), + extra={"task": facts, "trial": trial.summary(), "usage": trial.totals}) + + def library(self, adapter: Path | None, task: dict) -> dict: + """The skill library as the adapter's context tool renders it: {text (the functions' documentation), source + (their code)}; empty without an adapter or a library.""" + session = self.session(adapter) + if session is None: + return {"text": "", "source": "", "functions": []} + try: + text = session.context(query=task.get("suite") or "", task=task).strip() + result = session.last_context or {} + finally: + session.close() + source = result.get("source") if isinstance(result.get("source"), str) else "" + return {"text": text if source.strip() else "", "source": source, + "functions": list(result.get("functions") or [])} + + +class _Trial: + """One trial: its blocks, its turns, its images, the transcript, the log directory.""" + + def __init__(self, actor: CapAgent0Actor, sim, engine, task: dict, seed: int, log: Path, scratch: Path, + params: dict): + self.actor, self.sim, self.engine, self.task, self.seed = actor, sim, engine, task, int(seed) + self.log, self.scratch, self.params = log, scratch, params + self.suite, self.task_id = task["suite"], int(task.get("task_id", 0)) + self.library = {"text": "", "source": "", "functions": []} + self.language = "" + self.blocks: list[str] = [] + self.metadata: list[dict] = [] + self.refused: dict[int, str | None] = {} + self.turns: list[dict] = [] + self.images: list[Path] = [] # cap-x's visual_feedback_base64_history: the initial frame first + self.initial: Path | None = None + self.descriptions: list[str] = [] + self.executed = 0 + self.regenerations = self.finishes = 0 + self.program = "" + self.success = False + self.ended = "" + # what a turn's replay must reach: the keyframe count and the last frame's digest of the latest run that moved + # (a turn's; before any, the probe's reset frame, which a turn's first frame repeats) + self._frames: tuple[int, str, bool] | None = None + self.transcript: list[dict] = [] + self.candidates: list[dict] = [] + self.totals = {"calls": 0, "input_tokens": 0, "output_tokens": 0, "cost_usd": 0.0, "cut_off": 0, + "unpriced": 0} + self._lock = threading.Lock() + for d in ("programs", "images"): + (log / d).mkdir(parents=True, exist_ok=True) + self.scratch.mkdir(parents=True, exist_ok=True) + + # --- bookkeeping -------------------------------------------------------------------------------------------- + def account(self, usage, stage, reply, reasoning, finish_reason): + with self._lock: + for u in usage or []: + self.totals["calls"] += 1 + self.totals["input_tokens"] += u.input_tokens + self.totals["output_tokens"] += u.output_tokens + if u.cost_usd is None: # an unpriced call: the trial's cost is unknown + self.totals["unpriced"] += 1 + else: + self.totals["cost_usd"] += u.cost_usd + self.totals["cut_off"] += finish_reason == "length" + self.transcript.append({"stage": stage, "reply": reply, "reasoning_chars": len(reasoning or ""), + "finish_reason": finish_reason}) + + def spent(self) -> dict: + """The trial's cost (None when a call was unpriced) and tokens, as RunOutput takes them.""" + return {"cost_usd": None if self.totals["unpriced"] else self.totals["cost_usd"], + "tokens": (self.totals["input_tokens"] + self.totals["output_tokens"]) or None} + + def transcript_messages(self) -> list[dict]: + """The replies the trial acted on (a synthesis's, not each candidate's), in order.""" + return [{"role": "assistant", "content": f"[{t['stage']}]\n{t['reply']}"} for t in self.transcript + if "/candidate" not in t["stage"]] + + @property + def code(self) -> str: + """The trial's code as cap-x's summary holds it (`_annotate_code_blocks`): every generated block.""" + return _annotate_code_blocks(self.blocks, self.metadata) + + def summary(self) -> dict: + return {"seed": self.seed, "model": self.actor.model_name(), "language": self.language, + "success": self.success, "ended": self.ended, + "executed_blocks": self.executed, "blocks": len(self.blocks), "regenerations": self.regenerations, + "finishes": self.finishes, "code": self.code, "library_functions": self.library["functions"], + "turns": [{k: v for k, v in t.items() if k not in ("stdout", "stderr")} for t in self.turns], + "replay_mismatches": sum(1 for t in self.turns if t.get("replay_matches") is False)} + + def save(self, error: str | None = None): + record = {**self.summary(), "error": error, "descriptions": self.descriptions, + "turns": self.turns, "candidates": self.candidates} + (self.log / "trial.json").write_text(json.dumps(record, indent=1, default=str)) + (self.log / "transcript.jsonl").write_text("".join(json.dumps(t) + "\n" for t in self.transcript)) + (self.log / "code.py").write_text(self.code + "\n") + + def clean(self): + """The trial's simulator runs, unless keep_runs (their keyframes are tens of megabytes a run); and the frames + it kept for the VDM (images/: up to twelve), with keep_images false.""" + if not self.params.get("keep_runs"): + shutil.rmtree(self.scratch, ignore_errors=True) + if not self.params.get("keep_images", True): + shutil.rmtree(self.log / "images", ignore_errors=True) + + # --- the engine --------------------------------------------------------------------------------------------- + def run_program(self, name: str, source: str) -> dict: + path = self.log / "programs" / f"{name}.py" + path.write_text(source) + record = self.engine.run(path, suite=self.suite, seeds=[self.seed], out=self.scratch / name, + task_id=self.task_id)[0] + if record.get("termination_reason") in INFRA or not record.get("run_dir"): + raise RuntimeError(f"the engine ran no episode for {name} on seed {self.seed}: " + f"{str(record.get('error'))[-800:]}") + return record + + def keep(self, png: Path, name: str) -> Path: + kept = self.log / "images" / f"{name}.png" + shutil.copyfile(png, kept) + return kept + + def probe(self): + """The task's language and the reset frame (cap-x: `handle.task_language`, `env.render()` after reset).""" + record = self.run_program("probe", PROBE) + result = self.sim.program_result(record["run_dir"]).get("result") or {} + self.language = str(result.get("language") or "").strip() if isinstance(result, dict) else "" + if not self.language: + raise RuntimeError(f"the probe read no task language on seed {self.seed}: {record.get('error')}") + frames = frames_of(record["run_dir"]) + if frames: + self.initial = self.keep(frames[0], "initial") + self._frames = (1, _digest(frames[0]), False) # a turn's first frame is the same reset, before any motion + self.images = [self.initial] if self.initial else [] + self.prune(record["run_dir"]) + + def prune(self, run_dir): + if not self.params.get("keep_runs"): + shutil.rmtree(Path(run_dir) / "media", ignore_errors=True) + + def refusal(self, k: int) -> str | None: + """Why the engine refuses block k on its own (cached), or None: it must compile as the engine compiles a + program (with `from __future__ import annotations`, which ASPIRE's runtime.py passes on to it; a `return`, + `break` or `yield` outside a function or a loop parses but compiles nowhere, and the engine would refuse the + whole program for it), then pass the engine's validator.""" + if k not in self.refused: + why = compile_error(self.blocks[k]) + if why: # as the engine reports it + self.refused[k] = f"program rejected: {why}" + return self.refused[k] + path = self.scratch / "blocks" / f"block{k:02d}.py" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(self.blocks[k]) + why = self.engine.validate(path) + self.refused[k] = f"program rejected: {why}" if why else None + return self.refused[k] + + def execute(self, n: int) -> dict: + """Turn n-1: the library and blocks 0..n-1 from the reset; the newest block's stdout and stderr.""" + k = n - 1 + while True: + kept = [b if self.refusal(i) is None else None for i, b in enumerate(self.blocks[:n])] + source = program(self.library["source"], kept) + record = self.run_program(f"turn{k:02d}", source) + result = self.sim.program_result(record["run_dir"]) + error = result.get("error") + if result.get("ok") or "program rejected" not in json.dumps(error, default=str): + break + # The engine refused the program its validator passed (its check could not run in time): the newest + # block is the one it had not run before; without it, the program is the one the turn before ran + if self.refused.get(k) is not None: + raise RuntimeError(f"the engine refused turn {k}'s program: {error}") + self.refused[k] = str(error.get("message") if isinstance(error, dict) and error.get("message") else error) + stdout, error = block_output(result.get("stdout") or "", k) + limit = int(self.params.get("stdout_chars", 20000)) + frames = frames_of(record["run_dir"]) + matches = None # nothing to compare: no turn before it moved, nor this one + if self._frames is not None: + count, digest, by_turn = self._frames + if len(frames) >= count: + matches = _digest(frames[count - 1]) == digest + elif by_turn: # the replay recorded fewer frames than the run the model saw + matches = False + if frames: + self._frames = (len(frames), _digest(frames[-1]), True) + image = self.keep(frames[-1], f"turn{k:02d}") if frames else self.initial # nothing moved: the reset + turn = {"turn": k, "blocks": n, "stdout": stdout[-limit:], "stderr": (self.refusal(k) or error)[-limit:], + "task_success": bool(record.get("task_success")), "program_ok": record.get("program_ok"), + "termination_reason": record.get("termination_reason"), + "steps_executed": record.get("steps_executed"), "image": str(image) if image else None, + "replay_matches": matches} + self.turns.append(turn) + self.program, self.success, self.ended = source, turn["task_success"], str(turn["termination_reason"]) + self.prune(record["run_dir"]) + return turn + + # --- the models --------------------------------------------------------------------------------------------- + def vdm(self) -> tuple[object, float]: + p = self.params + return self.actor.direct(p.get("vdm_model"), p.get("vdm_effort")), float(p.get("temperature", 1.0)) + + def describe(self, task_description: str) -> str: + agent, temperature = self.vdm() + url = self.sim.image_part(self.initial)["image_url"]["url"] + reply = self.actor.ask(self, agent, P.describe_messages(task_description, url), "vdm/initial", temperature) + self.descriptions.append(reply["content"]) + return reply["content"] + + def difference(self, task_description: str, stage: str) -> str: + agent, temperature = self.vdm() + urls = [self.sim.image_part(png)["image_url"]["url"] for png in self.images[-2:]] + reply = self.actor.ask(self, agent, P.difference_messages(task_description, *urls), stage, temperature) + self.descriptions.append(reply["content"]) + return reply["content"] + + def generate(self, prompt: list[dict], *, is_multiturn: bool, stage: str) -> dict: + """One request, or the parallel ensemble and its synthesis (cap-x query_single_model_ensemble, + query_model_ensemble): the candidates in parallel, the failed ones left out, a synthesis at the synthesis + temperature; every candidate failing fails the trial, as upstream raises.""" + p = self.params + mode = str(p.get("ensemble", "single")) + if mode == "none": + return self.actor.ask(self, self.actor.direct(), prompt, stage, float(p.get("temperature", 1.0))) + if mode == "single": + pairs = [(None, float(t)) for t in (p.get("ensemble_temperatures") or SINGLE_TEMPERATURES)] + else: + pairs = [(m.get("model"), float(t)) for m in (p.get("ensemble_models") or MULTI_MODELS) + for t in m.get("temperatures") or []] + if not pairs: + raise ValueError("the ensemble has no candidates: ensemble_temperatures or ensemble_models is empty") + + def candidate(i: int) -> dict: + model, temperature = pairs[i] + try: + reply = self.actor.ask(self, self.actor.direct(model), prompt, f"{stage}/candidate{i}", temperature) + return {"model": self.actor.model_name(model), "temp": temperature, "content": reply["content"], + "ok": True} + except Exception as exc: + from hermit.agent.base.interface import login_failure + if login_failure(exc) is not None: + raise + return {"model": self.actor.model_name(model), "temp": temperature, "content": str(exc), "ok": False} + + with ThreadPoolExecutor(max_workers=len(pairs)) as pool: + responses = list(pool.map(candidate, range(len(pairs)))) + self.candidates.append({"stage": stage, "responses": responses}) + successful = [r for r in responses if r["ok"]] + if not successful: + raise RuntimeError(f"All ensemble queries failed ({stage}): {responses[0]['content'][:300]}") + synthesis = P.synthesis_messages(successful, prompt, is_multiturn=is_multiturn, single_model=mode == "single") + model = None if mode == "single" else p.get("synthesis_model") + return self.actor.ask(self, self.actor.direct(model), synthesis, f"{stage}/synthesis", + float(p.get("synthesis_temperature", 0.2))) + + # --- the trial (capx/envs/trial.py _run_single_trial) -------------------------------------------------------- + def run(self): + p = self.params + multi_turn = bool(p.get("multi_turn", True)) + vdm = bool(p.get("vdm", True)) + limit = int(p.get("multiturn_limit", MULTITURN_LIMIT)) + if self.library["source"].strip(): # checked by the template; refused here too, never run at all + path = self.scratch / "skill_library.py" + path.write_text(self.library["source"]) + why = self.engine.validate(path) or compile_error(self.library["source"]) + if why: + raise RuntimeError(f"the engine refuses the skill library: {why}") + reference = self.sim.workspace_docs(self.engine.root, self.engine.benchmark)["api-reference.md"] + if API_SECTIONS_END not in reference: # another ASPIRE commit moved it: never the host-only part too + raise RuntimeError(f"the engine's api-reference.md has no '{API_SECTIONS_END}' heading to cut at") + docs = [reference.split(API_SECTIONS_END)[0].strip()] + self.probe() + if vdm and self.initial is None: + raise RuntimeError(f"the probe recorded no frame on seed {self.seed}: the VDM has no initial image") + if self.library["text"].strip(): + docs.append(self.library["text"].strip()) + apis = P.APIS + "\n".join(f"\n{d}" for d in docs) + # the first user text, the goal filled (cap-x _patch_libero_goal formats the whole text; the goal is filled + # in the task prompt alone here, the engine's API reference holding braces) + task_description = P.TASK_PROMPT.format(libero_environment_goal=self.language) + apis + first = task_description + if vdm: + first += "\n\n" + P.INITIAL_FEEDBACK.format(description=self.describe(task_description)) + initial = [{"role": "system", "content": P.SYSTEM_PROMPT}, + {"role": "user", "content": [{"type": "text", "text": first}]}] + # The decision requests start from the environment's own prompt (cap-x: `obs` after env.step carries the + # environment's full_prompt, with the goal unformatted and no initial description); `initial`: from the + # first request instead + if p.get("decision_prompt", "upstream") == "initial": + base = initial + else: + base = [{"role": "system", "content": P.SYSTEM_PROMPT}, + {"role": "user", "content": [{"type": "text", "text": P.TASK_PROMPT + apis}]}] + (self.log / "prompt.json").write_text(json.dumps({"initial": first, "decision_base": base[-1]["content"][0] + ["text"]}, indent=1)) + reply = self.generate(initial, is_multiturn=False, stage="initial") + self.blocks = list(_extract_code(reply["content"])) + self.metadata = [{"generation": 0, "regenerated": False}] * len(self.blocks) + idx = 0 + while idx < len(self.blocks) and idx <= limit: + idx += 1 + turn = self.execute(idx) + self.executed = idx + if not multi_turn: + break + if turn["termination_reason"] in TERMINAL: + turn["decision"] = "episode over" + break + if turn["image"]: + self.images.append(Path(turn["image"])) + feedback = self.difference(task_description, f"vdm/turn{idx - 1:02d}") \ + if vdm and len(self.images) >= 2 else None + complete = P.MULTI_TURN_PROMPT.format(executed_code="\n".join(self.blocks[:idx]), + console_stdout=turn["stdout"], console_stderr=turn["stderr"]) + prompt = _build_multi_turn_decision_prompt({"full_prompt": base}, complete, None, feedback) + reply = self.generate(prompt, is_multiturn=True, stage=f"turn{idx - 1:02d}") + decision, new_code = _parse_multi_turn_decision(reply["content"]) + turn["decision"] = decision + if decision == "regenerate": + new_blocks = _extract_code(new_code) + del self.blocks[idx:] + del self.metadata[idx:] + self.blocks.extend(new_blocks) + self.metadata.extend([{"generation": self.regenerations + 1, "regenerated": True, + "regenerated_at_idx": idx}] * len(new_blocks)) + self.regenerations += 1 + else: + self.finishes += 1 + break diff --git a/hermit/agent/evolver/methods/cap_agent0/evolver.py b/hermit/agent/evolver/methods/cap_agent0/evolver.py new file mode 100644 index 00000000..feaffdf0 --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/evolver.py @@ -0,0 +1,481 @@ +"""CaP-Agent0's automatic skill-library synthesis (CaP-X, arXiv:2603.22435, §4.1, "Auto-Synthesized and Persistent +Skill Libraries"; capgym/cap-x scripts/skill_library_compilation/ at acac62f) as an Evolver, in two settings: + +- `paper`: the paper's single synthesis pass. The rollouts are the collection (the configs' collection rows run the + single-turn, low-level tier on the engine's API reference, which has no usage examples: the paper says it pools + the S3 rollouts, whose documentation has them, and cap-x's compile and its shipped library take the S3 and S4 + experiments, `_reduced_api` and `_reduced_api_exampleless`); every step adds its successful trials to the pool, + and the last step of the epoch synthesizes the library once from all of them. The configs run one epoch. +- `continual` (ours): CaP-Agent0 acts on the training tasks with the library as it stands, and after every step the + library is synthesized again from every successful trial so far ("the process is inherently iterative. As + additional successful executions are accumulated, the agent can continue to update its skill library over + time"), then scored on the validation tasks (run_agent); finalize keeps the library that scored best there. + +One synthesis, as cap-x's compile runs it (upstream/, verbatim but where named): + +1. each experiment's functions.txt from its successful trials (parse_outputs.py `compile_successful_functions`: + the top-level `def`s the regular expression finds in each trial's code); an experiment is the acting model on one + task, as cap-x's outputs///; +2. the functions read back and pooled by name across experiments (compile_skill_library.py `parse_functions_file`, + the loop of `collect_all_functions`), filtered (`filter_functions`: at least `min_occurrences` trials, three lines, + no task-specific name; `EXCLUDED_FUNCTION_NAMES` at parsing) and listed most frequent first + (`format_functions_for_prompt`); +3. `SKILL_LIBRARY_PROMPT` with that list, and after it the engine's program rules (prompts.ENGINE_RULES: ours), to the + run's model (ctx.agent; cap-x calls Gemini-3.1-Pro once); +4. ours, where the released code stops at the curated text (the paper calls the pipeline automated; the step from + that text to the nine-function API module is not in the code): every top-level function of the reply's Python + blocks (```python, ```py or bare), the first of each name, as written (its decorators too), kept if the template's + check accepts it in the library (a function that names one left out goes too), in the reply's order, and within + the library's size cap; and with `params.engine` named, if the engine's own validator on its benchmark's Python + takes the library (ASPIRE's venv may be an older Python than Hermit's); the library is written whole, so a + function the new reply leaves out is gone. + +A synthesis with nothing to curate (no function in `min_occurrences` successful trials) leaves the library as it is, +as cap-x's compile stops there. A curation is tried once more when its call fails, its reply was cut off (the +endpoint's `finish_reason` is `length`, or its last block is not closed) or none of its functions is kept; a second +failure fails the step, and the library stays as it was. +""" +from __future__ import annotations + +import ast +from collections import defaultdict +from dataclasses import dataclass +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import textwrap + +from hermit.agent.evolver.base import Evolver, FinalResult, StepContext, StepResult, ask +from hermit.trainer.budget import BudgetExceeded + +from hermit.agent.evolver.methods.cap_agent0 import prompts as P +from hermit.agent.evolver.methods.cap_agent0.actor import engine_module +from hermit.agent.evolver.methods.cap_agent0.upstream.compile_skill_library import ( + SKILL_LIBRARY_PROMPT, AggregatedFunction, filter_functions, format_functions_for_prompt, parse_functions_file) +from hermit.agent.evolver.methods.cap_agent0.upstream.parse_outputs import compile_successful_functions + +LIBRARY = "skill_library.py" +STATE = "cap_agent0.json" +TEMPLATE_CHECK = Path(__file__).resolve().parents[4] / "adapter" / "templates" / "cap_agent0" / ".hermit" / "check.py" +SETTINGS = ("paper", "continual") +SELECTS = ("validation", "last") +ATTEMPTS = 2 +PYTHON_FENCES = ("python", "py", "python3", "") # a block's info string: Python, or none given +HEADER = ('"""CaP-Agent0\'s skill library: the functions the coding agent\'s programs may call, synthesized from the ' + 'functions that\nrecur in successful programs ({how})."""\n') + + +@dataclass +class TrialData: + """What compile_successful_functions reads of a trial (capx/utils/eval_utils.py TrialData).""" + task_completed: bool + summary_txt: Path + + +def template_check(): + """The cap-agent0 template's own check (.hermit/check.py), loaded from the package.""" + spec = importlib.util.spec_from_file_location("_cap_agent0_template_check", TEMPLATE_CHECK) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def fenced_blocks(text: str) -> tuple[list[tuple[str, str]], bool]: + """(info string, body) of each fenced block, read line by line as Markdown reads them: a fence indented (a block + inside a list item) takes as much indentation off each of its lines (CommonMark), and what all of them still share + goes too; and whether the last one is left open (a reply cut off).""" + blocks, info, lines, indent = [], None, [], 0 + for line in (text or "").splitlines(): + mark = line.strip() + if info is None: + if mark.startswith("```"): + words = mark[3:].strip().split() + info, lines = (words[0].lower() if words else ""), [] + indent = len(line) - len(line.lstrip(" ")) + elif mark == "```": + blocks.append((info, textwrap.dedent("\n".join(lines)))) + info = None + else: + lines.append(line[min(indent, len(line) - len(line.lstrip(" "))):]) + return blocks, info is not None + + +def reply_functions(reply: str) -> tuple[list[tuple[str, str]], list[str]]: + """(name, source) of every top-level function in the reply's Python blocks (```python, ```py or bare), the first + of each name, in order; and why blocks were skipped (one that does not parse, a last one left open).""" + out, seen, skipped = [], set(), [] + blocks, unclosed = fenced_blocks(reply) + for i, (info, block) in enumerate(blocks): + if info not in PYTHON_FENCES: + continue + try: + tree = ast.parse(block) + except SyntaxError as exc: + skipped.append(f"block {i + 1} does not parse: {exc.msg} (line {exc.lineno})") + continue + for node in tree.body: + if isinstance(node, ast.FunctionDef) and node.name not in seen: + seen.add(node.name) # its decorators too (the segment starts at `def`): the check sees them + decorators = "".join(f"@{ast.get_source_segment(block, d)}\n" for d in node.decorator_list) + out.append((node.name, decorators + ast.get_source_segment(block, node))) + if unclosed: + skipped.append(f"block {len(blocks) + 1} is not closed: the reply was cut off") + return out, skipped + + +def assemble(functions: list[tuple[str, str]], how: str, refuse=None) -> tuple[str, dict[str, list[str]]]: + """The library of the functions the template's check accepts together, and why each other one was left out: + each round drops the failing ones, until the rest pass with only each other; a library past the size cap loses + its last function (the reply's order), and the rest are checked again (a function that called it goes too). + `refuse` (`engine_check`: the engine's own validator, on its benchmark's Python) is asked about a library that + passes; when it refuses it, the functions it refuses on their own go, and the rest are checked again.""" + check = template_check() + kept = list(functions) + dropped: dict[str, list[str]] = {} + uses_math = any(re.search(r"\bmath\.", src) for _, src in kept) # the library imports it then + while True: + names = {n for n, _ in kept} | ({"math"} if uses_math else set()) + failing = {} + for name, src in kept: + problems = check.function_problems(ast.parse(src).body[0], src, names) + if problems: + failing[name] = problems + if not failing: + body = "\n\n\n".join(src.rstrip() for _, src in kept) + text = HEADER.format(how=how) + ("\nimport math\n" if uses_math else "") + \ + ("\n\n" + body + "\n" if kept else "") + if kept and len(text.encode()) > check.LIBRARY_MAX: + failing = {kept[-1][0]: [f"the library would pass {check.LIBRARY_MAX} bytes"]} + elif kept and refuse is not None and (whole := refuse(text)): + failing = {n: [f"the engine's validator refuses it: {why}"] for n, s in kept if (why := refuse(s))} + if not failing: # refused only together: none of them is sure to run + failing = {n: [f"the engine's validator refuses the library: {whole}"] for n, _ in kept} + else: + return text, dropped + dropped.update(failing) + kept = [(n, s) for n, s in kept if n not in failing] + + +def engine_check(ctx): + """The engine's own validator on a library's text (sim.Engine.validate: ASPIRE's, on its benchmark's Python, in + the engine's sandbox), or None when `params.engine` names no engine. The template's check runs on Hermit's Python, + and ASPIRE's venv may be Python 3.10 or 3.11, whose parser refuses what 3.12's takes (an f-string that reuses its + quote or holds a backslash, `a[*b]`): every program would then be refused, the library first.""" + p = ctx.params + if not p.get("engine"): + return None + root = p.get("aspire_root") or os.environ.get("ASPIRE_ROOT") + if not root: + raise ValueError("evolver.params.aspire_root (or ASPIRE_ROOT): the engine's ASPIRE checkout") + base = Path(ctx.base) if ctx.base else Path.cwd() + sim = engine_module(base / os.path.expandvars(str(p["engine"]))) + engine = sim.Engine(base / os.path.expandvars(str(root)), env=json.loads(os.environ.get("ASPIRE_SIM_ENV") or "{}"), + workers=1, benchmark=p.get("benchmark") or "libero-pro") + folder = ctx.workspace.scratch / "engine-check" + folder.mkdir(parents=True, exist_ok=True) + + def refuse(text: str) -> str | None: + path = folder / f"{hashlib.sha256(text.encode()).hexdigest()[:16]}.py" + path.write_text(text) + return engine.validate(path) + return refuse + + +class CapAgent0Evolver(Evolver): + @staticmethod + def _problem(ctx) -> str | None: + """Why the run cannot step: no model, an unknown setting or select, or selection by validation without + validation tasks.""" + p = ctx.params + if ctx.agent is None: + return "cap_agent0 curates with the run's model: set `llm` in run.yaml" + if p.get("setting", "continual") not in SETTINGS: + return f"setting is one of {', '.join(SETTINGS)}, not {p.get('setting')!r}" + if p.get("select", "validation") not in SELECTS: + return f"select is one of {', '.join(SELECTS)}, not {p.get('select')!r}" + if p.get("setting", "continual") == "continual" and p.get("select", "validation") == "validation" \ + and ctx.access.validation is None: + return "the continual setting selects by validation: set data.val, or select: last" + return None + + def setup(self, ctx) -> None: + """A misconfigured run stops here, before its first rollouts (the step checks again, for a resume).""" + problem = self._problem(ctx) + if problem: + raise ValueError(problem) + + # --- the pool of successful trials -------------------------------------------------------------------------- + @staticmethod + def _load(ctx) -> dict: + path = ctx.workspace.state / STATE + if path.exists(): + return json.loads(path.read_text()) + return {"experiments": {}, "seen": [], "steps": [], "libraries": [], "final": None} + + @staticmethod + def _save(ctx, state: dict) -> None: + (ctx.workspace.state / STATE).write_text(json.dumps(state, ensure_ascii=False, indent=1)) + + @staticmethod + def _collect(ctx, state: dict, step: int) -> dict: + """This step's records into the pool: each successful trial's code under its experiment (model, task). A + record already pooled for this step (the same step's material read again) is not pooled twice.""" + success = float(ctx.params.get("success_score", 1.0)) + current = ctx.workspace.learning_material / "current" / "tasks" + counts = {"trials": 0, "successful": 0, "failed_runs": 0} + seen = set(state["seen"]) + for f in sorted(current.glob("*.json")) if current.is_dir() else []: + record = json.loads(f.read_text()) + key = f"{step}/{record.get('id')}" + if key in seen: + continue + seen.add(key) + state["seen"].append(key) + counts["trials"] += 1 + trial = (record.get("pipeline_extra") or {}).get("trial") or {} + if record.get("status") not in (None, "ok") or not trial.get("code"): + counts["failed_runs"] += 1 + continue + if float((record.get("judge") or {}).get("score") or 0.0) < success: + continue + row = record.get("input") or {} + experiment = f"{row.get('suite')}-t{int(row.get('task_id', 0)):02d}" + model = str(trial.get("model") or "acting-model") + key = f"{model}/{experiment}" + entry = state["experiments"].setdefault(key, {"model": model, "experiment": experiment, "trials": []}) + entry["trials"].append({"id": record["id"], "step": step, "code": trial["code"]}) + counts["successful"] += 1 + return counts + + # --- one synthesis (compile_skill_library.py main) ----------------------------------------------------------- + @staticmethod + def _functions(ctx, state: dict) -> tuple[dict[str, AggregatedFunction], int]: + """Every experiment's functions.txt, read back and pooled by name (collect_all_functions's loop).""" + work = ctx.workspace.scratch / "compile" + if work.exists(): + shutil.rmtree(work) + all_functions: dict[str, list] = defaultdict(list) + for i, (key, entry) in enumerate(sorted(state["experiments"].items())): + folder = work / f"experiment{i:04d}" + folder.mkdir(parents=True) + results = {} + for n, trial in enumerate(entry["trials"]): + summary = folder / f"trial{n:04d}.txt" + summary.write_text(trial["code"]) + results[n] = TrialData(task_completed=True, summary_txt=summary) + (folder / "functions.txt").write_text(compile_successful_functions(results)) + for func in parse_functions_file(folder / "functions.txt", entry["model"], entry["experiment"]): + all_functions[func.name].append(func) + aggregated = {name: AggregatedFunction(name=name, implementations=implementations) + for name, implementations in all_functions.items()} + return aggregated, len(state["experiments"]) + + def _synthesize(self, ctx, state: dict, record: dict) -> str | None: + """The curated library's text, or None when nothing recurs; `record` takes what happened.""" + p = ctx.params + aggregated, experiments = self._functions(ctx, state) + filtered = filter_functions(aggregated, min_occurrences=int(p.get("min_occurrences", 2))) + record.update(experiments=experiments, functions=len(aggregated), after_filtering=len(filtered)) + if not filtered: + return None + functions_text = format_functions_for_prompt(filtered) + check = template_check() + rules = P.ENGINE_RULES.format(builtins=", ".join(sorted(check.BUILTINS)), + api=", ".join(sorted(check.TOOLS | check.CONSTRUCTORS | check.EXTENSIONS))) + prompt = SKILL_LIBRARY_PROMPT.format(functions=functions_text) + rules + out = ctx.workspace.output + (out / "skill_library_raw.txt").write_text("RAW FUNCTION LIST (before LLM curation)\n" + "=" * 70 + "\n\n" + + functions_text) + (out / "prompt.md").write_text(prompt) + sampling = {k: p[k] for k in ("max_tokens", "temperature") if p.get(k) is not None} + how = f"{len(filtered)} candidate functions from {experiments} experiments" + refuse = engine_check(ctx) + failures, usage = [], [] + for n in range(1, ATTEMPTS + 1): + if ctx.cancel is not None and ctx.cancel.is_set(): + failures.append("stopped by the Trainer") + break + try: + reply = ask(ctx.agent, [{"role": "user", "content": prompt}], **sampling) + except BudgetExceeded: + raise + except Exception as exc: # noqa: BLE001 — tried once more, then the step fails + failures.append(f"the curation call failed: {type(exc).__name__}: {str(exc)[:300]}") + continue + content = reply["content"] or "" + usage.append(reply.get("usage")) + (out / f"skill_library.attempt{n}.txt").write_text(content) + functions, skipped = reply_functions(content) + text, dropped = assemble(functions, how, refuse) + kept = len(functions) - len(dropped) + if reply.get("finish_reason") == "length": + failures.append("the reply was cut off at max_tokens (finish_reason length)") + elif fenced_blocks(content)[1]: + failures.append("the reply was cut off: its last block is not closed") + elif not kept: + why = "; ".join([f"{k}: {v[0]}" for k, v in list(dropped.items())[:3]] + skipped[:3]) + found = f"{len(functions)} found" + (f": {why}" if why else "") + failures.append(f"no function of the reply was kept ({found})") + else: + (out / "skill_library.txt").write_text(content) + record.update(curated=len(functions), kept=kept, dropped=dropped, skipped_blocks=skipped, + attempts=failures + ["kept"], usage=usage) + return text + record.update(attempts=failures, usage=usage) + raise RuntimeError(f"no curated library: {'; '.join(failures) or 'stopped by the Trainer'}") + + # --- validation (continual) --------------------------------------------------------------------------------- + @staticmethod + def _val_ids(ctx) -> list[str]: + if ctx.access.validation is None: + return [] + return [json.loads(line)["id"] for line in (ctx.access.validation / "tasks.jsonl").read_text().splitlines() + if line.strip()] + + @staticmethod + def _validate(ctx, adapter: Path, ids: list[str]) -> dict: + """The mean judge score on the validation tasks; a run that failed for an infrastructure reason is run once + more, and if it fails again the library is not scored.""" + scores, todo, error = {}, list(ids), "" + for _ in range(ATTEMPTS): + try: + results = ctx.tools["run_agent"](task_ids=todo, adapter=str(adapter))["results"] + except BudgetExceeded: + raise + except Exception as exc: # noqa: BLE001 — as failed runs: tried once more + if ctx.cancel is not None and ctx.cancel.is_set(): + raise + results, error = [], f"; {type(exc).__name__}: {str(exc)[:200]}" + for r in results: + if r.get("status") in (None, "ok"): + scores[r["id"]] = float((r.get("judge") or {}).get("score") or 0.0) + todo = [t for t in ids if t not in scores] + if not todo: + return {"mean": sum(scores.values()) / len(scores), "scores": scores} + raise RuntimeError(f"{len(todo)} validation runs failed twice ({', '.join(todo[:3])}){error}") + + def _candidate(self, ctx, state: dict, name: str, text: str, step: int, ids: list[str]) -> dict: + """A library kept in the state (and scored on validation when the setting selects by it).""" + folder = ctx.workspace.state / "libraries" + folder.mkdir(exist_ok=True) + (folder / f"{name}.py").write_text(text) + entry = {"name": name, "step": step, "file": f"libraries/{name}.py"} + state["libraries"].append(entry) + if ids: + copy = ctx.workspace.scratch / "candidates" / name + if copy.exists(): + shutil.rmtree(copy) + shutil.copytree(ctx.workspace.adapter, copy, symlinks=True, ignore=shutil.ignore_patterns(".git")) + (copy / LIBRARY).write_text(text) + try: + entry["val"] = self._validate(ctx, copy, ids) + except BudgetExceeded: + self._save(ctx, state) + raise + except Exception as exc: # noqa: BLE001 — left out of the selection, recorded + entry["val_error"] = f"{type(exc).__name__}: {str(exc)[:300]}" + self._save(ctx, state) + return entry + + # --- the step ----------------------------------------------------------------------------------------------- + def step(self, ctx: StepContext) -> StepResult: + problem = self._problem(ctx) + if problem: + return StepResult("failed", problem) + state = self._load(ctx) + step = ctx.progress.step if ctx.progress else len(state["steps"]) + 1 + record = {"step": step, "epoch": ctx.progress.epoch if ctx.progress else 1, + **self._collect(ctx, state, step)} + self._save(ctx, state) # the pool first: a step stopped later keeps its trials + try: + return self._step(ctx, state, record, step) + except BudgetExceeded: + state["steps"].append({**record, "outcome": "budget exceeded"}) + self._save(ctx, state) + raise + + def _step(self, ctx: StepContext, state: dict, record: dict, step: int) -> StepResult: + p = ctx.params + setting = p.get("setting", "continual") + validating = setting == "continual" and p.get("select", "validation") == "validation" + ids = self._val_ids(ctx) if validating else [] + if validating and not ids: + state["steps"].append({**record, "outcome": "no validation tasks"}) + self._save(ctx, state) + return StepResult("failed", "the continual setting selects by validation: data.val has no tasks") + if validating and not state["libraries"]: # the starting library, once, for the selection + start = (ctx.workspace.adapter / LIBRARY).read_text() if (ctx.workspace.adapter / LIBRARY).exists() else "" + self._candidate(ctx, state, "start", start, 0, ids) + if setting == "paper" and not (ctx.progress is None or ctx.progress.is_epoch_end): + state["steps"].append({**record, "outcome": "collected; the synthesis runs at the epoch's end"}) + self._save(ctx, state) + return StepResult("done", f"collected {record['successful']} successful trials of {record['trials']}; " + f"the library is synthesized once, at the epoch's end") + try: + text = self._synthesize(ctx, state, record) + except BudgetExceeded: + raise + except Exception as exc: # noqa: BLE001 — the step fails, the library stays + state["steps"].append({**record, "outcome": f"failed: {type(exc).__name__}: {exc}"[:600]}) + self._save(ctx, state) + return StepResult("failed", f"the synthesis failed: {type(exc).__name__}: {str(exc)[:300]}") + if text is None: + state["steps"].append({**record, "outcome": "nothing recurs in enough successful trials"}) + self._save(ctx, state) + return StepResult("done", f"no function is in {p.get('min_occurrences', 2)} successful trials yet " + f"({record['functions']} found): the library is unchanged", + extra={"record": record}) + before = (ctx.workspace.adapter / LIBRARY).read_text() if (ctx.workspace.adapter / LIBRARY).exists() else "" + (ctx.workspace.adapter / LIBRARY).write_text(text) + check = ctx.tools["check_spec"]() + if not check.get("passed"): + (ctx.workspace.adapter / LIBRARY).write_text(before) + record["outcome"] = f"the synthesized library failed check_spec: {check.get('issues')}"[:1000] + state["steps"].append(record) + self._save(ctx, state) + return StepResult("failed", "the synthesized library failed check_spec; the library is unchanged") + entry = self._candidate(ctx, state, f"step{step:04d}", text, step, ids) + record["outcome"] = "synthesized" + record["library"] = entry["file"] + state["steps"].append(record) + self._save(ctx, state) + score = f"; validation {entry['val']['mean']:.3f}" if "val" in entry else "" + return StepResult("done", f"synthesized {record['kept']} functions from {record['after_filtering']} candidates " + f"({record['successful']} new successful trials){score}", + rationale=f"dropped: {sorted(record['dropped'])}" if record["dropped"] else "", + extra={"record": {k: v for k, v in record.items() if k != "usage"}}) + + @staticmethod + def _current(ctx, state: dict) -> str: + """The current library, as finalize names it: how many functions, and for an empty one the last step's end.""" + path = ctx.workspace.adapter / LIBRARY + try: + functions = sum(isinstance(n, ast.FunctionDef) for n in ast.parse(path.read_text()).body) + except (OSError, SyntaxError): + functions = 0 + if functions: + return f"the current library ({functions} functions)" + last = (state.get("steps") or [{}])[-1].get("outcome") or "no step ran" + return f"the current library, empty (the last step: {last})"[:600] + + def finalize(self, ctx) -> FinalResult: + p = ctx.params + state = self._load(ctx) + libraries = state.get("libraries") or [] + if p.get("setting", "continual") == "paper" or p.get("select", "validation") == "last" or not libraries: + return FinalResult(adapter=ctx.workspace.adapter, summary=self._current(ctx, state)) + scored = [e for e in libraries if "val" in e] + if not scored: + return FinalResult(adapter=ctx.workspace.adapter, + summary=f"no library was scored on validation; {self._current(ctx, state)}") + best = max(scored, key=lambda e: (e["val"]["mean"], e["step"])) # a tie: the later, from more trials + (ctx.workspace.adapter / LIBRARY).write_text((ctx.workspace.state / best["file"]).read_text()) + state["final"] = best["name"] + self._save(ctx, state) + means = ", ".join(f"{e['name']}: {e['val']['mean']:.3f}" for e in scored) + return FinalResult(adapter=ctx.workspace.adapter, + summary=f"{best['name']}, the best validation mean ({means})") diff --git a/hermit/agent/evolver/methods/cap_agent0/evolver.yaml b/hermit/agent/evolver/methods/cap_agent0/evolver.yaml new file mode 100644 index 00000000..73ff3d33 --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/evolver.yaml @@ -0,0 +1,22 @@ +description: >- + CaP-Agent0's automatic skill-library synthesis (CaP-X, arXiv:2603.22435, §4.1; capgym/cap-x): the functions that + recur in successful programs, pooled and filtered with cap-x's compile code and curated by the run's model with + cap-x's skill-library prompt, become the library the CaP-Agent0 actor's programs call. `setting: paper` runs the + paper's single synthesis pass over the collection rollouts at the epoch's end; `setting: continual` (ours) + synthesizes again after every step from every successful trial so far and keeps the library that scores best on + the validation tasks. +class: evolver.py:CapAgent0Evolver +needs: [llm, context_tool] # the curation calls the run's model (ctx.agent); the library reaches the actor through + # its context tool +params: + setting: continual # paper: one synthesis at the epoch's end | continual: one after every step (ours) + min_occurrences: 2 # cap-x compile_skill_library.py --min-occurrences (default 2) + success_score: 1.0 # a trial counts as successful at this judge score (cap-x: task_completed) + select: validation # continual: the best validation mean of the libraries (and the starting one) | last + max_tokens: 20480 # the curation request's (cap-x sends none; an endpoint's default may cut the library + # short): the acting calls' cap-x default + temperature: null # null: the endpoint's default (cap-x sends none) + engine: null # the engine's sim.py (relative to the config): its own validator, on the benchmark's + # Python, checks each library before it is kept (null: the template's check alone) + aspire_root: null # the engine's ASPIRE checkout (null: ASPIRE_ROOT) + benchmark: libero-pro # the engine's benchmark, whose venv's Python the validator runs on diff --git a/hermit/agent/evolver/methods/cap_agent0/prompts.py b/hermit/agent/evolver/methods/cap_agent0/prompts.py new file mode 100644 index 00000000..4b40e6c6 --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/prompts.py @@ -0,0 +1,201 @@ +"""The texts CaP-Agent0's acting loop and its skill-library synthesis send, from cap-x at acac62f (capgym/cap-x), each +with where it comes from. Two are adapted to the cap-harness engine and named so: the task prompt's last line (the +engine's programs may import only `math`) and ENGINE_RULES, a note after the synthesis prompt (a function the engine +would refuse cannot be in the library). Everything else is verbatim; tests/methods/cap_agent0 compares these with a +cap-x checkout when CAPX_ROOT names one. +""" +from __future__ import annotations + +# --- the acting loop ------------------------------------------------------------------------------------------- + +# capx/envs/tasks/base.py CodeExecutionEnvBase.__init__: the system message of every code-generation request +SYSTEM_PROMPT = "You are a helpful assistant that generates Python code to directly solve the task." + +# env_configs/libero/franka_libero_cap_agent0.yaml env.cfg.prompt, its last line adapted: upstream it reads "The +# functions (APIs) below are already imported to the environment. If you want to use numpy, you need to import it +# explicitly." (UPSTREAM_LAST_LINE); the engine's programs may import only `math` and are refused for the +# constructs ASPIRE cap_harness/runtime.py `_ProgramValidator` names. +UPSTREAM_LAST_LINE = ("The functions (APIs) below are already imported to the environment. If you want to use numpy, " + "you need to import it explicitly.\n") +ADAPTED_LAST_LINE = ("The functions (APIs) below are already imported to the environment. The only module you may " + "import is math (`import math`, without an alias): numpy and every other module are " + "unavailable, and code may not define classes, use `with`, `global`, `nonlocal`, `del` or " + "`async`, or use names or attributes that start with `_`.\n") +TASK_PROMPT = ("You are controlling a Franka Emika robot with API described below.\n" + "Goal: {libero_environment_goal}\n" + "You may write python code comments for reasoning but ONLY write the executable Python code and do " + "not write it in code fences.\n" + "After this code executes, you will be able to get a new observation of the environment and write " + "new code to complete the task if needed.\n" + + ADAPTED_LAST_LINE) + +# env_configs/libero/franka_libero_cap_agent0.yaml env.cfg.multi_turn_prompt, verbatim +MULTI_TURN_PROMPT = ("The following code blocks were just executed:\n```python\n{executed_code}\n```\n" + "The current console stdout is:\n```\n{console_stdout}\n```\n" + "The current console stderr is:\n```\n{console_stderr}\n```\n" + "If there were no errors during compilation or execution, the console stderr will be empty. " + "If there were errors, consider regenerating the code.\n" + "Please respond with EXACTLY ONE of the following:\n" + "- The word 'REGENERATE' followed immediately by new Python code in a fenced code block " + "(```python...```) if you want to modify the code.\n" + "- The word 'FINISH' if the task appears to be complete\n") + +# capx/envs/tasks/base.py CodeExecutionEnvBase._get_complete_prompt: the task prompt, then "APIs:", then each API's +# documentation after a blank line +APIS = "\nAPIs:\n" + +# capx/envs/trial.py _capture_initial_visual_feedback: the initial scene's description, after the first user text +INITIAL_FEEDBACK = "The initial state of the environment is described as follows:\n{description}" + +# capx/envs/trial.py _describe_initial_scene, verbatim +DESCRIBE_SYSTEM = ("You are a helpful assistant that describes the initial state of the " + "environment with the goal of the task in mind. You should try to provide " + "objective information and no assumptions. Do *NOT* write any code.") +DESCRIBE_USER = ("Describe the initial state of the environment with the goal of the " + "task in mind. You should try to provide objective information and no " + "assumptions. Do *NOT* write any code.") +MAIN_CAMERA = "Main camera view:" + +# capx/envs/trial.py _get_visual_differencing_feedback, verbatim (the user text ends in two periods upstream) +DIFFERENCE_SYSTEM = ("You are a helpful assistant that describes the difference between the " + "current state of the environment and the previous state of the environment " + "with the goal of the task in mind and whether the task has been completed. " + "You should try to provide objective information and no assumptions. " + "Do *NOT* write any code.") +DIFFERENCE_USER = ("Describe the difference between the current state of the " + "environment and the previous state of the environment with the " + "goal of the task in mind and whether the task has been completed. " + "You should try to provide objective information and no assumptions. " + "Do *NOT* write any code..") +PREVIOUS_STATE = "Previous state (main camera):" +CURRENT_STATE = "Current state (main camera):" + + +def describe_messages(task_description: str, image_url: str) -> list[dict]: + """capx/envs/trial.py _describe_initial_scene: the request (the main camera only: the paper's VDM).""" + return [{"role": "system", "content": DESCRIBE_SYSTEM}, + {"role": "user", "content": [{"type": "text", "text": task_description}, + {"type": "text", "text": DESCRIBE_USER}, + {"type": "text", "text": MAIN_CAMERA}, + {"type": "image_url", "image_url": {"url": image_url}}]}] + + +def difference_messages(task_description: str, previous_url: str, current_url: str) -> list[dict]: + """capx/envs/trial.py _get_visual_differencing_feedback: the request for the two most recent frames.""" + return [{"role": "system", "content": DIFFERENCE_SYSTEM}, + {"role": "user", "content": [{"type": "text", "text": task_description}, + {"type": "text", "text": DIFFERENCE_USER}, + {"type": "text", "text": PREVIOUS_STATE}, + {"type": "image_url", "image_url": {"url": previous_url}}, + {"type": "text", "text": CURRENT_STATE}, + {"type": "image_url", "image_url": {"url": current_url}}]}] + + +def synthesis_messages(successful: list[dict], prompt: list[dict], *, is_multiturn: bool, + single_model: bool) -> list[dict]: + """capx/llm/client.py query_model_ensemble (single_model False) and query_single_model_ensemble (True): the + synthesis request over the successful candidates ({model, temp, content}), its texts verbatim.""" + # Build synthesis prompt + original_text = "" + for msg in prompt: + if msg["role"] == "user": + c = msg["content"] + if isinstance(c, list): + original_text += "".join(x.get("text", "") for x in c if isinstance(x, dict)) + elif isinstance(c, str): + original_text += c + + if single_model: + candidates = "\n\n".join( + f"--- Candidate (temp={r['temp']}) ---\n{r['content']}" + for r in successful + ) + else: + candidates = "\n\n".join( + f"--- Candidate ({r['model']}, temp={r['temp']}) ---\n{r['content']}" + for r in successful + ) + + # Detect if this is a multiturn decision (candidates contain REGENERATE/FINISH) + regenerate_count = sum(1 for r in successful + if isinstance(r.get("content"), str) and "REGENERATE" in r["content"]) + finish_count = sum(1 for r in successful if isinstance(r.get("content"), str) and "FINISH" in r["content"]) + + if is_multiturn: + synthesis_system_prompt = f"""You are synthesizing {len(successful)} candidate responses for a multi-turn robot control task. + + DECISION ANALYSIS: + - {regenerate_count} candidates voted REGENERATE + - {finish_count} candidates voted FINISH + + SYNTHESIS RULES: + 1. Analyze critically and assume no candidate is fully correct + 2. Prefer explicit checks over assumptions + 3. Combine the best ideas from multiple candidates when appropriate + 4. If candidates disagree fundamentally, choose the more robust approach + 5. Combine best code ideas from REGENERATE candidates + + OUTPUT FORMAT (strict): + - You may include brief reasoning first + - Then output "REGENERATE" on its own line followed by exactly ONE fenced code block, OR output "FINISH" on its own line + """ + else: + synthesis_system_prompt = f"""You are synthesizing {len(successful)} candidate Python solutions into one optimal program. + + SYNTHESIS RULES: + 1. Analyze critically and assume no candidate is fully correct + 2. Prefer explicit checks over assumptions + 3. Combine the best ideas from multiple candidates when appropriate + 4. If candidates disagree fundamentally, choose the more robust approach + + OUTPUT FORMAT (strict): + You may include reasoning before the fenced code block. + Output ONLY ONE fenced code block (```python...```) containing the complete final solution. + Do NOT include any other code blocks or code snippets outside this single block. + """ + + synthesis_user_prompt = f"""Synthesize the best solution. + + + {original_text} + + + + {candidates} + + """ + + return [ + { + "role": "system", + "content": synthesis_system_prompt, + }, + { + "role": "user", + "content": [ + { + "type": "text", + "text": synthesis_user_prompt, + } + ], + }, + ] + + +# --- the skill-library synthesis ------------------------------------------------------------------------------- + +# Adapted (ours): after SKILL_LIBRARY_PROMPT (upstream/compile_skill_library.py, verbatim), the rules the library's +# functions run under: the engine prepends the library to every program, so a function it would refuse stops every +# program. The released code stops at the curated text; the API module of nine functions +# (capx/integrations/franka/libero_reduced_skill_library.py) is not made by it. The Evolver takes the functions from +# the reply's ```python blocks, so the note also asks for the code there. +ENGINE_RULES = """ +--- +The library is Python that runs under these rules, before every program the coding agent writes (ASPIRE's +Code-as-Policy harness): the only import is `import math` (no numpy, no other module); no classes, `with`, `global`, +`nonlocal`, `del`, `async` or decorators; no names or attributes that start with `_`; the only builtins are +{builtins}; besides them a function may use only `math`, the harness's functions and constructors ({api}), and the +library's other functions. Defaults are literals. Each function needs a docstring: the coding agent reads the +library as each function's signature and docstring. Put the code of every function you select in ```python blocks +(top-level `def`s only); a function that breaks these rules is left out. +""" diff --git a/hermit/agent/evolver/methods/cap_agent0/upstream/LICENSE b/hermit/agent/evolver/methods/cap_agent0/upstream/LICENSE new file mode 100644 index 00000000..fd84283b --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/upstream/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Max Fu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/hermit/agent/evolver/methods/cap_agent0/upstream/__init__.py b/hermit/agent/evolver/methods/cap_agent0/upstream/__init__.py new file mode 100644 index 00000000..5fb0a954 --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/upstream/__init__.py @@ -0,0 +1,24 @@ +"""cap-x (https://github.com/capgym/cap-x, MIT, LICENSE here) at acac62fcb1b6f9e02975004a2c729a65e11bffed: the +pure-Python definitions CaP-Agent0's port calls, each copied verbatim as its source segment (the file's other +definitions are not here; each file's header names what it holds): + +- trial.py capx/envs/trial.py: `_annotate_code_blocks` (the trial's code as its summary holds it) +- client.py capx/llm/client.py: `collapse_text_image_inputs` +- launch_utils.py capx/utils/launch_utils.py: `_extract_code`, `_build_multi_turn_decision_prompt`, + `_parse_multi_turn_decision` +- parse_outputs.py scripts/skill_library_compilation/parse_outputs.py: the function-definition regex and + `compile_successful_functions` (functions.txt of an experiment's successful trials) +- compile_skill_library.py scripts/skill_library_compilation/compile_skill_library.py: `SKILL_LIBRARY_PROMPT`, + `EXCLUDED_FUNCTION_NAMES`, `FunctionInfo`, `AggregatedFunction`, `parse_functions_file`, + `filter_functions`, `format_functions_for_prompt` + +The rest of cap-x's trial loop (capx/envs/trial.py `_run_single_trial`), its model client and its synthesis call +cannot be imported here: capx/envs and capx/integrations import torch, SAM 3, Ray, Open3D and JAX at package import, +capx/utils/launch_utils.py sets the process-wide multiprocessing start method when imported, and capx/llm/client.py +retries a failed request without end. ../actor.py and ../evolver.py reimplement those parts, naming for each the +upstream function it follows; tests/methods/cap_agent0 compares these copies, and the prompt texts in ../prompts.py, +with a cap-x checkout when CAPX_ROOT names one. The copies keep cap-x's annotations, which name types not imported here +(`np.ndarray`, `TrialData`): `from __future__ import annotations` leaves them unevaluated. +""" +UPSTREAM = "https://github.com/capgym/cap-x" +COMMIT = "acac62fcb1b6f9e02975004a2c729a65e11bffed" diff --git a/hermit/agent/evolver/methods/cap_agent0/upstream/client.py b/hermit/agent/evolver/methods/cap_agent0/upstream/client.py new file mode 100644 index 00000000..e38822b3 --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/upstream/client.py @@ -0,0 +1,22 @@ +"""cap-x capx/llm/client.py at acac62f (capgym/cap-x, MIT; ../LICENSE): collapse_text_image_inputs, verbatim. Nothing +else of the file is here; the imports are the ones these need.""" +from __future__ import annotations + + +def collapse_text_image_inputs(messages: list[dict]) -> list[dict]: + """ + Collapse a list of messages with sequential text into a single text input, images are still in the same relative position + """ + new_prompt = [] + current_text_input = "" + for message in messages: + if message["type"] == "text": + current_text_input += message["text"] + "\n" + else: + if current_text_input != "": + new_prompt.append({"type": "text", "text": current_text_input}) + current_text_input = "" + new_prompt.append(message) + if current_text_input != "": + new_prompt.append({"type": "text", "text": current_text_input}) + return new_prompt diff --git a/hermit/agent/evolver/methods/cap_agent0/upstream/compile_skill_library.py b/hermit/agent/evolver/methods/cap_agent0/upstream/compile_skill_library.py new file mode 100644 index 00000000..d5a805da --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/upstream/compile_skill_library.py @@ -0,0 +1,200 @@ +"""cap-x scripts/skill_library_compilation/compile_skill_library.py at acac62f (capgym/cap-x, MIT; ../LICENSE): +EXCLUDED_FUNCTION_NAMES, SKILL_LIBRARY_PROMPT, FunctionInfo, AggregatedFunction, parse_functions_file, +filter_functions, format_functions_for_prompt, verbatim. Nothing else of the file is here; the imports are the ones +these need.""" +from __future__ import annotations + +import re +from dataclasses import dataclass +from pathlib import Path + + +EXCLUDED_FUNCTION_NAMES = { + "main", + "run", + "execute", + "test", + "demo", + "setup", + "cleanup", + "init", + "initialize", +} + + +SKILL_LIBRARY_PROMPT = """You are an expert robotics software engineer curating a reusable skill library. + +Below are function definitions extracted from successful robot manipulation code generations across multiple tasks and models. +These functions were composed by LLM coding agents to solve various manipulation tasks using a reduced/low-level robotics API. + +Your task is to: +1. Identify the MOST USEFUL and REUSABLE functions that could form a general-purpose skill library +2. Group similar functions into categories (e.g., perception, motion, grasping, coordinate transforms) +3. For each category, select the BEST implementation(s) - prefer well-documented, general-purpose versions +4. Exclude task-specific or overly narrow functions +5. Note any functions that appear frequently - this indicates high utility + +Output format: +- Organize by category +- For each selected function, explain WHY it's useful and reusable +- Include the full function code, along with proper Python docstring and type hints, return types, etc. +- Note how many times similar functions appeared (popularity) + +Focus on functions that would be valuable additions to a robotics manipulation toolkit. + +--- +EXTRACTED FUNCTIONS (with occurrence counts and sources): +{functions} +""" + + +@dataclass +class FunctionInfo: + """Information about a single function definition.""" + name: str + signature: str + full_code: str + trials: list[int] + model_name: str + experiment_name: str + + @property + def trial_count(self) -> int: + return len(self.trials) + + +@dataclass +class AggregatedFunction: + """A function aggregated across multiple experiments.""" + name: str + implementations: list[FunctionInfo] + + @property + def total_occurrences(self) -> int: + return sum(f.trial_count for f in self.implementations) + + @property + def experiment_count(self) -> int: + return len(self.implementations) + + @property + def models(self) -> set[str]: + return {f.model_name for f in self.implementations} + + def best_implementation(self) -> FunctionInfo: + """Return the implementation with most occurrences (likely best tested).""" + return max(self.implementations, key=lambda f: f.trial_count) + + +def parse_functions_file(file_path: Path, model_name: str, experiment_name: str) -> list[FunctionInfo]: + """Parse a functions.txt file and extract function information.""" + functions = [] + + try: + content = file_path.read_text() + except Exception: + return functions + + # Split by function separator + sections = content.split("────────────────────────────────────────────────────────────") + + for section in sections[1:]: # Skip header + section = section.strip() + if not section: + continue + + lines = section.split("\n") + + # Parse function name + name_match = re.search(r"Function:\s*(\w+)", lines[0] if lines else "") + if not name_match: + continue + name = name_match.group(1) + + # Skip excluded functions + if name.lower() in EXCLUDED_FUNCTION_NAMES: + continue + + # Parse trials + trials = [] + trials_match = re.search(r"Found in trials:\s*([\d,\s]+)", section) + if trials_match: + trials = [int(t.strip()) for t in trials_match.group(1).split(",") if t.strip()] + + # Extract code (everything after the trials line) + code_start = section.find("def ") + if code_start == -1: + continue + + full_code = section[code_start:].strip() + + # Extract signature (first line of def) + sig_match = re.match(r"(def\s+\w+\s*\([^)]*\)[^:]*:)", full_code) + signature = sig_match.group(1) if sig_match else f"def {name}(...)" + + functions.append(FunctionInfo( + name=name, + signature=signature, + full_code=full_code, + trials=trials, + model_name=model_name, + experiment_name=experiment_name, + )) + + return functions + + +def filter_functions( + functions: dict[str, AggregatedFunction], + min_occurrences: int = 2, +) -> dict[str, AggregatedFunction]: + """Filter functions based on criteria.""" + filtered = {} + + for name, func in functions.items(): + # Skip if too few occurrences + if func.total_occurrences < min_occurrences: + continue + + # Skip very short functions (likely trivial) + best = func.best_implementation() + if len(best.full_code.split("\n")) < 3: + continue + + # Skip if name suggests task-specificity + task_specific_patterns = [ + r"cube", r"stack", r"lift", r"wipe", r"spill", r"place_.*_on", + r"pick_.*_up", r"grab_the", r"move_to_goal", + ] + if any(re.search(p, name.lower()) for p in task_specific_patterns): + continue + + filtered[name] = func + + return filtered + + +def format_functions_for_prompt(functions: dict[str, AggregatedFunction]) -> str: + """Format aggregated functions for the LLM prompt.""" + lines = [] + + # Sort by total occurrences (most popular first) + sorted_funcs = sorted( + functions.values(), + key=lambda f: f.total_occurrences, + reverse=True + ) + + for func in sorted_funcs: + best = func.best_implementation() + models = ", ".join(sorted(func.models)) + + lines.append(f"\n{'='*70}") + lines.append(f"FUNCTION: {func.name}") + lines.append(f"Total occurrences: {func.total_occurrences} (across {func.experiment_count} experiments)") + lines.append(f"Models: {models}") + lines.append(f"Best implementation from: {best.model_name}/{best.experiment_name} ({best.trial_count} trials)") + lines.append("") + lines.append(best.full_code) + + return "\n".join(lines) diff --git a/hermit/agent/evolver/methods/cap_agent0/upstream/launch_utils.py b/hermit/agent/evolver/methods/cap_agent0/upstream/launch_utils.py new file mode 100644 index 00000000..537f6adf --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/upstream/launch_utils.py @@ -0,0 +1,109 @@ +"""cap-x capx/utils/launch_utils.py at acac62f (capgym/cap-x, MIT; ../LICENSE): _extract_code, +_build_multi_turn_decision_prompt, _parse_multi_turn_decision, verbatim. Nothing else of the file is here; the +imports are the ones these need.""" +from __future__ import annotations + +import copy + +from .client import collapse_text_image_inputs + + +def _extract_code(content: str) -> list[str]: + """Extract Python code from Markdown fenced code block. + + Args: + content: Raw model response + + Returns: + Extracted Python code list + """ + fence_start = "```python\n" + fence_end = "```" + start_idx = 0 + end_idx = len(content) + 1 + if fence_start in content: + start_idx = content.find(fence_start) + len(fence_start) + content = content[start_idx:] + if fence_end in content: + end_idx = content.rfind(fence_end) + content = content[:end_idx] + + content = content.strip() + # NOTE: might gen empty code block at the end + # content_list = content.split("breakpoint_code_block()") + + return [content] + + +def _build_multi_turn_decision_prompt( + obs: dict[str, np.ndarray], + complete_multi_turn_prompt: str, + visual_feedback: str | None = None, + visual_differencing_feedback: str | None = None, + *, + is_video_feedback: bool = False, +) -> list[dict]: + """Build the multi-turn decision prompt for the model. + + Args: + obs: The observation + complete_multi_turn_prompt: The formatted multi-turn prompt with the executed and remaining code blocks + visual_feedback: The base64 encoded image of the current state of the environment + visual_differencing_feedback: Text description from VDM (image or video based) + is_video_feedback: If True, use video-appropriate framing for the differencing feedback. + + Returns: + The multi-turn decision prompt as a list of dictionaries + """ + multi_turn_decision_prompt = copy.deepcopy(obs["full_prompt"]) + # TODO: I think the order of the content is important, unsure if it should be before or after the complete_multi_turn_prompt + multi_turn_decision_prompt[-1]["content"].append( + {"type": "text", "text": complete_multi_turn_prompt} + ) + if visual_feedback is not None: + multi_turn_decision_prompt[-1]["content"].append( + { + "type": "text", + "text": "Included below is an image of the current state of the environment (after the code above was executed).", + } + ) + multi_turn_decision_prompt[-1]["content"].append( + {"type": "image_url", "image_url": {"url": visual_feedback}} + ) + if visual_differencing_feedback is not None: + if is_video_feedback: + feedback_header = ( + "Included below is a description of the robot's execution based " + "on video observation of this turn:" + ) + else: + feedback_header = ( + "Included below is the observed differences between the current " + "state of the environment (afer the code above was executed) and " + "the previous state of the environment (before the code above was " + "executed):" + ) + multi_turn_decision_prompt[-1]["content"].append( + {"type": "text", "text": f"{feedback_header}\n{visual_differencing_feedback}"} + ) + multi_turn_decision_prompt[-1]["content"].append( + {"type": "text", "text": "Based on the code output, potential error messages, and the observation made above, carefully reason about the following:\nPlease respond with EXACTLY ONE of the following:\n- The word 'REGENERATE' followed immediately by new Python code in a fenced code block (```python...```) if you want to modify the code.\n- The word 'FINISH' if the task appears to be complete"} + ) + # collapse the last message + multi_turn_decision_prompt[-1]["content"] = collapse_text_image_inputs(multi_turn_decision_prompt[-1]["content"]) + return multi_turn_decision_prompt + + +def _parse_multi_turn_decision(content: str) -> tuple[str, str | None]: + """Parses the multi-turn decision response from the model + + Args: + content: The model's response to the multi-turn decision prompt + + Returns: + A tuple containing the decision and the new code (if any) + """ + if content is not None and ("REGENERATE" in content): + return "regenerate", content.split("REGENERATE")[1].strip() # new code + else: + return "finish", content diff --git a/hermit/agent/evolver/methods/cap_agent0/upstream/parse_outputs.py b/hermit/agent/evolver/methods/cap_agent0/upstream/parse_outputs.py new file mode 100644 index 00000000..1275e880 --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/upstream/parse_outputs.py @@ -0,0 +1,100 @@ +"""cap-x scripts/skill_library_compilation/parse_outputs.py at acac62f (capgym/cap-x, MIT; ../LICENSE): +FUNCTION_DEF_PATTERN, FUNCTION_SIG_PATTERN, extract_functions_from_code, compile_successful_functions, verbatim. +Nothing else of the file is here; the imports are the ones these need.""" +from __future__ import annotations + +import re +from typing import Dict + + +FUNCTION_DEF_PATTERN = re.compile( + r'^(def\s+\w+\s*\([^)]*\)\s*(?:->\s*[^:]+)?:\s*\n(?:(?:[ \t]+.+\n?)+))', + re.MULTILINE +) + + +FUNCTION_SIG_PATTERN = re.compile( + r'^def\s+(\w+)\s*\(([^)]*)\)\s*(?:->\s*([^:]+))?:', + re.MULTILINE +) + + +def extract_functions_from_code(code: str) -> list[dict]: + """Extract all function definitions from code. + + Returns list of dicts with 'name', 'signature', and 'full_def' keys. + """ + functions = [] + + # Find all function definitions + for match in FUNCTION_DEF_PATTERN.finditer(code): + full_def = match.group(1).strip() + + # Extract signature info + sig_match = FUNCTION_SIG_PATTERN.match(full_def) + if sig_match: + name = sig_match.group(1) + params = sig_match.group(2).strip() + return_type = sig_match.group(3).strip() if sig_match.group(3) else None + + signature = f"def {name}({params})" + if return_type: + signature += f" -> {return_type}" + + functions.append({ + 'name': name, + 'signature': signature, + 'full_def': full_def, + }) + + return functions + + +def compile_successful_functions(sorted_results: Dict[int, TrialData]) -> str: + """Extract and compile all function definitions from successful trials. + + Returns a formatted string listing all unique functions found. + """ + all_functions = {} # name -> list of (trial_idx, function_info) + + for trial_idx, trial_data in sorted_results.items(): + if not trial_data.task_completed: + continue + + try: + code = trial_data.summary_txt.read_text() + functions = extract_functions_from_code(code) + + for func in functions: + name = func['name'] + if name not in all_functions: + all_functions[name] = [] + all_functions[name].append((trial_idx, func)) + except Exception: + continue + + if not all_functions: + return "No function definitions found in successful trials." + + # Format output + lines = [ + "Function Definitions from Successful Trials", + "=" * 60, + f"Total unique functions: {len(all_functions)}", + "", + ] + + for name in sorted(all_functions.keys()): + occurrences = all_functions[name] + trial_ids = [str(t[0]) for t in occurrences] + + lines.append(f"\n{'─' * 60}") + lines.append(f"Function: {name}") + lines.append(f"Found in trials: {', '.join(trial_ids)}") + lines.append("") + + # Show the first occurrence's full definition + _, func_info = occurrences[0] + lines.append(func_info['full_def']) + + return "\n".join(lines) diff --git a/hermit/agent/evolver/methods/cap_agent0/upstream/trial.py b/hermit/agent/evolver/methods/cap_agent0/upstream/trial.py new file mode 100644 index 00000000..6ae07bec --- /dev/null +++ b/hermit/agent/evolver/methods/cap_agent0/upstream/trial.py @@ -0,0 +1,16 @@ +"""cap-x capx/envs/trial.py at acac62f (capgym/cap-x, MIT; ../LICENSE): _annotate_code_blocks, verbatim. Nothing else +of the file is here; the imports are the ones these need.""" +from __future__ import annotations + +from typing import Any + + +def _annotate_code_blocks( + code_blocks: list[str], + code_block_metadata: list[dict[str, Any]], +) -> str: + """Join code blocks into a single string with ``# Code block N`` headers.""" + annotated = [] + for i, (block, metadata) in enumerate(zip(code_blocks, code_block_metadata, strict=False)): + annotated.append(f"# Code block {i}\n{block}") + return "\n\n".join(annotated) diff --git a/tests/README.md b/tests/README.md index 4f45e3ba..0ff940cc 100644 --- a/tests/README.md +++ b/tests/README.md @@ -10,7 +10,7 @@ python -m pytest --integration ... # also the tests that run an agent CLI insta | Group | What it covers | |---|---| | `core/` | the framework: the Trainer, templates and `check_spec`, deployment and host exporters, the agent layers (Base Agents, CLI agents, model bindings), the sandbox and isolation, the generic AgentEvolvers | -| `methods//` | one method: its Evolver, its template and its examples (`ace`, `ahe`, `aspire`, `continual_harness`, `evosafe`, `harness2`, `meta_harness_adapter`, `mwm`, `opro`, `optimizers` for GEPA and SkillOpt, `reharness`, `rrsi_adapter`, `she`) | +| `methods//` | one method: its Evolver, its template and its examples (`ace`, `ahe`, `aspire`, `cap_agent0`, `continual_harness`, `evosafe`, `harness2`, `meta_harness_adapter`, `mwm`, `opro`, `optimizers` for GEPA and SkillOpt, `reharness`, `rrsi_adapter`, `she`) | `--changed` reads `selection.py`: `core/` runs for every change but documentation (its tests also read every method's template, manifest and packaging); a method's own files (its Evolver, its template, its examples, its tests) diff --git a/tests/core/test_selection.py b/tests/core/test_selection.py index c48640c1..d2c8a3e4 100644 --- a/tests/core/test_selection.py +++ b/tests/core/test_selection.py @@ -62,8 +62,8 @@ def test_a_benchmarks_shared_files_run_the_methods_with_an_example_there(): "rrsi_adapter", "core"} assert groups_for("examples/servelearnbench/utils/x.py") == {"mwm", "core"} # an engine several benchmarks run on: the methods with an example under any of them - assert groups_for("examples/cap_harness/utils/agent/sim.py") == {"aspire", "core"} - assert groups_for("examples/libero/utils/agent/task.py") == {"aspire", "core"} + assert groups_for("examples/cap_harness/utils/agent/sim.py") == {"aspire", "cap_agent0", "core"} + assert groups_for("examples/libero/utils/agent/task.py") == {"aspire", "cap_agent0", "core"} assert groups_for("examples/robosuite/aspire/run.yaml") == {"aspire", "core"} groups, why = select(["hermit/cli.py", "examples/officeqa/rrsi_adapter/README.md", "docs/index.md"]) assert groups == {"core", "rrsi_adapter"} and why == {"core": "hermit/cli.py", diff --git a/tests/methods/cap_agent0/test_cap_agent0.py b/tests/methods/cap_agent0/test_cap_agent0.py new file mode 100644 index 00000000..d40ce57b --- /dev/null +++ b/tests/methods/cap_agent0/test_cap_agent0.py @@ -0,0 +1,1522 @@ +"""CaP-Agent0: the cap-agent0 template (the skill library, its reader and its check), its acting agent on the +cap-harness engine (actor.py: each block in its own `try` with markers, the turns replayed from the reset, the VDM's +frames, the ensemble, the decisions, the collection tier, a failed trial), the library synthesis in both settings +(evolver.py, with a scripted model and a scripted run_agent, and through the Trainer on a toy task), the LIBERO-Pro +rows, judge and configs (examples/libero/cap_agent0/), and the copies of cap-x's code and texts (upstream/, +prompts.py). + +The engine is its own code (examples/cap_harness/utils/agent/sim.py, in its bubblewrap sandbox) over a stand-in +ASPIRE checkout (`checkout`): its cap-harness runs each program as ASPIRE's ProgramExecutor does, with stand-in tools +on a scene of a bowl and a plate that record keyframes. The models are scripted; no simulator, no network. With +CAPX_ROOT (a cap-x checkout with acac62f) and ASPIRE_ROOT (an ASPIRE checkout at fa00f0e) set, the copies are compared +with their sources; without them those tests skip.""" +import __future__ +import ast +import base64 +import builtins +from concurrent.futures import ThreadPoolExecutor +import contextlib +import dataclasses +import importlib.util +import inspect +import io +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import threading +import time +from types import SimpleNamespace + +import pytest +import yaml + +from hermit.agent.evolver.base import Access, Progress, StepContext, Usage, Workspace +from hermit.agent.evolver.methods.cap_agent0 import actor as A +from hermit.agent.evolver.methods.cap_agent0 import evolver as E +from hermit.agent.evolver.methods.cap_agent0 import prompts as P +from hermit.agent.evolver.methods.cap_agent0 import upstream as U +from hermit.agent.evolver.methods.cap_agent0.upstream.trial import _annotate_code_blocks +from hermit.common import RunOutput +from hermit.spec import check_spec +from hermit.trainer.budget import BudgetExceeded +from fakes import agent_of + +ROOT = Path(__file__).resolve().parents[3] +TEMPLATE = ROOT / "hermit" / "adapter" / "templates" / "cap_agent0" +METHOD = ROOT / "hermit" / "agent" / "evolver" / "methods" / "cap_agent0" +ENGINE = ROOT / "examples" / "cap_harness" / "utils" +LIBERO = ROOT / "examples" / "libero" +EXAMPLE = LIBERO / "cap_agent0" +DEFAULTS = yaml.safe_load((METHOD / "evolver.yaml").read_text()) + + +def _fakes(): + spec_ = importlib.util.spec_from_file_location("cap_fakes", ENGINE / "tests" / "cap_fakes.py") + module = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(module) + return module + + +F = _fakes() +tmp_path = F.tmp_path # a fixture: a directory outside /tmp, for the sandboxes +needs_bwrap = F.needs_bwrap +_load = F._load +CHECK = E.template_check() + +LIBRARY = '''"""A library.""" +import math + + +def unit(v: list, eps: float = 1e-09) -> list: + """Scale v to length one. + + Returns a new list.""" + n = math.sqrt(sum(x * x for x in v)) + return [x / max(n, eps) for x in v] + + +def place(name: str, *, height=0.1) -> dict: + """Move above `name` and open the gripper.""" + move_to_pose(Pose(unit([0.0, 0.0, height]), [1.0, 0.0, 0.0, 0.0])) + return open_gripper() +''' +# Signatures as inspect.signature prints them (the reader parses, never runs, the library) +SIGNATURES = ''' + +def every_kind(a, /, b: int = -2, *args, c, d: float = 0.5, e=(1, 'x'), **kw) -> None: + """Every kind of parameter.""" + + +def keywords_only(*, flag=True, name: str = 'n'): + """Keyword-only parameters.""" + + +def no_doc(x): + return x +''' + + +def seed(tmp: Path, library: str | None = None) -> Path: + adapter = tmp / "adapter" + shutil.copytree(TEMPLATE, adapter, ignore=shutil.ignore_patterns("__pycache__")) + if library is not None: + (adapter / "skill_library.py").write_text(library) + return adapter + + +def spec(path) -> dict: + r = check_spec(Path(path), TEMPLATE, deploy=False) + return {"passed": r.passed, "issues": [{"path": i.path, "problem": i.problem} for i in r.issues]} + + +# ---------- the template ---------- + +def test_the_template_root_and_a_library_of_functions_pass_their_check(tmp_path): + assert spec(TEMPLATE)["passed"] + assert spec(seed(tmp_path, LIBRARY)) == {"passed": True, "issues": []} + + +def test_the_check_refuses_a_file_off_the_surface_and_a_library_past_its_size(tmp_path): + adapter = seed(tmp_path, '"""big"""\n' + "".join(f"# {'x' * 98}\n" for _ in range(700))) + (adapter / "notes.md").write_text("x") + problems = [i["problem"] for i in spec(adapter)["issues"]] + assert any("notes.md is off the adapter's surface" in p for p in problems), problems + assert any("past 60000" in p for p in problems), problems + + +def test_the_check_takes_the_names_a_match_pattern_binds(): + """`case (a, b):` binds a and b (3.10's grammar, which the engine runs): they are the function's own names.""" + library = ('"""L."""\n\n\ndef total(p):\n """The total."""\n match p:\n case (a, b):\n' + ' return a + b\n case [x, *rest]:\n return x\n' + ' case {"k": v, **others}:\n return v\n return 0\n') + assert CHECK.library_problems(library) == [] + + +@pytest.mark.parametrize("library, problem", [ + ("x = 1\n", "only function definitions"), + ("import numpy\n", "only function definitions"), + ('class Grip:\n """A class."""\n', "only function definitions"), + ('def f():\n """F."""\n return np.zeros(3)\n', "names neither the engine nor the library defines: np"), + ('def f():\n """F."""\n return Pose3D(0.0)\n', "names neither the engine nor the library defines: Pose3D"), + ('def f():\n """F."""\n return math.pi\n', "names neither the engine nor the library defines: math"), + ("def f():\n return 1\n", "no docstring"), + ('def f(n=len([])):\n """F."""\n return n\n', "a default that is not a literal"), + ('@print\ndef f():\n """F."""\n', "a decorator"), + ('def _f():\n """F."""\n', "starts with `_`"), + ('def go_home():\n """F."""\n', "is the engine's name"), + ('def result():\n """F."""\n', "is the engine's name"), + ('def f():\n """F."""\n return check_success()\n', "privileged access (check_success)"), + ('def f(o):\n """F."""\n return o.__dict__\n', "private and dunder attribute access"), + ('def f():\n """F."""\n class K:\n pass\n', "ClassDef is not allowed"), + ('def f(h):\n """F."""\n with h:\n pass\n', "With is not allowed"), + ('def f():\n """F."""\n import os\n', "only `import math`"), + ('def f():\n """F."""\n\n\ndef f():\n """G."""\n', "defined twice"), + ("def f(:\n", "does not parse"), + ('def f():\n """F."""\n break\n', "the engine would not compile it: 'break' outside loop"), + ('def f():\n """F."""\n return dict(a=1, a=2)\n', "keyword argument repeated: a"), + ('def f[T](x):\n """F."""\n return x\n', "only supported in Python 3.12 and greater"), # ASPIRE: 3.10+ +]) +def test_the_check_refuses_what_would_stop_every_program(library, problem): + """The library runs before every program: each of these would stop them all (the engine's validator or its + compile refusing it, a NameError, a privileged call), take an engine's name, or hide a function from the acting + agent.""" + problems = CHECK.library_problems(library) + assert any(problem in p for p in problems), problems + + +def test_the_reader_documents_each_function_as_cap_x_documents_an_api(tmp_path): + """interface.library: each function's name and signature as inspect.signature prints it, then its docstring + under " Doc:" as inspect.getdoc cleans it (cap-x ApiBase.combined_doc), in the file's order; the code as it + is; the empty library is nothing at all.""" + reader = _load("cap_agent0_reader", seed(tmp_path, LIBRARY + SIGNATURES) / "interface.py") + out = reader.library("libero_object", {"id": "x"}) + assert out["functions"] == ["unit", "place", "every_kind", "keywords_only", "no_doc"] + assert out["source"] == LIBRARY + SIGNATURES + assert out["text"].startswith("unit(v: list, eps: float = 1e-09) -> list\n Doc:\n Scale v to length one.\n" + " \n Returns a new list.\n\nplace(name: str, *, height=0.1) -> dict\n Doc:\n" + " Move above `name` and open the gripper.\n\n") + assert out["text"].endswith("\n\nno_doc(x)") + namespace = {} + exec(LIBRARY + SIGNATURES, namespace) # the reader's signatures are inspect's + for fn in reader.functions(LIBRARY + SIGNATURES): + assert fn.name + reader.signature(fn) == fn.name + str(inspect.signature(namespace[fn.name])) + assert (ast.get_docstring(fn) or None) == inspect.getdoc(namespace[fn.name]) + empty = _load("cap_agent0_empty", seed(tmp_path / "empty") / "interface.py") + assert empty.library() == {"text": "", "source": "", "functions": []} + + +def test_the_actor_reads_the_library_through_the_adapters_context_tool(tmp_path): + """The library reaches the acting agent only through the template's context tool (exports.yaml): its text and + its code, from one call before the trial; no adapter, no library.""" + actor = A.CapAgent0Actor({}) + got = actor.library(seed(tmp_path, LIBRARY), {"id": "t", "suite": "libero_object"}) + assert got["functions"] == ["unit", "place"] and got["source"] == LIBRARY + assert got["text"].startswith("unit(v: list, eps: float = 1e-09) -> list") + assert actor.library(None, {"id": "t"}) == {"text": "", "source": "", "functions": []} + assert actor.library(seed(tmp_path / "empty"), {"id": "t"}) == {"text": "", "source": "", "functions": []} + + +# ---------- a turn's program ---------- + +SAFE = {name: getattr(builtins, name) for name in CHECK.BUILTINS} + + +def _import(name, *args, **kwargs): + if name != "math": + raise ImportError(name) + return __import__(name) + + +def run_as_the_engine(source: str) -> str: + """`source` as ASPIRE's ProgramExecutor runs it: its builtins only, one namespace, stdout captured, compiled with + the `from __future__ import annotations` of its runtime.py (a type hint is never evaluated).""" + assert CHECK.program_problem(source) is None, CHECK.program_problem(source) # its validator takes it + out = io.StringIO() + with contextlib.redirect_stdout(out): + exec(compile(source, "", "exec", flags=__future__.annotations.compiler_flag, + dont_inherit=True), g := {"__builtins__": {**SAFE, "__import__": _import}}, g) + return out.getvalue() + + +def test_each_block_runs_in_its_own_try_and_the_run_splits_its_output_by_block(): + """cap-x runs each block as one `exec` in the episode's namespace: an exception ends that block, not the next, + and what a block defines stays for the later ones. A refused block (None) keeps only its marker.""" + library = '"""L."""\n\n\ndef twice(x):\n """Twice x."""\n return 2 * x\n' + blocks = ['print("zero")\ndef helper():\n return 3\nvalue = {}["k"]\nprint("never")', + None, + 'print("two", twice(helper()))', + 'raise ValueError("bad\\nvalue")', + "pass # nothing printed"] + stdout = run_as_the_engine(A.program(library, blocks)) + assert A.block_output(stdout, 0) == ("zero\n", "KeyError: 'k'") + assert A.block_output(stdout, 1) == ("", "") + assert A.block_output(stdout, 2) == ("two 6\n", "") + assert A.block_output(stdout, 3) == ("", "ValueError: bad\nvalue") + assert A.block_output(stdout, 4) == ("", "") + assert A.block_output(stdout, 5) == ("", "") # a block the program does not have + # a block is printed again from its syntax tree (a string's lines are never indented again; comments go) + assert A.program("", ['x = "a\\nb" # note']).startswith( + "print('<<>>')\ntry:\n x = 'a\\nb'\n") + + +# ---------- the trial on the engine ---------- + +API = ("# API reference\n\nmove_to_pose(target) -> dict\n Move the gripper to `target`.\n\n" + f"{A.API_SECTIONS_END}\n\nHost-side text a program never sees.\n") +# The stand-in of the checkout's cap_harness/runtime.py, which the engine's validator imports (`python -c` in the +# checkout): ASPIRE's program rules (runtime.py `_ProgramValidator` at fa00f0e, as the template's check states them; +# test_the_templates_engine_rules_are_aspires compares them with a checkout's) and its builtins +RUNTIME = r''' +import ast +import builtins +import importlib + +FORBIDDEN = (ast.AsyncFunctionDef, ast.Await, ast.ClassDef, ast.Delete, ast.Global, ast.ImportFrom, ast.Nonlocal, + ast.With) + + +def restricted_import(name, globals=None, locals=None, fromlist=(), level=0): + if level or name != "math": + raise ImportError(f"import of {name!r} is not allowed in generated programs") + return importlib.import_module(name) + + +SAFE_BUILTINS = {"__import__": restricted_import, **{n: getattr(builtins, n) for n in @BUILTINS@}} + + +class _ProgramValidator(ast.NodeVisitor): + def generic_visit(self, node): + if isinstance(node, FORBIDDEN): + raise ValueError(f"{type(node).__name__} is not allowed in generated programs") + if isinstance(node, ast.Import) and any(a.name != "math" or a.asname for a in node.names): + raise ValueError("Import of a module other than math is not allowed, nor an alias") + if isinstance(node, ast.Attribute) and node.attr.startswith("_"): + raise ValueError("private and dunder attribute access is not allowed") + if isinstance(node, ast.Name) and node.id.startswith("_"): + raise ValueError("private and dunder names are not allowed") + super().generic_visit(node) +''' +CAP_HARNESS = r'''#!@PYTHON@ +"""A stand-in for ASPIRE's `cap-harness run-batch` on LIBERO, which the engine runs in its sandbox: each seed's episode +runs the program as ASPIRE's ProgramExecutor does (validated; run with its builtins and tools in one namespace, its +stdout captured; an exception ends the program) on a scene of a bowl and a plate, records a keyframe before and after +each motion, and writes the run's files where ASPIRE does: results.jsonl, outcome.json, source/program-result.json +and media/keyframes/--/agentview.png. The bowl released over the plate is the task done, which +ends the episode (LIBERO's done): a motion after it fails. With FAKE_JITTER set, every frame differs from run to run +(a service that is not deterministic); FAKE_CRASH=harness_error ends each seed before its episode (ASPIRE's +harness_error), FAKE_CRASH=no_results writes no row for it (a sweep that died). As ASPIRE at fa00f0e: a run is +/// (artifacts.py RunRecorder, --flat-run-dir), and a program inherits the +`from __future__ import annotations` of runtime.py, whose compile() runs it (a type hint is never evaluated).""" +from __future__ import annotations +import argparse, ast, contextlib, io, json, os, pathlib, sys, types +sys.path.insert(0, os.getcwd()) # the checkout, where the engine runs it: its cap_harness +from cap_harness.runtime import SAFE_BUILTINS, _ProgramValidator + +ap = argparse.ArgumentParser() +for flag in ("--benchmark", "--suite", "--task-id", "--program", "--output-root", "--max-steps", "--seed", + "--workers", "--results-jsonl", "--log-dir", "--init-mode"): + ap.add_argument(flag) +ap.add_argument("--seeds", nargs="+") +ap.add_argument("--flat-run-dir", action="store_true") +ap.add_argument("--no-videos", action="store_true") +ap.add_argument("cmd") +a = ap.parse_args() +code = pathlib.Path(a.program).read_text() +out = pathlib.Path(a.output_root) +rows = [] +for seed in a.seeds: + run = out / f"{int(seed):04d}" / f"run-stand-in-{os.urandom(4).hex()}" + (run / "source").mkdir(parents=True, exist_ok=True) + crash = os.environ.get("FAKE_CRASH") + if crash: # a run lost after it began: its folder and a frame stay + lost = run / "media" / "keyframes" / "000000-before-move-to-pose" + lost.mkdir(parents=True) + (lost / "agentview.png").write_bytes(b"lost") + if crash == "no_results": + continue + if crash == "harness_error": + (run / "outcome.json").write_text(json.dumps({"task_success": False, "program_ok": False, + "termination_reason": "harness_error", "steps_executed": 0, + "error": {"message": "the simulator did not start"}})) + rows.append({"seed": int(seed), "run_dir": str(run)}) + continue + scene = {"at": "home", "held": False, "placed": False, "frames": 0, "steps": 0} + + def frame(when, tool): + folder = run / "media" / "keyframes" / f"{scene['frames']:06d}-{when}-{tool.replace('_', '-')}" + folder.mkdir(parents=True) + noise = os.urandom(4).hex() if os.environ.get("FAKE_JITTER") else "" + state = f"{a.suite} {seed} at {scene['at']} held {scene['held']} placed {scene['placed']} {noise}" + (folder / "agentview.png").write_bytes(state.encode()) + scene["frames"] += 1 + + def motion(tool, effect): + frame("before", tool) + if scene["placed"]: # LIBERO's done: the episode is over + return {"ok": False, "error": "episode terminated before control completed"} + effect() + scene["steps"] += 10 + frame("after", tool) + return {"ok": True} + + def release(): + scene.update(placed=scene["held"] and scene["at"] == "plate", held=False) + + tools = {"get_task_context": lambda: types.SimpleNamespace(language="put the bowl on the plate", + task_name="bowl_on_plate"), + "move_to_pose": lambda target: motion("move_to_pose", lambda: scene.update(at=str(target))), + "close_gripper": lambda: motion("close_gripper", lambda: scene.update(held=scene["at"] == "bowl")), + "open_gripper": lambda: motion("open_gripper", release)} + namespace = {"__builtins__": SAFE_BUILTINS, **tools} + stdout, error = io.StringIO(), None + try: # parsed, validated and compiled, or refused whole + tree = ast.parse(code) + _ProgramValidator().visit(tree) + compiled = compile(tree, "", "exec") + except (SyntaxError, ValueError) as exc: + error = {"code": "invalid_request", "message": f"program rejected: {exc}"} + else: + try: + with contextlib.redirect_stdout(stdout): + exec(compiled, namespace, namespace) + except Exception as exc: + error = {"code": "execution_failed", "message": f"program execution failed: {type(exc).__name__}: {exc}"} + ok, success = error is None, scene["placed"] + reason = "task_succeeded" if success else "program_completed" if ok else "program_error" + (run / "source" / "program-result.json").write_text(json.dumps( + {"ok": ok, "error": error, "result": namespace.get("result") if ok else None, "stdout": stdout.getvalue(), + "calls": []}, default=str)) + (run / "outcome.json").write_text(json.dumps({"task_success": success, "program_ok": ok, + "termination_reason": reason, "steps_executed": scene["steps"], + "error": error})) + rows.append({"seed": int(seed), "run_dir": str(run)}) +pathlib.Path(a.results_jsonl).write_text("".join(json.dumps(r) + "\n" for r in rows)) +''' + + +def checkout(tmp: Path) -> Path: + """A stand-in ASPIRE checkout: the docs the actor reads (the API reference with its host-only part, the benchmark's + page), and its .venv-libero's cap-harness (CAP_HARNESS) and python, which runs the engine's validator on RUNTIME.""" + root = tmp / "ASPIRE" + (root / "docs").mkdir(parents=True) + (root / "docs" / "api-reference.md").write_text(API) + (root / "docs" / "run-artifacts.md").write_text("# Run artifacts\n") + (root / "docs" / "libero-pro.md").write_text("# LIBERO-Pro\n\n## Task examples\n\nworked programs\n") + (root / "cap_harness").mkdir() + (root / "cap_harness" / "__init__.py").write_text("") + (root / "cap_harness" / "runtime.py").write_text(RUNTIME.replace("@BUILTINS@", repr(sorted(CHECK.BUILTINS)))) + venv = root / ".venv-libero" / "bin" + venv.mkdir(parents=True) + (venv / "cap-harness").write_text(CAP_HARNESS.replace("@PYTHON@", sys.executable)) + (venv / "python").write_text(f'#!/bin/sh\nexec "{sys.executable}" "$@"\n') + for f in venv.iterdir(): + f.chmod(0o755) + return root + + +ROW = {"id": "libero_object-t00-s051", "benchmark": "libero-pro", "suite": "libero_object", "task_id": 0, "seed": 51, + "eval_seeds": "51", "score_label": "trial", "role": "train"} +ACTING_LIBRARY = '"""The test\'s library."""\n\n\ndef twice(x: int) -> int:\n """Twice x."""\n return 2 * x\n' +DESCRIPTION = "A bowl and a plate on the table; the gripper is open." +DIFFERENCE = "The bowl is now in the gripper." + + +def texts(messages) -> str: + out = [] + for m in messages: + c = m["content"] + out += [c] if isinstance(c, str) else [p.get("text", "") for p in c if isinstance(p, dict)] + return "\n".join(out) + + +class Script: + """The acting model: the VDM's two replies, and `code(text, kind)` for a code request, kind "initial" or + "decision" (a synthesis answers as its request's candidates did); every request kept.""" + + def __init__(self, code): + self.code, self.calls = code, [] + + def __call__(self, messages, **sampling): + system, text = messages[0]["content"], texts(messages) + if system == P.DESCRIBE_SYSTEM: + kind, reply = "describe", DESCRIPTION + elif system == P.DIFFERENCE_SYSTEM: + kind, reply = "difference", DIFFERENCE + else: + kind = "synthesis" if system.startswith("You are synthesizing") else "request" + reply = self.code(text, "decision" if "Please respond with EXACTLY ONE" in text else "initial") + self.calls.append({"kind": kind, "text": text, "messages": messages, **sampling}) + return {"content": reply, "finish_reason": "stop"} + + def of(self, kind): + return [c for c in self.calls if c["kind"] == kind] + + +def scripted(script): + """CapAgent0Actor.direct: every model the actor names answers from `script`, which records the model's name.""" + def direct(self, model=None, effort=None): + return agent_of(lambda messages, **k: script(messages, model=self.model_name(model), **k)) + return direct + + +def actor(tmp: Path, root: Path, **params) -> A.CapAgent0Actor: + return A.CapAgent0Actor({"engine": str(ENGINE / "agent" / "sim.py"), "aspire_root": str(root), "sim_env": {}, + "logs": str(tmp / "logs"), "scratch": str(tmp / "scratch"), **params}, base=tmp) + + +def decoded(part: dict) -> bytes: + return base64.b64decode(part["image_url"]["url"].split(",", 1)[1]) + + +@needs_bwrap +def test_a_trial_replays_its_blocks_reads_the_vdm_and_regenerates_until_the_task_is_done(tmp_path, monkeypatch): + """CaP-Agent0's trial on the engine: the probe reads the task's language and the reset frame, the VDM describes + it, the ensemble writes the first block, which runs from the reset after the library; the decision request carries + the block's stdout and the VDM's difference of the newest two frames, starting from the environment's own prompt + (its goal unformatted, as cap-x builds it); REGENERATE appends a block, the next turn replays both from the reset + (reaching the frame the model saw), and the episode's end (the task done) ends the loop. The final program is the + one the judge runs.""" + monkeypatch.delenv("ASPIRE_OUT", raising=False) + root = checkout(tmp_path) + + def code(text, kind): + if kind == "initial": + return 'Reach and grasp.\n```python\nmove_to_pose("bowl")\nclose_gripper()\nprint("grasped", twice(2))\n```' + return 'Now place it.\nREGENERATE\n```python\nmove_to_pose("plate")\nopen_gripper()\n```' + script = Script(code) + monkeypatch.setattr(A.CapAgent0Actor, "direct", scripted(script)) + out = actor(tmp_path, root, ensemble="single", ensemble_temperatures=[0.1, 0.9]).run( + dict(ROW), seed(tmp_path, ACTING_LIBRARY)) + trial = out.extra["trial"] + assert out.output == 1.0 and trial["success"] and trial["ended"] == "task_succeeded" + assert (trial["executed_blocks"], trial["blocks"], trial["regenerations"], trial["finishes"]) == (2, 2, 1, 0) + assert [(t["termination_reason"], t["replay_matches"], t["decision"]) for t in trial["turns"]] == \ + [("program_completed", True, "regenerate"), ("task_succeeded", True, "episode over")] + assert trial["library_functions"] == ["twice"] and trial["replay_mismatches"] == 0 + assert trial["code"] == ('# Code block 0\nmove_to_pose("bowl")\nclose_gripper()\nprint("grasped", twice(2))\n\n' + '# Code block 1\nmove_to_pose("plate")\nopen_gripper()') + log = out.log + record = json.loads((log / "trial.json").read_text()) + assert record["turns"][0]["stdout"] == "grasped 4\n" and record["turns"][0]["stderr"] == "" + # the judge's program: the library, then each block in its try (the last turn's) + facts = out.extra["task"] + assert facts["fix_code"] == (log / "programs" / "turn01.py").read_text() + assert facts["fix_code"].startswith(ACTING_LIBRARY) and "move_to_pose('plate')" in facts["fix_code"] + assert (facts["role"], facts["suite"], facts["max_steps"]) == ("trial", "libero_object", 8000) + # the first request: cap-x's task prompt with the goal, the API reference's program part, the library's + # documentation, then the VDM's description of the reset frame + first = script.of("request")[0]["text"] + assert first.startswith(P.SYSTEM_PROMPT + "\n" + P.TASK_PROMPT.format(libero_environment_goal="put the bowl on the " + "plate")) + assert "\nAPIs:\n\n# API reference" in first and "Host-side text" not in first + assert "twice(x: int) -> int\n Doc:\n Twice x." in first + assert first.endswith(P.INITIAL_FEEDBACK.format(description=DESCRIPTION)) + describe = script.of("describe")[0]["messages"] + assert decoded(describe[1]["content"][-1]).startswith(b"libero_object 51 at home held False") + # the decision: from the environment's prompt (upstream: no goal, no description), with the block's output and + # the VDM's difference between the reset frame and the turn's last frame + decision = [c for c in script.of("request") if "Please respond with EXACTLY ONE" in c["text"]][0]["text"] + assert "Goal: {libero_environment_goal}" in decision and DESCRIPTION not in decision + assert P.MULTI_TURN_PROMPT.format(executed_code='move_to_pose("bowl")\nclose_gripper()\nprint("grasped", ' + 'twice(2))', console_stdout="grasped 4\n", + console_stderr="") in decision + assert DIFFERENCE in decision + previous, current = [p for p in script.of("difference")[0]["messages"][1]["content"] if p["type"] == "image_url"] + assert decoded(previous).startswith(b"libero_object 51 at home held False") + assert decoded(current).startswith(b"libero_object 51 at bowl held True") + # the ensemble: each candidate at its temperature, a synthesis at 0.2; the transcript is what the trial acted on + assert sorted(c["temperature"] for c in script.of("request")) == [0.1, 0.1, 0.9, 0.9] + assert [c["temperature"] for c in script.of("synthesis")] == [0.2, 0.2] + assert [m["content"].split("\n")[0] for m in out.messages] == ["[vdm/initial]", "[initial/synthesis]", + "[vdm/turn00]", "[turn00/synthesis]"] + assert out.extra["usage"]["calls"] == 8 and len(record["candidates"]) == 2 + assert sorted(p.name for p in (log / "programs").iterdir()) == ["probe.py", "turn00.py", "turn01.py"] + assert sorted(p.name for p in (log / "images").iterdir()) == ["initial.png", "turn00.png", "turn01.png"] + assert json.loads((log / "prompt.json").read_text())["initial"] == first[len(P.SYSTEM_PROMPT) + 1:] + assert not any((tmp_path / "scratch").iterdir()) # the simulator runs, removed + + +@needs_bwrap +def test_a_block_that_raises_is_its_stderr_and_finish_ends_the_trial(tmp_path, monkeypatch): + """A block's exception is its stderr in the decision request, which with `decision_prompt: initial` starts from + the first request (the goal, the description); FINISH ends the trial. With a service that is not deterministic + the replay differs from what the model saw, and the turn says so.""" + monkeypatch.delenv("ASPIRE_OUT", raising=False) + root = checkout(tmp_path) + + def code(text, kind): + return ('```python\nmove_to_pose("bowl")\nvalue = {}["k"]\n```' if kind == "initial" else "FINISH") + script = Script(code) + monkeypatch.setattr(A.CapAgent0Actor, "direct", scripted(script)) + out = actor(tmp_path, root, ensemble="none", decision_prompt="initial", sim_env={"FAKE_JITTER": "1"}, + vdm_model="vision-model").run(dict(ROW), None) + trial = out.extra["trial"] + assert out.output == 0.0 and (trial["finishes"], trial["regenerations"], trial["executed_blocks"]) == (1, 0, 1) + assert [(t["replay_matches"], t["decision"]) for t in trial["turns"]] == [(False, "finish")] + assert trial["replay_mismatches"] == 1 + decision = script.of("request")[1]["text"] + assert "Goal: put the bowl on the plate" in decision and DESCRIPTION in decision + assert "The current console stderr is:\n```\nKeyError: 'k'\n```" in decision + assert {c["model"] for c in script.of("describe") + script.of("difference")} == {"vision-model"} + assert {c["model"] for c in script.of("request")} == {A.DEFAULT_MODEL} + + +@needs_bwrap +def test_a_collection_row_runs_the_single_turn_tier_and_a_refused_block_is_its_refusal(tmp_path, monkeypatch): + """The paper's collection rows (multi_turn, vdm and ensemble off on the row, over the CaP-Agent0 params): one + request, no VDM, one block, no decision. A block the engine's validator refuses is left out of the program, and + its refusal is the turn's stderr; a turn that made no motion compares no frame. With keep_images false the trial's + frames go when it ends.""" + monkeypatch.delenv("ASPIRE_OUT", raising=False) + root = checkout(tmp_path) + script = Script(lambda text, kind: '```python\nimport numpy\nmove_to_pose("bowl")\n```') + monkeypatch.setattr(A.CapAgent0Actor, "direct", scripted(script)) + row = {**ROW, "id": "collect-libero_object-t00-s051", "role": "collect", "multi_turn": False, "vdm": False, + "ensemble": "none"} + out = actor(tmp_path, root, multi_turn=True, vdm=True, ensemble="single", keep_images=False).run(row, None) + assert [c["kind"] for c in script.calls] == ["request"] + assert (out.log / "trial.json").is_file() and not (out.log / "images").exists() # keep_images: false + turn = json.loads((out.log / "trial.json").read_text())["turns"][0] + assert turn["stderr"].startswith("program rejected: ValueError: Import of a module other than math") + assert turn["replay_matches"] is None and "decision" not in turn and out.output == 0.0 + assert "numpy" not in out.extra["task"]["fix_code"] + assert P.INITIAL_FEEDBACK.split("{")[0] not in script.calls[0]["text"] + + +@needs_bwrap +def test_a_block_that_cannot_compile_or_that_only_the_engines_run_refuses_is_left_out(tmp_path, monkeypatch): + """A `return` outside a function parses but compiles nowhere: the engine would refuse the whole program, so the + block is refused on its own. A block the engine refuses only when it runs the program (its static check could + not run in time) is left out and the turn run again without it; neither is a failed trial.""" + monkeypatch.delenv("ASPIRE_OUT", raising=False) + root = checkout(tmp_path) + blocks = iter(['move_to_pose("bowl")\nreturn', 'import numpy\nmove_to_pose("bowl")']) + monkeypatch.setattr(A.CapAgent0Actor, "direct", + scripted(Script(lambda text, kind: f"```python\n{next(blocks)}\n```"))) + one = actor(tmp_path, root, multi_turn=False, vdm=False, ensemble="none") + turns = lambda out: json.loads((out.log / "trial.json").read_text())["turns"] + out = one.run(dict(ROW), None) + assert turns(out)[0]["stderr"].startswith("program rejected: SyntaxError: 'return' outside function") + assert out.output == 0.0 and "session_failed" not in out.extra + sim = A.engine_module(ENGINE / "agent" / "sim.py") + monkeypatch.setattr(sim.Engine, "validate", lambda self, program: None) # the check timed out + out = one.run(dict(ROW), None) + assert turns(out)[0]["stderr"] == \ + "program rejected: Import of a module other than math is not allowed, nor an alias" + assert out.output == 0.0 and "session_failed" not in out.extra and "numpy" not in out.extra["task"]["fix_code"] + + +def test_a_failed_trial_keeps_what_it_spent_and_a_lost_sign_in_stops_the_run(tmp_path, monkeypatch): + sim = A.engine_module(ENGINE / "agent" / "sim.py") + + class Engine: + def __init__(self, root, **k): + self.root, self.benchmark = Path(root), k.get("benchmark") + + def outage(trial): # one paid call, then an outage past the retries + trial.account([Usage("m", input_tokens=10, output_tokens=5, calls=1, cost_usd=0.5)], "initial", "r", "", "stop") + raise RuntimeError(f"{A.UNAVAILABLE}: chat/completions HTTP 503") + monkeypatch.setattr(sim, "Engine", Engine) + monkeypatch.setattr(A._Trial, "run", outage) + one = actor(tmp_path, tmp_path) + with pytest.raises(ValueError, match="agent.params.engine"): # it names the engine it runs on + A.CapAgent0Actor({"aspire_root": str(tmp_path)}, base=tmp_path).run(dict(ROW), None) + with pytest.raises(ValueError, match="one seed"): + one.run({**ROW, "seed": None, "eval_seeds": "1-3"}, None) + out = one.run(dict(ROW), None) + assert out.output is None and out.cost_usd == 0.5 and out.tokens == 15 and "503" in out.extra["session_failed"] + assert json.loads((out.log / "trial.json").read_text())["error"].startswith("RuntimeError: acting model") + from hermit.agent.base.interface import LoginFailed + from hermit.trainer.rollout import run_one + monkeypatch.setattr(A._Trial, "run", lambda trial: (_ for _ in ()).throw(RuntimeError("hermit_login_failed: x"))) + with pytest.raises(LoginFailed): # a lost sign-in stops the run, not one trial + run_one(dict(ROW), None, lambda task, adapter: one.run(task, adapter), lambda task, out: {"score": 0}) + + +def test_concurrent_trials_load_the_engine_once_and_a_failed_load_is_not_kept(tmp_path, monkeypatch): + """The first trial of a process loads the engine's module; the trials started with it (agent.concurrency 4 in + the configs) took the module while its code still ran, with no `Engine` yet, and were lost as errors. They wait + for the load now; and a load that fails is not left for the next trial to take as loaded.""" + monkeypatch.setattr(sys, "path", list(sys.path)) + monkeypatch.setattr(sys, "dont_write_bytecode", True) + slow, broken = tmp_path / "slow_sim.py", tmp_path / "broken_sim.py" + names = [f"_cap_sim_{abs(hash(str(m.resolve())))}" for m in (slow, broken)] + slow.write_text("import time\ntime.sleep(1.0) # the load's window\n\n\nclass Engine:\n pass\n") + try: + first = [] + loader = threading.Thread(target=lambda: first.append(A.engine_module(slow))) + loader.start() + deadline = time.time() + 30 + while names[0] not in sys.modules and time.time() < deadline: # the first load has begun + time.sleep(0.01) + with ThreadPoolExecutor(3) as pool: # each takes `Engine` at once, as a trial does + engines = list(pool.map(lambda _: A.engine_module(slow).Engine, range(3))) + loader.join() + assert len({id(e) for e in engines + [first[0].Engine]}) == 1 + broken.write_text("raise ImportError('a dependency is missing')\n") + with pytest.raises(ImportError): + A.engine_module(broken) + broken.write_text("class Engine:\n pass\n\n\nINSTALLED_SINCE = True\n") + assert hasattr(A.engine_module(broken), "Engine") + finally: + for name in names: + sys.modules.pop(name, None) + + +def test_an_api_reference_without_its_host_only_heading_fails_the_trial_before_it_runs(tmp_path, monkeypatch): + """The model reads the engine's API reference up to its host-only part; a reference whose heading moved (another + ASPIRE commit) would be passed whole, so the trial fails instead, before its first episode.""" + root = checkout(tmp_path) + (root / "docs" / "api-reference.md").write_text(API.replace(A.API_SECTIONS_END, "## Elsewhere")) + sim = A.engine_module(ENGINE / "agent" / "sim.py") + + class Engine: + def __init__(self, root, **k): + self.root, self.benchmark = Path(root), k.get("benchmark") + + def run(self, *args, **kwargs): + raise AssertionError("no episode runs") + monkeypatch.setattr(sim, "Engine", Engine) + out = actor(tmp_path, root).run(dict(ROW), None) + assert out.output is None and f"has no '{A.API_SECTIONS_END}' heading" in out.extra["session_failed"] + + +def test_a_request_the_endpoint_did_not_serve_is_tried_again_before_it_fails(monkeypatch): + sleeps = [] + monkeypatch.setattr(A.time, "sleep", sleeps.append) + fails = {"n": 2} + + def reply(messages, **k): + if fails["n"]: + fails["n"] -= 1 + raise RuntimeError("chat/completions HTTP 503: overloaded") + return {"content": "ok", "finish_reason": "stop"} + trial = SimpleNamespace(account=lambda *a: None) + ask = lambda params, fn: A.CapAgent0Actor(params).ask(trial, agent_of(fn), [{"role": "user", "content": "x"}], + "initial", 0.5) + assert ask({"unserved_retries": 2}, reply)["content"] == "ok" and sleeps == [60.0, 120.0] + fails["n"] = 1 + with pytest.raises(RuntimeError, match=A.UNAVAILABLE): + ask({"unserved_retries": 0}, reply) + with pytest.raises(RuntimeError, match="hermit_login_failed"): # not an outage: never tried again + ask({}, lambda messages, **k: (_ for _ in ()).throw(RuntimeError("hermit_login_failed: x"))) + assert sleeps == [60.0, 120.0] + + +def test_the_actor_keeps_its_models_spec_adds_the_effort_and_refuses_unknown_settings(monkeypatch): + from hermit.agent.model import llm + specs = [] + monkeypatch.setattr(llm.ChatClient, "from_spec", classmethod(lambda cls, spec, **k: specs.append(spec) or object())) + model = {"base_url": "http://127.0.0.1:9/v1", "model": "m", "timeout": 7, "extra_body": {"top_k": 5}} + one = A.CapAgent0Actor({"model": model, "effort": "high"}) + agent = one.direct() + assert specs[-1]["timeout"] == 7 and specs[-1]["extra_body"] == {"top_k": 5, "reasoning_effort": "high"} + assert agent.settings == {"max_tokens": 20480} and one.direct() is agent # one per model and effort + assert one.direct(None, "low") is not agent and specs[-1]["extra_body"]["reasoning_effort"] == "low" + assert one.settings({"multi_turn": False, "ensemble": "none", "model": "other"})["model"] == model # a row's own + with pytest.raises(ValueError, match="ensemble is one of"): + one.settings({"ensemble": "triple"}) + with pytest.raises(ValueError, match="decision_prompt"): + A.CapAgent0Actor({"decision_prompt": "first"}).settings({}) + + +# ---------- the synthesis ---------- + +REACH = ('def reach(target, height=0.1):\n """Move above `target`, then down to it."""\n' + ' move_to_pose("above " + target)\n return move_to_pose(target)\n') +GRASP = ('def grasp_at(target):\n """Reach `target` and close the gripper."""\n reach(target)\n' + ' return close_gripper()\n') +OTHER = 'def tilt(angle):\n """Tilt."""\n move_to_pose(angle)\n return angle\n' +CURATED = '''## Motion + +`reach` and `grasp_at` recur in every task. + +```python +def reach(target: str, height: float = 0.1) -> dict: + """Move above `target`, then down to it.""" + move_to_pose("above " + target) + return move_to_pose(target) + + +def grasp_at(target: str) -> dict: + """Reach `target` and close the gripper.""" + reach(target) + return close_gripper() +``` + +## Geometry + +```python +import numpy as np + + +def spread(points): + """The points' spread.""" + return np.std(points) + + +def spread_twice(points): + """Twice the spread.""" + return 2 * spread(points) + + +def reach(target): + """A second reach: the first of a name is the one kept.""" + return None + + +def norm(v): + """The length of v.""" + return math.sqrt(sum(x * x for x in v)) +``` + +```python +def broken(: +``` +''' + + +def trial_code(*functions, main='grasp_at("bowl")') -> str: + """A trial's code as the actor records it (`_annotate_code_blocks`): its one block.""" + return _annotate_code_blocks(["\n\n".join(functions) + "\n" + main], [{}]) + + +def record(id_: str, code: str | None, score: float, status: str = "ok") -> dict: + suite, task = id_.split("-")[0], int(id_.split("-t")[1][:2]) + return {"id": id_, "input": {"id": id_, "suite": suite, "task_id": task}, "status": status, + "judge": {"score": score}, "pipeline_extra": {"trial": {"code": code, "model": "glm"}} if code else {}} + + +class Curator: + """The run's model for the curation: replies in turn (an Exception is raised; a dict is the reply with its + finish_reason), every prompt and every request's sampling kept.""" + + def __init__(self, *replies): + self.replies, self.prompts, self.sampling = list(replies), [], [] + + def __call__(self, messages, **sampling): + self.prompts.append(messages[0]["content"]) + self.sampling.append(sampling) + reply = self.replies.pop(0) if len(self.replies) > 1 else self.replies[0] + if isinstance(reply, Exception): + raise reply + return reply if isinstance(reply, dict) else {"content": reply, "finish_reason": "stop"} + + +def run_agent_by(rule): + """Scores each validation task by `rule(library text, id)`; every call kept.""" + calls = [] + + def run_agent(task_ids, adapter): + text = (Path(adapter) / "skill_library.py").read_text() + calls.append(list(task_ids)) + return {"results": [{"id": t, "status": "ok", "judge": {"score": float(rule(text, t))}} for t in task_ids]} + run_agent.calls = calls + return run_agent + + +def context(tmp: Path, adapter: Path, curator, records: list[dict], *, step: int = 1, epoch_end: bool = True, + run_agent=None, val_ids=(), **params) -> StepContext: + ws = Workspace(adapter=adapter, learning_material=tmp / "material", task_info=tmp / "task-info", + history=tmp / "history", state=tmp / "state", scratch=tmp / "scratch", output=tmp / f"output{step}") + for d in (ws.state, ws.scratch, ws.output, ws.task_info): + d.mkdir(parents=True, exist_ok=True) + current = ws.learning_material / "current" / "tasks" + if current.exists(): + shutil.rmtree(current) + current.mkdir(parents=True) + for r in records: + (current / f"{r['id']}.json").write_text(json.dumps(r)) + validation = None + if val_ids: + validation = tmp / "validation" + validation.mkdir(exist_ok=True) + (validation / "tasks.jsonl").write_text("".join(json.dumps({"id": i}) + "\n" for i in val_ids)) + + def check_spec_tool() -> dict: + return spec(adapter) + tools = {"check_spec": check_spec_tool, **({"run_agent": run_agent} if run_agent else {})} + return StepContext(workspace=ws, access=Access(validation=validation), tools=tools, + agent=agent_of(curator) if curator else None, + params={**DEFAULTS["params"], **params}, progress=Progress(1, step, epoch_end)) + + +STEP1 = [record("libero_object-t00-s051", trial_code(REACH, GRASP), 1.0), + record("libero_object-t00-s052", trial_code(REACH, GRASP), 1.0), + record("libero_spatial-t01-s051", trial_code(OTHER), 0.0), # failed: not pooled + record("libero_goal-t02-s051", None, 0.0, status="error")] # no trial: not pooled +STEP2 = [record("libero_spatial-t03-s051", trial_code(REACH, OTHER, main='tilt(1)'), 1.0)] + + +def test_reply_functions_and_assemble_keep_what_the_engine_takes(): + """The reply's Python blocks (```python, ```py or bare), every top-level function, the first of each name; a + function the check refuses is left out, and so is one that names it, round after round; `import math` when a kept + function uses it. A type hint stays as written (`List[float]`, `np.ndarray`, which the verbatim prompt invites): + the engine never evaluates one. A decorator stays too, for the check to refuse. The size cap cuts the last + functions and checks the rest again. A last block left open is the reply cut off.""" + functions, skipped = E.reply_functions(CURATED) + assert [n for n, _ in functions] == ["reach", "grasp_at", "spread", "spread_twice", "norm"] + assert len(skipped) == 1 and skipped[0].startswith("block 3 does not parse") + text, dropped = E.assemble(functions, "how") + assert sorted(dropped) == ["spread", "spread_twice"] + assert "np" in dropped["spread"][0] and "spread" in dropped["spread_twice"][0] + assert text.startswith(E.HEADER.format(how="how") + "\nimport math\n\n\ndef reach(target: str") + assert CHECK.library_problems(text) == [] + assert [n for n, _ in E.reply_functions("```python\n" + text + "```")[0]] == ["reach", "grasp_at", "norm"] + big = [(f"f{i}", f'def f{i}():\n """{"x" * 2000}"""\n') for i in range(40)] + text, dropped = E.assemble(big, "big") # the cap: the last of the reply's order go + assert len(text.encode()) <= CHECK.LIBRARY_MAX and "f0" not in dropped and "f39" in dropped + assert E.assemble([], "none")[0] == E.HEADER.format(how="none") + hinted = ("Notes first.\n\n```text\nnot code\n```\n\n```\ndef lift(points: List[float], height: float = 0.1) -> " + "np.ndarray:\n \"\"\"Lift to `height`.\"\"\"\n # a comment\n return move_to_pose(height)\n```\n") + functions, skipped = E.reply_functions(hinted) + assert [n for n, _ in functions] == ["lift"] and skipped == [] + text, dropped = E.assemble(functions, "how") + assert not dropped and "def lift(points: List[float], height: float = 0.1) -> np.ndarray:" in text + assert " # a comment\n" in text and CHECK.library_problems(text) == [] + assert run_as_the_engine(text + "print(bool(lift))\n") == "True\n" # defined: its hints are text + functions, skipped = E.reply_functions(hinted + "\n```python\ndef cut(x):\n return") + assert [n for n, _ in functions] == ["lift"] and skipped == ["block 3 is not closed: the reply was cut off"] + decorated = ('```python\n@twice\ndef lift():\n """Lift."""\n return 1\n\n\n' + 'def twice(f):\n """Twice."""\n return f\n```\n') + functions, _ = E.reply_functions(decorated) + assert functions[0] == ("lift", '@twice\ndef lift():\n """Lift."""\n return 1') # not dropped silently + text, dropped = E.assemble(functions, "how") + assert "a decorator" in dropped["lift"][0] and "def lift" not in text and "def twice" in text + calls = [("user", 'def user():\n """Use the helper."""\n return helper()\n'), *big[:35], + ("helper", f'def helper():\n """{"x" * 2000}"""\n')] + text, dropped = E.assemble(calls, "big") # the cap cuts the helper, and its caller goes: the rest checked again + assert "helper" in dropped and "helper" in dropped["user"][0] and CHECK.library_problems(text) == [] + + +def test_a_reply_whose_blocks_sit_in_a_list_is_read_as_markdown_reads_it(): + """A curation reply that numbers its functions puts each block inside a list item, indented with it: Markdown + takes the fence's indentation off each line, and so does the Evolver (each block parsed as it stood failed as an + unexpected indent, and the step kept nothing).""" + reply = ('1. **reach**: moves to a target.\n ```python\n def reach(target):\n """Reach it."""\n' + ' return move_to_pose(target)\n ```\n2. **lift**:\n\n ```py\n def lift(h=0.1):\n' + ' """Lift by h."""\n return h\n ```\n') + functions, skipped = E.reply_functions(reply) + assert [n for n, _ in functions] == ["reach", "lift"] and skipped == [] + assert functions[0][1].startswith('def reach(target):\n """Reach it."""\n return move_to_pose') + text, dropped = E.assemble(functions, "how") + assert not dropped and CHECK.library_problems(text) == [] + + +def test_a_library_the_engines_own_validator_refuses_loses_the_functions_it_refuses(): + """The check runs on Hermit's Python, and the engine's venv may be Python 3.10, whose parser refuses an f-string + that reuses its quote (3.12 takes it). The engine's validator is asked about a library the check passes, and when + it refuses it, about each function: those it refuses go, a function that calls one goes too, the rest stay.""" + calls = [] + + def refuse(text): # Python 3.10's parser, as far as these functions go + calls.append(text) + return "SyntaxError: f-string: unmatched '['" if 'f"{d["' in text else None + functions = [("label", 'def label(d):\n """The label."""\n return f"{d["name"]}"\n'), + ("show", 'def show(d):\n """Show it."""\n return label(d)\n'), + ("reach", 'def reach(target):\n """Reach it."""\n return move_to_pose(target)\n')] + assert CHECK.library_problems(E.assemble(functions, "how")[0]) == [] # the check alone takes them all + text, dropped = E.assemble(functions, "how", refuse) + assert sorted(dropped) == ["label", "show"] and "unmatched '['" in dropped["label"][0] + assert "def reach" in text and "def label" not in text and CHECK.library_problems(text) == [] + calls.clear() + assert E.assemble(functions[2:], "how", refuse)[1] == {} and len(calls) == 1 # one call when it takes it + + +def test_the_evolver_asks_the_engine_named_in_its_params_about_each_library(tmp_path, monkeypatch): + """`params.engine` (relative to the run config, as the actor's) and `aspire_root`: the engine's validator, on + the benchmark's venv, checks the curated library before it is kept; a function it refuses is not in it.""" + sim = A.engine_module(ENGINE / "agent" / "sim.py") + made = [] + + class Engine: + def __init__(self, root, **k): + made.append((Path(root), k.get("benchmark"))) + + def validate(self, program): + return "SyntaxError: f-string: unmatched '['" if 'f"{d["' in Path(program).read_text() else None + monkeypatch.setattr(sim, "Engine", Engine) + adapter = seed(tmp_path) + reply = ('```python\ndef label(d):\n """The label."""\n return f"{d["name"]}"\n\n\n' + 'def reach(target):\n """Reach it."""\n return move_to_pose(target)\n```\n') + ctx = context(tmp_path, adapter, Curator(reply), STEP1, setting="paper", + engine="../../cap_harness/utils/agent/sim.py", aspire_root=str(tmp_path / "aspire-checkout")) + result = E.CapAgent0Evolver().step(dataclasses.replace(ctx, base=EXAMPLE)) + library = (adapter / "skill_library.py").read_text() + assert result.status == "done" and "def reach" in library and "def label" not in library + assert "the engine's validator refuses it" in result.extra["record"]["dropped"]["label"][0] + assert made == [(tmp_path / "aspire-checkout", "libero-pro")] + + +def test_the_paper_setting_pools_every_step_and_synthesizes_once_at_the_epochs_end(tmp_path): + """`setting: paper`: a step before the epoch's end adds its successful trials to the pool (once: the same step's + material read again adds nothing) and leaves the library; the last step's synthesis runs cap-x's compile over the + whole pool: functions.txt per experiment, pooled by name, filtered, listed most frequent first in + SKILL_LIBRARY_PROMPT with the engine's rules after it; the reply's functions the check takes become the library. + finalize keeps it.""" + adapter = seed(tmp_path) + curator = Curator(CURATED) + ctx = context(tmp_path, adapter, curator, STEP1, step=1, epoch_end=False, setting="paper") + evolver = E.CapAgent0Evolver() + evolver.setup(ctx) + result = evolver.step(ctx) + assert result.status == "done" and "synthesized once" in result.summary and not curator.prompts + assert evolver.step(ctx).summary.startswith("collected 0 successful trials of 0;") # the same material again + assert (adapter / "skill_library.py").read_text() == (TEMPLATE / "skill_library.py").read_text() + result = evolver.step(context(tmp_path, adapter, curator, STEP2, step=2, setting="paper")) + assert result.status == "done", result.summary + state = json.loads((tmp_path / "state" / E.STATE).read_text()) + assert sorted(state["experiments"]) == ["glm/libero_object-t00", "glm/libero_spatial-t03"] + assert [len(e["trials"]) for e in state["experiments"].values()] == [2, 1] + step1, again, step2 = state["steps"] + assert (step1["trials"], step1["successful"], step1["failed_runs"]) == (4, 2, 1) + assert (step2["experiments"], step2["functions"], step2["after_filtering"]) == (2, 3, 2) # tilt: once + prompt = curator.prompts[0] + assert len(curator.prompts) == 1 and prompt.startswith(E.SKILL_LIBRARY_PROMPT.split("{")[0]) + assert prompt.index("FUNCTION: reach") < prompt.index("FUNCTION: grasp_at") # 3 occurrences before 2 + assert "Total occurrences: 3 (across 2 experiments)" in prompt and "FUNCTION: tilt" not in prompt + assert prompt.endswith(P.ENGINE_RULES.format(builtins=", ".join(sorted(CHECK.BUILTINS)), + api=", ".join(sorted(CHECK.TOOLS | CHECK.CONSTRUCTORS | + CHECK.EXTENSIONS)))) + library = (adapter / "skill_library.py").read_text() + assert [n for n, _ in E.reply_functions("```python\n" + library + "```")[0]] == ["reach", "grasp_at", "norm"] + assert (tmp_path / "output2" / "skill_library.txt").read_text() == CURATED + assert (tmp_path / "output2" / "prompt.md").read_text() == prompt + assert result.extra["record"]["dropped"].keys() == {"spread", "spread_twice"} + assert spec(adapter)["passed"] + final = evolver.finalize(context(tmp_path, adapter, curator, [], step=3, setting="paper")) + assert final.summary == "the current library (3 functions)" + assert (adapter / "skill_library.py").read_text() == library + assert curator.sampling[0]["max_tokens"] == 20480 # explicit: an endpoint's default may cut the library short + + +def test_nothing_recurring_leaves_the_library_as_it_is(tmp_path): + adapter = seed(tmp_path, LIBRARY) + curator = Curator(CURATED) + ctx = context(tmp_path, adapter, curator, STEP1, setting="continual", select="last", min_occurrences=3) + result = E.CapAgent0Evolver().step(ctx) + assert result.status == "done" and "no function is in 3 successful trials" in result.summary + assert not curator.prompts and (adapter / "skill_library.py").read_text() == LIBRARY + + +def test_the_continual_setting_scores_every_library_on_validation_and_keeps_the_best(tmp_path): + """`setting: continual`: the starting library is scored once, then every step's library on the validation tasks; + finalize writes the best validation mean back (a tie: the later, from more trials), the others kept in the + state.""" + adapter = seed(tmp_path) + without_grasp = CURATED.replace("def grasp_at(target: str)", "def grasp_on(target: str)") + curator = Curator(CURATED, without_grasp, CURATED) + run_agent = run_agent_by(lambda text, t: "def grasp_at(" in text) + evolver = E.CapAgent0Evolver() + for step, records in ((1, STEP1), (2, STEP2), (3, STEP2)): + ctx = context(tmp_path, adapter, curator, records, step=step, run_agent=run_agent, val_ids=["v1", "v2"]) + if step == 1: + evolver.setup(ctx) + result = evolver.step(ctx) + assert result.status == "done", result.summary + assert run_agent.calls == [["v1", "v2"]] * 4 # start, then each step's + state = json.loads((tmp_path / "state" / E.STATE).read_text()) + assert [(e["name"], e["val"]["mean"]) for e in state["libraries"]] == \ + [("start", 0.0), ("step0001", 1.0), ("step0002", 0.0), ("step0003", 1.0)] + final = evolver.finalize(ctx) + assert final.summary.startswith("step0003, the best validation mean") + assert (adapter / "skill_library.py").read_text() == (tmp_path / "state" / "libraries" / "step0003.py").read_text() + assert state["libraries"][2]["file"] == "libraries/step0002.py" + last = context(tmp_path, adapter, curator, [], step=4, select="last") + assert evolver.finalize(last).summary == "the current library (3 functions)" + + +def test_a_validation_run_that_failed_is_run_again_and_a_library_never_scored_is_not_chosen(tmp_path): + adapter = seed(tmp_path) + attempts = {"n": 0} + + def run_agent(task_ids, adapter): + attempts["n"] += 1 + status = "error" if attempts["n"] in (1, 3, 4) else "ok" # the start: once more; step 1: twice failed + return {"results": [{"id": t, "status": status, "judge": {"score": 1.0}} for t in task_ids]} + ctx = context(tmp_path, adapter, Curator(CURATED), STEP1, run_agent=run_agent, val_ids=["v1"]) + result = E.CapAgent0Evolver().step(ctx) + assert result.status == "done" and attempts["n"] == 4 + state = json.loads((tmp_path / "state" / E.STATE).read_text()) + start, step1 = state["libraries"] + assert start["val"]["mean"] == 1.0 and "failed twice" in step1["val_error"] + assert E.CapAgent0Evolver().finalize(ctx).summary.startswith("start, the best validation mean") + assert (adapter / "skill_library.py").read_text() == (TEMPLATE / "skill_library.py").read_text() + + +def test_a_failed_curation_is_tried_once_more_then_fails_the_step_and_leaves_the_library(tmp_path): + adapter = seed(tmp_path, LIBRARY) + curator = Curator(RuntimeError("chat/completions HTTP 500"), CURATED) + assert E.CapAgent0Evolver().step(context(tmp_path, adapter, curator, STEP1, select="last")).status == "done" + assert len(curator.prompts) == 2 + curator = Curator(RuntimeError("chat/completions HTTP 500")) + (adapter / "skill_library.py").write_text(LIBRARY) + result = E.CapAgent0Evolver().step(context(tmp_path, adapter, curator, STEP1, step=2, select="last")) + assert result.status == "failed" and "the curation call failed" in result.summary and len(curator.prompts) == 2 + assert (adapter / "skill_library.py").read_text() == LIBRARY + state = json.loads((tmp_path / "state" / E.STATE).read_text()) + assert state["steps"][-1]["outcome"].startswith( + "failed: RuntimeError: no curated library: the curation call failed") + + +def test_a_curation_cut_off_or_with_nothing_kept_is_tried_once_more_then_fails_the_step(tmp_path): + """A reply the endpoint cut off (finish_reason length, or its last block left open) or one of which no function + is kept would be written as an empty or partial library and the step still called done: in the paper setting the + one synthesis, so the final adapter would be the root's. It is a failed attempt, tried once more; two fail the + step, the library stays, and finalize says why it is empty.""" + adapter = seed(tmp_path) + cut = CURATED[:CURATED.index("def grasp_at")] # inside the first block: never closed + curator = Curator(cut, CURATED) + result = E.CapAgent0Evolver().step(context(tmp_path, adapter, curator, STEP1, select="last")) + assert result.status == "done" and len(curator.prompts) == 2 + assert result.extra["record"]["attempts"] == ["the reply was cut off: its last block is not closed", "kept"] + assert (tmp_path / "output1" / "skill_library.attempt1.txt").read_text() == cut + assert (tmp_path / "output1" / "skill_library.txt").read_text() == CURATED + start = (TEMPLATE / "skill_library.py").read_text() + (adapter / "skill_library.py").write_text(start) + nothing = "```python\ndef spread(points):\n \"\"\"The spread.\"\"\"\n return np.std(points)\n```\n" + curator = Curator({"content": CURATED, "finish_reason": "length"}, nothing) + ctx = context(tmp_path, adapter, curator, STEP1, step=2, setting="paper") + result = E.CapAgent0Evolver().step(ctx) + assert result.status == "failed" and len(curator.prompts) == 2 + assert "cut off at max_tokens" in result.summary and "no function of the reply was kept (1 found: spread" in \ + result.summary + assert (adapter / "skill_library.py").read_text() == start + unparsed = Curator("```python\ndef reach(:\n```\n") + result = E.CapAgent0Evolver().step(context(tmp_path, adapter, unparsed, STEP1, step=3, setting="paper")) + assert result.status == "failed" and "no function of the reply was kept (0 found: block 1 does not parse" in \ + result.summary + summary = E.CapAgent0Evolver().finalize(ctx).summary + assert summary.startswith("the current library, empty (the last step: failed: RuntimeError: no curated library") + + +def test_a_library_that_fails_check_spec_is_put_back_and_a_spent_budget_stops_the_step(tmp_path): + adapter = seed(tmp_path, LIBRARY) + ctx = context(tmp_path, adapter, Curator(CURATED), STEP1, select="last") + ctx.tools["check_spec"] = lambda: {"passed": False, "issues": [{"path": "skill_library.py", "problem": "x"}]} + result = E.CapAgent0Evolver().step(ctx) + assert result.status == "failed" and "failed check_spec" in result.summary + assert (adapter / "skill_library.py").read_text() == LIBRARY + with pytest.raises(BudgetExceeded): + E.CapAgent0Evolver().step(context(tmp_path, adapter, Curator(BudgetExceeded("usd")), STEP1, step=2, + select="last")) + + def spent(task_ids, adapter): + raise BudgetExceeded("hours") + with pytest.raises(BudgetExceeded): + E.CapAgent0Evolver().step(context(tmp_path, adapter, Curator(CURATED), STEP1, step=3, run_agent=spent, + val_ids=["v1"])) + state = json.loads((tmp_path / "state" / E.STATE).read_text()) + assert [s["outcome"] for s in state["steps"]][1:] == ["budget exceeded", "budget exceeded"] + assert [(e["name"], "val" in e) for e in state["libraries"]] == [("start", False)] + assert len(state["experiments"]["glm/libero_object-t00"]["trials"]) == 6 # each step's trials, kept + + +@pytest.mark.parametrize("params, validation, curator, error", [ + ({"setting": "online"}, True, True, "setting is one of"), + ({"select": "best"}, True, True, "select is one of"), + ({}, False, True, "set data.val, or select: last"), + ({}, True, False, "curates with the run's model")]) +def test_a_misconfigured_run_stops_before_its_first_rollouts(tmp_path, params, validation, curator, error): + ctx = context(tmp_path, seed(tmp_path), Curator(CURATED) if curator else None, [], + val_ids=["v1"] if validation else (), **params) + with pytest.raises(ValueError, match=error): + E.CapAgent0Evolver().setup(ctx) + result = E.CapAgent0Evolver().step(ctx) # a resumed run: the step says it too + assert result.status == "failed" and error.replace("\\", "") in result.summary + + +PIPELINE = ''' +from pathlib import Path +from hermit.common import RunOutput + +HELPER = 'def grasp_at(target):\\n """Reach and close."""\\n move_to_pose(target)\\n return close_gripper()\\n' + + +def run(task, adapter): + library = (Path(adapter) / "skill_library.py").read_text() if adapter else "" + known = "def grasp_at(" in library + code = "# Code block 0\\n" + ("" if known else HELPER) + "grasp_at('bowl')" + ok = known or task["n"] % 2 == 0 + return RunOutput(output="done" if ok else "failed", cost_usd=0.0, tokens=0, + extra={"trial": {"code": code, "model": "toy"}}) +''' +JUDGE = ''' +def score(task, output): + return {"score": float(output.output == "done")} +''' + + +class ScriptedCurator: + model = "scripted" + + def __init__(self): + self.prompts = [] + + def chat(self, messages, **kwargs): + self.prompts.append(messages[0]["content"]) + reply = ('```python\ndef grasp_at(target: str) -> dict:\n """Reach `target` and close the gripper."""\n' + ' move_to_pose(target)\n return close_gripper()\n```') + return {"content": reply, "finish_reason": "stop"}, Usage("scripted", 10, 0, 10, 1, 0.0) + + +def test_cap_agent0_learns_a_library_through_the_trainer(tmp_path): + """The whole loop on a toy task: the even rows succeed and define the helper, the continual setting synthesizes + it after each step and keeps the library the validation tasks score best; `eval --adapter final` runs it.""" + from hermit.config import Config + from hermit.evaluate import evaluate + from hermit.trainer.trainer import Trainer + rows = [{"id": f"libero_object-t{i:02d}-s051", "suite": "libero_object", "task_id": i, "n": i} for i in range(12)] + (tmp_path / "tasks.jsonl").write_text("".join(json.dumps(r) + "\n" for r in rows)) + for name, ids in (("train", range(8)), ("val", range(8, 10)), ("test", range(10, 12))): + (tmp_path / f"{name}.txt").write_text("".join(f"{rows[i]['id']}\n" for i in ids)) + (tmp_path / "pipeline.py").write_text(PIPELINE) + (tmp_path / "judge.py").write_text(JUDGE) + (tmp_path / "task-info").mkdir() + (tmp_path / "task-info" / "README.md").write_text("Toy robot tasks.\n") + config = {"data": {"tasks": "tasks.jsonl", "train": "train.txt", "val": "val.txt", "test": "test.txt", + "step_size": 4, "shuffle": False}, + "task_info": "task-info", "agent": {"name": "pipeline.py:run", "concurrency": 2}, + "judge": {"path": "judge.py"}, "template": str(TEMPLATE), + "evolver": {"name": "cap_agent0", "params": {"setting": "continual"}}, + "sandbox": {"enabled": False}, + "trainer": {"run_name": "cap-toy", "output_dir": "runs", "epochs": 1, "budget": {"hours": 1}}} + (tmp_path / "run.yaml").write_text(yaml.safe_dump(config)) + config = Config.load(tmp_path / "run.yaml") + trainer = Trainer(config, log=lambda *_: None) + trainer.llm = model = ScriptedCurator() + summary = trainer.train() + run = tmp_path / "runs" / "cap-toy" + assert summary["steps"] == 2 and len(model.prompts) == 2 + steps = [json.loads(line) for line in (run / "steps.jsonl").read_text().splitlines()] + assert all(s["status"] == "done" for s in steps), steps + state = json.loads((run / "workspace" / "state" / E.STATE).read_text()) + assert [(e["name"], e["val"]["mean"]) for e in state["libraries"]] == \ + [("start", 0.5), ("step0001", 1.0), ("step0002", 1.0)] + assert "def grasp_at(target: str) -> dict:" in (run / "checkout" / "skill_library.py").read_text() + assert evaluate(config, "final", log=lambda *_: None)["mean_score"] == 1.0 + assert evaluate(config, "root", log=lambda *_: None)["mean_score"] == 0.5 + + +# ---------- the LIBERO-Pro rows, judge and configs ---------- + +def rows_module(): + return _load("cap_agent0_rows", EXAMPLE / "rows.py") + + +def prepared(tmp: Path, monkeypatch) -> Path: + """The benchmark's tasks as the launcher prepares them (prepare.py), in tmp/bench.""" + Pr = _load("libero_prepare", LIBERO / "utils" / "benchmark" / "prepare.py") + monkeypatch.setattr(Pr, "HERE", tmp / "bench") + monkeypatch.setattr(sys, "argv", ["prepare.py"]) + (tmp / "bench").mkdir() + Pr.main() + return tmp / "bench" + + +def test_the_rows_are_one_trial_each_and_the_splits_never_share_a_seed(tmp_path, monkeypatch): + """rows.py: the collection and the training trials on the four LIBERO suites (seeds 51-55), the validation trials + on the six test suites (seed 66), the test trials on Table 2's six LIBERO-Pro suites (seeds 1-50), its sample and + LIBERO-Long-Pro; a row's seed is its own and the judge's; only a collection row carries its tier.""" + R = rows_module() + R.main(["--benchmark", str(prepared(tmp_path, monkeypatch)), "--out", str(tmp_path / "rows")]) + Fd = _load("cap_fields", ENGINE / "agent" / "fields.py") + rows = Fd.task_rows(tmp_path / "rows" / "tasks") + split = lambda name: [rows[i] for i in (tmp_path / "rows" / "splits" / f"{name}.txt").read_text().split()] + sizes = {name: len(split(name)) for name in ("collect", "train", "val", "test", "test_sample", "test_long", + "collect_smoke", "train_smoke", "val_smoke", "test_smoke")} + assert sizes == {"collect": 200, "train": 200, "val": 60, "test": 3000, "test_sample": 300, "test_long": 1000, + "collect_smoke": 2, "train_smoke": 2, "val_smoke": 1, "test_smoke": 2} + seeds = lambda name: {r["seed"] for r in split(name)} + suites = lambda name: {r["suite"] for r in split(name)} + assert seeds("collect") == seeds("train") == set(range(51, 56)) and seeds("val") == {66} + assert seeds("test") == seeds("test_long") == set(range(1, 51)) and seeds("test_sample") == set(range(1, 6)) + assert suites("collect") == suites("train") == set(R.TRAIN_SUITES) + assert suites("val") == suites("test") == set(R.TEST_SUITES) and suites("test_long") == set(R.LONG_SUITES) + ids = {name: {r["id"] for r in split(name)} for name in ("collect", "train", "val", "test", "test_long")} + assert sum(map(len, ids.values())) == len(set().union(*ids.values())) + assert {r["id"] for r in split("test_sample")} <= ids["test"] + for name in ("train", "val", "test"): + assert not any(k in r for r in split(name) for k in A.ROW_KEYS), name + assert all({k: r[k] for k in A.ROW_KEYS} == R.COLLECT and r["role"] == "collect" for r in split("collect")) + assert json.dumps(rows["libero_object_swap-t03-s007"]) == json.dumps( + {"id": "libero_object_swap-t03-s007", "benchmark": "libero-pro", "suite": "libero_object_swap", "task_id": 3, + "seed": 7, "eval_seeds": "7", "score_label": "trial", "role": "test"}) + with pytest.raises(SystemExit): # a validation seed among the training ones + R.main(["--benchmark", str(tmp_path / "bench"), "--out", str(tmp_path / "rows"), "--val-seeds", "55"]) + with pytest.raises(SystemExit): + R.main(["--benchmark", str(tmp_path / "bench"), "--out", str(tmp_path / "rows"), "--sample-seeds", "60"]) + + +def test_the_configs_read_the_rows_and_keep_the_papers_pipeline_apart_from_ours(tmp_path, monkeypatch): + """paper.yaml trains on the collection rows (the single-turn tier) and synthesizes once; continual.yaml trains + CaP-Agent0 itself on the training rows and selects on the validation rows; both test the same trials with + CaP-Agent0 (the actor's params), on the engine, with the template and the engine's judge; each smoke is its + run's on the smoke splits.""" + from hermit.config import Config + from hermit.task import Benchmark + R = rows_module() + R.main(["--benchmark", str(prepared(tmp_path, monkeypatch)), "--out", str(tmp_path / "rows")]) + configs = sorted(EXAMPLE.glob("*.yaml")) + assert [c.name for c in configs] == ["continual.yaml", "paper.yaml", "smoke_continual.yaml", "smoke_paper.yaml"] + hook = (EXAMPLE / "tasks.sh").read_text() + assert '"$HERMIT" rows.py --benchmark ../utils/benchmark --out .' in hook and 'TASKS="$PWD/tasks"' in hook + for path in configs: + config = Config.load(path) + d, params = config.data, config.data["agent"]["params"] + setting = d["evolver"]["params"]["setting"] + assert setting == ("paper" if "paper" in path.name else "continual"), path + assert d["agent"]["name"] == "hermit.agent.evolver.methods.cap_agent0.actor:CapAgent0Actor" + assert config.path(params["engine"]) == (ENGINE / "agent" / "sim.py").resolve() + assert (params["multi_turn"], params["vdm"], params["ensemble"]) == (True, True, "single"), path + assert d["template"] == "cap-agent0@1.0" and d["evolver"]["name"] == "cap_agent0" + assert config.path(d["judge"]["path"]) == (EXAMPLE / "judge.py").resolve() + assert d["environment"]["runner"] == "host" and d["sandbox"]["enforce"] == "required" + assert config.path(d["data"]["tasks"]) == (EXAMPLE / "tasks").resolve() + given = [k for k in ("train", "val", "test") if d["data"].get(k)] + assert given == (["train", "test"] if setting == "paper" else ["train", "val", "test"]), path + for key in given: + name = Path(d["data"][key]).name + assert config.path(d["data"][key]) == (EXAMPLE / "splits" / name).resolve() + monkeypatch.setitem(d["data"], key, str(tmp_path / "rows" / "splits" / name)) + monkeypatch.setitem(d["data"], "tasks", str(tmp_path / "rows" / "tasks")) + tasks = Benchmark.from_config(config) + split = lambda key: [tasks.tasks[i].given() for i in Path(d["data"][key]).read_text().split()] + smoke = path.name.startswith("smoke") + assert {r["role"] for r in split("train")} == {"collect" if setting == "paper" else "train"}, path + assert {r["role"] for r in split("test")} == {"test"} and len(split("test")) == (2 if smoke else 3000) + if setting == "continual": + assert {r["role"] for r in split("val")} == {"val"} + + +@needs_bwrap +def test_the_judge_is_the_engines_and_prunes_the_images_of_the_runs_it_scored(tmp_path, monkeypatch): + """The engine's judge on the row's seed, then each rerun's media/ removed (ASPIRE writes a run at + ///: a pattern one level short removed nothing, and a test split's keyframes filled + the disk); CAP_AGENT0_KEEP_MEDIA=1 keeps them.""" + root = checkout(tmp_path) + monkeypatch.setenv("ASPIRE_ROOT", str(root)) + monkeypatch.setenv("ASPIRE_OUT", str(tmp_path / "out")) + monkeypatch.setenv("ASPIRE_SIM_ENV", "{}") + judge = _load("cap_agent0_judge", EXAMPLE / "judge.py") + program = 'move_to_pose("bowl")\nclose_gripper()\nmove_to_pose("plate")\nopen_gripper()\n' + out = RunOutput(output=1.0, extra={"task": {"fix_code": program, "max_steps": 8000}}) + assert judge.score(dict(ROW), out)["score"] == 1.0 + runs = list((tmp_path / "out" / "stage2").glob(f"{ROW['id']}-*/runs/0051/run-*")) + assert len(runs) == 1 and (runs[0] / "outcome.json").is_file() and not (runs[0] / "media").exists() + monkeypatch.setenv("CAP_AGENT0_KEEP_MEDIA", "1") + shutil.rmtree(tmp_path / "out" / "stage2") + assert judge.score(dict(ROW), RunOutput(output=0.0, extra={"task": {"fix_code": 'move_to_pose("bowl")\n'}}))[ + "score"] == 0.0 + assert list((tmp_path / "out" / "stage2").glob(f"{ROW['id']}-*/runs/0051/run-*/media/keyframes/*")) + + +@needs_bwrap +def test_a_judges_rerun_that_ran_no_episode_is_a_judge_error_not_a_zero(tmp_path, monkeypatch): + """The engine's judge counts task_success alone: a rerun the harness failed, or one that wrote no result, was a 0 + with status ok, so a successful trial left the paper setting's pool and a validation run counted as a real 0. It + raises now, and so does a refusal of the program the trial ran; the rollout records the row as a judge error.""" + from hermit.trainer.rollout import run_one + root = checkout(tmp_path) + monkeypatch.setenv("ASPIRE_ROOT", str(root)) + monkeypatch.setenv("ASPIRE_OUT", str(tmp_path / "out")) + judge = _load("cap_agent0_judge_crash", EXAMPLE / "judge.py") + out = RunOutput(output=1.0, extra={"task": {"fix_code": 'move_to_pose("bowl")\n', "max_steps": 8000}}) + for crash, says in (("harness_error", "(harness_error)"), ("no_results", "(no termination reason)")): + monkeypatch.setenv("ASPIRE_SIM_ENV", json.dumps({"FAKE_CRASH": crash})) + with pytest.raises(RuntimeError) as failed: + judge.score(dict(ROW), out) + assert f"the judge's rerun ran no episode on seed 51 {says}" in str(failed.value) + assert not list((tmp_path / "out" / "stage2").glob("*/runs/*/*/media")) # pruned all the same + rec = run_one(dict(ROW), None, lambda task, adapter: out, judge.score) + assert rec["status"] == "judge_error" and "ran no episode" in rec["error"] + monkeypatch.setenv("ASPIRE_SIM_ENV", "{}") + assert not list((tmp_path / "out" / "stage2").glob("*/runs/*/*/media")) # a lost run's frames too + with pytest.raises(RuntimeError, match="refused, at judging, the program the trial ran"): + judge.score(dict(ROW), RunOutput(output=1.0, extra={"task": {"fix_code": "import numpy\n"}})) + assert judge.score(dict(ROW), out)["score"] == 0.0 # a program that ran and failed: the engine's 0 + + + +def test_the_judges_prune_follows_no_link_and_removes_nothing_outside_its_rerun(tmp_path): + """The confined program can leave links in its output; when the engine's removal of them fails, its judge raises + before stage2.json is written, and the prune walks the run folders itself. It follows no link and removes only + real directories inside the rerun's folder, from the run folders and from the records (a stale one too): a run + the harness lost (a folder, no record) loses its images, and nothing a link points to is touched.""" + judge = _load("cap_agent0_judge_links", EXAMPLE / "judge.py") + out = RunOutput(output=1.0, extra={"task": {"fix_code": 'move_to_pose("bowl")\n'}}) + stage2 = tmp_path / "out" / "stage2" + folder = judge.rerun_folder(dict(ROW), out, stage2) + host = tmp_path / "host" + for name in "abcde": + (host / name / "media").mkdir(parents=True) + (host / name / "media" / "keep.png").write_text("host") + runs = folder / "runs" + own, lost = runs / "0051" / "run-own", runs / "0051" / "run-lost" + for run in (own, lost): + (run / "media" / "keyframes").mkdir(parents=True) + (runs / "0052").symlink_to(host) # a seed folder that is a link + (runs / "0053").mkdir() + (runs / "0053" / "run-link").symlink_to(host / "c") # a run folder that is a link + (runs / "0054" / "run-media").mkdir(parents=True) + (runs / "0054" / "run-media" / "media").symlink_to(host / "d" / "media") # a media/ that is a link + judge.prune(dict(ROW), out, stage2) # no stage2.json: the judge raised + assert not (own / "media").exists() and not (lost / "media").exists() + (own / "media").mkdir() + (folder / "stage2.json").write_text(json.dumps({"refused": None, "records": [ + {"run_dir": str(own)}, {"run_dir": str(host / "e")}, {"run_dir": str(runs / "0053" / "run-link")}]})) + judge.prune(dict(ROW), out, stage2) + assert not (own / "media").exists() + assert sorted(p.parent.parent.name for p in host.glob("*/media/keep.png")) == list("abcde") + + +@needs_bwrap +def test_a_library_the_engine_would_not_compile_fails_the_trial_before_it_runs(tmp_path, monkeypatch): + """The engine's validator only parses, and the engine compiles every program with the library first: a library + with an error only compiling finds (`break` outside a loop) would stop every program, so the trial fails with + that reason before its first episode, never blaming the model's first block.""" + root = checkout(tmp_path) + sim = A.engine_module(ENGINE / "agent" / "sim.py") + + class Engine: + def __init__(self, root, **k): + self.root, self.benchmark = Path(root), k.get("benchmark") + + def validate(self, program): + return None # ASPIRE's validator takes it: it parses + + def run(self, *args, **kwargs): + raise AssertionError("no episode runs") + monkeypatch.setattr(sim, "Engine", Engine) + library = ('"""A library."""\n\n\ndef lift(n):\n """Lift n times."""\n for i in range(n):\n' + ' move_to_pose("bowl")\n break\n') + out = actor(tmp_path, root).run(dict(ROW), seed(tmp_path, library)) + assert out.output is None + assert "the engine refuses the skill library: SyntaxError: 'break' outside loop" in out.extra["session_failed"] + + +# ---------- the copies of cap-x and the engine's rules ---------- + +CAPX = Path(os.environ["CAPX_ROOT"]) if os.environ.get("CAPX_ROOT") else None +ASPIRE = Path(os.environ["ASPIRE_ROOT"]) if os.environ.get("ASPIRE_ROOT") else None +needs_capx = pytest.mark.skipif(CAPX is None or not (CAPX / "capx").is_dir(), + reason="CAPX_ROOT names no cap-x checkout") +needs_aspire = pytest.mark.skipif(ASPIRE is None or not (ASPIRE / "src" / "cap_harness" / "runtime.py").is_file(), + reason="ASPIRE_ROOT names no ASPIRE checkout") +SOURCES = {"trial.py": "capx/envs/trial.py", "client.py": "capx/llm/client.py", + "launch_utils.py": "capx/utils/launch_utils.py", + "parse_outputs.py": "scripts/skill_library_compilation/parse_outputs.py", + "compile_skill_library.py": "scripts/skill_library_compilation/compile_skill_library.py"} + + +def capx_source(path: str) -> str: + """A cap-x file at the pinned commit (the checkout's history), or as the checkout has it.""" + shown = subprocess.run(["git", "-C", str(CAPX), "show", f"{U.COMMIT}:{path}"], capture_output=True, text=True) + return shown.stdout if shown.returncode == 0 else (CAPX / path).read_text() + + +def definitions(source: str) -> dict[str, str]: + """A module's top-level functions, classes and assignments by name, as their AST dumps.""" + out = {} + for node in ast.parse(source).body: + if isinstance(node, (ast.FunctionDef, ast.ClassDef)): + out[node.name] = ast.dump(node) + elif isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): + out[node.targets[0].id] = ast.dump(node) + return out + + +def nodes(source: str, kind, within: tuple[str, ...] = ()) -> list: + tree = ast.parse(source) + roots = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name in within] if within else [tree] + return [n for root in roots for n in ast.walk(root) if isinstance(n, kind)] + + +@needs_capx +def test_the_copies_are_cap_xs_code_at_the_pinned_commit(): + for ours, theirs in SOURCES.items(): + mine, upstream = definitions((METHOD / "upstream" / ours).read_text()), definitions(capx_source(theirs)) + assert mine, ours + for name, dump in mine.items(): + assert upstream.get(name) == dump, (ours, name) + assert (METHOD / "upstream" / "LICENSE").read_text() == capx_source("LICENSE") + + +@needs_capx +def test_the_prompts_are_cap_xs_but_the_task_prompts_last_line(): + cfg = yaml.safe_load(capx_source("env_configs/libero/franka_libero_cap_agent0.yaml"))["env"]["cfg"] + assert P.TASK_PROMPT.replace(P.ADAPTED_LAST_LINE, P.UPSTREAM_LAST_LINE) == cfg["prompt"] + assert P.MULTI_TURN_PROMPT == cfg["multi_turn_prompt"] + trial, base, client = (capx_source(p) for p in ("capx/envs/trial.py", "capx/envs/tasks/base.py", + "capx/llm/client.py")) + strings = {n.value for n in nodes(trial + "\n" + base, ast.Constant) if isinstance(n.value, str)} + for text in (P.SYSTEM_PROMPT, P.DESCRIBE_SYSTEM, P.DESCRIBE_USER, P.MAIN_CAMERA, P.DIFFERENCE_SYSTEM, + P.DIFFERENCE_USER, P.PREVIOUS_STATE, P.CURRENT_STATE, P.APIS): + assert text in strings, text + feedback = ast.dump(ast.parse("f" + repr(P.INITIAL_FEEDBACK), mode="eval").body) + assert feedback in {ast.dump(n) for n in nodes(trial, ast.JoinedStr)} + ensembles = {ast.dump(n) for n in nodes(client, ast.JoinedStr, ("query_model_ensemble", + "query_single_model_ensemble"))} + mine = {ast.dump(n) for n in nodes(inspect.getsource(P), ast.JoinedStr, ("synthesis_messages",))} + assert len(mine) == 5 and mine <= ensembles + + +@needs_capx +def test_the_reader_is_cap_xs_combined_doc(tmp_path): + """interface.library's text is what cap-x's ApiBase.combined_doc prints for the same functions.""" + method = next(n for n in nodes(capx_source("capx/integrations/base_api.py"), ast.FunctionDef) + if n.name == "combined_doc") + namespace = {"inspect": inspect} + exec(compile(ast.Module([method], []), "base_api.py", "exec"), namespace) + functions = {} + exec(LIBRARY + SIGNATURES, functions) + names = [fn.name for fn in ast.parse(LIBRARY + SIGNATURES).body if isinstance(fn, ast.FunctionDef)] + api = SimpleNamespace(functions=lambda: {name: functions[name] for name in names}) + reader = _load("cap_agent0_reader_capx", seed(tmp_path, LIBRARY + SIGNATURES) / "interface.py") + assert reader.library()["text"] == namespace["combined_doc"](api) + + +@needs_aspire +def test_the_checks_compile_is_the_engines(): + """ASPIRE compiles a program after its validator takes it (runtime.py: `compile(tree, "", + "exec")`, inheriting the module's `from __future__ import annotations`): the check's compile refuses what that + compile refuses and takes what it takes (type hints naming anything, a match statement).""" + runtime = (ASPIRE / "src" / "cap_harness" / "runtime.py").read_text() + assert 'compile(tree, "", "exec")' in runtime + flags = compile(runtime, "runtime.py", "exec", dont_inherit=True).co_flags & __future__.annotations.compiler_flag + assert flags # what the program inherits + cases = {"def f():\n break\n": True, "f(a=1, a=2)\n": True, "def f(x, x):\n pass\n": True, + "def f(x: (y := 1)):\n pass\n": True, "def f() -> (yield):\n pass\n": True, + "[y for x in (y := [1])]\n": True, "*a = [1]\n": True, + "def f(x: List[float]) -> np.ndarray:\n return x\n": False, + "match p:\n case (a, b):\n pass\n": False} + for src, refused in cases.items(): + try: + compile(ast.parse(src), "", "exec", flags=flags, dont_inherit=True) + engine = None + except SyntaxError as exc: + engine = exc.msg + assert (engine is not None) == refused == (CHECK.compile_problem(src) is not None), (src, engine) + + +@needs_aspire +def test_the_templates_engine_rules_are_aspires(): + """The check's names and rules are ASPIRE's (runtime.py `_SAFE_BUILTINS`, `_SAFE_CONSTRUCTORS`, + `_ProgramValidator`; api.py `register_tools`), and the two validators agree on programs, the actor's wrapping + included.""" + src = ASPIRE / "src" / "cap_harness" + runtime, api = (src / "runtime.py").read_text(), (src / "api.py").read_text() + assigned = {n.targets[0].id: n.value for n in ast.parse(runtime).body + if isinstance(n, ast.Assign) and isinstance(n.targets[0], ast.Name)} + keys = lambda name: {k.value for k in assigned[name].args[0].keys} + assert keys("_SAFE_BUILTINS") - {"__import__"} == CHECK.BUILTINS + assert keys("_SAFE_CONSTRUCTORS") == CHECK.CONSTRUCTORS + assert ast.literal_eval(assigned["ALLOWED_IMPORTS"].args[0]) == {"math"} + register = next(n for n in nodes(api, ast.FunctionDef) if n.name == "register_tools") + tools = next(n.value for n in register.body if isinstance(n, ast.Assign) and n.targets[0].id == "tools") + assert {k.value for k in tools.keys} == CHECK.TOOLS + validator = next(n for n in ast.parse(runtime).body + if isinstance(n, ast.ClassDef) and n.name == "_ProgramValidator") + namespace = {"ast": ast, "ALLOWED_IMPORTS": frozenset({"math"})} + exec(compile(ast.Module([validator], []), "runtime.py", "exec"), namespace) + forbidden = next(n.value for n in validator.body if isinstance(n, ast.Assign)) + assert {e.attr for e in forbidden.elts} == {t.__name__ for t in CHECK.FORBIDDEN} + + def aspire_refuses(text: str) -> bool: + try: + namespace["_ProgramValidator"]().visit(ast.parse(text)) + except (SyntaxError, ValueError): + return True + return False + programs = ["import math\nx = math.pi", "import numpy", "import math as m", "from math import pi", "class K: pass", + "with a: pass", "del x", "global g", "x._y", "_x = 1", "f = lambda v: v", "async def f(): pass", + "def f():\n nonlocal x", "try:\n pass\nexcept Exception as e:\n print(f'{e!r}')", + A.program(LIBRARY, ['move_to_pose("bowl")', None, 'value = {}["k"]']), LIBRARY] + for text in programs: + assert aspire_refuses(text) == (CHECK.program_problem(text) is not None), text + libero = src / "libero" / "adapter.py" + if libero.is_file(): + assert 'return "libero"' in libero.read_text() and "libero" in CHECK.EXTENSIONS diff --git a/tests/selection.py b/tests/selection.py index 37f93bde..f78ef4fb 100644 --- a/tests/selection.py +++ b/tests/selection.py @@ -27,6 +27,8 @@ def fnmatch(path: str, pattern: str) -> bool: # group -> the paths (patterns, as `fnmatch` above reads them) that are the method's own METHODS = { "aspire": ["hermit/agent/evolver/methods/aspire/*", "hermit/adapter/templates/aspire/*", "examples/*/aspire/*"], + "cap_agent0": ["hermit/agent/evolver/methods/cap_agent0/*", "hermit/adapter/templates/cap_agent0/*", + "examples/*/cap_agent0/*"], "she": ["hermit/agent/evolver/methods/she/*", "hermit/adapter/templates/she/*", "examples/*/she/*"], "ace": ["hermit/agent/evolver/methods/ace/*", "hermit/adapter/templates/ace/*", "examples/*/ace/*"], "ahe": ["hermit/agent/evolver/methods/ahe_adapter/*", "hermit/adapter/templates/ahe/*",