diff --git a/.env.example b/.env.example index 6fecedd1a..176519180 100644 --- a/.env.example +++ b/.env.example @@ -81,7 +81,7 @@ HG_AGENT_RETRIES=3 # Optional additional dependencies for nonstandard layouts (JSON array): # HG_OPENCLAW_RUNTIME_PATHS='["/path/to/dedicated-dependency"]' -# The OpenCode task Harness installs a native npm release in the experiment store. +# OpenCode defaults to editable v2 source. Use --mode fixed for a native release. # harnessgrad harness install opencode # HG_AGENT_OPENCODE_WIRE=chat @@ -106,8 +106,10 @@ HG_AGENT_RETRIES=3 # HG_AGENT_API_KEY=local # # `HG_AGENT_API_KEY` is a placeholder here: vLLM does not authenticate, but the -# client library refuses to build without a value. Be aware of what the run record -# will therefore say -- `describe_model()` reports "credentials: present" for a local +# client library refuses to build without a value. For Pi, Oh My Pi, Hermes Agent, +# and OpenCode, `local` with this plain loopback HTTP URL is a public placeholder. +# Use a different value for an endpoint that authenticates. +# `describe_model()` reports "credentials: present" for a local # server exactly as it does for a hosted one, because from inside the platform the two # are the same shape. It is not a claim that a key was verified. # diff --git a/.github/RELEASING.md b/.github/RELEASING.md index 61bc6ce91..8cae65acb 100644 --- a/.github/RELEASING.md +++ b/.github/RELEASING.md @@ -33,7 +33,7 @@ apply an `area:` label. ## 🌐 Website deployments -The existing [Deploy site workflow](workflows/deploy.yml) builds the `website` -branch and publishes GitHub Pages when its configured triggers run or a maintainer -dispatches it. Review the workflow and site changes before any manual deployment; -deployment history is not a substitute for a tested release. +The [Deploy site workflow](workflows/deploy.yml) publishes [website/](../website/) +from the triggering `main` commit. Changes to the website, the workflow or +`docs/contributors.html` trigger deployment. Maintainers can also select `main` +for a manual deployment. See the [site build instructions](../website/README.md). diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 16be9b091..4127788c7 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -1,10 +1,10 @@ -# Platform changes rebuild the website branch and overlay this commit's contributor record. name: Deploy site on: push: branches: [main] paths: + - 'website/**' - 'docs/contributors.html' - '.github/workflows/deploy.yml' workflow_dispatch: @@ -20,21 +20,13 @@ concurrency: jobs: build: + if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest steps: - - name: Check out website source - uses: actions/checkout@v4 - with: - ref: website - path: site - - - name: Check out triggering platform commit + - name: Check out the triggering commit uses: actions/checkout@v4 with: ref: ${{ github.sha }} - path: platform-record - sparse-checkout: docs/contributors.html - sparse-checkout-cone-mode: false - uses: pnpm/action-setup@v4 with: @@ -44,24 +36,18 @@ jobs: with: node-version: 22.22.1 cache: pnpm - cache-dependency-path: site/pnpm-lock.yaml + cache-dependency-path: website/pnpm-lock.yaml - - name: Install and build website - working-directory: site + - name: Build the site and check its links + working-directory: website run: | pnpm install --frozen-lockfile - pnpm exec astro build - - - name: Stage platform contributor record - run: cp platform-record/docs/contributors.html site/dist/contributors.html - - - name: Check built links - run: pnpm --dir site check:links + pnpm build - uses: actions/configure-pages@v5 - uses: actions/upload-pages-artifact@v3 with: - path: site/dist + path: website/dist deploy: needs: build diff --git a/.gitignore b/.gitignore index 251b2d4fa..87d32434f 100644 --- a/.gitignore +++ b/.gitignore @@ -297,6 +297,9 @@ harnessgrad_work/ !/docs/egress.md !/docs/moving-docker-data-root.md !/docs/architecture.md +!/docs/domain-customization.md +!/docs/domain-customization-design.md +!/docs/harness-plugins.md !/docs/import-direction.md !/docs/import-migration.md !/docs/provenance-separation-design.md diff --git a/INTERFACE.md b/INTERFACE.md index 312850f06..6423c9711 100644 --- a/INTERFACE.md +++ b/INTERFACE.md @@ -5,6 +5,12 @@ > Every rule below states *why* it exists. A rule without a reason is a rule > someone will break. +This document specifies the experiment protocol and shared Harness execution contracts. +Domain customization has its own [workflow guide](docs/domain-customization.md) and +[design](docs/domain-customization-design.md); experiment rules for a fixed task set, +shared H0 and round budgets do not define that workflow's data lifecycle. Historical +design rationale is labeled where it has been superseded by the current interface. + --- ## 0. What this framework is @@ -72,13 +78,17 @@ care about its internal structure. There is exactly one interface point: | --- | --- | --- | | `name` | yes | harness identity, reported on every curve point | | `version` | yes | harness identity, reported on every curve point | -| `path` | no (`"."`) | where the harness lives relative to the repo root. A harness may be a **subdirectory** of a larger project — RRSI's is `third_party/harbor_terminus2/`, DGM's is a subset of its repo root. | -| `entrypoint` | yes | the file the platform invokes | +| `path` | no (`"."`) | relative directory used by validation; execution does not consistently honor non-default values. Use `"."` and a repository-relative `entrypoint`. | +| `entrypoint` | yes | Python entrypoint file or Python wrapper the platform invokes | | `backend` | no (`"cli"`) | how the entrypoint is driven; only `cli` is implemented | -| `install` | no (`null`) | dependency file relative to the harness root — `requirements.txt` (pip) or `.sh` (shell). **Runs once at import time** into the environment, via `tools/import_env.py --harness`; never during a measurement. **Required in practice by any harness that runs in a container and calls a model**: the image does not have your packages and the harness tree is read-only during a run. See §2.5.6. | +| `install` | no (`null`) | legacy dependency file prepared via `tools/import_env.py --harness`, never installed during measurement. With managed Python, it must match `runtime.requirements` if present; use the managed preparation path below. | +| `runtime` | no | explicit managed Python or Bun contract, validated by `eval/ckpt/source_tree.py:runtime_spec`; see [managed Python dependencies](docs/writing_a_harness.md#21-managed-python-dependencies). | | `env_kinds` | no (`["files"]`) | which environments this harness can operate on (§2.5). The platform **refuses** a run whose dataset needs a kind the harness does not declare, rather than scoring it zero on every task. | | `runtime_paths` | no (`[]`) | absolute trees mounted read-only because the harness needs them — a CLI installed outside `/usr`, a runtime it was built against. Bound *before* the platform is hidden, so declaring the platform's own path does not expose it. **Applies to `files` and to `exec`.** An earlier version restricted it to `files` on the theory that "inside a container the runtime is the image's" — which is false for a task image that ships no runtime at all (measured: the real Terminal-Bench image is `ubuntu:24.04` plus a `COPY`, with no `python3`). | +Managed Python requires `runtime_paths` to be empty: dependencies come from its prepared +runtime contract. For other Harnesses, the host-tree rules below apply. + For `files`, runtimes are mounted read-only at their physical host paths, with the links used by every declared path restored. Parent and child declarations remain accessible in any order. Platform and temporary trees stay hidden through aliases. @@ -90,11 +100,12 @@ or scratch state directories; conflicting layouts are refused before launch. ### 1.1.1 The harness is a command, not a language -The platform invokes `entrypoint` with an interpreter the environment provides. Python, -Node, a shell script and a compiled binary are all acceptable, and so is a **wrapper** -around somebody else's program: `base_harness/codex/`, `opencode/`, `miniswe/` and the -rest are the worked examples, and they are how an agent CLI (Claude Code, Codex, -OpenCode) becomes a harness here. The generic wrapper that was the first example of +The platform invokes `entrypoint` with the selected Python interpreter and passes +`--task` and `--workdir`. Node programs, shell scripts, compiled binaries and other agent +CLIs need a Python wrapper that forwards those arguments; they cannot be named directly +as this entrypoint. `base_harness/codex/`, `base_harness/opencode/` and +`base_harness/miniswe/` show how external agent CLIs become Harnesses here. +The generic wrapper that was the first example of this, `cli_agent`, moved to `tests/fixtures/base_harness/` on 2026-11-01: it drives one program and sees one exit code, so its trace cannot satisfy §4's clauses by construction, which makes it a test instrument rather than an example to copy. @@ -117,9 +128,12 @@ formats spelled out, is [`docs/writing_a_harness.md`](docs/writing_a_harness.md) Conformance is checked by `tools/validate_harness.py` rather than asserted in prose.** -**A Trainer MAY overwrite every other file in the repository, including the -entrypoint. A Trainer MAY NOT change `name` or `version`** — otherwise it can -submit work under another harness's identity. +**A Trainer may edit candidate source, including the entrypoint, subject to the +selected editing path and admission checks. It may not change `name` or `version`.** +The shared editor in `methods/apply.py` protects the entire root `harness.json`; +experiment candidate admission also rejects widening `env_kinds` or changing `role`. +Domain customization's adaptation step can supply a complete manifest separately from +ordinary improvement. The component map attributes edits; it does not grant permission. ### 1.2 Entrypoint contract @@ -885,7 +899,7 @@ this happened. | situation | what the platform does | | --- | --- | -| `files`, network omitted | the native sandbox inherits the host network and reaches the model directly | +| `files`, network omitted | the native sandbox inherits the host network. Live Pi, Oh My Pi and Hermes Chat Completions calls use a task-local loopback relay to the configured HTTP(S) endpoint | | `files`, `network: none`, live backend | keeps `--unshare-net`; binds one read-only AF_UNIX model socket and a trusted loopback forwarder, hands the client an ordinary HTTP URL; native plan 4 | | `exec`, model on this host | creates the internal network if the task has none, publishes the endpoint, rewrites `HG_AGENT_BASE_URL` for the container | | `exec`, model **not** on this host, `network: bridge` | nothing: the harness reaches it over the internet, which the task asked for | @@ -899,6 +913,13 @@ closed. The harness client, prompts and budgets are unchanged. The socket and forwarder are infrastructure mounts, never setup files or task capability metadata, and are not projected into verification. Native `bridge` and `services` remain unsupported and refused; omitted native network still means inherited host network. +For the observed Chat Completions routes, a terminal inference failure with HTTP +401, 403, 429, a server 5xx, or an observed loss of the upstream transport makes a +failed attempt invalid. Authentication failures require the configured credential. +A successful retry or passing artifact keeps its ordinary score. A task timeout +alone has no model-service attribution. The relay keeps only status and transport +evidence. The dataset's explicit `model_failure_policy` can apply a stricter +invalidation rule. The backend-observation admission rule is: **refuse a declared policy when, and only when, this process is not the thing that applies it.** The gate's ownership table is: @@ -1566,19 +1587,14 @@ last, is not about telling runs apart but about telling *candidates* apart: ## 4. The method interface -**A method is not a plugin. A method is the implementation of two entrypoints -inside the harness repository.** - -```json -// harness.json -{ - "improve_entrypoint": ["python", "-m", "method.improve"], - "accept_entrypoint": ["python", "-m", "method.accept"], - "platform_api_version": "0.1.0" -} -``` +**A method runs outside the Harness repository.** The experiment selects its command +with `--method-entrypoint`; the method receives a base Harness and scratch space and +returns candidate directories/trajectory records. The current exchange is defined in +[§4.55](#455-where-a-method-lives). Manifest fields `improve_entrypoint` and +`accept_entrypoint` belong to the superseded embedded-method design, not the current +method-selection interface. -The platform invokes these as **subprocesses** and talks JSON on stdin/stdout: +The platform invokes the method as a **subprocess** and talks JSON on stdin/stdout: ``` platform -> method (stdin) one JSON object @@ -1587,6 +1603,11 @@ method -> platform (stdout) one JSON object ### 4.1 Why processes and not imports +> **Historical rationale:** §§4.1–4.3 describe the superseded design with a method +> inside the candidate. They do not grant the current candidate authority to edit its +> external method or the platform's acceptance/scoring rules. See §4.55 for the current +> placement and exchange; the historical reasoning and attribution example follow. + The first draft imported a method as a Python module from a `trainers/` directory. That draft could not represent its own subject matter. @@ -1608,6 +1629,10 @@ and removes the problem entirely: ### 4.2 What this buys: the editable surface becomes observable +> **Historical embedded-method example:** the method-placement premise below was +> superseded by §4.55. Changed-path/component attribution remains useful, but it does not +> show that the candidate can modify the external method's acceptance policy. + Because the method lives inside the harness, the boundary between "the artifact being improved" and "the thing doing the improving" is a fact about the repository rather than a claim in a paper. The platform records it every round: @@ -1632,6 +1657,9 @@ genuine/pseudo distinction becomes a reading rather than a setting. ### 4.3 What the platform will not do +> **Historical boundary statement:** this refers to the embedded-method design. +> Current methods run outside the Harness and exchange candidates through §4.55. + **The platform never reads, writes, or imports anything under a harness's `method/` directory**, and never edits `accept`. This is enforced by AST test (`tests/quality/test_boundaries.py`). If the platform touched the acceptance @@ -1642,7 +1670,7 @@ rule it would become a participant in the comparison instead of the referee. The platform no longer holds methods, so the modes describe *who owns the loop*: **Mode A -- platform-driven.** The platform owns the sampling loop and calls -`improve_entrypoint` once per round. Best comparability; the method does not +the selected external method command once per round. Best comparability; the method does not choose its own rhythm. **Mode B -- method-driven.** The method runs its own loop in its own process and @@ -1836,7 +1864,22 @@ It is not a cosmetic defect, because the sha is load-bearing in three places: address: equal trees get equal names, `.gitignore` applies by construction (so a harness's own `.state/` scratch cannot enter its identity), and the object it names is in the object store -- `materialize` can still `git archive` it, which a hash computed outside git could -not. Two consequences worth stating rather than discovering: +not. + +A checkpoint eligible for measurement stages owned source files in `harness.json.checkpoint_files` +by their exact paths, including paths matched by Git ignore rules. The final training H0 +commit, standalone evaluation, and improved candidate commits check for ignored source +that would be missing from Git. An incomplete training H0 stops before measurement or +score reuse. An incomplete improved candidate is recorded as unmeasured with the omitted +paths. Rename the files or add exact `.gitignore` exceptions before submitting them again. +Runtime state, dependency directories, and editor backups are excluded from this check. + +Mode A records `checkpoint_rejected` on each improved round. Resume uses it to +rebuild the Git tree from the H0 index with the original staging rules and +checks the tree hash against the recorded round. A later runtime preparation +failure still retains the normal staging rules used for its source checkpoint. + +Two consequences worth stating rather than discovering: * **`reset_hard` had to take trees as well as commits.** `git checkout --force ` fails with `pathspec ... did not match any file(s)`, and `git reset --hard ` fails @@ -2422,22 +2465,18 @@ the two modes are not comparable, and `run_meta.json` records which one produced run (`sandbox.active`), so a mixed directory of runs is readable rather than ambiguous. -**Still a gap, and now written down rather than implied:** the sandbox constrains -the filesystem and nothing else. A subject keeps unrestricted network access and it -keeps the agent's API key, because a harness that cannot reach a model cannot be -measured at all. It can therefore send that key anywhere. Closing this needs egress -filtering or a key scoped to the benchmark's endpoint; neither is implemented, and -neither is free -- an egress allowlist has to name every endpoint a contributed -harness might use, and a mistake there presents as "the model call failed", which is -the hardest kind of sandbox bug to see because it looks like a harness defect. - -Neither is a sandbox, and the platform does not claim to be one: a subject running -as your user can still open the platform by absolute path. What it cannot do is -change it and have the run continue. A mismatch prints `FAILING RUN`, names the -files that moved, and exits `3` — and no `curve.jsonl` is written, because a -curve that exists is a curve someone will plot. The only file under `runs//` -is `run_meta.json`, written before round 0 so that even a failed run says which -workspace holds its commits. +**Network behavior depends on the task contract.** Native `files` execution without +an explicit network restriction inherits host networking. With `network: "none"`, +the sandbox creates a network namespace and live model calls use a fixed model-route +bridge. The actor receives a route token rather than the upstream model key on that +route. This policy requires the sandbox and cannot be bypassed with `--no-sandbox`. +It is not a general allowlist for arbitrary Harness endpoints; inspect the dataset's +declared environment and [runtime interfaces](docs/dataset-runtime-interfaces.md). + +With `--no-sandbox`, a subject running as the user can open platform paths directly. +Platform hashing still detects modifications around method calls, but it does not prevent +reads or provide filesystem isolation. A mismatch fails the run and records the changed +files; inspect the run's failure records rather than treating an incomplete result as a curve. What is hashed is the referee, not the candidate: `driver.py`, `harnessgrad/`, `eval/`, `eval/ckpt/`, `data/`, `tools/`, `methods/`, `tests/`, `docs/`, `INTERFACE.md` and `.env` — @@ -2445,13 +2484,9 @@ everything the platform reads to decide what a number means, plus the credential that paid for it. `base_harness/` is excluded on purpose: it is a candidate, and every run copies it into a workspace before anything edits it. -The two checks answer different fears. The directory rule stops a *careless* -harness from wandering into the referee, and it costs nothing. The hash stops a -*deliberate* one from rewriting it, which is the fear worth spending on, because a -subject that means to cheat is exactly the subject the platform is built to -produce. Neither is a sandbox; both are cheap enough to run on every call, and -together they make "the score is the platform's opinion" a claim with a mechanism -behind it rather than a convention. +Workspace separation and platform hashing supplement the sandbox: separation avoids +accidental overlap, and hashing detects platform modifications around method calls. +Neither replaces namespace isolation or the task's network policy. ## 4.9 What nine adapters found, and the assumption they did not change diff --git a/README.md b/README.md index 9f83bf7c0..633f9a4bb 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@

HarnessGrad: Harness as A Continual Learner

-

Build agent harnesses that improve with feedback.
Run reproducible experiments, build for a new domain, or turn corrections into changes to your own harness.

+

Run experiments and customize agent harnesses.
Compare harness changes on benchmarks. Build a harness for your domain and refine it from feedback during use.

-

🧭 Contents · 🧪 Experiments · 🛠️ Customize · 🌱 Evolve · 📚 Docs · 💬 Community · 📖 Citation

+

🧭 Contents · 🧪 Experiments · 🛠️ Customize · 📚 Docs · 💬 Community · 📖 Citation

Quality checks @@ -28,23 +28,17 @@ - - -
+ ScienceWorld experiment curve
🧪 Run experiments
Follow how a harness changes across rounds.
Open experiments →
+ Ocean Harness showing research evidence
🛠️ Customize a harness -
See a domain harness collect evidence and answer. -
Open customization → -
- Xiao Lü desktop assistant alongside a chat -
🌱 Evolve your harness -
Turn a correction into a proposed change. -
Open personal evolution → +
Build for a domain or refine a harness from session feedback. +
Domain customization · Test-time evolving
@@ -60,10 +54,9 @@ - [Dataset storage](#dataset-storage) - [Experiment workbench](#the-workbench) · [Contributors](#contributors) - [🛠️ Customize a harness](#customize-harness) - - [Installation](#customize-installation) · [Quick start](#customize-quick-start) - - [Customization workbench](#customize-workbench) -- [🌱 Evolve your personal harness](#evolve-personal-harness) - - [Installation](#personal-installation) · [Quick start](#personal-quick-start) + - [Domain customization](#domain-customization) · [Installation](#customize-installation) · [Quick start](#customize-quick-start) + - [From a benchmark harness to an interactive agent](#interactive-agent) · [Customization workbench](#customize-workbench) + - [Test-time evolving](#test-time-evolving) · [Start the local workspace](#personal-quick-start) - [💬 Community](https://github.com/Xubqpanda/HarnessGrad-Community) - [📚 Documentation](docs/README.md) - [📖 Citation](#citation) @@ -145,7 +138,7 @@ The table records the inventory at this README revision; the benchmark row is ch | axis | what ships | where | | --- | --- | --- | -| **harnesses** | 8: `loop`, `codex`, `opencode`, `deepseek-harness`, `openclaw`, `claude-code`, `miniswe`, `oracle` | `base_harness//` | +| **harnesses** | 11: `loop`, `codex`, `opencode`, `deepseek-harness`, `openclaw`, `claude-code`, `pi`, `oh-my-pi`, `hermes-agent`, `miniswe`, `oracle` | `base_harness//` | | **RSI methods** | 9: `dgm`, `rrsi`, `ahe`, `tthe`, `dream_rsi`, `sica_ci`, `hyperagents`, `meta_harness`, `harnessx` | `experiments/method-.json` | | **benchmarks** | 43 declared adapters; preparation and runtime prerequisites vary — every one listed: `agentdojo`, `aime`, `alfworld`, `appworld`, `authored_example_fix_bug`, `bfcl_v3`, `bird_minidev`, `chessbench_puzzles`, `cooperbench`, `costbench`, `costbench_dynamic`, `deepswe`, `ds1000`, `fever`, `gaia`, `gsm8k`, `hotpotqa`, `jericho`, `jobbench`, `kumo`, `livecodebench`, `locomo`, `memoryagentbench`, `musique`, `personamem_v2`, `physicsquestions`, `ptc_bench`, `reasoning_gym`, `robocasa365`, `scienceworld`, `sportsunderstanding`, `spreadsheetbench`, `spreadsheetbench2`, `strategyqa`, `strongreject`, `swe_bench_pro`, `tau2_bench`, `tau3_bench`, `tau_bench`, `terminal_bench`, `triviaqa`, `twowikimultihopqa`, `wtm_bench` | `data/datasets/`, detail in [`DATASETS.md`](DATASETS.md) | @@ -247,13 +240,19 @@ Want to join? [Bring a harness](docs/bring-your-own-harness.md), [add a method](

-🛠️ Customize a harness — build for a model, environment or task +🛠️ Customize a harness — build for a domain and refine the harness during use +The workflow starts with a domain task. Develop a harness on examples you can train on, give people an interface to its useful capabilities, then use their feedback to refine it. + + + +### Domain customization +

Ocean Harness assembles research evidence and returns a sourced answer

-Ocean Harness is one example built with HarnessGrad. It combines domain sources, research tools, and an answer workflow to answer ocean questions with citations. Build a harness for your own domain using the workflow below. +If a domain benchmark supplies only a test set, reserve it for the final evaluation. Use separate domain sources to construct training and validation questions. The domain workflow evaluates a baseline, edits candidate source and checks candidate changes against validation tasks. Compatible harnesses can also install versioned plugins from the library. [Domain workflow](docs/domain-customization.md) · [Plugin library and supported formats](docs/harness-plugins.md) @@ -267,20 +266,20 @@ python -m pip install . -### Current capabilities - -**Choose a starting harness → Edit a candidate → Inspect the diff → Try it on tasks.** - -Start from a base or saved candidate, edit its files with an assistant and evaluate the result. See [bring your own harness](docs/bring-your-own-harness.md). The [customization proposal command](docs/customization.md) can also generate an unevaluated candidate from explicitly supplied feedback and text, using the explicit `text-edit-v1` stage and export a source-checked patch for review. - -> [!TIP] -> Already have a harness? Run `harnessgrad customize inspect --root ./my-harness` to see the components declared in its manifest, or see [bring your own harness](docs/bring-your-own-harness.md) for the entrypoint and manifest format. +If you already have a harness, `harnessgrad customize inspect --root ./my-harness` lists its declared components. You can also propose a single change to selected text files with the example below. [Harness manifest and entrypoint](docs/bring-your-own-harness.md) ### 🚀 Quick start -[Install HarnessGrad](docs/getting-started.md) and configure an OpenAI-compatible editor endpoint as described in the [customization guide](docs/customization.md). Choose the files and feedback you want to share with that endpoint; for example, put the following in `feedback.json`: +Prepare a task configuration with your domain sources and validation criteria using the [domain workflow guide](docs/domain-customization.md#start-a-run). Keep the run directory outside the checkout. List the available plugins and start development with: + +```bash +harnessgrad customize plugins list +harnessgrad customize workflow run --config /path/to/task.json --run-dir /path/to/domain-run --env-file /path/to/.env +``` + +For a single text edit, configure an editor endpoint using the [customization guide](docs/customization.md) and choose the feedback and files you want it to see. For example, put the following in `feedback.json`. ```json [{"id": "review-1", "kind": "failure", "text": "The task ended without running the project tests."}] @@ -295,46 +294,40 @@ harnessgrad customize review --request request.json --proposal proposal.json --r Replace `./my-harness` and `skills/main.md` with your own selected paths. The proposal includes candidate text and a diff for review; use the [guide](docs/customization.md#export-a-patch) to export a patch and test it on a copy. + -### Customization workbench +### From a benchmark harness to an interactive agent -The same Console used to inspect experiments also provides a workspace for editing harness candidates. See the [workbench guide](console/WORKBENCH.md) for setup and sessions. +Choose a task that shows what the harness does well, then expose the inputs, evidence and result a user needs. In the Ocean Harness demo above, a user asks an ocean-science question and can inspect the sources behind the answer. A browser workbench can present a domain-specific interaction like this. The Console also provides an editor for the harness itself. [Browser workbench plugins](docs/harness-plugins.md) · [Console editor](console/WORKBENCH.md)

Harness editor view
Harness editor

-
- -
-🌱 Evolve your harness — turn feedback into improvements to your own harness - + -

Xiao Lü demonstrates turning personal feedback into a proposed change

+### 🌱 Test-time evolving -Xiao Lü is one example of personal Harness evolution built with HarnessGrad. The desktop assistant shows how a correction from a session can become a scoped change proposal for review. +Use feedback from a session to adapt a harness you already use. Select a correction and the project instructions it concerns. The local workspace freezes those inputs, generates a proposed edit and shows its diff. For a supported instruction check, it can also compare the baseline and candidate and retain both run records for review. [Offline review guide](docs/personal-evolution-review.md) - - -### 📦 Installation +Today this path uses an adapter for the selected project instructions. Extending it to a newly evolved harness requires discovering which parts can be edited and how to check the resulting behavior. -Use Python 3.12+ and install from the HarnessGrad checkout. To build the native desktop shell, follow the [desktop setup guide](desktop/personal/README.md). +

Xiao Lü demonstrates turning personal feedback into a proposed change

-```bash -python -m pip install . -``` + +Xiao Lü demonstrates the workflow in a desktop assistant. The local service uses the same [HarnessGrad installation](#customize-installation). To build the native shell, follow the [desktop setup guide](desktop/personal/README.md). -### 🚀 Quick start +#### Start the local workspace Open the local personal workspace with a synthetic session. Choose an existing project directory and a separate state directory outside the checkout and project. ```bash -harnessgrad personal demo --state-root /path/to/state --project /path/to/project -harnessgrad personal serve --state-root /path/to/state +harnessgrad customize test-time demo --state-root /path/to/state --project /path/to/project +harnessgrad customize test-time serve --state-root /path/to/state ``` -Open the printed local URL and select the service's `connection.json` in the browser. This example previews the workspace without model calls. For the desktop workflow shown above, see the [personal evolution guide](docs/personal-evolution.md) and the [proposal preview in PR #64](https://github.com/zjunlp/HarnessGrad/pull/64). +Open the printed local URL and select the service's `connection.json` in the browser. The demo uses a synthetic session and makes no model calls. Existing `harnessgrad personal` commands use the same local service. [Test-time evolving guide](docs/personal-evolution.md)
@@ -370,7 +363,7 @@ If the platform, the measurement protocol or a curve produced here is useful in - PenguinHarness + Prism-Shadow
PenguinHarness
diff --git a/base_harness/claude-code/harness.json b/base_harness/claude-code/harness.json index 35ccb0984..7eeccc713 100644 --- a/base_harness/claude-code/harness.json +++ b/base_harness/claude-code/harness.json @@ -1,4 +1,8 @@ { - "name":"claude-code","version":"0.1.0","path":".","entrypoint":"agent.py","backend":"cli","install":null,"runtime_paths":[],"env_kinds":["files","exec"], + "name":"claude-code","external_adapter":"claude-code","version":"0.1.0","path":".","entrypoint":"agent.py","backend":"cli","install":null,"runtime_paths":[],"env_kinds":["files","exec"], + "plugin_capabilities": { + "skill": {"format": "agent-skills", "directory": "skills"}, + "workbench": {"format": "static-html"} + }, "components":{"control":["harness.json","settings.json",".claude-plugin/**"],"context":["CLAUDE.md","output-styles/**"],"tools":["skills/**","commands/**",".mcp.json",".lsp.json","servers/**"],"delegation":["agent.py","agents/**"],"recovery":["hooks/**"],"reliability":["claude_runtime.py","resources.py"],"unattributed":["README.md"]} } diff --git a/base_harness/codex/agent.py b/base_harness/codex/agent.py index 52cf39231..a90ebda85 100644 --- a/base_harness/codex/agent.py +++ b/base_harness/codex/agent.py @@ -252,7 +252,9 @@ def run(task: dict, workdir: Path) -> int: env["XDG_CONFIG_HOME"] = str(Path(home, ".config")) env["HARNESS_ROOT"] = home resources = _resources() - resource_identity = resources.stage(Path(__file__).resolve().parent, Path(home)) + candidate = Path(__file__).resolve().parent + native_home = Path(home) + resource_identity = resources.stage(candidate, native_home) config = {"approval_policy": "never", "sandbox_mode": "danger-full-access", "model_context_window": 32768, "model_auto_compact_token_limit": 16000, @@ -265,7 +267,8 @@ def run(task: dict, workdir: Path) -> int: config["model_providers"] = {"task_endpoint": { "name": "task_endpoint", "base_url": env["HG_AGENT_BASE_URL"], "env_key": "HG_AGENT_API_KEY", "wire_api": "responses"}} - effective = resources.configuration(Path(home), config) + effective = resources.configuration(native_home, config, + plugin_servers=resources.installed_mcp_servers(candidate, native_home)) plugin_receipts = resources.activate_plugins(Path(home), effective, selected['argv'], env) resource_identity['effective_config_sha256'] = hashlib.sha256(Path(home, 'config.toml').read_bytes()).hexdigest() resource_identity['native_hook_trust_bypass'] = bool(effective.get('hooks') or plugin_receipts) @@ -273,8 +276,8 @@ def run(task: dict, workdir: Path) -> int: (workdir / "codex.stderr.log").open("w") as errors: def record(value): trace.write(json.dumps(value, ensure_ascii=False) + "\n") - record({"harness_identity": {"harness": "codex-agent", - "agent_backend": "codex", "agent_model": model, + record({"harness_identity": {"harness": "codex", + "agent_backend": "openai", "agent_model": model, "codex_runtime": selected, "candidate_resources": resource_identity}, "task_id": task.get("task_id")}) if plugin_receipts: diff --git a/base_harness/codex/harness.json b/base_harness/codex/harness.json index 6d3291fe1..4f6c7a7ee 100644 --- a/base_harness/codex/harness.json +++ b/base_harness/codex/harness.json @@ -1,11 +1,18 @@ { "name": "codex", + "external_adapter": "codex", "version": "0.5.0", "path": ".", "entrypoint": "agent.py", "backend": "cli", + "smoke_mock_model": "responses", "install": null, "runtime_paths": [], + "plugin_capabilities": { + "skill": {"format": "agent-skills", "directory": "skills"}, + "mcp": {"format": "mcp"}, + "workbench": {"format": "static-html"} + }, "env_kinds": [ "files", "exec" diff --git a/base_harness/codex/resources.py b/base_harness/codex/resources.py index 97288e114..551e1ef6f 100644 --- a/base_harness/codex/resources.py +++ b/base_harness/codex/resources.py @@ -55,7 +55,7 @@ def _toml(value): raise ValueError('Codex configuration uses an unsupported value type') -def configuration(home: Path, fixed: dict) -> dict: +def configuration(home: Path, fixed: dict, *, plugin_servers=None) -> dict: path = home / 'config.toml' if path.exists(): # Explicit runtime-local expansion, not shell evaluation. Native path @@ -67,6 +67,11 @@ def configuration(home: Path, fixed: dict) -> dict: blocked = sorted(PLATFORM_KEYS & candidate.keys()) if blocked: raise ValueError('Codex candidate config cannot replace platform settings: ' + ', '.join(blocked)) + if plugin_servers: + servers = candidate.get('mcp_servers', {}) + if not isinstance(servers, dict) or servers.keys() & plugin_servers.keys(): + raise ValueError('Installed plugin MCP server conflicts with native Codex configuration') + candidate['mcp_servers'] = {**servers, **plugin_servers} agents = candidate.get('agents') or {} if not isinstance(agents, dict): raise ValueError('Codex agents configuration must be a table') @@ -88,6 +93,28 @@ def configuration(home: Path, fixed: dict) -> dict: return result +def installed_mcp_servers(candidate: Path, home: Path) -> dict: + receipt = candidate / 'harnessgrad-plugins.json' + if not receipt.is_file(): + return {} + if receipt.is_symlink(): + raise ValueError('Installed plugin receipt must be a candidate-owned file') + rows = json.loads(receipt.read_text(encoding='utf-8')) + servers = {} + for item in (item for row in rows for item in row.get('components', []) if item['kind'] == 'mcp'): + name = item['name'] + if name in servers: + raise ValueError(f'Installed plugin MCP server is declared twice: {name}') + settings = {**item['config'], 'required': True} + if 'path' in item: + entry = (home / item['path']).resolve(strict=True) + if not entry.is_relative_to((home / 'plugins').resolve()) or not entry.is_file(): + raise ValueError('MCP entry must be a staged plugin resource') + settings['args'] = [str(entry), *settings.get('args', [])] + servers[name] = settings + return servers + + def stage(candidate: Path, home: Path) -> dict: candidate = candidate.resolve() hashes = {} diff --git a/base_harness/deepseek-harness/agent.py b/base_harness/deepseek-harness/agent.py index 1f0c43b8b..e2d4f4d78 100644 --- a/base_harness/deepseek-harness/agent.py +++ b/base_harness/deepseek-harness/agent.py @@ -577,7 +577,8 @@ def run(task: dict, workdir: Path) -> int: # Refuse them by default to avoid recording a different model from the one used. # HG_AGENT_DSH_KEEP_HOME=1 explicitly opts into that inherited configuration. inherited_settings = home / ".dsh" / "settings.yaml" - if inherited_settings.is_file() and env.get("HG_AGENT_DSH_KEEP_HOME") != "1": + has_inherited_settings = inherited_settings.is_file() + if has_inherited_settings and env.get("HG_AGENT_DSH_KEEP_HOME") != "1": raise ValueError( f"refusing to run DSH against an operator home: {inherited_settings} holds a " "saved model selection that overrides the model this adapter declares; point " @@ -629,6 +630,7 @@ def run(task: dict, workdir: Path) -> int: # record named a model (or the shipped default) while DSH answered with its own. Now the # patch decides, so the record is taken from the patch. model_ran = env.get("HG_AGENT_MODEL") or env.get("HG_AGENT_DSH_MODEL") or DEFAULT_MODEL + model_backend = "openai" if patch and not has_inherited_settings else "unknown" with (workdir / "trace.jsonl").open("w", buffering=1) as trace: def record(value: dict) -> None: trace.write(json.dumps(value, ensure_ascii=False) + "\n") @@ -636,7 +638,7 @@ def record(value: dict) -> None: measured = facts(env, home, prompt, patch, selected) record({"harness_identity": {"harness": "deepseek-harness", "harness_version": "0.5.0", - "agent_backend": "dsh-headless", + "agent_backend": model_backend, "agent_model": model_ran, "agent_base_url": env.get("HG_AGENT_BASE_URL"), "model_patch": str(patch) if patch else None, diff --git a/base_harness/deepseek-harness/harness.json b/base_harness/deepseek-harness/harness.json index 8a233d2b1..0c3c789a1 100644 --- a/base_harness/deepseek-harness/harness.json +++ b/base_harness/deepseek-harness/harness.json @@ -1,15 +1,21 @@ { "name": "deepseek-harness", + "external_adapter": "deepseek-harness", "version": "0.5.0", "path": ".", "entrypoint": "agent.py", "backend": "cli", + "smoke_mock_model": "chat-completions", "install": null, "runtime_paths": [], "env_kinds": [ "files", "exec" ], + "plugin_capabilities": { + "skill": {"format": "agent-skills", "directory": "skills"}, + "workbench": {"format": "static-html"} + }, "components": { "context": [ "knobs.json", diff --git a/base_harness/hermes-agent/README.md b/base_harness/hermes-agent/README.md new file mode 100644 index 000000000..a5bf02cad --- /dev/null +++ b/base_harness/hermes-agent/README.md @@ -0,0 +1,63 @@ +# Hermes Agent + +Install on Linux x86-64 with Git and uv on `PATH`. + +The default mode is `editable`. Select `--mode fixed` to improve the adapter +against a fixed Hermes runtime. +Omitting `--version` selects the latest verified release. An exact unverified +version prints a warning to stderr and attempts to use that release's Git tag +and `uv.lock`. The installer records the resolved commit and selects exact +public registry pins for the Linux x86-64 Python environment. A successful +version check still leaves the installation marked unverified. + +```sh +hermes_harness="$(harnessgrad harness install hermes-agent --version v0.23.4)" +harnessgrad run --dataset demo --tasks t01 --harness-path "$hermes_harness" \ + --rounds 0 --improver none +``` + +The installer verifies tag `v0.23.4` against commit +`8fc0374447313e276f6b9a2764bfc750190c966a` in a bare Git cache and exports +the headless source into the base candidate's `hermes/` directory. The source +includes the upstream license, Python packages, and runtime resources. The +export excludes upstream CI, tests, evaluations, the website, contributor +assets, and the desktop and mobile apps. + +The editable seed records its exported files in `checkpoint_files`. HarnessGrad +uses the list to retain source and the release stamp in Git even when upstream +ignore rules match them. Historical candidates can be reconstructed from their +Git checkpoints. + +HarnessGrad copies the base candidate into the run's round 0 workspace. The +improver can edit `hermes/` along with the adapter. HarnessGrad checkpoints +each candidate and runs its source read-only during evaluation. The install +command prints the base candidate path on stdout for `--harness-path`. +For improvement rounds, pass your experiment method to `--method-entrypoint` +and select a configured `--improver`. + +To prepare the fixed mode, run +`harnessgrad harness install hermes-agent --version v0.23.4 --mode fixed`. +Pass the printed path to `--harness-path` in the same way. The candidate +contains the adapter. The installer exports the same release from the bare +Git cache into a separate read-only runtime and binds it in the launch +manifest. Sandbox execution keeps that source outside the improver's +writable workspace, and the platform rejects changes to the runtime binding. +For a custom fixed installation, choose an `--install-root` outside `/tmp`. +The sandbox uses a private `/tmp` during the version check and task execution. + +The installer provisions CPython 3.14.10 and prepares the base dependencies +through HarnessGrad's managed Python runtime. The candidate's +`requirements.lock` pins the Linux x86-64 base dependencies selected from the +upstream `hermes/uv.lock`, including its Pillow override. A source-only edit +reuses the dependency environment. Both install modes use that same locked +environment. To change Python dependencies for an editable candidate, update +its `requirements.lock`. Any new wheels must be available in the operator's +offline cache before evaluation. Use the same managed runtime store during +fixed installation and runs if you configure `HG_HARNESS_RUNTIME_ROOT`. + +Each task uses a private Hermes home and the model route configured in +HarnessGrad. The adapter uses headless stream JSON, Chat Completions, and +the terminal and file toolsets for the `files` environment. It supports +text and file submissions and the platform's offline model mock. +The task trace preserves streamed assistant text before tool calls and records +the final reply from the terminal result. diff --git a/base_harness/hermes-agent/agent.py b/base_harness/hermes-agent/agent.py new file mode 100644 index 000000000..9963b1b02 --- /dev/null +++ b/base_harness/hermes-agent/agent.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +"""Run a file-environment task via Hermes Agent's headless CLI.""" +from __future__ import annotations + +import argparse +import json +import math +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import hermes_runtime + + +def _task_prompt(task): + spec = task.get("submission", {"kind": "text"}) + paths = [] + if spec != {"kind": "text"}: + if not isinstance(spec, dict) or set(spec) != {"kind", "paths"} or spec["kind"] != "files": + raise ValueError("Invalid public submission descriptor") + paths = spec["paths"] + if not isinstance(paths, list) or not paths or any( + not isinstance(name, str) or not name.strip() or "\\" in name or ":" in name + or any(part in ("", ".", "..") for part in name.split("/")) for name in paths + ): + raise ValueError("File submission paths must be relative to the workdir") + prompt = task.get("cli_task") + if prompt is None: + prompt = task.get("goal") or task.get("instruction") + if isinstance(prompt, str) and prompt.strip(): + if task.get("inputs") is not None: + prompt += "\n\nTask inputs:\n" + json.dumps(task["inputs"], ensure_ascii=False) + if paths: + prompt += "\n\nLeave these files in the working directory: " + json.dumps(paths) + if not isinstance(prompt, str) or not prompt.strip(): + raise ValueError("Task requires a nonempty public prompt") + return prompt, paths + + +def _answer_stamp(path): + if path.is_symlink() or (path.exists() and not path.is_file()): + raise ValueError("Unsafe answer.txt") + return (path.stat().st_mtime_ns, path.read_bytes()) if path.is_file() else None + + +def _submit(work, paths, before, final): + if paths: + for name in paths: + path = work / name + if path.resolve() != path or not path.is_file(): + raise ValueError(f"Missing or unsafe submission file: {name}") + return {"submitted": True, "answer": "", "answer_source": "files", "submitted_files": paths} + answer = work / "answer.txt" + current = _answer_stamp(answer) + if current and current != before and current[1].strip(): + return {"submitted": True, "answer": current[1].decode("utf-8"), "answer_source": "artifact"} + if not final.strip(): + raise ValueError("Hermes produced no final answer or changed answer.txt") + answer.write_text(final, encoding="utf-8") + return {"submitted": True, "answer": final, "answer_source": "final_message"} + + +def _read_stream(output, model, record, *, partial=False): + initialized, terminal, pending = False, None, {} + text_parts = [] + lines = output.split("\n") + for line in (lines[:-1] if partial else lines): + if not line.strip(): + continue + event = json.loads(line) + kind = event["type"] + if kind == "system" and event.get("subtype") == "init": + if initialized or event.get("model") != model: + raise ValueError("Hermes init did not identify the selected model") + initialized = True + elif kind == "text": + text_parts.append(event["text"]) + elif kind == "tool_use": + # A tool call closes the preceding commentary. The terminal result + # supplies the final reply, including any streamed text after the last tool. + if text_parts: + text = "".join(text_parts) + if text.strip(): + record({"reply": text, "hermes_interim": True}) + text_parts.clear() + pending[event.get("tool_call_id") or event["name"]] = event.get("input") or {} + elif kind == "tool_result": + tool, output = event["name"], event["output"] + call_id = event.get("tool_call_id") + args = pending.pop(call_id or tool, {}) + command = args.get("command") if tool == "terminal" else None + try: + result = json.loads(output) + except ValueError: + result = None + code = result.get("exit_code") if isinstance(result, dict) else None + record({"command": command or tool + " " + json.dumps(args, ensure_ascii=False), + "tool": tool, "tool_call_id": call_id, "tool_error": event.get("is_error"), + "output": output[:8000], "observation": { + "kind": "shell" if tool == "terminal" else "filesystem", + "returncode": code if type(code) is int else None, + "output_chars": len(output), "truncated": len(output) > 8000, + }}) + elif kind == "result": + if terminal is not None: + raise ValueError("Hermes sent more than one terminal result") + terminal = event + if partial: + return terminal if initialized else None + if not initialized or terminal is None or pending: + raise ValueError("Hermes stream did not finish with a complete result") + return terminal + + +def _usage(report): + values = {"calls": "api_calls", "input_tokens": "input_tokens", "output_tokens": "output_tokens", + "cached_input_tokens": "cache_read_tokens", "cache_write_input_tokens": "cache_write_tokens"} + return {name: value if type(value := report.get(field)) is int and value >= 0 else None + for name, field in values.items()} + + +def _report_provider_error(detail, record): + if isinstance(detail, str) and (match := re.match(r"HTTP ([45][0-9]{2})(?:[:\s]|$)", detail)): + status = int(match[1]) + print(f"Model provider failure: HTTP {status}", file=sys.stderr) + record({"error": "Hermes model request failed", "http_status": status, "stop_reason": "error"}) + return True + return False + + +def _timeout(): + limit = float(os.environ.get("HG_AGENT_HERMES_TIMEOUT_S", "780")) + deadline = float(os.environ.get("HG_AGENT_DEADLINE_S") or (limit + 5)) + if not all(math.isfinite(value) and value > 0 for value in (limit, deadline)): + raise ValueError("Hermes timeout and deadline must be finite and positive") + return min(limit, deadline - min(5, deadline / 5)) + + +def _redact(value, key): + if isinstance(value, dict): + return {name: _redact(item, key) for name, item in value.items()} + if isinstance(value, list): + return [_redact(item, key) for item in value] + return value.replace(key, "") if isinstance(value, str) else value + + +def run(task, work): + work = work.resolve() + work.mkdir(parents=True, exist_ok=True) + model, endpoint, key = (os.environ.get(f"HG_AGENT_{name}") for name in ("MODEL", "BASE_URL", "API_KEY")) + diagnostic_key = None if os.environ.get("HG_AGENT_PUBLIC_CREDENTIAL") == "1" else key + mocked = os.environ.get("HG_AGENT_BACKEND") == "mock" + report = {} + with (work / "trace.jsonl").open("w", encoding="utf-8", buffering=1) as trace: + def record(row): + if diagnostic_key: + row = _redact(row, diagnostic_key) + trace.write(json.dumps(row, ensure_ascii=False) + "\n") + + try: + prompt, paths = _task_prompt(task) + launcher, version = hermes_runtime.launch(Path(__file__).resolve().parent, sys.executable) + if not (model and endpoint and key): + raise ValueError("Hermes requires HG_AGENT_MODEL, HG_AGENT_BASE_URL and HG_AGENT_API_KEY") + before = None if paths else _answer_stamp(work / "answer.txt") + # The gateway can still be closing its home as the task process exits. + with tempfile.TemporaryDirectory(prefix="hg-hermes-task-", ignore_cleanup_errors=True) as home: + ledger = Path(home) / "usage.json" + env = {"PATH": os.environ.get("PATH", os.defpath), "HOME": home, + "HERMES_HOME": str(Path(home) / ".hermes"), "TMPDIR": home, + "PYTHONDONTWRITEBYTECODE": "1", "TERM": "dumb", "NO_COLOR": "1", + "OPENAI_API_KEY": key, "OPENAI_BASE_URL": endpoint} + record({"harness_identity": {"harness": "hermes-agent", + "agent_backend": "mock" if mocked else "openai", + "agent_model": model, "agent_base_url": endpoint, + "cli_version": version}, + "task_id": task.get("task_id")}) + argv = [*launcher, "--usage-file", str(ledger), "chat", "--query-file", "-", + "--format", "stream-json", "--safe-mode", "--toolsets", "terminal,file", + "--max-turns", "8", "--provider", "custom", "--base-url", endpoint, "--model", model] + try: + result = subprocess.run(argv, cwd=work, env=env, input=prompt, capture_output=True, + text=True, encoding="utf-8", errors="replace", timeout=_timeout()) + except subprocess.TimeoutExpired as exc: + if ledger.is_file(): + report = json.loads(ledger.read_text(encoding="utf-8")) + output = (exc.stdout or b"").decode("utf-8", "replace") + terminal = _read_stream(output, model, record, partial=True) or {} + if _report_provider_error(terminal.get("error") or report.get("failure"), record): + return 1 + raise + if ledger.is_file(): + report = json.loads(ledger.read_text(encoding="utf-8")) + terminal = _read_stream(result.stdout, model, record) + if result.returncode or terminal["exit_code"] != 0 or report.get("failed"): + detail = terminal.get("error") or report.get("failure") + if _report_provider_error(detail, record): + return 1 + record({"reply": terminal["text"], "stop_reason": "error"}) + detail = detail or result.stderr.strip()[-1000:] + raise ValueError(f"Hermes failed with exit code {result.returncode}: {detail}") + record({"reply": terminal["text"], "stop_reason": "stop"}) + if _usage(report)["calls"] is None: + raise ValueError("Hermes did not report its model call count") + record(_submit(work, paths, before, terminal["text"])) + return 0 + except subprocess.TimeoutExpired: + record({"error": "Hermes exceeded the task deadline"}) + except (OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: + record({"error": str(exc)}) + finally: + record({"usage": _usage(report)}) + return 1 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--task", required=True, type=Path) + parser.add_argument("--workdir", required=True, type=Path) + args = parser.parse_args() + return run(json.loads(args.task.read_text(encoding="utf-8")), args.workdir) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/base_harness/hermes-agent/harness.json b/base_harness/hermes-agent/harness.json new file mode 100644 index 000000000..85ed1974b --- /dev/null +++ b/base_harness/hermes-agent/harness.json @@ -0,0 +1,24 @@ +{ + "name": "hermes-agent", + "external_adapter": "hermes-agent", + "version": "0.1.0", + "path": ".", + "entrypoint": "agent.py", + "backend": "cli", + "mock_model": "chat-completions", + "install": null, + "env_kinds": ["files"], + "runtime_paths": [], + "runtime": { + "kind": "python", + "python": "3.14", + "requirements": "requirements.lock", + "overrides": ["pillow"] + }, + "components": { + "control": ["harness.json"], + "delegation": ["agent.py"], + "reliability": ["hermes_runtime.py", "requirements.lock"], + "unattributed": ["README.md"] + } +} diff --git a/base_harness/hermes-agent/hermes_runtime.py b/base_harness/hermes-agent/hermes_runtime.py new file mode 100644 index 000000000..d321d468c --- /dev/null +++ b/base_harness/hermes-agent/hermes_runtime.py @@ -0,0 +1,184 @@ +"""Hermes launcher and validation of fixed source snapshots.""" +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import stat + +RECORD = "_hermes_runtime" +FIXED_SCHEMA = 2 +RELEASES = {"0.23.4": "8fc0374447313e276f6b9a2764bfc750190c966a"} +RELEASE_VERSION = re.compile(r"(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*)){2}(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?") +PYTHON = "3.14.10" +BOOTSTRAP = ( + "import runpy,sys; sys.path.insert(0,sys.argv.pop(1)); " + "runpy.run_module('hermes_cli.main',run_name='__main__',alter_sys=True)" +) + + +def _release_stamp(source): + stamp = json.loads((source / "install-stamp.json").read_text()) + version, commit = stamp["baseVersion"], stamp["commit"] + if stamp.get("verified") is False: + valid = (isinstance(version, str) and RELEASE_VERSION.fullmatch(version) + and stamp.get("displayVersion") == version + and isinstance(commit, str) and re.fullmatch(r"[0-9a-f]{40}", commit)) + else: + valid = isinstance(version, str) and version in RELEASES and RELEASES[version] == commit + if not valid: + raise ValueError("Invalid Hermes candidate release stamp") + return stamp + + +def candidate_launch(source, python): + if not (source / "hermes_cli/main.py").is_file(): + raise ValueError("Prepare a candidate with harnessgrad harness install hermes-agent") + version = _release_stamp(source)["baseVersion"] + return [str(python), "-I", "-B", "-c", BOOTSTRAP, str(source)], version + + +def launch(harness, python): + manifest = json.loads((harness / "harness.json").read_text()) + if RECORD in manifest: + record = manifest[RECORD] + return record["argv"], record["version"] + return candidate_launch(harness / "hermes", python) + + +def digest(path): + with path.open("rb") as handle: + return hashlib.file_digest(handle, "sha256").hexdigest() + + +def inventory(root, *, read_only=False): + """Fingerprint owned paths and file bytes without following directory links.""" + rows = [] + if read_only and root.stat().st_mode & 0o222: + raise ValueError("Hermes fixed source must be read-only") + + def fail(error): + raise error + + for directory, folders, files in os.walk(root, followlinks=False, onerror=fail): + folders.sort() + for filename in sorted(folders + files): + path = Path(directory) / filename + mode = path.lstat().st_mode + if read_only and not stat.S_ISLNK(mode) and mode & 0o222: + raise ValueError(f"Hermes fixed source is writable: {path}") + if stat.S_ISLNK(mode): + target = path.resolve(strict=True) + if not target.is_relative_to(root): + raise ValueError(f"Hermes runtime link escapes its binding: {path}") + link = os.readlink(path) + value = ["link", target.relative_to(root).as_posix(), + None if Path(link).is_absolute() else link] + elif stat.S_ISREG(mode): + value = ["file", digest(path)] + elif stat.S_ISDIR(mode): + value = ["directory"] + else: + raise ValueError(f"Unsupported Hermes runtime file: {path}") + rows.append([path.relative_to(root).as_posix(), stat.S_IMODE(mode), value]) + return hashlib.sha256(json.dumps(rows, separators=(",", ":")).encode()).hexdigest() + + +def dependency_key(source): + """The lock and project declaration select a reusable Python environment.""" + pins = [PYTHON, digest(source / "uv.lock"), digest(source / "pyproject.toml")] + return hashlib.sha256(json.dumps(pins).encode()).hexdigest() + + +def require_fixed_storage(path): + if path.is_relative_to("/tmp") or path.is_relative_to(Path("/tmp").resolve()): + raise ValueError("Install Hermes fixed source outside /tmp, which the sandbox hides") + + +def fixed_installation(source, artifact, version, *, forbidden=()): + machine = platform.machine() + if platform.system() != "Linux" or machine != "x86_64": + raise ValueError("Hermes Agent installation requires Linux x86-64") + if (len(source.parts) < 7 or source.parts[-6:-2] != ("hermes-agent", version, machine, "fixed") + or source.name != "source"): + raise ValueError("Invalid Hermes fixed source layout") + require_fixed_storage(source) + blocked = (*forbidden, Path("/usr"), Path("/etc"), Path("/proc"), Path("/sys"), Path("/dev"), + Path("/run"), Path.home() / ".config", Path.home() / ".ssh", Path.home() / ".hermes") + if (not source.is_absolute() or source.resolve(strict=True) != source + or any(char in str(source) for char in (",", "\n", "\r")) + or any(source.is_relative_to(path.resolve()) or path.resolve().is_relative_to(source) + for path in blocked)): + raise ValueError("Hermes fixed source needs dedicated physical storage") + source_sha = inventory(source, read_only=True) + argv, stamped_version = candidate_launch(source, artifact["python"]) + if source_sha != source.parent.name or stamped_version != version: + raise ValueError("Hermes fixed source differs from its installed release") + stamp = _release_stamp(source) + return {"schema": FIXED_SCHEMA, "version": version, "architecture": machine, "python": PYTHON, + "release_commit": stamp["commit"], "source_sha256": source_sha, "artifact": artifact, + "argv": argv, "runtime_paths": [str(source), *artifact["runtime_paths"]], "cacheable": True, + **({"verified": False} if stamp.get("verified") is False else {})} + + +def installation(source, environment, version, *, forbidden=()): + machine = platform.machine() + if version not in RELEASES or platform.system() != "Linux" or machine != "x86_64": + raise ValueError("Hermes Agent installation requires a supported release on Linux x86-64") + if len(source.parents) < 5 or len(environment.parents) < 3: + raise ValueError("Invalid Hermes source and environment layout") + base = source.parents[2] + if (source.name != "source" or source.parents[1].name != "snapshots" + or base.name != machine or base.parent.name != version or base.parents[1].name != "hermes-agent" + or environment.name != "runtime" or not environment.parent.name.startswith("install-") + or environment.parents[2] != base / "environments"): + raise ValueError("Invalid Hermes source and environment layout") + blocked = (*forbidden, Path("/tmp"), Path("/var/tmp"), Path("/usr"), Path("/etc"), + Path("/proc"), Path("/sys"), Path("/dev"), Path("/run"), + Path.home() / ".config", Path.home() / ".ssh", Path.home() / ".hermes") + for root in (source, environment): + if (not root.is_absolute() or root.resolve(strict=True) != root + or any(char in str(root) for char in (",", "\n", "\r")) + or any(root.is_relative_to(path.resolve()) or path.resolve().is_relative_to(root) for path in blocked)): + raise ValueError("Hermes runtime needs dedicated physical storage") + + source_sha = inventory(source) + if source_sha != source.parent.name or environment.parents[1].name != dependency_key(source): + raise ValueError("Hermes source snapshot or Python dependency binding changed") + stamp = json.loads((source / "install-stamp.json").read_text()) + commit = stamp["commit"] + if (stamp.get("baseVersion") != version or stamp.get("displayVersion") != version + or not isinstance(commit, str) or not re.fullmatch(r"[0-9a-f]{40}", commit)): + raise ValueError("Invalid Hermes source version stamp") + python = environment / "venv/bin/python" + if not python.resolve(strict=True).is_relative_to(environment) or not os.access(python, os.X_OK): + raise ValueError("Hermes Python interpreter is outside the frozen environment") + return {"schema": 1, "version": version, "architecture": machine, "python": PYTHON, + "release_commit": RELEASES[version], "source_commit": commit, "source_sha256": source_sha, + "lock_sha256": digest(source / "uv.lock"), "environment_sha256": inventory(environment), + "argv": [str(python), "-I", "-B", "-c", BOOTSTRAP, str(source)], + "runtime_paths": [str(source), str(environment)], "cacheable": True} + + +def resolve(harness, _env, *, forbidden=()): + """Recheck a fixed binding, including the original format for recorded runs.""" + manifest = json.loads((harness / "harness.json").read_text()) + record = manifest.get(RECORD) + if not isinstance(record, dict): + raise ValueError("Prepare a copy with harnessgrad harness install hermes-agent") + paths, version = record.get("runtime_paths"), record.get("version") + if (not isinstance(paths, list) or len(paths) < 2 or not all(isinstance(path, str) for path in paths) + or manifest.get("runtime_paths") != paths or not isinstance(version, str)): + raise ValueError("Invalid Hermes runtime binding") + if record.get("schema") == FIXED_SCHEMA and not manifest.get("runtime"): + expected = fixed_installation(Path(paths[0]), record["artifact"], version, forbidden=(*forbidden, harness)) + elif record.get("schema") == 1 and len(paths) == 2: + expected = installation(Path(paths[0]), Path(paths[1]), version, forbidden=(*forbidden, harness)) + else: + raise ValueError("Invalid Hermes runtime binding") + if expected != record: + raise ValueError("Hermes runtime changed after preparation") + return record diff --git a/base_harness/hermes-agent/requirements.lock b/base_harness/hermes-agent/requirements.lock new file mode 100644 index 000000000..09606736a --- /dev/null +++ b/base_harness/hermes-agent/requirements.lock @@ -0,0 +1,67 @@ +# Hermes Agent v0.23.4 base dependencies from upstream uv.lock. +# Target: Linux x86-64, CPython 3.14.10. +annotated-doc==0.0.5 +annotated-types==0.8.0 +anyio==4.15.1 +browser-harness==0.1.13 +cdp-use==1.4.5 +certifi==2026.10.19 +cffi==2.1.1 +charset-normalizer==3.5.2 +click==8.5.0 +croniter==6.2.4 +cryptography==50.0.2 +distro==1.9.0 +fastapi==0.133.1 +fetch-use==0.4.0 +fire==0.7.1 +firecrawl-anydoc==0.2.4 +h11==0.16.0 +httpcore==1.0.9 +httptools==0.8.0 +httpx==0.28.1 +idna==3.20 +jinja2==3.1.6 +jiter==0.17.0 +markdown==3.11.2 +markdown-it-py==4.2.0 +markupsafe==3.0.4 +mdurl==0.1.2 +nemo-relay==0.11.0 +openai==2.54.0 +packaging==26.3 +pathspec==1.1.1 +pillow==13.0.0 +pillow-heif==1.8.1 +prompt-toolkit==3.0.53 +psutil==7.2.2 +ptyprocess==0.7.0 +pycparser==3.11 +pydantic==2.14.1 +pydantic-core==2.50.1 +pygments==2.21.0 +pyjwt==2.15.1 +python-dateutil==2.9.0.post0 +python-dotenv==1.2.4 +python-multipart==0.0.32 +requests==2.34.2 +resvg-py==0.5.0 +rich==14.3.4 +ruamel-yaml==0.18.16 +ruamel-yaml-clib==0.2.15 +six==1.17.0 +sniffio==1.3.1 +snowballstemmer==3.1.1 +socksio==1.0.0 +starlette==1.9.0 +termcolor==3.3.0 +tomli-w==1.2.0 +tqdm==4.70.1 +truststore==0.10.5 +typing-extensions==4.16.0 +typing-inspection==0.4.4 +urllib3==2.8.0 +uvicorn==0.54.0 +watchfiles==1.3.0 +wcwidth==0.9.2 +websockets==15.0.1 diff --git a/base_harness/launchable.json b/base_harness/launchable.json index c609e42c4..bf2d7f325 100644 --- a/base_harness/launchable.json +++ b/base_harness/launchable.json @@ -7,6 +7,9 @@ "openclaw", "codex", "opencode", - "claude-code" + "claude-code", + "pi", + "oh-my-pi", + "hermes-agent" ] } diff --git a/base_harness/oh-my-pi/README.md b/base_harness/oh-my-pi/README.md new file mode 100644 index 000000000..6960810ce --- /dev/null +++ b/base_harness/oh-my-pi/README.md @@ -0,0 +1,30 @@ +# Oh My Pi Harness + +Install the pinned Linux executable and prepare a copy of the adapter with Bubblewrap. + +```sh +HARNESS_DIR=$(harnessgrad harness install oh-my-pi) +harnessgrad run --harness-path "$HARNESS_DIR" ... +``` + +The installer defaults to `19.2.0`. It downloads the glibc Linux x86-64 executable from the +[v19.2.0 release](https://github.com/can1357/oh-my-pi/releases/tag/v19.2.0), +verifies its pinned SHA-256, and checks the version inside a network-isolated +sandbox. Ubuntu x86-64 is the tested target. The executable bundles Bun. +The command prints the prepared adapter path. Set `--install-root` to use +a different store from `${XDG_DATA_HOME:-$HOME/.local/share}/harnessgrad/base-harnesses`. +Omitting `--version` selects the latest verified release. An exact unverified +version prints a warning to stderr and attempts installation when GitHub provides +the Linux x86-64 executable and its SHA-256 digest. A successful version check +still leaves the installation marked unverified. + +The adapter runs one headless JSON session per native `files` task. It sends +Chat Completions through `HG_AGENT_BASE_URL` with `HG_AGENT_MODEL` and +`HG_AGENT_API_KEY`, makes a private configuration for the task, and enables +the native read, bash, edit, and write tools. The trace contains assistant +turns, completed tools, reported token usage, and text or file submissions. + +`HG_AGENT_BACKEND=mock` runs the actual CLI against HarnessGrad's local +Chat Completions fixture for text and file submissions. The prepared manifest +selects the fixture for platform runs and smoke checks. +`HG_AGENT_OMP_TIMEOUT_S` caps the CLI's wall time within the platform deadline. diff --git a/base_harness/oh-my-pi/agent.py b/base_harness/oh-my-pi/agent.py new file mode 100644 index 000000000..b7390a1ea --- /dev/null +++ b/base_harness/oh-my-pi/agent.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Run one task through Oh My Pi's headless JSON mode.""" +from __future__ import annotations + +import json +from pathlib import Path +import sys + +if __package__: + from . import omp_runtime + from base_harness.pi import task_support +else: + directory = Path(__file__).resolve().parent + if not (directory / "task_support.py").is_file(): + raise SystemExit("Prepare a copy with harnessgrad harness install oh-my-pi") + sys.path.insert(0, str(directory)) + import omp_runtime + import task_support + + +def _configure(home, model, endpoint, env): + context = int(env.get("HG_AGENT_CONTEXT_WINDOW", "32768")) + output = int(env.get("HG_AGENT_MAX_OUTPUT_TOKENS", env.get("HG_AGENT_MAX_TOKENS", "8192"))) + if not 0 < output <= context: + raise ValueError("Oh My Pi token budget must satisfy 0 < max output <= context window") + models = {"providers": {"harnessgrad": { + "baseUrl": endpoint, "api": "openai-completions", "apiKey": "HG_AGENT_API_KEY", + "models": [{"id": model, "name": model, "input": ["text"], "reasoning": False, + "contextWindow": context, "maxTokens": output}], + }}} + settings = {"compaction": {"enabled": False}, "retry": {"enabled": False}, + "providers": {"cacheWarming": "off"}} + # JSON is a valid YAML subset. The release uses the .yml filenames. + (home / "models.yml").write_text(json.dumps(models), encoding="utf-8") + (home / "config.yml").write_text(json.dumps(settings), encoding="utf-8") + + +def _argv(model): + return ["-p", "--mode", "json", "--model", "harnessgrad/" + model, + "--no-session", "--offline", "--no-title", "--no-tools", + "--tools", "read,bash,edit,write", "--no-context-files", "--no-rules", + "--no-skills", "--no-lsp", "--no-pty", "--no-prewalk"] + + +def run(task, work): + return task_support.run(task, work, name="oh-my-pi", harness=Path(__file__).resolve().parent, + resolve=omp_runtime.resolve, configure=_configure, cli_args=_argv, + timeout_key="HG_AGENT_OMP_TIMEOUT_S", terminal_event="agent_end") + + +if __name__ == "__main__": + raise SystemExit(task_support.main(run)) diff --git a/base_harness/oh-my-pi/harness.json b/base_harness/oh-my-pi/harness.json new file mode 100644 index 000000000..521248981 --- /dev/null +++ b/base_harness/oh-my-pi/harness.json @@ -0,0 +1,18 @@ +{ + "name": "oh-my-pi", + "external_adapter": "oh-my-pi", + "version": "0.1.0", + "path": ".", + "entrypoint": "agent.py", + "backend": "cli", + "mock_model": "chat-completions", + "install": null, + "env_kinds": ["files"], + "runtime_paths": [], + "components": { + "control": ["harness.json"], + "delegation": ["agent.py"], + "reliability": ["omp_runtime.py"], + "unattributed": ["README.md"] + } +} diff --git a/base_harness/oh-my-pi/omp_runtime.py b/base_harness/oh-my-pi/omp_runtime.py new file mode 100644 index 000000000..ac83994a9 --- /dev/null +++ b/base_harness/oh-my-pi/omp_runtime.py @@ -0,0 +1,79 @@ +"""Runtime admission for the native Oh My Pi release.""" +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +import platform +import re + +RECORD = "_omp_runtime" +UNVERIFIED_RECEIPT = "unverified-installation.json" +RELEASE_VERSION = re.compile(r"(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*)){2}(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?") +RELEASES = { + "19.2.0": { + "x86_64": ("omp-linux-x64", "74cb641d3fcdc22fa3f2141dafa4e66c9fc581d7d2d71753e690160980472c31"), + }, +} + + +def asset(version, machine): + if version not in RELEASES: + raise ValueError(f"Unknown Oh My Pi release {version!r}") + if machine not in RELEASES[version]: + raise ValueError(f"Unsupported Oh My Pi Linux architecture {machine!r}") + return RELEASES[version][machine] + + +def unverified_asset(machine): + if machine != "x86_64": + raise ValueError(f"Unsupported Oh My Pi Linux architecture {machine!r}") + return "omp-linux-x64" + + +def installation(root, version, *, forbidden=(), unverified_sha256=None): + machine = platform.machine() + if unverified_sha256 is None: + asset_name, expected = asset(version, machine) + else: + if not RELEASE_VERSION.fullmatch(version) or not re.fullmatch(r"[0-9a-f]{64}", unverified_sha256): + raise ValueError("Invalid unverified Oh My Pi release binding") + asset_name, expected = unverified_asset(machine), unverified_sha256 + if (platform.system() != "Linux" or not root.is_absolute() or root.resolve(strict=True) != root + or root.name != "omp" or not root.parent.name.startswith("install-") + or root.parents[1].name != machine or root.parents[2].name != version + or root.parents[3].name != "oh-my-pi"): + raise ValueError("Invalid Oh My Pi release directory") + blocked = (*forbidden, Path("/tmp"), Path("/var/tmp"), Path("/usr"), Path("/etc"), + Path("/proc"), Path("/sys"), Path("/dev"), Path("/run"), Path.home() / ".config", + Path.home() / ".ssh", Path.home() / ".omp") + if (any(root.is_relative_to(path.resolve()) or path.resolve().is_relative_to(root) for path in blocked) + or any(char in str(root) for char in (",", "\n", "\r"))): + raise ValueError("Oh My Pi runtime must be bound from dedicated storage") + binary = root / "omp" + if (set(root.iterdir()) != {binary} or binary.is_symlink() or not binary.is_file() + or not os.access(binary, os.X_OK)): + raise ValueError("Oh My Pi release must contain exactly the owned executable") + with binary.open("rb") as stream: + if hashlib.file_digest(stream, "sha256").hexdigest() != expected: + raise ValueError("Oh My Pi executable differs from the pinned release") + return {"schema": 1, "version": version, "architecture": machine, "asset": asset_name, + "asset_sha256": expected, "argv": [str(binary)], "runtime_paths": [str(root)], "cacheable": True, + **({"verified": False} if unverified_sha256 is not None else {})} + + +def resolve(harness, _env, *, forbidden=()): + manifest = json.loads((harness / "harness.json").read_text(encoding="utf-8")) + record = manifest.get(RECORD) + if not isinstance(record, dict) or record.get("schema") != 1: + raise ValueError("Prepare a copy with harnessgrad harness install oh-my-pi") + paths, version = record.get("runtime_paths"), record.get("version") + if (not isinstance(paths, list) or len(paths) != 1 or not isinstance(paths[0], str) + or manifest.get("runtime_paths") != paths or not isinstance(version, str)): + raise ValueError("Invalid Oh My Pi release binding") + experimental = record["asset_sha256"] if record.get("verified") is False else None + if installation(Path(paths[0]), version, forbidden=(*forbidden, harness), + unverified_sha256=experimental) != record: + raise ValueError("Oh My Pi release changed since installation") + return record diff --git a/base_harness/openclaw/harness.json b/base_harness/openclaw/harness.json index a0feecd82..cdddf214c 100644 --- a/base_harness/openclaw/harness.json +++ b/base_harness/openclaw/harness.json @@ -1,5 +1,6 @@ { "name": "openclaw", + "external_adapter": "openclaw", "version": "0.8.0", "path": ".", "entrypoint": "agent.py", @@ -10,6 +11,10 @@ ], "runtime_paths": [], "notes": "Prepare a Harness copy with tools/configure_openclaw_harness.py before measurement. Runs the pinned external OpenClaw CLI with a private Gateway and isolated per-task config/state. The prepared manifest records Node, package identity and read-only runtime bindings together. This adapter supports files environments only.", + "plugin_capabilities": { + "skill": {"format": "agent-skills", "directory": "skills"}, + "workbench": {"format": "static-html"} + }, "components": { "context": [ "prompt.md", diff --git a/base_harness/opencode/README.md b/base_harness/opencode/README.md index 9a93dc071..cd5d27fc0 100644 --- a/base_harness/opencode/README.md +++ b/base_harness/opencode/README.md @@ -1,47 +1,61 @@ # OpenCode Harness -The adapter runs the released OpenCode CLI from a prepared Harness copy. -On Linux x86-64 with Bubblewrap, install the verified npm releases with: +Install OpenCode on Linux x86-64 with Bubblewrap. ```sh -harnessgrad harness install opencode --version 1.19.5 HARNESS_DIR=$(harnessgrad harness install opencode) +harnessgrad harness install opencode --mode fixed +harnessgrad harness install opencode --mode fixed --version 2.4.1 +harnessgrad harness install opencode --version 1.19.5 ``` Use the printed directory with `harnessgrad run --harness-path`. Omitting -`--version` selects the latest verified release, currently `2.4.1`. +`--version` selects the latest verified release for the selected mode, currently +`2.4.3`. `--install-root` selects the dedicated store, which defaults to `harnessgrad/base-harnesses` under the user data directory. -The installer uses Node.js 24.22.2 and npm 11.19.1 to install the exact native -package. It checks the npm archive digest and retains the lockfile. -`1.19.5` uses `opencode-linux-x64`. The verified 2.x releases use -`@opencode/cli-linux-x64`. -Tasks invoke the native executable directly. The prepared manifest records -the executable and its package metadata as read-only bindings, together with -their hashes and modes. Preparation checks the version in a network-isolated -sandbox. Explicit unverified v1 or v2 releases are attempted with a warning. - -To bind an existing npm native installation, copy the Harness and run +**Editable** is the default for the latest verified v2 release. The installer verifies the source archive, prepares +Bun 1.4.4 and populates a dependency store using the upstream lockfile. The H0 +candidate contains OpenCode source in `opencode/`, where the improve agent can +edit it. Evaluation uses the current candidate's TypeScript and mounts Bun and +the prepared dependencies read-only. TypeScript edits can reuse that store. +The installer materializes internal source file links for portable snapshots. +Both source preparation and the CLI run use locked dependencies. Evaluation +requires a sandbox and uses no package downloads. + +**Fixed** uses a Linux x86-64 executable. Verified GitHub Release versions are `2.4.0`, `2.4.1`, `2.4.2`, and `2.4.3`. +The installer verifies the archive and executable and probes the CLI version +with network access disabled. Evaluation mounts the executable read-only, and the +candidate contains the adapter. + +The fixed installer also supports native npm packages. OpenCode 1.x uses +`opencode-linux-x64`, and npm installations of 2.x use `@opencode/cli-linux-x64`. +The installer verifies the archive digest of known packages, retains the lockfile, +and binds the executable and package metadata read-only. Requesting 1.x, a +verified npm-only version (2.2.6, 2.2.7 or 2.3.0), or 2.4.1 without a mode +selects a fixed installation. + +Verification is tracked per installation mode. An explicit release +unverified for the selected mode produces a warning and installation proceeds +without a confirmation prompt. + +To bind an existing v1 or v2 native npm installation, run `python3 tools/configure_opencode_harness.py "$HARNESS_DIR" --opencode "$OPENCODE_BIN"`. `OPENCODE_BIN` points to the Linux x86-64 ELF executable at `bin/opencode` inside -its native npm package, with `package.json` at the package root. Prepare a fresh -copy for a different installation to keep the original binding available for -earlier experiments. - -Both release series use `run --format json` for tool events. The adapter uses -each series' provider configuration and session export to record the final -answer and usage. It keeps OpenCode's configuration and state local to the -task and passes the task's model endpoint and credential. Set +its native npm package, with `package.json` at the package root. + +Both release series use `run --format json` for tool events. The adapter reads +the final answer and usage from `export` in v1 and `session export` in v2. +It keeps OpenCode's configuration and state local to the task and passes the task's model endpoint and credential. Set `HG_AGENT_OPENCODE_WIRE` to `responses` for a Responses endpoint. The default transport is Chat Completions (`chat`). The platform records the effective transport in the measurement's runtime identity. Cache reuse, H0 reuse, and resume require a matching transport. If the recorded runtime identity omits the transport, start a new run and measure again. -To resume an experiment with a schema 2 OpenCode source binding, use the -original platform revision and source binding. Start a new run when moving -that experiment to an npm release. +Start a new run when switching versions or installation modes. Historical schema 2 +source bindings require the original platform revision to resume. The task prompt does not prohibit native subagents. Parent and child sessions are recorded separately; child text cannot replace the parent answer. For 2.x, token diff --git a/base_harness/opencode/agent.py b/base_harness/opencode/agent.py index a216941d3..339a873e3 100644 --- a/base_harness/opencode/agent.py +++ b/base_harness/opencode/agent.py @@ -29,14 +29,68 @@ def prepared_installation(env): spec = importlib.util.spec_from_file_location("_task_opencode_runtime", ROOT / "opencode_runtime.py") helper = importlib.util.module_from_spec(spec) spec.loader.exec_module(helper) + manifest = json.loads((ROOT / "harness.json").read_text()) + if helper.SOURCE_RECORD in manifest: + source = helper.source_identity(ROOT, manifest) + entry = ROOT / manifest["runtime"]["source"] / manifest["runtime"]["entrypoint"] + if env.get("HG_HARNESS_ENTRYPOINT") != str(entry) or not env.get("HG_HARNESS_BUN"): + raise ValueError("OpenCode editable mode requires the prepared candidate Bun runtime") + return {"argv": [env["HG_HARNESS_BUN"], str(entry)], + "version": source["version"], "editable": True} return helper.resolve(ROOT, env) -def redact(text: str, env: dict) -> str: - for key, value in env.items(): - if value and any(word in key.upper() for word in ("API_KEY", "SECRET", "PASSWORD", "ACCESS_TOKEN")): - text = text.replace(value, "") - return text +def source_environment(env, version, entrypoint, state): + package = Path(entrypoint).parent.parent + preload = f'globalThis.OPENCODE_VERSION = {json.dumps(version)};\n' + preload += 'globalThis.OPENCODE_CHANNEL = "latest";\n' + # Bun has consumed the startup options when the standalone server runs this + # preload. Drop them before the server starts any task shell commands. + preload += ( + 'if (process.argv[2] === "serve" && process.argv.includes("--stdio")) {\n' + ' delete process.env.BUN_OPTIONS;\n' + '}\n' + ) + (state / "preload.ts").write_text(preload) + options = json.loads((package / "tsconfig.json").read_text())["compilerOptions"] + if "paths" in options: + options["paths"] = {name: [str(package / value) for value in values] + for name, values in options["paths"].items()} + (state / "tsconfig.json").write_text(json.dumps({"compilerOptions": options})) + # The server re-execs Bun from the task directory and inherits these flags. + env["BUN_OPTIONS"] = ("--config=/dev/null --no-env-file --no-install " + "--preload=./.opencode-state/preload.ts " + "--tsconfig-override=./.opencode-state/tsconfig.json") + + +def diagnostic_secrets(env: dict) -> tuple[str, ...]: + public_key = env.get("HG_AGENT_API_KEY") if env.get("HG_AGENT_PUBLIC_CREDENTIAL") == "1" else None + return tuple({value for key, value in env.items() if value and value != public_key and any( + word in key.upper() for word in ("API_KEY", "SECRET", "PASSWORD", "ACCESS_TOKEN") + )}) + + +def redact(value, secrets): + if isinstance(value, dict): + return {redact(name, secrets): redact(item, secrets) for name, item in value.items()} + if isinstance(value, list): + return [redact(item, secrets) for item in value] + if isinstance(value, str): + for secret in secrets: + escaped = json.dumps(secret, ensure_ascii=False)[1:-1] + value = value.replace(escaped, "").replace(secret, "") + return value + + +def diagnostic_line(line, secrets): + if not secrets: + return line + try: + value = json.loads(line) + except ValueError: + return redact(line, secrets) + masked = redact(value, secrets) + return line if masked == value else json.dumps(masked, ensure_ascii=False) def task_prompt(task: dict) -> str: @@ -89,7 +143,7 @@ def configuration(env: dict, profile: str) -> dict: def child_environment(parent: dict, state: Path, profile: str = "1") -> dict: # Retain task service endpoints/PATH; the platform has already selected task credentials. - excluded = {"OPENAI_API_KEY", "ANTHROPIC_API_KEY", "DEEPSEEK_API_KEY", + excluded = {"OPENAI_API_KEY", "ANTHROPIC_API_KEY", "DEEPSEEK_API_KEY", "BUN_OPTIONS", "CODEX_HOME", "OPENCODE_SERVER", "OPENCODE_CONFIG", "NODE_OPTIONS", "NODE_PATH"} env = {k: v for k, v in parent.items() if not k.startswith(("HG_METHOD_", "HG_ENV_", "HG_JUDGE_", "OPENCODE_", "OPENAI_", "CODEX_")) and k not in excluded} @@ -510,27 +564,32 @@ def run(task: dict, work: Path) -> int: work = work.resolve() work.mkdir(parents=True, exist_ok=True) parent = dict(os.environ) + secrets = diagnostic_secrets(parent) with (work / "trace.jsonl").open("w", encoding="utf-8", buffering=1) as trace: def record(value): - trace.write(redact(json.dumps(value, ensure_ascii=False), parent) + "\n") + trace.write(json.dumps(redact(value, secrets), ensure_ascii=False) + "\n") started = time.monotonic() stream = EventCollector(record) try: expires = started + timeout_seconds(parent) prompt = task_prompt(task) installed = prepared_installation(parent) - profile = installed["profile"] + profile = installed["version"].split(".", 1)[0] + stream.profile = profile startup, export_command = RELEASE_COMMANDS[profile] - env = child_environment(parent, work / ".opencode-state", profile) - surfaces = prepare_surfaces(work / ".opencode-state", env, profile, version=installed.get("version")) + state = work / ".opencode-state" + env = child_environment(parent, state, profile) + if installed.get("editable"): + source_environment(env, installed["version"], installed["argv"][-1], state) + surfaces = prepare_surfaces(state, env, profile, version=installed["version"]) env["OPENCODE_CONFIG_CONTENT"] = json.dumps(surfaces["config"]) env["PWD"] = str(work) - record({"opencode_resources": surfaces}) - record({"harness_identity": {"harness": "opencode-agent", "agent_backend": "opencode", + record({"harness_identity": {"harness": "opencode", "agent_backend": "openai", "agent_model": parent.get("HG_AGENT_MODEL"), "agent_base_url": parent.get("HG_AGENT_BASE_URL"), "wire": parent.get("HG_AGENT_OPENCODE_WIRE", "chat"), "runtime": installed}, "task_id": task.get("task_id")}) + record({"opencode_resources": surfaces}) prefix = [*installed["argv"], *startup] argv = [*prefix, "run", "--format", "json", "--auto", "--model", "harnessgrad/" + parent["HG_AGENT_MODEL"], "--agent", surfaces["selected_agent"]] @@ -545,10 +604,13 @@ def record(value): except subprocess.TimeoutExpired as expired: timed_out = True stdout, stderr, cleanup = drain_after_timeout(process, expired) - (work / "opencode.events.jsonl").write_text(redact(stdout, parent), encoding="utf-8") - (work / "opencode.stderr.log").write_text(redact(stderr, parent), encoding="utf-8") - for line in stdout.splitlines(): - stream.feed(redact(line, parent)) + with (work / "opencode.events.jsonl").open("w", encoding="utf-8") as events: + for line in stdout.split("\n"): + if not line: + continue + events.write(diagnostic_line(line, secrets) + "\n") + stream.feed(line) + (work / "opencode.stderr.log").write_text(redact(stderr, secrets), encoding="utf-8") failed = timed_out or process.returncode != 0 or stream.provider_errors or stream.invalid_lines if failed: record({"error": "OpenCode timeout" if timed_out else "OpenCode execution failed", @@ -558,7 +620,7 @@ def record(value): if stream.provider_errors and str(stream.provider_errors[-1].get("type", "")).startswith("provider."): last_error = stream.provider_errors[-1] summary = {k: last_error[k] for k in ("type", "status", "message") if k in last_error} - print("OpenCode provider failure: " + redact(json.dumps(summary), parent), file=sys.stderr) + print("OpenCode provider failure: " + json.dumps(redact(summary, secrets)), file=sys.stderr) else: print("OpenCode execution failed; inspect trace.jsonl", file=sys.stderr) return 1 @@ -580,17 +642,18 @@ def export_one(session_id): record({"export_timeout_cleanup": cleanup}) raise ValueError("OpenCode session export exceeded the task deadline") if export.returncode or not text.strip(): - raise ValueError("OpenCode session export failed: " + redact(error[-800:], parent)) - return json.loads(redact(text, parent)) + raise ValueError("OpenCode session export failed: " + redact(error[-800:], secrets)) + return json.loads(text) try: snapshot = export_one(stream.primary_session) except (OSError, ValueError, TypeError) as exc: - record({"export": {"ok": False, "detail": redact(str(exc), parent)}}) + record({"export": {"ok": False, "detail": str(exc)}}) if stream.child_sessions: stream.child_usage_incomplete = True else: - (work / "opencode.session.json").write_text(json.dumps(snapshot, ensure_ascii=False), encoding="utf-8") + rendered = json.dumps(redact(snapshot, secrets), ensure_ascii=False) + (work / "opencode.session.json").write_text(rendered, encoding="utf-8") stream.reconcile(snapshot, profile) collect_child_sessions(stream, export_one, profile) answer, origin = save_answer(work, before, stream.final_text(), task=task) @@ -598,8 +661,8 @@ def export_one(session_id): **({"submitted_files": submission_paths(task)} if origin == "files" else {})}) return 0 except (OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: - record({"error": redact(str(exc), parent)}) - print(redact(str(exc), parent), file=sys.stderr) + record({"error": str(exc)}) + print(redact(str(exc), secrets), file=sys.stderr) return 1 finally: # A submission/export failure still consumed model tokens. Report what diff --git a/base_harness/opencode/harness.json b/base_harness/opencode/harness.json index 7e14779e5..027cfe7b2 100644 --- a/base_harness/opencode/harness.json +++ b/base_harness/opencode/harness.json @@ -1,16 +1,22 @@ { "name": "opencode", + "external_adapter": "opencode", "version": "0.6.0", "path": ".", "entrypoint": "agent.py", "backend": "cli", + "smoke_mock_model": "chat-completions", "install": null, "env_kinds": [ "files", "exec" ], "runtime_paths": [], - "notes": "Install a dedicated OpenCode release with harnessgrad harness install opencode. The prepared manifest pins the native CLI and its package metadata.", + "notes": "Install OpenCode with harnessgrad harness install opencode. Use editable v2 source or a fixed native release.", + "plugin_capabilities": { + "skill": {"format": "agent-skills", "directory": ".opencode/skills"}, + "workbench": {"format": "static-html"} + }, "components": { "control": [ "harness.json", diff --git a/base_harness/opencode/opencode_runtime.py b/base_harness/opencode/opencode_runtime.py index 1b99072e3..73f54c4fb 100644 --- a/base_harness/opencode/opencode_runtime.py +++ b/base_harness/opencode/opencode_runtime.py @@ -12,8 +12,76 @@ RECORD = "_opencode_runtime" SCHEMA = 3 +RELEASE_SCHEMA = 4 +SOURCE_RECORD = "_opencode_source" REMEDY = "prepare this Harness with tools/configure_opencode_harness.py" PACKAGES = {"1": "opencode-linux-x64", "2": "@opencode/cli-linux-x64"} +NPM_PACKAGE = PACKAGES["2"] +RELEASES = { + "2.4.0": ("66cf6adeb02fbfe9ccbb1f6497fcf46cecf2d299a1dc3a7a32e01ea30ff20201", + "7915c1cf09fac2fa475dc5f2e008486579da1c181a439699e2097ac3866f1da3"), + "2.4.1": ("9ddd18e3faf64eaeccf6a0fcbc96a5c7a14520ae5fd5b61e5be51d894f478b47", + "ec93043f18f8a6b4d8e71ec9260e292ba6f91b66b142782135d40f0b58b0c152"), + "2.4.2": ("452912288f934d1771bd5bd0d8611ba3a6adc3db3ac3333c37facf373770ba66", + "523b1502d1d556998b0904235cef65eb1d8cf8362b4e2faa7ae7a170c9a44cd4"), + "2.4.3": ("1bf509e8055b00693bf14d1623fd74712a7c6c107565e2acf38044944e7535d7", + "a96b460eb050b92ae49ab6598d6652790870c8e211c325ad907f89ebd54ea184"), +} +SOURCE_RELEASES = { + "2.4.2": ("fc31a485317970bcf6be7b431a9830aaef875731", + "306007d4b26be266f54249723028753647082f081ca6abc28beac68226bc0db4"), + "2.4.3": ("4e517ca4987fd57daffef1b47dd16c31c165b114", + "d91c6b946249011ba86a93442daf0b4ffff7da2bb88d0260df265acc172e8c14"), +} +UNVERIFIED_RECEIPT = "unverified-installation.json" + + +def require_v2(version): + if not isinstance(version, str) or not re.fullmatch(r"2\.[0-9]+\.[0-9]+", version): + raise ValueError("OpenCode requires an exact v2 release, such as 2.4.2") + + +def unverified_asset(machine): + if machine != "x86_64": + raise ValueError("OpenCode requires Linux x86-64") + return "opencode-linux-x64.tar.gz" + + +def asset(version, machine): + return unverified_asset(machine), RELEASES[version][0] + + +def source_spec(installation): + return {"kind": "bun", "source": "opencode", "entrypoint": "packages/cli/src/index.ts", + "package": "@opencode/cli", "installation": installation} + + +def _check_binding_mode(manifest): + if SOURCE_RECORD in manifest and RECORD in manifest: + raise ValueError(f"OpenCode manifest declares both source and binary runtimes; {REMEDY}") + + +def source_identity(harness, manifest): + _check_binding_mode(manifest) + record = manifest[SOURCE_RECORD] + version = record["version"] + require_v2(version) + commit, archive_sha256 = record["release_commit"], record["source_archive_sha256"] + pinned = SOURCE_RELEASES.get(version) + if (record.get("verified") is not (pinned is not None) + or not re.fullmatch(r"[0-9a-f]{40}", commit) or not re.fullmatch(r"[0-9a-f]{64}", archive_sha256) + or (pinned is not None and pinned != (commit, archive_sha256))): + raise ValueError("OpenCode source release provenance is invalid") + spec = manifest["runtime"] + if spec != source_spec(spec["installation"]): + raise ValueError("OpenCode source runtime does not match the v2 CLI") + entrypoint = harness / spec["source"] / spec["entrypoint"] + if not entrypoint.is_file() or entrypoint.resolve() != entrypoint: + raise ValueError("OpenCode needs its candidate-owned CLI entrypoint") + package = json.loads((entrypoint.parent.parent / "package.json").read_text()) + if package.get("version") != version or package.get("name") != spec["package"]: + raise ValueError("OpenCode source package does not match its bound release") + return record def execution_wire(env: dict) -> str: @@ -71,9 +139,31 @@ def _linux_x64_elf(binary: Path) -> bool: and program_offset >= header_size and program_offset + count * entry_size <= file_size) -def installation(binary: Path, *, forbidden: tuple[Path, ...] = ()) -> dict: +def installation(binary: Path, version=None, *, forbidden: tuple[Path, ...] = (), + unverified_sha256=None) -> dict: binary = binary.resolve(strict=True) validate_binding(binary, forbidden=forbidden) + if version is not None: + require_v2(version) + if binary.name != "opencode" or not os.access(binary, os.X_OK) or not _linux_x64_elf(binary): + raise ValueError("OpenCode needs a Linux x86-64 release executable") + binary_sha256 = digest(binary) + pinned = RELEASES.get(version) + verified = unverified_sha256 is None + if verified: + if pinned is None: + raise ValueError("Unverified OpenCode requires its published archive digest") + archive_sha256 = pinned[0] + else: + if not isinstance(unverified_sha256, str) or not re.fullmatch(r"[0-9a-f]{64}", unverified_sha256): + raise ValueError("Unverified OpenCode requires its published archive digest") + archive_sha256 = unverified_sha256 + if pinned is not None and (archive_sha256, binary_sha256) != pinned: + raise ValueError("OpenCode release digests do not match the verified release") + return {"schema": RELEASE_SCHEMA, "argv": [str(binary)], "version": version, + "runtime_paths": [str(binary)], "sha256": [binary_sha256], + "modes": [stat.S_IMODE(binary.stat().st_mode)], "archive_sha256": archive_sha256, + "cacheable": True, "verified": verified} metadata = binary.parent.parent / "package.json" validate_binding(metadata, forbidden=forbidden) if (binary.name != "opencode" or binary.parent.name != "bin" @@ -98,14 +188,24 @@ def installation(binary: Path, *, forbidden: tuple[Path, ...] = ()) -> dict: def resolve(harness: Path, _env: dict, *, forbidden: tuple[Path, ...] = ()) -> dict: manifest = json.loads((harness / "harness.json").read_text(encoding="utf-8")) + _check_binding_mode(manifest) record = manifest.get(RECORD) - if not isinstance(record, dict) or record.get("schema") != SCHEMA: + if not isinstance(record, dict) or record.get("schema") not in (SCHEMA, RELEASE_SCHEMA): raise ValueError(f"OpenCode release is unprepared; {REMEDY}") argv, paths = record.get("argv"), record.get("runtime_paths") if (not isinstance(argv, list) or len(argv) != 1 or not isinstance(argv[0], str) or not isinstance(paths, list) or manifest.get("runtime_paths") != paths): raise ValueError(f"invalid OpenCode runtime binding; {REMEDY}") binary = Path(argv[0]) + if record["schema"] == RELEASE_SCHEMA: + require_v2(record.get("version")) + if not binary.is_absolute() or binary.resolve() != binary or paths != [str(binary)]: + raise ValueError("invalid OpenCode release binding") + expected = installation(binary, record.get("version"), forbidden=(*forbidden, harness), + unverified_sha256=record["archive_sha256"] if record.get("verified") is False else None) + if expected != record: + raise ValueError("OpenCode installation changed") + return record if (not binary.is_absolute() or binary.resolve() != binary or paths != [str(binary), str(binary.parent.parent / "package.json")]): raise ValueError(f"invalid OpenCode runtime paths; {REMEDY}") diff --git a/base_harness/oracle/agent.py b/base_harness/oracle/agent.py index 1cb6ede90..ddf45b917 100644 --- a/base_harness/oracle/agent.py +++ b/base_harness/oracle/agent.py @@ -74,7 +74,7 @@ def main() -> int: print(proc.stderr[-2000:], file=sys.stderr) (work / "trace.jsonl").write_text(json.dumps({ - "harness_identity": {"agent_model": "oracle", "harness": "oracle 1"}, + "harness_identity": {"agent_model": "oracle", "harness": "oracle"}, "usage": {"input_tokens": 0, "output_tokens": 0, "calls": 0}, }) + "\n") return 0 diff --git a/base_harness/pi/README.md b/base_harness/pi/README.md new file mode 100644 index 000000000..3e97c646a --- /dev/null +++ b/base_harness/pi/README.md @@ -0,0 +1,49 @@ +# Pi Harness + +Install Pi on Linux with Bubblewrap. + +```sh +HARNESS_DIR=$(harnessgrad harness install pi) +harnessgrad run --harness-path "$HARNESS_DIR" ... +``` + +The default release is [Pi v1.6.0](https://github.com/earendil-works/pi/releases/tag/v1.6.0). + +- **Editable (default, Linux x86-64).** The installer verifies the upstream + source archive and places it under `pi/` in the H0 harness. The improve agent + can edit Pi itself. Each round launches its own TypeScript source with the + upstream source resolver on Node.js `24.22.2`. npm `11.19.1` installs the + upstream lock with `npm ci --ignore-scripts`. The sandbox attaches dependencies + read-only, and candidate preparation reuses the install cache offline. +- **Fixed (`--mode fixed`, Linux x86-64 or ARM64).** The installer verifies and uses + the standalone release for the host CPU. The prepared manifest binds the + extracted binary and its embedded Bun runtime read-only outside the candidate. + The improve agent can edit the adapter. + +Use `--version 1.6.0` to select the release explicitly and `--install-root` to +choose a dedicated store outside the platform and temporary storage. +Omitting `--version` selects the latest verified release for the chosen mode. +On Linux x86-64, an exact unverified version prints a warning to stderr and +attempts installation. The release must provide the asset for the selected +mode and a GitHub SHA-256 digest. A successful version check still leaves the +installation marked unverified. + +The adapter runs a fresh, one-shot Pi session for each native `files` task. It +routes Chat Completions through `HG_AGENT_BASE_URL`, selects `HG_AGENT_MODEL`, +and passes `HG_AGENT_API_KEY` to Pi through its task environment. Settings, +credentials, and session state are private to the task. Pi enables its native +read, bash, edit, and write tools. The adapter skips config and instructions +discovered from the task workspace or user environment, marketplace +extensions and MCP servers. It disables automatic compaction, retries, and +cache warming so measured usage comes from the recorded model turns. + +Pi's model responses and completed tools become the standard `trace.jsonl`. +Shell return codes are recorded when Pi includes them in tool metadata. +Missing provider usage stays unknown. A text task can deliver its final reply +or a changed `answer.txt`. A file task must leave its declared files in the +working directory. The platform scores the result. + +`HG_AGENT_BACKEND=mock` runs Pi against HarnessGrad's local +Chat Completions fixture for text and file submissions. The prepared manifest +selects the fixture for platform runs and smoke checks. `HG_AGENT_PI_TIMEOUT_S` +caps Pi's wall time within the platform deadline. diff --git a/base_harness/pi/agent.py b/base_harness/pi/agent.py new file mode 100644 index 000000000..26621342e --- /dev/null +++ b/base_harness/pi/agent.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Run one task through Pi's native headless CLI.""" +from __future__ import annotations + +import json +from pathlib import Path +import sys + +if __package__: + from . import pi_runtime, task_support +else: + sys.path.insert(0, str(Path(__file__).resolve().parent)) + import pi_runtime + import task_support + + +def _configure(home, model, endpoint, env): + context = int(env.get("HG_AGENT_CONTEXT_WINDOW", "32768")) + output = int(env.get("HG_AGENT_MAX_OUTPUT_TOKENS", env.get("HG_AGENT_MAX_TOKENS", "8192"))) + if not 0 < output <= context: + raise ValueError("Pi token budget must satisfy 0 < max output <= context window") + models = {"providers": {"harnessgrad": { + "baseUrl": endpoint, "api": "openai-completions", "apiKey": "$HG_AGENT_API_KEY", + "models": [{"id": model, "contextWindow": context, "maxTokens": output}], + }}} + settings = {"compaction": {"enabled": False}, "retry": {"enabled": False}, "cacheWarming": "off"} + (home / "models.json").write_text(json.dumps(models), encoding="utf-8") + (home / "settings.json").write_text(json.dumps(settings), encoding="utf-8") + + +def _argv(model): + return ["--mode", "json", "--provider", "harnessgrad", "--model", model, + "--no-session", "--offline", "--no-approve", "--no-context-files", + "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", + "--no-mcp", "--tools", "read,bash,edit,write"] + + +def run(task, work): + return task_support.run(task, work, name="pi", harness=Path(__file__).resolve().parent, + resolve=pi_runtime.resolve, configure=_configure, cli_args=_argv, + timeout_key="HG_AGENT_PI_TIMEOUT_S", terminal_event="agent_settled") + + +def main(): + return task_support.main(run) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/base_harness/pi/harness.json b/base_harness/pi/harness.json new file mode 100644 index 000000000..f0649ae51 --- /dev/null +++ b/base_harness/pi/harness.json @@ -0,0 +1,18 @@ +{ + "name": "pi", + "external_adapter": "pi", + "version": "0.1.0", + "path": ".", + "entrypoint": "agent.py", + "backend": "cli", + "mock_model": "chat-completions", + "install": null, + "env_kinds": ["files"], + "runtime_paths": [], + "components": { + "control": ["harness.json"], + "delegation": ["agent.py", "task_support.py"], + "reliability": ["pi_runtime.py"], + "unattributed": ["README.md"] + } +} diff --git a/base_harness/pi/pi_runtime.py b/base_harness/pi/pi_runtime.py new file mode 100644 index 000000000..4997c6a5f --- /dev/null +++ b/base_harness/pi/pi_runtime.py @@ -0,0 +1,165 @@ +"""Prepared bindings for the Pi standalone release and candidate-owned source.""" +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import stat + +RECORD = "_pi_runtime" +SCHEMA = 1 +EDITABLE_SCHEMA = 2 +UNVERIFIED_RECEIPT = "unverified-installation.json" +RELEASE_VERSION = re.compile(r"(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*)){2}(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?") +SOURCE_RELEASES = { + "1.6.0": ("faac585884ae2c013a6b1400f3e9e77f10b34bac", + "14519e288e84e713629b220bb6ade6818e32d4ff23f205fd80a7cc49dedc413e"), +} +NODE_VERSION = "24.22.2" +NPM_VERSION = "11.19.1" +NODE_DIST = f"node-v{NODE_VERSION}-linux-x64" +NODE_ARCHIVE_SHA256 = "48cc0e21e048790e54c0cf5749c2725005313d652651c40b7a21feb9697aaf75" +SOURCE_CLI = "packages/coding-agent/src/cli.ts" +SOURCE_RESOLVER = "packages/coding-agent/src/experimental/source-resolver.ts" +REMEDY = "prepare a copy with harnessgrad harness install pi" +RELEASES = { + "1.6.0": { + "x86_64": ("pi-linux-x64.tar.gz", "ef77dbe4379b3bdeb425a1e1b862fa3c915c255000dfe4965c98eee96a5765d1"), + "aarch64": ("pi-linux-arm64.tar.gz", "5404547b9739be596d50ae7142c52535899e8e7dd37a7bace9be593e0355b468"), + }, +} + + +def asset(version: str, machine: str) -> tuple[str, str]: + if version not in RELEASES: + raise ValueError(f"Unknown Pi release {version!r}") + if machine not in RELEASES[version]: + raise ValueError(f"Unsupported Pi Linux architecture {machine!r}") + return RELEASES[version][machine] + + +def unverified_asset(machine: str) -> str: + if machine != "x86_64": + raise ValueError(f"Unsupported architecture for unverified Pi releases: {machine!r}") + return "pi-linux-x64.tar.gz" + + +def _inventory(root: Path) -> str: + entries = [] + for path in sorted(root.rglob("*")): + mode = path.lstat().st_mode + if stat.S_ISDIR(mode): + kind, sha = "directory", None + elif stat.S_ISREG(mode): + kind = "file" + with path.open("rb") as stream: + sha = hashlib.file_digest(stream, "sha256").hexdigest() + else: + raise ValueError(f"Pi release contains an unsupported entry: {path}") + entries.append([path.relative_to(root).as_posix(), kind, stat.S_IMODE(mode), sha]) + return hashlib.sha256(json.dumps(entries, separators=(",", ":")).encode()).hexdigest() + + +def installation(root: Path, version: str, *, forbidden: tuple[Path, ...] = (), + unverified_sha256: str | None = None) -> dict: + machine = platform.machine() + if unverified_sha256 is None: + asset_name, archive_sha256 = asset(version, machine) + else: + if not RELEASE_VERSION.fullmatch(version) or not re.fullmatch(r"[0-9a-f]{64}", unverified_sha256): + raise ValueError("Invalid unverified Pi release binding") + asset_name, archive_sha256 = unverified_asset(machine), unverified_sha256 + if (platform.system() != "Linux" or not root.is_absolute() or root.resolve(strict=True) != root + or root.name != "pi" or not root.parent.name.startswith("install-") + or root.parent.parent.name != machine or root.parent.parent.parent.name != version): + raise ValueError(f"Invalid Pi release directory; {REMEDY}") + blocked = (*forbidden, Path("/tmp"), Path("/var/tmp"), Path("/usr"), Path("/etc"), + Path("/proc"), Path("/sys"), Path("/dev"), Path("/run"), Path.home() / ".config", + Path.home() / ".ssh", Path.home() / ".pi") + if any(root.is_relative_to(path.resolve()) or path.resolve().is_relative_to(root) for path in blocked): + raise ValueError(f"Pi runtime overlaps a protected directory: {root}") + if any(char in str(root) for char in (",", "\n", "\r")): + raise ValueError(f"Pi runtime path cannot be bound: {root}") + binary, manifest = root / "pi", root / "package.json" + inventory = _inventory(root) + if not binary.is_file() or not os.access(binary, os.X_OK) or not manifest.is_file(): + raise ValueError(f"Pi release is missing its executable or package metadata; {REMEDY}") + with binary.open("rb") as stream: + if stream.read(4) != b"\x7fELF": + raise ValueError(f"Pi release executable must be ELF; {REMEDY}") + metadata = json.loads(manifest.read_text(encoding="utf-8")) + if metadata.get("name") != "@earendil-works/pi-coding-agent" or metadata.get("version") != version: + raise ValueError(f"Pi release metadata differs from {version}; {REMEDY}") + return {"schema": SCHEMA, "version": version, "architecture": machine, "asset": asset_name, + "archive_sha256": archive_sha256, "inventory_sha256": inventory, + "argv": [str(binary)], "runtime_paths": [str(root)], "cacheable": True, + **({"verified": False} if unverified_sha256 is not None else {})} + + +def editable(harness, manifest): + record = manifest.get(RECORD) + if not isinstance(record, dict) or record.get("schema") != EDITABLE_SCHEMA: + raise ValueError(f"Pi source runtime is unprepared; {REMEDY}") + version = record.get("version") + if platform.system() != "Linux" or platform.machine() != "x86_64": + raise ValueError("Pi editable mode requires Linux x86-64") + if not isinstance(version, str) or not RELEASE_VERSION.fullmatch(version): + raise ValueError("Invalid Pi source release version") + paths = manifest.get("runtime_paths") + if (manifest.get("runtime") != {"kind": "npm", "source": "pi"} or not isinstance(paths, list) + or len(paths) != 1 or not isinstance(paths[0], str)): + raise ValueError("Invalid Pi editable runtime binding") + node = Path(paths[0]) + if (not node.is_absolute() or node.name != NODE_DIST or node.resolve(strict=True) != node + or not (node / "bin/node").is_file()): + raise ValueError("Invalid Pi Node.js toolchain directory") + if record.get("verified") is False: + commit, sha = record.get("release_commit"), record.get("source_archive_sha256") + if (not isinstance(commit, str) or not re.fullmatch(r"[0-9a-f]{40}", commit) + or not isinstance(sha, str) or not re.fullmatch(r"[0-9a-f]{64}", sha)): + raise ValueError("Invalid unverified Pi source release binding") + verification = {"verified": False} + else: + if version not in SOURCE_RELEASES: + raise ValueError(f"Unknown Pi source release {version!r}") + commit, sha = SOURCE_RELEASES[version] + verification = {} + expected = {"schema": EDITABLE_SCHEMA, "version": version, "release_commit": commit, + "source_archive_sha256": sha, "node_version": NODE_VERSION, "npm_version": NPM_VERSION, + "node_sha256": record.get("node_sha256"), "npm_sha256": record.get("npm_sha256"), + **verification} + if record != expected or any( + not isinstance(record.get(key), str) or not re.fullmatch(r"[0-9a-f]{64}", record[key]) + for key in ("node_sha256", "npm_sha256") + ): + raise ValueError("Invalid Pi editable release receipt") + source = harness / "pi" + if source.resolve() != harness.resolve() / "pi": + raise ValueError("Pi source directory must belong to the candidate") + for name in (SOURCE_CLI, SOURCE_RESOLVER): + path = source / name + if path.resolve(strict=True) != path or not path.is_file(): + raise ValueError("Pi source entrypoints must belong to the candidate") + return {**record, "argv": [str(node / "bin/node"), "--import", (source / SOURCE_RESOLVER).as_uri(), + str(source / SOURCE_CLI)], "runtime_paths": paths} + + +def resolve(harness: Path, _env: dict, *, forbidden: tuple[Path, ...] = ()) -> dict: + manifest = json.loads((harness / "harness.json").read_text(encoding="utf-8")) + if (manifest.get("runtime") or {}).get("kind") == "npm": + return editable(harness, manifest) + record = manifest.get(RECORD) + if not isinstance(record, dict) or record.get("schema") != SCHEMA: + raise ValueError(f"Pi runtime is unprepared; {REMEDY}") + paths = record.get("runtime_paths") + if (not isinstance(paths, list) or len(paths) != 1 or not isinstance(paths[0], str) + or manifest.get("runtime_paths") != paths or not isinstance(record.get("version"), str)): + raise ValueError(f"Invalid Pi runtime binding; {REMEDY}") + experimental = record["archive_sha256"] if record.get("verified") is False else None + if installation(Path(paths[0]), record["version"], forbidden=(*forbidden, harness), + unverified_sha256=experimental) != record: + raise ValueError(f"Pi runtime changed; {REMEDY}") + return record diff --git a/base_harness/pi/task_support.py b/base_harness/pi/task_support.py new file mode 100644 index 000000000..fca989a58 --- /dev/null +++ b/base_harness/pi/task_support.py @@ -0,0 +1,252 @@ +"""Shared one-shot execution and trace normalization for Pi-family CLIs.""" + +import argparse +from contextlib import suppress +import json +import math +import os +from pathlib import Path +import re +import signal +import subprocess +import sys +import tempfile + + +def submission_paths(task): + spec = task.get("submission", {"kind": "text"}) + if spec == {"kind": "text"}: + return [] + if not isinstance(spec, dict) or set(spec) != {"kind", "paths"} or spec["kind"] != "files": + raise ValueError("Invalid public submission descriptor") + paths = spec["paths"] + if not isinstance(paths, list) or not paths or any( + not isinstance(name, str) or not name.strip() or "\\" in name or ":" in name + or any(part in ("", ".", "..") for part in name.split("/")) for name in paths + ): + raise ValueError("File submission paths must be nonempty paths relative to the workdir") + return paths + + +def task_prompt(task, paths): + if (public := task.get("cli_task")) is not None: + if not isinstance(public, str) or not public.strip(): + raise ValueError("Invalid public CLI task") + return public + goal = task.get("goal") or task.get("instruction") + if not isinstance(goal, str) or not goal.strip(): + raise ValueError("Task requires a nonempty goal or instruction") + if task.get("inputs") is not None: + goal += "\n\nTask inputs:\n" + json.dumps(task["inputs"], ensure_ascii=False) + if paths: + goal += "\n\nLeave these files in the working directory: " + json.dumps(paths, ensure_ascii=False) + return goal + + +def _answer_stamp(path): + if path.is_symlink() or (path.exists() and not path.is_file()): + raise ValueError("Unsafe answer.txt") + if path.is_file(): + return path.stat().st_mtime_ns, path.read_bytes() + return None + + +def submit(work, paths, before, final): + if paths: + for name in paths: + path = work / name + if path.resolve() != path or not path.is_file(): + raise ValueError(f"Missing or unsafe submission file: {name}") + return {"submitted": True, "answer": "", "answer_source": "files", "submitted_files": paths} + answer = work / "answer.txt" + current = _answer_stamp(answer) + if current and current != before and current[1].strip(): + return {"submitted": True, "answer": current[1].decode("utf-8"), "answer_source": "artifact"} + if not final.strip(): + raise ValueError("Harness produced no final answer or changed answer.txt") + answer.write_text(final, encoding="utf-8") + return {"submitted": True, "answer": final, "answer_source": "final_message"} + + +def _redact(value, key): + if not key: + return value + if isinstance(value, str): + return value.replace(key, "") + if isinstance(value, dict): + return {name: _redact(item, key) for name, item in value.items()} + if isinstance(value, list): + return [_redact(item, key) for item in value] + return value + + +def _text(content): + return "".join(block["text"] for block in content + if block.get("type") == "text" and isinstance(block.get("text"), str)) + + +def _provider_status(message): + if message.get("stopReason") != "error": + return None + status = message.get("errorStatus") + if status is None and isinstance(detail := message.get("errorMessage"), str): + # Pi's OpenAI SDK puts the status at the start of the error message. + # Oh My Pi emits the numeric status separately. + match = re.match(r"([45][0-9]{2})(?=[\s:]|$)", detail) + status = int(match[1]) if match else None + return status if type(status) is int and 400 <= status <= 599 else None + + +class Trace: + def __init__(self, record, model, terminal_event="agent_settled"): + self.terminal_event = terminal_event + self.record = record + self.model = model + self.calls = 0 + self.tokens = dict.fromkeys(("input", "output", "cacheRead", "cacheWrite"), 0) + self.pending = {} + self.final = "" + self.reason = None + self.provider_status = None + self.settled = False + + def feed(self, event): + kind = event.get("type") + if kind == "message_end" and (message := event["message"]).get("role") == "assistant": + if (message.get("provider"), message.get("model")) != ("harnessgrad", self.model): + raise ValueError("CLI reported a different provider or model") + self.calls += 1 + self.final = _text(message.get("content", [])) + self.reason = message.get("stopReason") + self.provider_status = _provider_status(message) + self.record({"reply": self.final, "stop_reason": self.reason}) + usage = message.get("usage") or {} + for field, total in self.tokens.items(): + value = usage.get(field) + self.tokens[field] = (total + value if total is not None and usage.get("totalTokens") + and type(value) is int and value >= 0 else None) + elif kind == "tool_execution_start": + self.pending[event["toolCallId"]] = event.get("args") or {} + elif kind == "tool_execution_end": + call_id = event["toolCallId"] + if call_id not in self.pending: + return + args = self.pending.pop(call_id) + tool, result = event["toolName"], event["result"] + output = _text(result.get("content", [])) + details = result.get("details") + if not isinstance(details, dict): + details = {} + code = details.get("exitCode") + structured = result.get("structuredContent") + if type(code) is not int and isinstance(structured, dict): + code = structured.get("exit_code") + self.record({"command": (args.get("command") or tool) if tool == "bash" + else tool + " " + json.dumps(args, ensure_ascii=False), + "tool": tool, "tool_call_id": call_id, "tool_error": event.get("isError"), + "output": output[:8000], "observation": { + "kind": "shell" if tool == "bash" else "filesystem", + "returncode": code if type(code) is int else None, + "output_chars": len(output), + "truncated": len(output) > 8000 or bool( + (details.get("truncation") or {}).get("truncated")), + }}) + elif kind == self.terminal_event: + self.settled = not event.get("aborted") and event.get("isTerminal", True) + + def usage(self): + tokens = self.tokens if self.calls else dict.fromkeys(self.tokens) + # The CLI reports uncached input separately from cache reads and writes. + prompt = (tokens["input"], tokens["cacheRead"], tokens["cacheWrite"]) + return {"calls": self.calls, + "input_tokens": sum(prompt) if all(value is not None for value in prompt) else None, + "uncached_input_tokens": tokens["input"], "output_tokens": tokens["output"], + "cached_input_tokens": tokens["cacheRead"], "cache_write_input_tokens": tokens["cacheWrite"]} + + +def _timeout(env, key): + limit = float(env.get(key, "780")) + deadline = float(env.get("HG_AGENT_DEADLINE_S") or (limit + 5)) + if not all(math.isfinite(value) and value > 0 for value in (limit, deadline)): + raise ValueError("CLI timeout and deadline must be finite and positive") + return min(limit, deadline - min(5, deadline / 5)) + + +def run(task, work, *, name, harness, resolve, configure, cli_args, timeout_key, terminal_event): + work = work.resolve() + work.mkdir(parents=True, exist_ok=True) + parent = os.environ + mocked = parent.get("HG_AGENT_BACKEND") == "mock" + model, endpoint, key = (parent.get(field) for field in + ("HG_AGENT_MODEL", "HG_AGENT_BASE_URL", "HG_AGENT_API_KEY")) + diagnostic_key = None if parent.get("HG_AGENT_PUBLIC_CREDENTIAL") == "1" else key + with (work / "trace.jsonl").open("w", encoding="utf-8", buffering=1) as trace: + def record(row): + trace.write(json.dumps(_redact(row, diagnostic_key), ensure_ascii=False) + "\n") + + stream = Trace(record, model, terminal_event) + try: + paths = submission_paths(task) + prompt = task_prompt(task, paths) + timeout = _timeout(parent, timeout_key) + binding = resolve(harness, {}) + if not model or not endpoint or not key: + raise ValueError("CLI harness needs HG_AGENT_MODEL, HG_AGENT_BASE_URL and HG_AGENT_API_KEY") + before = None if paths else _answer_stamp(work / "answer.txt") + with tempfile.TemporaryDirectory(prefix="hg-pi-task-") as directory: + home = Path(directory) + configure(home, model, endpoint, parent) + env = {"PATH": parent.get("PATH", os.defpath), "HOME": str(home), "TMPDIR": str(home), + "PI_CODING_AGENT_DIR": str(home), "HG_AGENT_API_KEY": key} + record({"harness_identity": {"harness": name, "agent_backend": "mock" if mocked else "openai", + "agent_model": model, "agent_base_url": endpoint, + "cli_version": binding["version"]}, + "task_id": task.get("task_id")}) + argv = [*binding["argv"], *cli_args(model)] + with subprocess.Popen(argv, cwd=work, env=env, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + encoding="utf-8", errors="replace", start_new_session=True) as process: + timed_out = False + try: + stdout, stderr = process.communicate(prompt, timeout=timeout) + except subprocess.TimeoutExpired: + timed_out = True + # The CLI handles SIGTERM and its detached shell processes. The + # runner's PID namespace covers a forced shutdown as well. + process.terminate() + try: + stdout, stderr = process.communicate(timeout=1) + except subprocess.TimeoutExpired: + with suppress(ProcessLookupError): + os.killpg(process.pid, signal.SIGKILL) + stdout, stderr = process.communicate() + lines = stdout.split("\n") + for line in (lines[:-1] if timed_out else lines): + if line.strip(): + stream.feed(json.loads(line)) + if stream.provider_status is not None: + print(f"Model provider failure: HTTP {stream.provider_status}", file=sys.stderr) + record({"error": "CLI model request failed", "http_status": stream.provider_status}) + return 1 + if timed_out: + raise ValueError("CLI exceeded the task deadline") + if process.returncode: + detail = _redact(stderr, diagnostic_key).strip()[-1000:] + raise ValueError(f"CLI failed with exit code {process.returncode}: {detail}") + if not stream.settled or stream.pending or stream.reason != "stop": + raise ValueError("CLI did not finish a successful turn") + record(submit(work, paths, before, stream.final)) + return 0 + except (OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: + record({"error": str(exc)}) + return 1 + finally: + record({"usage": stream.usage()}) + + +def main(run_task): + parser = argparse.ArgumentParser() + parser.add_argument("--task", required=True, type=Path) + parser.add_argument("--workdir", required=True, type=Path) + args = parser.parse_args() + return run_task(json.loads(args.task.read_text(encoding="utf-8")), args.workdir) diff --git a/console/DEVELOPMENT.md b/console/DEVELOPMENT.md index ecc4dd049..8508fd907 100644 --- a/console/DEVELOPMENT.md +++ b/console/DEVELOPMENT.md @@ -34,8 +34,25 @@ and direct write followed by chmod. It is not an atomic-write protocol. UI serialization uses its redacted projection. Endpoint probing is explicit and is not part of launch preview or validation. -Launch preflight only inspects shared capacity; it does not reserve a run -namespace or create a lease. Detached launch invokes its supplied spawn port once +Launch preflight checks shared capacity without reserving a run namespace or +creating a lease. For external harnesses, the launcher reads the installation +store used by `harnessgrad harness install`. Set +`HG_CONSOLE_HARNESS_INSTALL_ROOT` on the Console server if installations use a +custom `--install-root`. The version selector defaults to the highest usable +verified installation in the selected mode. Unverified versions require an +explicit selection. A successful preview pins the installed source and runtime +for the launch request. + +For OpenCode v2 fixed mode, Console prefers the registered install, then the +architecture-specific release directory. It can also use an older npm +installation with its original receipt and package lock. + +Both OpenCode installation modes require the live solver backend. Console +resolves `HG_AGENT_OPENCODE_WIRE` using the driver's configuration precedence +and uses that value for the installation fingerprint and the child driver. +Preview again if the protocol changes before launch. + +Detached launch invokes its supplied spawn port once with the owned log handle and `start_new_session=True`. An HTTP response failure does not retry the launch or kill the detached child. Trials instead reserve both namespaces in an administrator-provided existing root; failed handoff or timeout diff --git a/console/README.md b/console/README.md index e2c863429..74306255f 100644 --- a/console/README.md +++ b/console/README.md @@ -4,11 +4,10 @@ diff 和轨迹。改 harness 走**编辑**屏(左:文件树与代码;右:与助手的对话),跑实验走 **启动**屏(受服务端守卫保护);观察页仍然不修改实验。 -顶部导航对应三个独立工作流: +顶部导航有两个工作流。 -- **运行实验**:启动、查看曲线、逐轮轨迹、版本、评测和证据导出。 -- **领域定制**:按说明构建任务包、导入归档、查看已有产物或编辑候选 Harness。 -- **个人进化**:本机快速入门和小绿示例。个人工作台由`harnessgrad personal serve`独立启动。 +- **运行实验**支持启动实验、查看曲线、逐轮轨迹和版本,以及评测和证据导出。 +- **定制 Harness**支持构建或导入领域任务包、查看已有产物和编辑候选 Harness。侧栏的**测试时演化**提供个人工作台、小绿示例和本机快速入门。打开 `/evolve.html` 或 `/evolve.html#local-quickstart` 会直接进入这一节。个人工作台由 `harnessgrad personal serve` 在本机独立启动。 评分场景及其后端 API 保留,供实验启动与评测使用。原`/author.html#/scenarios`兼容转到经验构建。 diff --git a/console/launch.py b/console/launch.py index 5554eb97d..4d267f5d9 100644 --- a/console/launch.py +++ b/console/launch.py @@ -46,6 +46,30 @@ class InvocationPort: argv: Callable environment: Callable method_identity: Callable | None = None + installation: Callable | None = None + + +class InstallationRefused(ValueError): + pass + + +class LaunchEnvironmentRefused(ValueError): + pass + + +def _invocation(form, run_id, plan, *, launch=False): + if plan.installation is None: + return plan.argv(form, run_id), None + try: + selected = plan.installation(form) + except (OSError, TypeError, ValueError, KeyError) as exc: + raise InstallationRefused(str(exc)) from exc + if selected is None: + return plan.argv(form, run_id), None + if launch and form.get("installation_sha256") != selected["sha256"]: + raise InstallationRefused("The installed harness changed or has not been confirmed. Preview it again.") + return plan.argv(form, run_id, installation=selected), selected + def parse_capacity(value) -> int: if not re.fullmatch(r'[1-9][0-9]{0,3}', str(value)): @@ -186,18 +210,23 @@ def _custom_method(form, paths): return data, digest -def build_argv(form: dict, run_id: str, *, paths, budget_capacity) -> list[str]: +def build_argv(form: dict, run_id: str, *, paths, budget_capacity, installation=None) -> list[str]: """预览与真正起跑**共用这一个函数** —— 否则"预览的命令"和"实际跑的命令"迟早分叉。""" jobs = int(form["jobs"]) single = _single_measurement(form) improver = "none" if single else str(form["improver"]) improver_model = str(form.get("improver_model") or "") candidate = _candidate_spec(form, paths) + if installation: + source = installation["argv"] + elif candidate: + source = ["--harness-path", str(candidate[0]), + "--expected-harness-sha256", str(form.get('candidate_sha256') or candidate[1]), + "--expected-harness-filesystem-sha256", str(form.get('candidate_filesystem_sha256') or candidate[2])] + else: + source = ["--harness", str(form["harness"])] return [sys.executable, str(paths.driver), - *(["--harness-path", str(candidate[0]), - "--expected-harness-sha256", str(form.get('candidate_sha256') or candidate[1]), - "--expected-harness-filesystem-sha256", str(form.get('candidate_filesystem_sha256') or candidate[2])] - if candidate else ["--harness", str(form["harness"])]), + *source, "--dataset", str(form["dataset"]), "--split", "declared", "--side", "train", @@ -245,6 +274,7 @@ def new_run_id(form: dict) -> str: def _field_types(form): for field in ('dataset', 'harness', 'candidate_sha256', 'candidate_filesystem_sha256', 'custom_method_sha256', 'sampling', 'improver', 'improver_model', 'method', + 'harness_mode', 'harness_version', 'installation_sha256', 'task_backend', 'task_model', 'task_base_url', 'meta_base_url', 'task_api_key', 'meta_api_key'): if field in form and not isinstance(form[field], str): @@ -413,12 +443,19 @@ def validate_launch_request(form: dict, *, paths, catalogue, python_supported, s backend = str(form.get("task_backend") or ("mock" if form.get("task_model") == "mock" else "openai")) if backend not in ("mock", "openai"): return 400, {"error": "bad-task-backend", "detail": "task backend 只能是 mock 或 openai"} + if form.get("harness") == "opencode" and backend == "mock": + return 400, {"error": "unsupported-task-backend", "detail": + "OpenCode 需要实际模型。请选择 openai 并填写模型、端点和密钥。 " + "OpenCode needs a live model. Select openai and provide a model, endpoint and API key."} model = str(form.get("task_model") or "").strip() if backend == "openai" and (not model or model == "mock"): return 400, {"error": "no-task-model", "detail": "实时 task 模型需要填写实际模型名(不能是 mock)"} if backend == "mock" and model not in ("", "mock"): return 400, {"error": "task-backend-mismatch", "detail": "mock backend 只能使用 mock 模型"} - env = launch_env(form) + try: + env = launch_env(form) + except LaunchEnvironmentRefused as exc: + return 400, {"error": "bad-task-wire", "detail": str(exc)} problem = _solver_credentials(form, env, backend, model, preview_key_pending) if problem: return problem @@ -443,7 +480,9 @@ def start(form: dict, *, paths, catalogue, plan, make_run_id, spawn, base_enviro return code, err run_id = make_run_id(form) try: - argv = plan.argv(form, run_id) + argv, _ = _invocation(form, run_id, plan, launch=True) + except InstallationRefused as exc: + return 400, {'error': 'installation-unavailable', 'detail': str(exc)} except (OSError, ValueError, RuntimeError): return 400, {'error': 'source-changed', 'detail': '候选或方法不可用;请重新预览。'} environment = {**base_environment, **plan.environment(form)} @@ -505,13 +544,15 @@ def scope_preview(form: dict, effective_env: dict, *, catalogue) -> dict: if row.get("name") == editor_name and row.get("kind") == "cli"), {}) kind = selected.get("kind") model = (form.get("improver_model") or selected.get("model") or None) if selected else None + wire = effective_env.get("HG_AGENT_OPENCODE_WIRE") return { "dataset": form.get("dataset"), "side": "train", "split": "declared", "sampling": form.get("sampling") or "all", "task_count": None, "rounds": 0 if single else form.get("rounds"), "trials_per_task": form.get("trials"), "jobs": form.get("jobs"), "solver": {"backend": effective_env.get("HG_AGENT_BACKEND"), - "model": effective_env.get("HG_AGENT_MODEL") or None}, + "model": effective_env.get("HG_AGENT_MODEL") or None, + **({"wire": wire} if wire else {})}, "editor": {"method": form.get("method") or "none", "improver": editor_name, "model": model, "kind": kind, "active": False if editor_name == "none" else None}, @@ -526,14 +567,20 @@ def preview(form: dict, *, plan, catalogue) -> dict: code, err = plan.validate(form, preview_key_pending=form.get("task_key_present") in (True, "true", "1"), preview_meta_key_pending=form.get("meta_key_present") in (True, "true", "1")) - try: - argv = plan.argv(form, "rsi10----train") - except (KeyError, TypeError, ValueError, OverflowError, OSError, RuntimeError): - argv = [] - if code == 200: - code = 400 - err = {"error": "bad-value", "detail": "运行参数不完整或格式不正确"} - effective_env = plan.environment(form) + argv, installation, effective_env = [], None, {} + if err.get("error") not in ("unsupported-task-backend", "bad-task-wire"): + try: + effective_env = plan.environment(form) + argv, installation = _invocation(form, "rsi10----train", plan) + except LaunchEnvironmentRefused as exc: + if code == 200: + code, err = 400, {"error": "bad-task-wire", "detail": str(exc)} + except InstallationRefused as exc: + if code == 200: + code, err = 400, {"error": "installation-unavailable", "detail": str(exc)} + except (KeyError, TypeError, ValueError, OverflowError, OSError, RuntimeError): + if code == 200: + code, err = 400, {"error": "bad-value", "detail": "运行参数不完整或格式不正确"} shown_env = {key: ("***" if "KEY" in key else display_base_url(value) if key.endswith("BASE_URL") else value) for key, value in effective_env.items()} form = dict(form) @@ -550,6 +597,8 @@ def preview(form: dict, *, plan, catalogue) -> dict: "preflight": {"ok": code == 200, "status": code, **err}, "scope": scope_preview(form, effective_env, catalogue=catalogue), } + if installation: + result["installation"] = {key: installation[key] for key in ("version", "mode", "verified", "sha256")} if code == 200 and str(form.get('method') or '').startswith('custom:') and plan.method_identity: try: custom = plan.method_identity(form) diff --git a/console/server.py b/console/server.py index 72dfc6a7b..b89532bcc 100644 --- a/console/server.py +++ b/console/server.py @@ -18,6 +18,7 @@ import argparse import ast +from collections import OrderedDict import hashlib import http.client import importlib.util @@ -114,9 +115,70 @@ def _launch_paths(): STATE_ROOT / 'methods') -def _invocation_port(): - return launch.InvocationPort(guard_launch, launch_argv, launch_env, - lambda form: launch._custom_method(form, _launch_paths())) +def _invocation_port(*, preview=False): + effective_env = None + + def environment(form): + # A preview or start owns one configuration snapshot, including the wire + # used in the installation fingerprint and passed to the driver. + nonlocal effective_env + if effective_env is None: + effective_env = launch_env(form) + return effective_env + + def validate(form, **kwargs): + if form.get("harness") == "opencode": + return guard_launch(form, resolve_environment=environment, **kwargs) + return guard_launch(form, **kwargs) + + return launch.InvocationPort(validate, launch_argv, environment, + lambda form: launch._custom_method(form, _launch_paths()), + lambda form: _installed_harness( + form, environment=environment(form), preview=preview)) + + +def _harness_install_root(): + from tools import install_harness + custom = os.environ.get("HG_CONSOLE_HARNESS_INSTALL_ROOT") + return (pathlib.Path(custom).expanduser().resolve() if custom else install_harness.default_root()), bool(custom) + + +_installation_previews = OrderedDict() +_installation_previews_lock = threading.Lock() + + +def _installed_harness(form, *, environment=None, preview=False): + from tools import install_harness + from tools.harness_setup import installation_store + name = form["harness"] + if name not in installation_store.MODES: + return None + if environment is None: + environment = launch_env(form) + root, custom = _harness_install_root() + mode, version = form.get("harness_mode") or "", form.get("harness_version") or "" + ambient = dict(os.environ) + if preview: + # The launch form only overrides backend, model connection and OpenCode wire. + # The connection is validated separately and does not select an installation. + ambient_sha = hashlib.sha256(json.dumps(ambient, sort_keys=True).encode()).digest() + key = (root, custom, name, mode, version, ambient_sha, + environment.get("HG_AGENT_BACKEND"), environment.get("HG_AGENT_OPENCODE_WIRE")) + with _installation_previews_lock: + previous = _installation_previews.pop(key, None) + if previous is not None and form.get("installation_sha256") == previous["sha256"]: + _installation_previews[key] = previous + return previous + + selected = installation_store.select(root, name, mode, version, + verified_versions=install_harness.verified_versions, version_key=install_harness._version_key, + env={**ambient, **environment}, custom_root=custom) + if preview: + with _installation_previews_lock: + _installation_previews[key] = selected + if len(_installation_previews) > 32: + _installation_previews.popitem(last=False) + return selected if __name__ == "__main__" and not __package__: import candidates, candidate_trial @@ -455,7 +517,12 @@ def method_catalogue() -> list[dict]: def launch_form() -> dict: + from tools import install_harness + from tools.harness_setup import installation_store result = launch.describe(_launch_catalogue(), load_settings=load_settings, pools=POOLS) + root, _ = _harness_install_root() + result["installations"] = installation_store.catalogue( + root, result["harnesses"], install_harness.verified_versions, install_harness._version_key) result['candidates'] = [{'name': row['dir']} for row in harness_candidates().get('rows', [])] result['methods'] += [{**row, 'name': 'custom:' + row['name']} for row in custom_methods.list_methods(STATE_ROOT / 'methods')] @@ -493,22 +560,41 @@ def launch_log(run_id: str): settings=load_settings()) -def launch_argv(form: dict, run_id: str) -> list[str]: - return launch.build_argv(form, run_id, paths=_launch_paths(), budget_capacity=budget_capacity) +def launch_argv(form: dict, run_id: str, *, installation=None) -> list[str]: + if installation is None: + installation = _installed_harness(form) + return launch.build_argv(form, run_id, paths=_launch_paths(), budget_capacity=budget_capacity, + installation=installation) def launch_env(form: dict) -> dict: - return launch.build_environment(form, load_settings=load_settings) + env = launch.build_environment(form, load_settings=load_settings) + if form.get("harness") != "opencode" or env["HG_AGENT_BACKEND"] != "openai": + return env + from base_harness.opencode import opencode_runtime + from harnessgrad.env_file import read_env_file, reviewed_environment_only + key = "HG_AGENT_OPENCODE_WIRE" + try: + source = os.environ + if key not in source and not reviewed_environment_only(): + source = read_env_file(DRIVER.parent / ".env") + env[key] = opencode_runtime.execution_wire(source) + except (OSError, UnicodeError) as exc: + raise launch.LaunchEnvironmentRefused("Cannot read the driver's .env for the OpenCode model protocol.") from exc + except ValueError as exc: + raise launch.LaunchEnvironmentRefused(str(exc)) from exc + return env def new_run_id(form: dict) -> str: return launch.new_run_id(form) -def guard_launch(form: dict, *, preview_key_pending: bool = False, preview_meta_key_pending: bool = False) -> tuple[int, dict]: +def guard_launch(form: dict, *, preview_key_pending: bool = False, preview_meta_key_pending: bool = False, + resolve_environment=None) -> tuple[int, dict]: return launch.validate_launch_request(form, paths=_launch_paths(), catalogue=_launch_catalogue(), python_supported=python_supported, sandbox_supported=sandbox_supported, - budget_capacity=budget_capacity, launch_env=launch_env, + budget_capacity=budget_capacity, launch_env=resolve_environment or launch_env, preview_key_pending=preview_key_pending, preview_meta_key_pending=preview_meta_key_pending) @@ -527,7 +613,7 @@ def launch_scope_preview(form: dict, effective_env: dict) -> dict: def launch_preview(form: dict) -> dict: - return launch.preview(form, plan=_invocation_port(), catalogue=_launch_catalogue()) + return launch.preview(form, plan=_invocation_port(preview=True), catalogue=_launch_catalogue()) def api_health() -> dict: diff --git a/console/static/author.html b/console/static/author.html index 1806f9275..4ae86c1f5 100644 --- a/console/static/author.html +++ b/console/static/author.html @@ -3,7 +3,7 @@ -HarnessGrad · 领域定制 +HarnessGrad · 定制 Harness @@ -14,7 +14,7 @@