From ac9dd3bfb84e24a3b43981103103724e197a36ef Mon Sep 17 00:00:00 2001 From: yizhuod Date: Mon, 9 Nov 2026 03:18:20 -0500 Subject: [PATCH 1/3] Add opencode as a CLI Base Agent (acting agent and Evolver) --- CHANGELOG.md | 9 + docs/framework/adapter.md | 18 +- docs/framework/agent-layers.md | 10 +- docs/framework/commands.md | 5 +- docs/framework/custom-evolver.md | 2 +- docs/framework/evolver.md | 2 +- docs/framework/task.md | 2 +- docs/framework/what-is-a-harness-adapter.md | 2 +- docs/get-started/installation.md | 3 +- docs/guides/model-backends.md | 6 +- docs/methods/agent.md | 8 +- docs/reference/compatibility.md | 4 +- docs/reference/config-fields.md | 12 +- docs/web/index.html | 2 +- hermit/agent/acting/agent.py | 9 +- hermit/agent/acting/workspace.py | 22 +- hermit/agent/base/cli.py | 200 ++++++++- hermit/agent/base/login.py | 7 +- hermit/agent/base/records.py | 27 ++ hermit/agent/base/trajectory.py | 58 ++- hermit/agent/evolver/agent.py | 18 +- .../agent/evolver/methods/opencode/RESUME.md | 4 + .../agent/evolver/methods/opencode/START.md | 15 + .../evolver/methods/opencode/evolver.yaml | 13 + hermit/agent/model/backends.py | 42 +- hermit/cli.py | 7 +- hermit/config.py | 24 +- hermit/defaults.yaml | 10 +- hermit/hosts/opencode.py | 83 ++++ hermit/isolate.py | 4 +- tests/README.md | 4 +- tests/core/test_opencode_agent.py | 401 ++++++++++++++++++ tests/core/test_sandbox.py | 2 +- tests/core/test_selection.py | 2 +- tests/fixtures/opencode/README.md | 17 + tests/fixtures/opencode/failure_401.jsonl | 2 + tests/fixtures/opencode/failure_429.jsonl | 12 + tests/fixtures/opencode/failure_500.jsonl | 12 + tests/fixtures/opencode/failure_refused.jsonl | 12 + tests/fixtures/opencode/resume.jsonl | 4 + tests/fixtures/opencode/success.jsonl | 13 + tests/selection.py | 3 +- 42 files changed, 1015 insertions(+), 97 deletions(-) create mode 100644 hermit/agent/evolver/methods/opencode/RESUME.md create mode 100644 hermit/agent/evolver/methods/opencode/START.md create mode 100644 hermit/agent/evolver/methods/opencode/evolver.yaml create mode 100644 hermit/hosts/opencode.py create mode 100644 tests/core/test_opencode_agent.py create mode 100644 tests/fixtures/opencode/README.md create mode 100644 tests/fixtures/opencode/failure_401.jsonl create mode 100644 tests/fixtures/opencode/failure_429.jsonl create mode 100644 tests/fixtures/opencode/failure_500.jsonl create mode 100644 tests/fixtures/opencode/failure_refused.jsonl create mode 100644 tests/fixtures/opencode/resume.jsonl create mode 100644 tests/fixtures/opencode/success.jsonl diff --git a/CHANGELOG.md b/CHANGELOG.md index 335235c3..932348f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,15 @@ Changes are grouped by software version. Entries under Unreleased describe work call's tools are an MCP server offered directly; a failed request fails the session although Pi exits 0. Pi takes no roles and has no web search; `image_input: true` declares a bound model that takes images. `hermit deploy --host pi` declares the adapter's tools `exposure: direct`, with a 120 s timeout. +- OpenCode as a CLI Base Agent (`opencode`): the acting agent `agent.base: opencode` and the `opencode` Evolver run + OpenCode 2.2's `run --format json --standalone` (a server of the session's own, never its shared background + service) in its own home and XDG folders, with no update, catalog or download requests. It runs a model reference + only, as OpenCode's provider `hermit` (the key as `{env:VARIABLE}`, chat completions); what the session must hold + (the provider, the permissions, no sharing) is its inline config, which outranks a workspace's `opencode.json`; + the call's tools are an MCP server offered directly (not through code mode). Whether its provider could not serve + is read from OpenCode's own error type (`provider.rate-limit`, `.internal`, `.transport`, `.timeout`), so the + acting agent runs such a task again. OpenCode takes no roles and has no web search. `hermit deploy --host opencode` + writes `AGENTS.md`, the project's `opencode.json` and `.opencode/skills`. - Models in sandboxes as Harbor's agents get theirs: each sandbox gets its models' key variables and provider hosts (an isolated network becomes an allowlist) and forwards a model meter on the loopback; what a run keeps (the learning material, the step records, the adapter) is scrubbed of key values (`hermit/redact.py`). The allowlist diff --git a/docs/framework/adapter.md b/docs/framework/adapter.md index 41062547..a9f4ec17 100644 --- a/docs/framework/adapter.md +++ b/docs/framework/adapter.md @@ -79,15 +79,15 @@ for stays a file of the copy, and the context names it with what to do with it. host, and for the built-in `codex` and `claude-code` acting agents, which deploy as `hermit deploy` does: an adapter is deployed as far as the host can take it, and nothing it holds is out of the agent's reach. -| Adapter source | Deployment operation | Codex output | Claude Code output | Pi output | -|---|---|---|---|---| -| Every file but `.hermit/` and `.git/` | Copy it as it is. | `hermit//` | `hermit//` | `hermit//` | -| `ADAPTER.md` (always exported) | Insert the line above and its text into a managed instruction block. | `AGENTS.md` | `CLAUDE.md` | `AGENTS.md` | -| `skills/verify-output/`, through `skills` in `exports.yaml` | Copy the skill directory. | `.codex/skills/verify-output/` | `.claude/skills/verify-output/` | `.pi/skills/verify-output/` | -| `agents/reviewer.md` (or `agents/reviewer/AGENT.md`), through `agents` in `exports.yaml` | Convert the subagent into native host files: frontmatter gives name and description, the body becomes its instructions. | `.codex/agents/reviewer.toml`, registered in `.codex/config.toml` | `.claude/agents/reviewer.md` | named in `AGENTS.md` (Pi has no subagents): name, description, the path of its instructions | -| `tools.py`, through `tools` in `exports.yaml` | Configure a framework MCP server that loads the source adapter. | `.codex/config.toml` | `.mcp.json` | `.pi/mcp.json` | -| a hooks file, through `hooks` in `exports.yaml` | Write the hooks the host runs, each command run from `hermit//`; name the others in the context (a command to run, a `prompt` hook's check to make at that moment); a hook of another type is refused. | `.codex/hooks.json` (command hooks; Codex runs no prompt or agent hooks) | `hooks` in `.claude/settings.json` (command and prompt hooks) | named in `AGENTS.md` (Pi reads no hook file) | -| every other file of the copy | Name it, with its frontmatter description or first line, under "Adapter resources" in the context (up to 60 files; the rest are counted). | `AGENTS.md` | `CLAUDE.md` | `AGENTS.md` | +| Adapter source | Deployment operation | Codex output | Claude Code output | Pi output | OpenCode output | +|---|---|---|---|---|---| +| Every file but `.hermit/` and `.git/` | Copy it as it is. | `hermit//` | `hermit//` | `hermit//` | `hermit//` | +| `ADAPTER.md` (always exported) | Insert the line above and its text into a managed instruction block. | `AGENTS.md` | `CLAUDE.md` | `AGENTS.md` | `AGENTS.md` | +| `skills/verify-output/`, through `skills` in `exports.yaml` | Copy the skill directory. | `.codex/skills/verify-output/` | `.claude/skills/verify-output/` | `.pi/skills/verify-output/` | `.opencode/skills/verify-output/` | +| `agents/reviewer.md` (or `agents/reviewer/AGENT.md`), through `agents` in `exports.yaml` | Convert the subagent into native host files: frontmatter gives name and description, the body becomes its instructions. | `.codex/agents/reviewer.toml`, registered in `.codex/config.toml` | `.claude/agents/reviewer.md` | named in `AGENTS.md` (Pi has no subagents): name, description, the path of its instructions | named in `AGENTS.md`, as for Pi | +| `tools.py`, through `tools` in `exports.yaml` | Configure a framework MCP server that loads the source adapter. | `.codex/config.toml` | `.mcp.json` | `.pi/mcp.json` | `opencode.json` (`mcp.servers`, `codemode: false`) | +| a hooks file, through `hooks` in `exports.yaml` | Write the hooks the host runs, each command run from `hermit//`; name the others in the context (a command to run, a `prompt` hook's check to make at that moment); a hook of another type is refused. | `.codex/hooks.json` (command hooks; Codex runs no prompt or agent hooks) | `hooks` in `.claude/settings.json` (command and prompt hooks) | named in `AGENTS.md` (Pi reads no hook file) | named in `AGENTS.md` | +| every other file of the copy | Name it, with its frontmatter description or first line, under "Adapter resources" in the context (up to 60 files; the rest are counted). | `AGENTS.md` | `CLAUDE.md` | `AGENTS.md` | `AGENTS.md` | This is how the adapter reaches the acting system. The host reads the generated instruction, skill, role and hook files; tool configuration makes the declared tools available through its tool interface. What the adapter does not diff --git a/docs/framework/agent-layers.md b/docs/framework/agent-layers.md index 644c7832..86ec3c21 100644 --- a/docs/framework/agent-layers.md +++ b/docs/framework/agent-layers.md @@ -49,6 +49,7 @@ How a model takes steps. Layer 2 holds only the framework's agents: | `codex` | The Codex CLI, working in a workspace | | `claude` | The Claude Code CLI, working in a workspace | | `pi` | The Pi CLI, working in a workspace (no roles, no web search) | +| `opencode` | The OpenCode CLI, working in a workspace (a model reference only; no roles, no web search) | API, the only one Layer 3 sees: @@ -81,7 +82,7 @@ none), Codex's own sandbox mode, the CLI's home, the time limit (the full list i leaves the agent as it was. Running a task again when the provider could not serve it is Layer 3's: the workspace is placed anew first. -Codex, Claude Code and Pi share one runner, `CliAgent`: the isolation, the home, the sign-in, the tool server and the +Codex, Claude Code, Pi and OpenCode share one runner, `CliAgent`: the isolation, the home, the sign-in, the tool server and the process are the same for every CLI. Each CLI is a subclass whose hooks give what is its own: its command, its home, and how its event stream is read (the reply, the trajectory, the usage, whether the provider served it, and what a session that was not served met: `outcome`). A new CLI is @@ -99,8 +100,8 @@ What the Base Agent is used for. Two kinds: record). - The **Evolver Agent** learns. Its API to the Trainer is `step(ctx)` and `finalize(ctx)`. It reads the acting runs' trajectories and writes a new adapter, calling a Base Agent: `direct` for methods that decide every step in - their own code (GEPA, SkillOpt, ReHarness, Continual Harness), `codex`, `claude` or `pi` for methods whose learner - is an agent (Meta-Harness Adapter, the `codex`, `claude` and `pi` Evolvers). The run's model reaches an Evolver as + their own code (GEPA, SkillOpt, ReHarness, Continual Harness), `codex`, `claude`, `pi` or `opencode` for methods + whose learner is an agent (Meta-Harness Adapter, the `codex`, `claude`, `pi` and `opencode` Evolvers). The run's model reaches an Evolver as `ctx.agent`, a `direct` Base Agent metered against the budget; `ask(ctx.agent, messages, max_tokens=...)` returns the reply as the `llm` tool does. @@ -141,7 +142,7 @@ Each Base Agent offers the tools to the model in its own way: |---|---|---| | `direct` | Their schemas in the API request | Layer 3, which then calls `direct` again | | `react` | Their schemas in the API request | `react`, in its loop | -| `codex`, `claude`, `pi` | The framework's tool server, over MCP (streamable HTTP) | The tool server | +| `codex`, `claude`, `pi`, `opencode` | The framework's tool server, over MCP (streamable HTTP) | The tool server | The tool server (`hermit/agent/base/tool_server.py`) is started for the one call and stopped after it. It carries a token in its URL, so that only the session it was started for can call it, and tells Codex to approve its tools @@ -225,6 +226,7 @@ accepted; a key given in two layers is refused. On the command line a layer's se | GEPA, SkillOpt, ReHarness, Continual Harness, OPRO | Evolver Agent | `direct` (`ctx.agent`); OPRO in OfficeQA: `codex` through `llm: {cli: codex}` | | Meta-Harness Adapter, `codex` and `claude` Evolvers | Evolver Agent | `codex` or `claude` | | `pi` Evolver | Evolver Agent | `pi` | +| `opencode` Evolver | Evolver Agent | `opencode` | | RRSI Adapter | Evolver Agent: upstream's rules and roles, the proposer's prompt | `codex` or `claude` for the proposer, and the same, one call per upstream `generate`, for the analyst, digesters and critic | | AHE Adapter | Evolver Agent: the Evolve Agent and the Agent Debugger | `codex` or `claude`, one session per step and per task | | CL-Bench, ServeLearnBench | Acting Agent running the benchmark's loop | `direct`, per call, through the local endpoint | diff --git a/docs/framework/commands.md b/docs/framework/commands.md index 025828d3..0b51d98c 100644 --- a/docs/framework/commands.md +++ b/docs/framework/commands.md @@ -71,12 +71,15 @@ user chooses: `--adapter none` runs the acting agent with no harness adapter at hermit deploy --adapter DIR --workspace WORKSPACE --host codex hermit deploy --adapter DIR --workspace WORKSPACE --host claude-code hermit deploy --adapter DIR --workspace WORKSPACE --host pi +hermit deploy --adapter DIR --workspace WORKSPACE --host opencode ``` This generates host instruction files, role/skill files, and tool configuration. It does not launch the acting agent. Pi has no subagents and reads no hook file, so `--host pi` names an adapter's roles and hooks in `AGENTS.md` instead; its `.pi/` files (tools, skills) load once the user trusts the project in Pi, while `AGENTS.md` needs no -trust. `--context-limit BYTES` (Codex) is the `project_doc_max_bytes` your Codex configuration sets, 32768 (Codex's +trust. `--host opencode` writes `AGENTS.md`, the project's `opencode.json` (the tools, offered directly) and +`.opencode/skills`, which OpenCode loads with no trust step; it names roles and hooks in `AGENTS.md`, as for Pi. +`--context-limit BYTES` (Codex) is the `project_doc_max_bytes` your Codex configuration sets, 32768 (Codex's default) when not given: a longer `AGENTS.md` is refused, since Codex would cut it; `0` skips the check. It is the per-project way to use an adapter; the per-agent way, `convert`, and how the two compare are in [What is a harness adapter?](what-is-a-harness-adapter.md#two-ways-to-use-an-adapter). The workspace must be an empty directory or one previously generated for the same host, separate from the adapter directory. See the [file mapping](adapter.md#acting-interface) for exact paths and update behavior. diff --git a/docs/framework/custom-evolver.md b/docs/framework/custom-evolver.md index 97937eb8..70bc3701 100644 --- a/docs/framework/custom-evolver.md +++ b/docs/framework/custom-evolver.md @@ -75,7 +75,7 @@ You can reuse a launcher instead of implementing a new Python learning loop: | `hermit.agent.evolver.agent:AgentEvolver` | Backend, prompt files, model selection, and host arguments. | The learner agent edits the working directory. | | `hermit.agent.evolver.agent:CommandEvolver` | An external command and optional environment values. | The program edits the working directory and may write a result file. | -`AgentEvolver` supports `codex`, `claude` and `pi`. Its parameters include `backend`, `prompt`, `resume_prompt`, `model`, +`AgentEvolver` supports `codex`, `claude`, `pi` and `opencode`. Its parameters include `backend`, `prompt`, `resume_prompt`, `model`, `args`, and `home`. Prompt placeholders include the workspace paths, `message`, `epoch`, and `step`. The bundled definitions are under `hermit/agent/evolver/methods/`. diff --git a/docs/framework/evolver.md b/docs/framework/evolver.md index fa78f209..50e8cc91 100644 --- a/docs/framework/evolver.md +++ b/docs/framework/evolver.md @@ -130,7 +130,7 @@ For selection guidance, setup, and the complete parameter defaults, use [Choose | `evolver.name` | Method | Needs | |---|---|---| -| `codex`, `claude`, `pi` | A Codex, Claude Code or Pi agent edits the adapter from the learning material; `codex` on the `prompt-only@1.0` template is the [prompt-only](../methods/prompt-only.md) method. | The agent CLI | +| `codex`, `claude`, `pi`, `opencode` | A Codex, Claude Code, Pi or OpenCode agent edits the adapter from the learning material; `codex` on the `prompt-only@1.0` template is the [prompt-only](../methods/prompt-only.md) method. | The agent CLI | | `gepa` | [GEPA](https://github.com/gepa-ai/gepa): one iteration per step. It reflects on the step's trajectories, keeps a child that does better on the same tasks, scores it on validation, and hands back the next parent from its Pareto front. | `llm`, `data.val`, `python -m pip install -e . --group gepa` | | `skillopt` | [SkillOpt](https://github.com/microsoft/SkillOpt): one SkillOpt step per training step. It turns the step's trajectories into a few bounded edits under its learning rate (decaying when `total_steps` is set) and keeps them only if the validation score improves; the slow update and meta skill run at each epoch's end. | `llm`, `data.val`, `python -m pip install -e . --group skillopt` | | `ace` | [ACE](https://github.com/ace-agent/ace): per rollout, a Reflector tags the playbook bullets the agent named and diagnoses the attempt (a wrong answer is run again with the reflection, up to `max_num_rounds`), and a Curator adds bullets; the playbook grows by deltas. See `docs/methods/ace.md`. | `llm`; `data.val` to keep the best validation playbook | diff --git a/docs/framework/task.md b/docs/framework/task.md index 0c4a1852..e3dd3c78 100644 --- a/docs/framework/task.md +++ b/docs/framework/task.md @@ -86,7 +86,7 @@ agent: | `agent.name` | Agent | Settings | |---|---|---| | `react` | a chat-completions tool-calling loop over the task's tools and the adapter's tools | `model`, `prompt`, `tools`, `user`, `max_turns`, `max_output_tokens`, `max_tokens`, `temperature`, `answer_tag`, `tool_result_chars`, `logs` | -| `codex`, `claude-code`, `pi` | Codex, Claude Code or Pi run in a fresh workspace the adapter is deployed into (Pi: no `login`, no roles; its project's `.pi/` is trusted for the session) | `model`, `login`, `effort`, `prompt`, `files`, `mounts`, `prepare`, `answer`, `collect`, `context_query`, `project_doc_max_bytes`, `args`, `env`, `price`, `timeout_s`, `retries`, `retry_wait_s`, `workspaces` | +| `codex`, `claude-code`, `pi`, `opencode` | Codex, Claude Code, Pi or OpenCode run in a fresh workspace the adapter is deployed into (Pi and OpenCode: no `login`, no roles; Pi's project `.pi/` is trusted for the session; OpenCode needs a model reference) | `model`, `login`, `effort`, `prompt`, `files`, `mounts`, `prepare`, `answer`, `collect`, `context_query`, `project_doc_max_bytes`, `args`, `env`, `price`, `timeout_s`, `retries`, `retry_wait_s`, `workspaces` | ### A coding-agent CLI as the acting agent diff --git a/docs/framework/what-is-a-harness-adapter.md b/docs/framework/what-is-a-harness-adapter.md index c29512b5..9d9e4143 100644 --- a/docs/framework/what-is-a-harness-adapter.md +++ b/docs/framework/what-is-a-harness-adapter.md @@ -32,7 +32,7 @@ manifest-driven service lifecycle remains a [proposal](../developer/service-desi | Route | Output | Use when | |---|---|---| -| `deploy` | A Codex, Claude Code, or Pi workspace | You want project instructions, skills, roles, and tool configuration | +| `deploy` | A Codex, Claude Code, Pi, or OpenCode workspace | You want project instructions, skills, roles, and tool configuration | | `convert` | A native plugin package for a supported target | You want host-native packaging and can accept that target's export limits | | Custom pipeline | Your agent receives the exports directly | You own the acting loop or need dynamic integration | diff --git a/docs/get-started/installation.md b/docs/get-started/installation.md index a8c88366..c3b0e1ed 100644 --- a/docs/get-started/installation.md +++ b/docs/get-started/installation.md @@ -93,7 +93,7 @@ never shown). |---|---| | [Offline first training](quickstart.md) | None beyond the core install | | [First real-model training](first-model.md) | `python -m pip install -e . --group gepa`, a compatible chat-completions endpoint, model id, and credential; data is included | -| Generate a Codex / Claude Code / Pi workspace | No host CLI is needed until you start the host | +| Generate a Codex / Claude Code / Pi / OpenCode workspace | No host CLI is needed until you start the host | | Run an acting host | Installed and authenticated host, plus adapter tool dependencies | | Prompt-only learner | The Codex CLI, Linux with bubblewrap, and a learner backend that serves the Responses API | | GEPA | `python -m pip install -e . --group gepa`, learner endpoint, validation split | @@ -104,6 +104,7 @@ never shown). | MWM | Linux learner environment, Codex or Claude Code, evidence store, task deployment contract, model access | | Acting and learning on a Claude subscription | Claude Code 2.1.248 or later, `claude setup-token`, Linux with bubblewrap for its sandboxes; see [Claude subscription](../guides/claude-subscription.md) | | Pi acting agent or learner | The `pi` release binary on `PATH` (GitHub release `pi-linux-x64.tar.gz`, checked against its `SHA256SUMS`) and a model reference | +| OpenCode acting agent or learner | The `opencode` 2.2 release binary on `PATH` (GitHub release `opencode-linux-x64.tar.gz` of `anomalyco/opencode`, checked against the release's sha256 digest) and a model reference | | Benchmark recipe | Its dataset, scorer, model settings, and environment; see [catalog](../recipes/index.md) | Core installation and the deterministic tutorial work on macOS. The sandboxes (the acting agent's, the judge's, the diff --git a/docs/guides/model-backends.md b/docs/guides/model-backends.md index 44bc10f5..ca639ec4 100644 --- a/docs/guides/model-backends.md +++ b/docs/guides/model-backends.md @@ -27,6 +27,7 @@ hermit train --config run.yaml model=vllm/Qwen/Qwen3-30B-A3B-Instruct-2507-FP8 | `agent.params.model` (or `agent.model`) with `agent.name: codex` / `claude-code` | the CLI acting agent | Responses API / Messages API | | `evolver.params.model` of the `codex`, `claude` and `mwm` Evolvers | the learner's CLI session | Responses API / Messages API | | `agent.params.model` with `agent.name: pi`, `evolver.params.model` of the `pi` Evolver | Pi | chat completions, else the Messages API, else the Responses API: the first the backend serves | +| `agent.params.model` with `agent.name: opencode`, `evolver.params.model` of the `opencode` Evolver | OpenCode | chat completions | | `model` (top level) | the default for all of the above when they name none | | | the examples' task agents (`agent.params.model`, or the launchers' `MW_MODEL`) | CL-Bench's litellm host, ServeLearnBench's loop, the SkillOpt rollout | chat completions | @@ -41,6 +42,9 @@ For Pi a reference becomes its `models.json` provider `hermit`: the backend's UR at each request, so no file holds the key) and the backend's price. The cost recorded follows the price (the agent's own `price`, else the backend's), not Pi's own figure. Pi sends such a model text only; for a model that takes images (a tool's result, such as a screenshot), set `image_input: true` in `agent.pi` or `evolver.pi`. +For OpenCode a reference becomes its config's provider `hermit` (OpenCode's OpenAI-compatible package): the +backend's chat-completions URL and the key as `{env:VARIABLE}` (so no config holds the key). OpenCode runs a +reference only; the cost recorded follows the price, not OpenCode's own figure. A string whose first segment is no backend's name is not a reference: for a Codex or Claude Code agent it is a model of the CLI's own provider (`gpt-5.4`), as before. So a provider id that happens to start with a backend's @@ -100,7 +104,7 @@ lab-sglang: # a new one, like the built-in sglang at ## Dialects: what Codex and Claude Code need The framework's own client, the react agent and the examples' task agents speak **chat completions**, and so does Pi -where the backend serves them. Codex and Claude Code do not: **Codex speaks the OpenAI Responses API only** +where the backend serves them, and OpenCode. Codex and Claude Code do not: **Codex speaks the OpenAI Responses API only** (`wire_api = "chat"` is rejected since Codex 0.95), and **Claude Code speaks the Anthropic Messages API only**. A backend's `apis` says what it serves, and the framework checks a model's dialect against its backend before a run starts: `hermit check` reports it, `train` refuses to start on a mismatch, and `hermit backends check ` sends diff --git a/docs/methods/agent.md b/docs/methods/agent.md index 9ec8b88e..8f6576d2 100644 --- a/docs/methods/agent.md +++ b/docs/methods/agent.md @@ -1,9 +1,11 @@ -# Codex, Claude and Pi agent learners +# Codex, Claude, Pi and OpenCode agent learners -Use `evolver.name: codex`, `claude` or `pi` when a learner should inspect trajectories, use tools, and edit an -adapter directory over several actions. This is useful for skills, multiple files, and tool code that a single text +Use `evolver.name: codex`, `claude`, `pi` or `opencode` when a learner should inspect trajectories, use tools, and +edit an adapter directory over several actions. This is useful for skills, multiple files, and tool code that a single text rewrite does not capture well. The `pi` learner signs in through a model reference (`evolver.base: pi` with `evolver.model: /`, or `evolver.params.model`); it copies no login from `~/.pi/agent` (`home: []`). +The `opencode` learner runs only a model reference the same way (`evolver.base: opencode`); without one its session +is refused. On the single-file prompt-only template, the Codex learner is the [prompt-only](prompt-only.md) method. ## Requirements and setup diff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.md index 9277d6d4..c4a4b27f 100644 --- a/docs/reference/compatibility.md +++ b/docs/reference/compatibility.md @@ -11,8 +11,8 @@ numbers alone may not distinguish unreleased changes. | Local deterministic Quick Start | No model account, GPU, external dataset, or host CLI | | Context-only workspace generation | macOS and Linux | | Sandboxed learner programs | Linux with bubblewrap and permitted namespaces | -| Built-in methods | Prompt-only (the Codex learner on the prompt-only template), Codex, Claude, Pi, GEPA, SkillOpt, MWM, Harness², Continual Harness, ReHarness, Meta-Harness Adapter, ACE, AHE Adapter, RRSI Adapter, EvoSafeHarness, OPRO | -| Workspace deployment | Codex, Claude Code, and Pi | +| Built-in methods | Prompt-only (the Codex learner on the prompt-only template), Codex, Claude, Pi, OpenCode, GEPA, SkillOpt, MWM, Harness², Continual Harness, ReHarness, Meta-Harness Adapter, ACE, AHE Adapter, RRSI Adapter, EvoSafeHarness, OPRO | +| Workspace deployment | Codex, Claude Code, Pi, and OpenCode | | A subscription instead of an API key | Codex (`login: chatgpt`) and Claude Code (`login: claude`, CLI 2.1.248 or later, tested on 2.1.318), acting and learning; see [Claude subscription](../guides/claude-subscription.md) | | Native plugin conversion | Claude Code, Codex, Pi, Hermes, with export restrictions | | Stdio tool server | `hermit serve DIR`; normally started by the host | diff --git a/docs/reference/config-fields.md b/docs/reference/config-fields.md index 1b26aa1b..ca39a6f9 100644 --- a/docs/reference/config-fields.md +++ b/docs/reference/config-fields.md @@ -32,13 +32,13 @@ guarantee that their consumer supports arbitrary fields. | `data.shuffle` | boolean / true | Shuffle training order; set false for ordered streams | | `data.shuffle_seed` | integer / 0 | Training shuffle seed; does not seed every model or method | | `task_info` | directory / null | Learner-facing task description; provide `README.md` | -| `agent.name` | string / null; required | Built-in `react`, `codex`, `claude-code`, `pi`, `harbor` (a benchmark's task set in Harbor's format, see [Benchmarks](../framework/task.md#benchmarks)), an Agent class, or a `file.py:function` / `module:function` | +| `agent.name` | string / null; required | Built-in `react`, `codex`, `claude-code`, `pi`, `opencode`, `harbor` (a benchmark's task set in Harbor's format, see [Benchmarks](../framework/task.md#benchmarks)), an Agent class, or a `file.py:function` / `module:function` | | `agent.concurrency` | integer / 4 | Maximum concurrent rollout/evaluation task executions; use a positive value | | `agent.timeout_min` | number / null | A sandboxed task call (its worker) running longer is stopped and recorded as an error; null: no limit | | `agent.params` | mapping / {} | Passed to Agent constructors; plain functions receive it when they declare a `params` argument | -| `agent.base` | string / null | Layer 2 in the per-layer form ([Agent layers](../framework/agent-layers.md#settings-by-layer)): `codex`, `claude`, `pi`, `react`, or `direct` (with `agent.name`, a task's own loop); sets `agent.name` when unset | +| `agent.base` | string / null | Layer 2 in the per-layer form ([Agent layers](../framework/agent-layers.md#settings-by-layer)): `codex`, `claude`, `pi`, `opencode`, `react`, or `direct` (with `agent.name`, a task's own loop); sets `agent.name` when unset | | `agent.model` | string / mapping / null | Layer 1: a `/` reference, or `{ref` or `name, login, effort, price, ...}`; read into `agent.params` | -| `agent.codex`, `agent.claude`, `agent.pi`, `agent.react`, `agent.direct` | mapping / null | Layer 2's settings for that Base Agent (the one `agent.base` names); read into `agent.params`. A key set in two layers is refused | +| `agent.codex`, `agent.claude`, `agent.pi`, `agent.opencode`, `agent.react`, `agent.direct` | mapping / null | Layer 2's settings for that Base Agent (the one `agent.base` names); read into `agent.params`. A key set in two layers is refused | | `pipeline.run` | string / null | Legacy alias for `agent.name`, applied only when `agent.name` is unset | | `pipeline.concurrency` | integer / null | Legacy concurrency override when the legacy pipeline alias is used | | `pipeline.params` | mapping / {} | Legacy parameters merged into `agent.params` when the pipeline alias is used | @@ -57,9 +57,9 @@ Task row fields become training material, so private labels require judge-owned | `evolver.name` | string / null; required | Built-in method or directory containing its Evolver definition | | `evolver.resume` | boolean / false | Request learner-session continuation; method must support it | | `evolver.params` | mapping / {} | Overrides merged with the chosen method's defaults | -| `evolver.base` | string / null | Layer 2 the method runs on: `codex`, `claude` or `pi` (an agent Evolver: sets `evolver.params.backend`) or `direct` | +| `evolver.base` | string / null | Layer 2 the method runs on: `codex`, `claude`, `pi` or `opencode` (an agent Evolver: sets `evolver.params.backend`) or `direct` | | `evolver.model` | string / mapping / null | Layer 1, as `agent.model`; with `evolver.base: direct` it is the run's `llm` | -| `evolver.codex`, `evolver.claude`, `evolver.pi`, `evolver.direct` | mapping / null | Layer 2's settings, read into `evolver.params` | +| `evolver.codex`, `evolver.claude`, `evolver.pi`, `evolver.opencode`, `evolver.direct` | mapping / null | Layer 2's settings, read into `evolver.params` | | `evolver_access.environment` | list / [] | Granted environment resources; required for MWM's evidence integration | | `evolver_access.tools` | list / [] | Task tool declarations offered to the learner | | `evolver_access.send_material_out` | boolean / false | Consent declaration checked for methods requesting that need; not a network filter | @@ -79,7 +79,7 @@ dialects it serves, prices). See [Model backends](../guides/model-backends.md). | `llm` | reference, mapping / null | The run's chat-completions `llm` tool: a reference, `{model: , price, extra_body}`, the endpoint itself (below), or a CLI's sessions, `{cli: ..., ...}` (below) | `agent.params.model` takes the same forms. For a Codex or Claude Code acting agent or Evolver a reference becomes -the CLI's provider settings (`args` for Codex, `env` for Claude Code, `provider` for Pi) and the model's id; a plain id without a +the CLI's provider settings (`args` for Codex, `env` for Claude Code, `provider` for Pi and OpenCode) and the model's id; a plain id without a backend goes to the CLI's own provider as before. ### Learner model tool diff --git a/docs/web/index.html b/docs/web/index.html index f7af611f..e702b1c6 100644 --- a/docs/web/index.html +++ b/docs/web/index.html @@ -145,7 +145,7 @@

§What Hermit gives you out of the box

  • One Trainer for every method: rollouts, judge feedback, an Evolver step, a checked commit, the next version
  • Built-in evolution methods and a shared interface for your own Evolver
  • Adapters as files in a git tree: inspect every version, roll back, ship the final one
  • -
  • Deploy workspaces for Codex, Claude Code or Pi, or export supported contents as a native plugin for compatible hosts
  • +
  • Deploy workspaces for Codex, Claude Code, Pi or OpenCode, or export supported contents as a native plugin for compatible hosts
  • Adapter specification checks and versioned updates, with sandboxing for supported learner programs
  • Any model backend by reference: Fireworks, OpenAI, Anthropic, DeepSeek, vLLM, SGLang, Ollama
  • diff --git a/hermit/agent/acting/agent.py b/hermit/agent/acting/agent.py index 8cafd23b..3c9dffcb 100644 --- a/hermit/agent/acting/agent.py +++ b/hermit/agent/acting/agent.py @@ -7,7 +7,7 @@ def run(self, task: dict, adapter: Path | None) -> RunOutput A config names the agent: agent: - name: react # a built-in: react | codex | claude-code | pi + name: react # a built-in: react | codex | claude-code | pi | opencode name: agent/agent.py:CLBenchAgent # or the task's own class (file.py:Class, module:Class) name: agent/pipeline.py:run # or a plain function run(task, adapter), wrapped as a FunctionAgent concurrency: 4 @@ -75,9 +75,10 @@ def builtin(name: str): if name == "react": from hermit.agent.acting.react import ReactAgent return ReactAgent - if name in ("cli", "codex", "claude-code", "claude", "pi"): + if name in ("cli", "codex", "claude-code", "claude", "pi", "opencode"): from hermit.agent.acting.workspace import CliAgent - backend = {"codex": "codex", "claude-code": "claude", "claude": "claude", "pi": "pi"}.get(name) + backend = {"codex": "codex", "claude-code": "claude", "claude": "claude", "pi": "pi", + "opencode": "opencode"}.get(name) if backend is None: return CliAgent return lambda params, base: CliAgent({"backend": backend, **(params or {})}, base) @@ -87,7 +88,7 @@ def builtin(name: str): return None -BUILTIN_NAMES = ("react", "codex", "claude-code", "pi", "cli", "harbor") +BUILTIN_NAMES = ("react", "codex", "claude-code", "pi", "opencode", "cli", "harbor") def load_agent(name: str, params: dict | None, base: Path) -> Agent: diff --git a/hermit/agent/acting/workspace.py b/hermit/agent/acting/workspace.py index f280c344..8f06b378 100644 --- a/hermit/agent/acting/workspace.py +++ b/hermit/agent/acting/workspace.py @@ -1,5 +1,5 @@ -"""The `codex`, `claude-code` and `pi` agents: one task run by the agent CLI in a workspace the adapter is deployed -into. They are the framework's one way to act with a coding-agent CLI; a task adds only what is its own. +"""The `codex`, `claude-code`, `pi` and `opencode` agents: one task run by the agent CLI in a workspace the adapter is +deployed into. They are the framework's one way to act with a coding-agent CLI; a task adds only what is its own. agent: name: codex # or claude-code; `cli` with params.backend is the same @@ -66,10 +66,10 @@ from hermit.agent.acting.agent import Agent from hermit.agent.base import container from hermit.agent.base.interface import BaseAgent, Limits, LoginFailed, Mount, make -from hermit.agent.base.login import LOGINS +from hermit.agent.base.login import LOGINS, NO_LOGIN from hermit.task import RunOutput, load_callable -BACKENDS = ("codex", "claude", "pi") +BACKENDS = ("codex", "claude", "pi", "opencode") DEPLOYS = ("host",) ISOLATIONS = ("none", "container") INPUT_FIELDS = ("question", "prompt", "instruction", "input", "query") @@ -144,6 +144,9 @@ def deploy(adapter: Path, workspace: Path, backend: str, *, context: str | None if backend == "pi": from hermit.hosts.pi import prepare as prepare_pi return prepare_pi(adapter, workspace, sys.executable, context=context) + if backend == "opencode": + from hermit.hosts.opencode import prepare as prepare_opencode + return prepare_opencode(adapter, workspace, sys.executable, context=context) from hermit.hosts.claude_code import prepare return prepare(adapter, workspace, sys.executable, context=context, serve_tools=serve_tools) @@ -170,9 +173,12 @@ def _deploy(task: dict, adapter: Path | None, work: Path, backend: str, params: def _session_args(backend: str, deployed: dict, work: Path) -> list[str]: """What the session needs to use what the deployment connected: the workspace's own Codex configuration (its tools, roles and hooks) trusted, as a person trusts a deployed project, and its sub-agents enabled; Pi's project - configuration (.pi/mcp.json, .pi/skills) trusted for the session (--approve), without which Pi skips it.""" + configuration (.pi/mcp.json, .pi/skills) trusted for the session (--approve), without which Pi skips it. OpenCode + loads its project's opencode.json and .opencode/skills with no trust step.""" if backend == "pi": return ["--approve"] + if backend == "opencode": + return [] if backend == "codex": return ["-c", f'projects={{"{work}" = {{ trust_level = "trusted" }} }}', *(["--enable", "multi_agent"] if deployed.get("roles") else [])] @@ -277,11 +283,11 @@ def _check(backend: str, params: dict) -> str: if not isinstance(params.get("web_search"), bool): raise ValueError("agent.params.web_search must be set, true or false: Codex's hosted search runs at the " "provider, past any sandbox or proxy, so it is never left to a default") - if backend == "pi": # Pi signs in through a model reference, and runs on this machine + if backend in NO_LOGIN: # signs in through a model reference, and runs on this machine if params.get("login") is not None: - raise ValueError("agent pi takes no login: its model is a / reference") + raise ValueError(f"agent {backend} takes no login: its model is a / reference") if params.get("isolation") == "container": - raise ValueError("isolation: container runs Codex or Claude Code; agent pi takes isolation: none") + raise ValueError(f"isolation: container runs Codex or Claude Code; agent {backend} takes isolation: none") return backend login, label = params.get("login"), {"codex": "Codex", "claude": "Claude Code"}[backend] if login is not None and login not in LOGINS: diff --git a/hermit/agent/base/cli.py b/hermit/agent/base/cli.py index ef6e2152..44ed3c7d 100644 --- a/hermit/agent/base/cli.py +++ b/hermit/agent/base/cli.py @@ -1,4 +1,5 @@ -"""`codex`, `claude` and `pi`: a coding-agent CLI as a Base Agent (docs/framework/agent-layers.md#layer-2-base-agent). +"""`codex`, `claude`, `pi` and `opencode`: a coding-agent CLI as a Base Agent +(docs/framework/agent-layers.md#layer-2-base-agent). One `run` is one session of the CLI in print mode: the prompt is given, the CLI works in `workspace` with its own tools and the call's `tools` (served over MCP by the framework's tool server), and its last message is the reply. @@ -69,6 +70,10 @@ image_input (true: the bound model takes images, such as a tool's result; default: text only, Pi's default for a model it does not know), append_system_prompt, effort (its --thinking level). Pi takes no roles, has no web search and runs under isolation none or sandbox. + OpenCode only: provider (its config's provider for the bound model, from the binding: Binding.opencode_provider; + required: OpenCode runs a model reference and takes no login), append_system_prompt (an instructions file in the + home), effort (the model's reasoningEffort). OpenCode takes no roles, has no web search and runs under isolation + none or sandbox. Limits are enforced by the isolation, or the call is refused (Unsupported): @@ -96,9 +101,9 @@ from hermit.agent.base import container, login as codex_login from hermit.agent.base.interface import BaseAgent, Limits, Mount, Result, Unsupported -from hermit.agent.base.records import parse_claude, parse_codex, parse_pi, price_usage +from hermit.agent.base.records import parse_claude, parse_codex, parse_opencode, parse_pi, price_usage from hermit.agent.base.tool import Tool -from hermit.agent.base.trajectory import claude_steps, codex_steps, events, pi_steps +from hermit.agent.base.trajectory import claude_steps, codex_steps, events, opencode_steps, pi_steps from hermit.agent.model.backends import CLAUDE_ENV ISOLATIONS = ("none", "sandbox", "container") @@ -1462,8 +1467,195 @@ def _pi_session(home: Path, handle) -> Path | None: return sorted(found)[-1] if found else None +OPENCODE_PROVIDER = "hermit" # the config provider a bound model is given under +# Tools a session is not offered: questions for a person (no one answers), its own sub-agents (OpenCode takes no +# roles), code mode (the call's tools are offered directly) and what reaches the network past the run's sandbox. +OPENCODE_DENIED = ("question", "subagent", "execute", "webfetch", "websearch", "opencode_*") +# No update, catalog or language-server download; no Claude Code files (~/.claude) and no skills from .claude/ or +# .agents/ folders (an adapter's skills are deployed to .opencode/skills) +OPENCODE_ENV = {"OPENCODE_DISABLE_AUTOUPDATE": "1", "OPENCODE_DISABLE_MODELS_FETCH": "1", + "OPENCODE_DISABLE_LSP_DOWNLOAD": "1", "OPENCODE_DISABLE_CLAUDE_CODE": "1", + "OPENCODE_DISABLE_EXTERNAL_SKILLS": "1"} +# OpenCode's reports (its error event's `type`) of a provider that could not serve, which it retries itself first +OPENCODE_OUTAGES = ("provider.rate-limit", "provider.internal", "provider.transport", "provider.timeout") +# ... and of a request that a retry would send to the same refusal +OPENCODE_REJECTED = ("provider.auth", "provider.invalid-request", "provider.content-filter", + "provider.unsupported-operation") +OPENCODE_UNFINISHED = ("tool-calls", "length", "error", "content-filter") # a last step's reason that is no answer + + +def _part(event: dict) -> dict: + return event.get("part") if isinstance(event.get("part"), dict) else {} + + +class OpenCode(CliAgent): + """OpenCode (`opencode run --format json`, 2.2). Its home is its HOME and XDG folders (config, data with its + sessions, cache, state), with no update, catalog or download requests. A bound model is the config's provider + `hermit`, its key read by OpenCode from the backend's variable; it runs a model reference only (no login). What + the session must hold is the inline config (OPENCODE_CONFIG_CONTENT), which outranks a workspace's opencode.json: + the provider, the permissions, no sharing or snapshots. The call's tools are an MCP server in the home's config + (OPENCODE_CONFIG), offered directly rather than through code mode. Whether the session failed, and whether its + provider could not serve, is read from its own error event (`outcome`).""" + name = backend = program = "opencode" + label = "OpenCode" + home_var, user_folder = "XDG_DATA_HOME", ".local/share" + home_files = ("auth.json",) # its sign-in (under XDG_DATA_HOME/opencode), never copied: _sign_in + turn_done = "step_finish" + + def home_env(self, home): + """Every variable OpenCode reads goes here, so that it passes the sandbox's filter: its HOME and XDG folders, + its two configs (the home's file, the inline one), no update, catalog or download requests.""" + return {"HOME": str(home), "XDG_CONFIG_HOME": str(home / "config"), "XDG_DATA_HOME": str(home / "data"), + "XDG_CACHE_HOME": str(home / "cache"), "XDG_STATE_HOME": str(home / "state"), + "OPENCODE_CONFIG": str(home / "opencode.json"), + "OPENCODE_CONFIG_CONTENT": json.dumps(self._held(home), ensure_ascii=False), **OPENCODE_ENV} + + def dropped_env(self): + """The caller's own OpenCode settings (another config, database, permission set or search): the session has + only its home's. And the caller's PWD: OpenCode works in the directory PWD names, before the one it is started + in (the workspace).""" + return ("PWD", *(k for k in os.environ if k.startswith("OPENCODE_"))) + + @classmethod + def user_home(cls) -> Path: + return Path(os.environ.get("XDG_DATA_HOME") or Path.home() / cls.user_folder) / "opencode" + + def _sign_in(self, home): + """None: OpenCode runs a model reference, its key read from the backend's variable.""" + s = self.settings + if s.get("login"): + raise Unsupported("opencode takes no login: its model is a / reference") + if not s.get("provider") or not s.get("model"): + raise Unsupported("opencode runs a / reference (agent.model or evolver.model): it signs " + "in no other way") + return [] + + def _held(self, home: Path) -> dict: + """The inline config: the bound model (its reasoning effort), no other provider, the permissions, no update + check, sharing or snapshots, and the call's system instructions (a file in the home, named by its path, which + a sandbox spells as it is inside, as it does every variable).""" + s = self.settings + provider = json.loads(json.dumps(s.get("provider") or {})) + if s.get("effort") and s["effort"] != "off": + for entry in (provider.get("models") or {}).values(): + if isinstance(entry, dict): + entry.setdefault("options", {})["reasoningEffort"] = s["effort"] + ref = f"{OPENCODE_PROVIDER}/{s.get('model') or ''}" + return {"provider": {OPENCODE_PROVIDER: provider}, "model": ref, "small_model": ref, + "enabled_providers": [OPENCODE_PROVIDER], "autoupdate": False, "share": "disabled", "snapshot": False, + "permission": {"*": "allow", "external_directory": "allow", "doom_loop": "allow", + **{tool: "deny" for tool in OPENCODE_DENIED}}, + **({"instructions": [str(home / "system.md")]} if s.get("append_system_prompt") else {})} + + def prepare_home(self, home, roles, tools_url, tools_name): + """The home's config (the call's tools, offered directly, with Codex's tool_timeout_sec rather than + OpenCode's 30 s: a Trainer tool runs rollouts) and the system instructions' file. No host path is written in + them: a sandbox translates only the command, the environment and the prompt.""" + if roles: + raise Unsupported("opencode takes no roles: an adapter's roles stay files its AGENTS.md names") + servers = {tools_name: {"type": "remote", "url": tools_url, "codemode": False, + "timeout": {"execution": 1800 * 1000}}} if tools_url else {} + _clear(home / "opencode.json") + (home / "opencode.json").write_text(json.dumps({"mcp": {"servers": servers}}, indent=1)) + _clear(home / "system.md") + (home / "system.md").unlink(missing_ok=True) + if self.settings.get("append_system_prompt"): + (home / "system.md").write_text(str(self.settings["append_system_prompt"])) + + @classmethod + def web_search_args(cls, enabled: bool) -> list[str]: + """OpenCode's web search and fetch reach the network past the run's sandbox: off is the only setting.""" + if enabled: + raise Unsupported("opencode has no web search here: set web_search to false") + return [] + + def system_settings(self, system, prompt): + return {"append_system_prompt": system}, prompt + + def on_stdin(self): + return False # the prompt is an argument, after `--` + + @classmethod + def _finish(cls, objects) -> str | None: + finishes = [e for e in objects if e.get("type") == cls.turn_done] + return _part(finishes[-1]).get("reason") if finishes else None + + @classmethod + def served(cls, raw): + """A request ended the session with an answer, and OpenCode reported no error.""" + objects = _objects(raw)[0] + return not any(e.get("type") == "error" for e in objects) and \ + cls._finish(objects) not in (None, *OPENCODE_UNFINISHED) + + @classmethod + def errors(cls, event): + """The error a session ended with (its retries are `retry` events).""" + if event.get("type") != "error": + return [] + error = event.get("error") if isinstance(event.get("error"), dict) else {} + return [": ".join(str(x) for x in (error.get("type"), error.get("message")) if x) or "the session failed"] + + def outcome(self, raw, stream, last_file): + """From OpenCode's own error event: its `type` (provider.rate-limit, provider.internal, provider.transport, + provider.timeout: a provider that could not serve) and the HTTP status, never its wording.""" + objects = _objects(raw)[0] + notes, done = self.notices(raw), self.served(raw) + error = next((e["error"] for e in reversed(objects) + if e.get("type") == "error" and isinstance(e.get("error"), dict)), {}) + kind, status = str(error.get("type") or ""), error.get("status") + status = status if isinstance(status, int) else None + busy = not done and (kind in OPENCODE_OUTAGES or status == 429 or (status or 0) >= 500) + cut = self._finish(objects) == "length" + return {"reply": self.last_message(stream, last_file), "served": done, "unavailable": busy, + "refused": False, "failed": not done, + "rejected": not done and not busy and (kind in OPENCODE_REJECTED or status in (400, 401, 403, 404)), + "finish_reason": "stop" if done else ("length" if cut else None), + "failure": "" if done else (notes or ("the reply was cut at its output limit" if cut else + "the session ended without an answer"))[-600:]} + + def adjust_usage(self, home, handle, usage, resumed): + """A bound model's cost is left to its price (price_usage): OpenCode counts a model whose config gives no + cost as free.""" + if self.settings.get("binding") or self.settings.get("provider"): + for u in usage: + u.cost_usd = None + return usage + + @classmethod + def last_message(cls, log, last=None): + """The text of the last message that has any.""" + texts, current = [], None + for event in events(log): + if event.get("type") == "text": + part = _part(event) + if part.get("messageID") != current: + texts, current = [], part.get("messageID") + texts.append(str(part.get("text") or "")) + return "".join(texts) + + @classmethod + def parse(cls, log, model): + return parse_opencode(log, model) + + @classmethod + def steps(cls, stream): + return opencode_steps(stream) + + def command(self, prompt, workspace, last_file, *, session=None, roles=(), tools_url=None): + """`--standalone`: a server of the session's own, never OpenCode's background service, which other sessions + (other homes, other workspaces) would share. `--title` names the session, so no request is spent on a title; + `--thinking` keeps the model's reasoning in the stream. A session handle that is no OpenCode session id + starts a new session.""" + s = self.settings + resume = str(session) if session and re.fullmatch(r"ses_[A-Za-z0-9]+", str(session)) else None + return [str(s.get("bin") or self.program), "run", "--standalone", "--format", "json", + "-m", f"{OPENCODE_PROVIDER}/{s.get('model') or ''}", "--title", "hermit", "--thinking", + *self.web_search_args(bool(s.get("web_search"))), + *(["--session", resume] if resume else []), *(s.get("args") or []), "--", prompt] + + # Every CLI Base Agent, by each name make() takes for it. -CLIS: dict[str, type[CliAgent]] = {n: c for c in (Codex, Claude, Pi) for n in (c.backend, *c.aliases)} +CLIS: dict[str, type[CliAgent]] = {n: c for c in (Codex, Claude, Pi, OpenCode) for n in (c.backend, *c.aliases)} def _this_call(home: Path, handle: str, reported, resumed: bool): diff --git a/hermit/agent/base/login.py b/hermit/agent/base/login.py index e6141a77..a25f12f0 100644 --- a/hermit/agent/base/login.py +++ b/hermit/agent/base/login.py @@ -36,6 +36,7 @@ import time LOGINS = {"chatgpt": "codex", "claude": "claude"} # a `login`: the CLI it signs in +NO_LOGIN = ("pi", "opencode") # the CLIs that sign in only through a / reference FILE = "auth.json" ROOT = Path.home() / ".cache" / "hermit" / "codex-login" # the shared copy: ROOT/login/auth.json TOKEN_ENV = "CLAUDE_CODE_OAUTH_TOKEN" # the token of `claude setup-token`, the user's to export @@ -612,9 +613,9 @@ def evolver_problems(params: dict | None) -> list[str]: own = LOGINS.get(login) backend = {"claude-code": "claude"}.get(params.get("backend"), params.get("backend")) out = [] - if backend == "pi": - out.append(f"login: {login} is a Codex or Claude Code sign-in; the pi Evolver signs in through its model " - "reference (evolver.model: /)") + if backend in NO_LOGIN: + out.append(f"login: {login} is a Codex or Claude Code sign-in; the {backend} Evolver signs in through its " + "model reference (evolver.model: /)") if own is not None and backend in ("codex", "claude") and own != backend: out.append(f"login: {login} is {'Codex' if own == 'codex' else 'Claude Code'}'s sign-in; the Evolver's " f"sessions run {'Codex' if backend == 'codex' else 'Claude Code'}, which takes login: " diff --git a/hermit/agent/base/records.py b/hermit/agent/base/records.py index 225360d0..1865c185 100644 --- a/hermit/agent/base/records.py +++ b/hermit/agent/base/records.py @@ -124,6 +124,33 @@ def parse_pi(log: Path, model: str) -> tuple[str | None, list[Usage]]: return _parse(log, model, _pi_event) +def _opencode_event(event: dict, usage: Usage, session): + """OpenCode: the session id every event carries, and each model request's usage as its `step_finish` keeps it. + OpenCode's `input` leaves the cache out and its `output` the reasoning, so the input counted is input, cache + reads and cache writes and the output is output and reasoning, as Codex and Claude Code count them; its cost is + OpenCode's own (for a bound model, OpenCode.adjust_usage leaves it to the price). A request that failed has no + `step_finish` (its retries are `retry` events) and counts as no call.""" + session = session or event.get("sessionID") + part = event.get("part") if isinstance(event.get("part"), dict) else {} + if event.get("type") != "step_finish" or not isinstance(part.get("tokens"), dict): + return session + t = part["tokens"] + cache = t.get("cache") if isinstance(t.get("cache"), dict) else {} + cached = int(cache.get("read") or 0) + usage.input_tokens += int(t.get("input") or 0) + cached + int(cache.get("write") or 0) + usage.cached_input_tokens += cached + usage.output_tokens += int(t.get("output") or 0) + int(t.get("reasoning") or 0) + usage.calls += 1 + if isinstance(part.get("cost"), (int, float)): + usage.cost_usd = (usage.cost_usd or 0.0) + float(part["cost"]) + return session + + +def parse_opencode(log: Path, model: str) -> tuple[str | None, list[Usage]]: + """OpenCode's `run --format json` events: the session id, and every model request's usage and cost.""" + return _parse(log, model, _opencode_event) + + def parse_codex(log: Path, model: str) -> tuple[str | None, list[Usage]]: """Codex's `exec --json` events: the thread id, and each completed turn's usage.""" return _parse(log, model, _codex_event) diff --git a/hermit/agent/base/trajectory.py b/hermit/agent/base/trajectory.py index 8cb731df..12574d65 100644 --- a/hermit/agent/base/trajectory.py +++ b/hermit/agent/base/trajectory.py @@ -9,8 +9,8 @@ text(steps, message=1200, output=600) # one line per step, each field clipped from its start The streams read: Codex's `codex exec --json` events (`agent-codex.jsonl`), Claude Code's stream-json -(`agent-claude.jsonl`) and Pi's `--mode json` events (`agent-pi.jsonl`), also under another name below a log -directory (Harbor's `agent/codex.txt`). A normalised +(`agent-claude.jsonl`), Pi's `--mode json` events (`agent-pi.jsonl`) and OpenCode's `run --format json` events +(`agent-opencode.jsonl`), also under another name below a log directory (Harbor's `agent/codex.txt`). A normalised message list (`RunOutput.messages`) is the pipeline's own rendering and is left to each Evolver. """ from __future__ import annotations @@ -22,7 +22,9 @@ CODEX_STREAM = "agent-codex.jsonl" CLAUDE_STREAM = "agent-claude.jsonl" PI_STREAM = "agent-pi.jsonl" -STREAM_HOSTS = {CODEX_STREAM: "codex", CLAUDE_STREAM: "claude", PI_STREAM: "pi"} # the file a host's log keeps +OPENCODE_STREAM = "agent-opencode.jsonl" +STREAM_HOSTS = {CODEX_STREAM: "codex", CLAUDE_STREAM: "claude", PI_STREAM: "pi", # the file a host's log keeps + OPENCODE_STREAM: "opencode"} STREAMS = tuple(STREAM_HOSTS) OTHER_STREAMS = ("agent/codex.txt", "codex.txt") # a Harbor trial's Codex events: from the trial or its agent/ @@ -213,12 +215,58 @@ def pi_steps(stream: list[dict]) -> list[Step]: return steps +OPENCODE_SHELL = ("shell", "bash") # 2.x names it shell, 1.x bash +OPENCODE_FILE_TOOLS = ("edit", "write", "apply_patch", "patch", "multiedit") + + +def opencode_steps(stream: list[dict]) -> list[Step]: + """OpenCode's `run --format json` events, each a finished part: text as a message, reasoning as reasoning, a tool + part (its call and its result together) as a command (the shell, with its exit code and output), a file change + (its tool and path) or a tool call (any other tool, an MCP server's included, named `_`, with + its input and its result as `output`); an `error` event as an error. Step boundaries, retries and usage are left + out.""" + steps = [] + for event in stream: + kind = event.get("type") + part = event.get("part") if isinstance(event.get("part"), dict) else {} + if kind == "text" and str(part.get("text") or "").strip(): + steps.append(Step("message", str(part["text"]))) + elif kind == "reasoning" and str(part.get("text") or "").strip(): + steps.append(Step("reasoning", str(part["text"]))) + elif kind == "tool_use": + name = str(part.get("tool") or "") + state = part.get("state") if isinstance(part.get("state"), dict) else {} + args = state.get("input") if isinstance(state.get("input"), dict) else {} + failed = state.get("status") == "error" + output = str(state.get("error") if failed else state.get("output") or "") + if name in OPENCODE_SHELL: + meta = (state.get("metadata") or {}).get("metadata") if isinstance(state.get("metadata"), dict) \ + else None + code = meta.get("exit") if isinstance(meta, dict) else None + # a call refused or stopped before it ran has no exit code: unknown, as Codex reports it + steps.append(Step("command", command=str(args.get("command") or ""), output=output, + exit_code=code if isinstance(code, int) and not failed else None)) + elif name in OPENCODE_FILE_TOOLS: + steps.append(Step("file_change", json.dumps({"tool": name, "path": args.get("path") or + args.get("filePath")}, ensure_ascii=False, default=str), + output=output if failed else "")) + else: + steps.append(Step("tool_call", json.dumps({"tool": name, "input": args}, ensure_ascii=False, + default=str), output=output)) + elif kind == "error": + error = event.get("error") if isinstance(event.get("error"), dict) else {} + steps.append(Step("error", ": ".join(str(x) for x in (error.get("type"), error.get("message")) if x) + or "the session failed")) + return steps + + # Each host's stream: the reader of its events, and the event types that mark it (tried in this order when a stream # is found by its events). A host's stream is added here and in STREAM_HOSTS. -READERS = {"codex": codex_steps, "claude": claude_steps, "pi": pi_steps} +READERS = {"codex": codex_steps, "claude": claude_steps, "pi": pi_steps, "opencode": opencode_steps} MARKS = (("codex", {"thread.started", "turn.started", "turn.completed", "turn.failed", "item.completed"}), ("claude", {"system", "assistant", "user", "result"}), - ("pi", {"agent_start", "agent_settled", "message_end", "tool_execution_end"})) + ("pi", {"agent_start", "agent_settled", "message_end", "tool_execution_end"}), + ("opencode", {"step_start", "step_finish", "tool_use"})) def _host(stream: list[dict]) -> str | None: diff --git a/hermit/agent/evolver/agent.py b/hermit/agent/evolver/agent.py index 9c6595f0..4ddf1033 100644 --- a/hermit/agent/evolver/agent.py +++ b/hermit/agent/evolver/agent.py @@ -1,13 +1,14 @@ -"""AgentEvolver: a built-in agent (Codex, Claude Code or Pi) run on the workspace with a prompt; CommandEvolver: any -program. +"""AgentEvolver: a built-in agent (Codex, Claude Code, Pi or OpenCode) run on the workspace with a prompt; +CommandEvolver: any program. AgentEvolver params: - backend: codex | claude | pi + backend: codex | claude | pi | opencode model: the model passed to the agent (optional: the agent's default); with `login`, the CLI's model name on the user's subscription (hermit.agent.base.login: `chatgpt` for Codex, `claude` for Claude Code). A `/` reference (see hermit.agent.model.backends) binds it to that backend: the provider settings go into `args` (Codex), `env` - (Claude Code) or `provider` (Pi's models.json entry) and `price` is taken from the backend + (Claude Code) or `provider` (Pi's models.json entry, OpenCode's config provider) and `price` is taken from the + backend login, plan_dir, plan_max_wait_s, plan_rerun, usage_credits: the CLI's subscription and its plan (hermit.agent.base.cli, hermit.agent.base.login; claude: the token in CLAUDE_CODE_OAUTH_TOKEN) env: environment variables set for the agent; a `$NAME` value is expanded from the environment at launch (Claude @@ -22,9 +23,10 @@ tools: the only Trainer tools the agent may use (for example [check_spec]); null: all of them. With a list, the task message names no endpoint URL either web_search: the CLI's web search, true or false -This is Layer 3 over the `codex`, `claude` or `pi` Base Agent (docs/framework/agent-layers.md): it fills the prompt, -picks the Trainer's tools and resumes the last session; the Base Agent runs the CLI in the run's evolver sandbox (the -workspace under /w, the paths in the prompt relative to it), with the tools as one MCP server (`evolver_tools`). +This is Layer 3 over the `codex`, `claude`, `pi` or `opencode` Base Agent (docs/framework/agent-layers.md): it fills +the prompt, picks the Trainer's tools and resumes the last session; the Base Agent runs the CLI in the run's evolver +sandbox (the workspace under /w, the paths in the prompt relative to it), with the tools as one MCP server +(`evolver_tools`). """ from __future__ import annotations @@ -78,7 +80,7 @@ class AgentEvolver(Evolver): def step(self, ctx: StepContext) -> StepResult: params = ctx.params backend = params.get("backend", "codex") - if backend not in ("codex", "claude", "pi"): + if backend not in ("codex", "claude", "pi", "opencode"): return StepResult("failed", f"unknown backend {backend!r}") if not isinstance(params.get("web_search"), bool): return StepResult("failed", "evolver.params.web_search must be set, true or false") diff --git a/hermit/agent/evolver/methods/opencode/RESUME.md b/hermit/agent/evolver/methods/opencode/RESUME.md new file mode 100644 index 00000000..08d6fc0b --- /dev/null +++ b/hermit/agent/evolver/methods/opencode/RESUME.md @@ -0,0 +1,4 @@ +A new step. {message} +Read {learning_material}/current/ (the rollouts of the adapter you handed back last time, and check_feedback.json if +the Trainer had to repair it), then improve {adapter} again as before: change only the adapter, call `check_spec`, +and write {output}/report.md (first line: what you changed and why). diff --git a/hermit/agent/evolver/methods/opencode/START.md b/hermit/agent/evolver/methods/opencode/START.md new file mode 100644 index 00000000..5560934e --- /dev/null +++ b/hermit/agent/evolver/methods/opencode/START.md @@ -0,0 +1,15 @@ +You are improving a harness adapter: the files an acting agent receives (context, tools, skills) when it works on a +task. Your job in this call is to change the adapter so the acting agent does better on tasks like the ones in the +learning material, within the adapter's specification. + +{message} +How to work: +1. Read the task description ({task_info}/README.md) and the adapter's guide ({adapter}/.hermit/EVOLVER.md): it says which + files you may change and in what format. +2. Read the learning material of this step ({learning_material}/current/): each task's input, the agent's output, the + judge's score and feedback, and the full trajectory. Earlier steps are next to it; index.jsonl shows the trend. +3. Decide what to change, and change only files in {adapter}. Keep what still helps; generalise from the material + instead of writing down facts about individual tasks. +4. Call the `check_spec` tool before you finish; fix what it reports. +5. Write {output}/report.md: first line one sentence on what you changed and why, then the details. +You may keep notes for later calls in {state}. Do not touch anything else. diff --git a/hermit/agent/evolver/methods/opencode/evolver.yaml b/hermit/agent/evolver/methods/opencode/evolver.yaml new file mode 100644 index 00000000..4d5a9ad5 --- /dev/null +++ b/hermit/agent/evolver/methods/opencode/evolver.yaml @@ -0,0 +1,13 @@ +description: An OpenCode agent improves the adapter from the step's learning material. +class: hermit.agent.evolver.agent:AgentEvolver +needs: [] +params: + backend: opencode + prompt: START.md + resume_prompt: RESUME.md + args: [] + model: null # a / reference (OpenCode's config provider, the key from its variable) + price: null # USD per million tokens {input, cached_input, output}; null: the backend's + home: [] # no file of OpenCode's data folder is copied: it signs in through the model reference + tools: null # the only Trainer tools the agent may use, e.g. [check_spec]; null: all + web_search: false # OpenCode's web search and fetch are off: false is its only setting diff --git a/hermit/agent/model/backends.py b/hermit/agent/model/backends.py index 78b02ce8..a0a9d00a 100644 --- a/hermit/agent/model/backends.py +++ b/hermit/agent/model/backends.py @@ -61,9 +61,12 @@ def user_file() -> Path: "context_window", "developer_role", "models", "description"} DEVELOPER_ROLES = ("keep", "system") # What each consumer speaks: the dialect a backend must serve for it. -NEEDS = {"chat": "chat", "react": "chat", "llm": "chat", "codex": "responses", "claude": "messages", "pi": "chat"} +NEEDS = {"chat": "chat", "react": "chat", "llm": "chat", "codex": "responses", "claude": "messages", "pi": "chat", + "opencode": "chat"} # Pi speaks several dialects: the one it is given is the first the backend serves (Binding.pi_dialect). PI_APIS = {"chat": "openai-completions", "messages": "anthropic-messages", "responses": "openai-responses"} +# OpenCode reaches a bound model through its OpenAI-compatible provider package, which OpenCode 2.2 ships. +OPENCODE_PACKAGE = "@ai-sdk/openai-compatible" # The variable litellm reads the key from, per route prefix (the examples' CL-Bench host calls through litellm). LITELLM_KEY_ENV = {"fireworks_ai": "FIREWORKS_AI_API_KEY", "openai": "OPENAI_API_KEY", "hosted_vllm": "HOSTED_VLLM_API_KEY", "deepseek": "DEEPSEEK_API_KEY", "anthropic": "ANTHROPIC_API_KEY", "ollama": "OLLAMA_API_KEY"} @@ -325,6 +328,20 @@ def pi_provider(self) -> dict: provider["compat"] = {"supportsDeveloperRole": False} # the backend refuses the developer role return provider + def opencode_provider(self) -> dict: + """OpenCode's provider entry for this model (a `provider` value of its config): the backend's chat-completions + URL through OpenCode's OpenAI-compatible package, the key as `{env:VARIABLE}`, which OpenCode reads when it + starts, so no config holds the key (a placeholder for a server that needs none), and the model with its + context window. The cost hermit records follows the price (OpenCode.adjust_usage).""" + key_env = self.key_env_if_set() + model: dict = {"name": self.model} + if self.backend.context_window: + model["limit"] = {"context": int(self.backend.context_window)} + return {"npm": OPENCODE_PACKAGE, "name": "hermit", + "options": {"baseURL": self.base_url.rstrip("/"), + "apiKey": f"{{env:{key_env}}}" if key_env else PLACEHOLDER_KEY}, + "models": {self.model: model}} + CLAUDE_ENV = ("ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY", "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", @@ -396,11 +413,11 @@ def _spec_of(value, binding: Binding) -> dict: def bind_agent_params(params: dict, kind: str, backends: dict[str, Backend], default=None) -> dict: - """The params of a Codex (`kind` codex), Claude Code (`kind` claude) or Pi (`kind` pi) agent or Evolver with its - model bound: `model` becomes the id the endpoint expects, the provider settings go into `args` (Codex), `env` - (Claude Code) ahead of the user's own, or `provider` (Pi's models.json entry), `price` is filled from the - backend, and `binding` records the whole. A `model` that is no reference (the CLI's own provider) is left - alone.""" + """The params of a Codex (`kind` codex), Claude Code (`kind` claude), Pi (`kind` pi) or OpenCode (`kind` + opencode) agent or Evolver with its model bound: `model` becomes the id the endpoint expects, the provider + settings go into `args` (Codex), `env` (Claude Code) ahead of the user's own, or `provider` (Pi's models.json + entry, OpenCode's config provider), `price` is filled from the backend, and `binding` records the whole. A + `model` that is no reference (the CLI's own provider) is left alone.""" binding = as_binding(params.get("model") or default, backends) if binding is None: return params @@ -412,6 +429,8 @@ def bind_agent_params(params: dict, kind: str, backends: dict[str, Backend], def out["env"] = {**binding.claude_env(), **(params.get("env") or {})} elif kind == "pi": out["provider"] = params.get("provider") or binding.pi_provider() + elif kind == "opencode": + out["provider"] = params.get("provider") or binding.opencode_provider() else: raise ValueError(f"kind must be one of {CLI_KINDS}, not {kind!r}") if not out.get("price"): @@ -422,8 +441,9 @@ def bind_agent_params(params: dict, kind: str, backends: dict[str, Backend], def # ---- the run config ------------------------------------------------------------------------------------------- -CLI_AGENTS = {"codex": "codex", "claude-code": "claude", "claude": "claude", "pi": "pi", "cli": None} -CLI_KINDS = ("codex", "claude", "pi") # the CLI Base Agents a model is bound for (bind_agent_params) +CLI_AGENTS = {"codex": "codex", "claude-code": "claude", "claude": "claude", "pi": "pi", "opencode": "opencode", + "cli": None} +CLI_KINDS = ("codex", "claude", "pi", "opencode") # the CLI Base Agents a model is bound for (bind_agent_params) def needs(kind: str, binding: Binding) -> str: @@ -432,9 +452,9 @@ def needs(kind: str, binding: Binding) -> str: def _cli_kind(agent: dict, params: dict) -> str: - """codex, claude or pi for an acting agent that is a CLI (by its name, `cli`'s backend, or a task's own agent's - agent.base), else "".""" - names = {"codex": "codex", "claude": "claude", "claude-code": "claude", "pi": "pi"} + """codex, claude, pi or opencode for an acting agent that is a CLI (by its name, `cli`'s backend, or a task's own + agent's agent.base), else "".""" + names = {"codex": "codex", "claude": "claude", "claude-code": "claude", "pi": "pi", "opencode": "opencode"} kind = CLI_AGENTS.get(str(agent.get("name") or ""), "") if kind is None: # `cli`: the backend is a param return names.get(params.get("backend", "codex"), "") diff --git a/hermit/cli.py b/hermit/cli.py index d2e9390f..2ba16a84 100644 --- a/hermit/cli.py +++ b/hermit/cli.py @@ -30,11 +30,12 @@ def main(argv=None) -> int: p.add_argument("--adapter", required=True, help="final | root | none | a tag | a commit | a local path") if name == "check": p.add_argument("--no-probe", action="store_true", help="skip running one task through the pipeline") - dep = sub.add_parser("deploy", help="deploy an adapter's exports into a Codex, Claude Code or Pi workspace") + dep = sub.add_parser("deploy", + help="deploy an adapter's exports into a Codex, Claude Code, Pi or OpenCode workspace") dep.add_argument("--adapter", type=Path, required=True) dep.add_argument("--workspace", "--output", dest="workspace", type=Path, required=True, help="the project directory the agent will work in (--output is the older spelling)") - dep.add_argument("--host", choices=["codex", "claude-code", "pi"], default="codex") + dep.add_argument("--host", choices=["codex", "claude-code", "pi", "opencode"], default="codex") dep.add_argument("--python", default=sys.executable) dep.add_argument("--context-limit", type=int, default=None, help="codex: the project_doc_max_bytes your Codex config sets (default 32768, Codex's own); " @@ -97,6 +98,8 @@ def main(argv=None) -> int: from hermit.hosts.codex import prepare elif args.host == "pi": from hermit.hosts.pi import prepare + elif args.host == "opencode": + from hermit.hosts.opencode import prepare else: from hermit.hosts.claude_code import prepare try: diff --git a/hermit/config.py b/hermit/config.py index 70e65649..5a0da31e 100644 --- a/hermit/config.py +++ b/hermit/config.py @@ -44,10 +44,12 @@ def _merge(base: dict, extra: dict, prefix: str = "") -> dict: FREE = ("params", "llm", "backends", "container", "resources", # sections whose keys the framework does not know - "model", *("codex", "claude", "pi", "react", "direct")) # a layer's settings (docs/framework/agent-layers.md) -BASES = {"codex": "codex", "claude": "claude-code", "claude-code": "claude-code", "pi": "pi", "react": "react", + "model", *("codex", "claude", "pi", "opencode", "react", "direct")) # a layer's settings + # (docs/framework/agent-layers.md) +BASES = {"codex": "codex", "claude": "claude-code", "claude-code": "claude-code", "pi": "pi", "opencode": "opencode", + "react": "react", "direct": None} -CLI_BASES = ("codex", "claude-code", "pi") # the bases that are a CLI (their Layer 1 settings: _model) +CLI_BASES = ("codex", "claude-code", "pi", "opencode") # the bases that are a CLI (their Layer 1 settings: _model) MODEL_KEYS = ("login", "effort", "price") # Layer 1 settings a CLI takes beside its model # A login's plan settings: Layer 2's (agent., evolver.), refused beside the model's name. PLAN_KEYS = {"plan_dir", "plan_max_wait_s", "plan_rerun", "usage_credits", "login_root"} @@ -114,15 +116,16 @@ def layered(data: dict) -> None: agent = data["agent"] base = agent.pop("base", None) model = agent.pop("model", None) - sections = {b: agent.pop(b, None) for b in ("codex", "claude", "pi", "react", "direct")} + sections = {b: agent.pop(b, None) for b in ("codex", "claude", "pi", "opencode", "react", "direct")} if base is None: if model is not None or any(sections.values()): - raise ValueError("agent.model and agent. need agent.base (codex, claude, pi, react or direct)") + raise ValueError("agent.model and agent. need agent.base (codex, claude, pi, opencode, react or " + "direct)") else: if base not in BASES: raise ValueError(f"agent.base must be one of {sorted(BASES)}, not {base!r}") builtin = {"codex": "codex", "claude-code": "claude-code", "claude": "claude-code", "pi": "pi", - "react": "react", "cli": None} + "opencode": "opencode", "react": "react", "cli": None} if not agent.get("name"): if BASES[base] is None: raise ValueError("agent.base: direct needs agent.name (the task's own loop calls it)") @@ -142,13 +145,14 @@ def layered(data: dict) -> None: evolver = data["evolver"] base = evolver.pop("base", None) model = evolver.pop("model", None) - sections = {b: evolver.pop(b, None) for b in ("codex", "claude", "pi", "react", "direct")} + sections = {b: evolver.pop(b, None) for b in ("codex", "claude", "pi", "opencode", "react", "direct")} if base is None: if model is not None or any(sections.values()): - raise ValueError("evolver.model and evolver. need evolver.base (codex, claude, pi or direct)") + raise ValueError("evolver.model and evolver. need evolver.base (codex, claude, pi, opencode or " + "direct)") return - if base not in ("codex", "claude", "claude-code", "pi", "direct"): - raise ValueError(f"evolver.base must be codex, claude, pi or direct, not {base!r}") + if base not in ("codex", "claude", "claude-code", "pi", "opencode", "direct"): + raise ValueError(f"evolver.base must be codex, claude, pi, opencode or direct, not {base!r}") params = dict(evolver.get("params") or {}) if base == "direct": if model is not None: diff --git a/hermit/defaults.yaml b/hermit/defaults.yaml index 04e4243c..60ed53ca 100644 --- a/hermit/defaults.yaml +++ b/hermit/defaults.yaml @@ -9,15 +9,18 @@ data: shuffle_seed: 0 task_info: null agent: - name: null # react | codex | claude-code | pi, or file.py:Class / file.py:function of the task's own + name: null # react | codex | claude-code | pi | opencode, or file.py:Class / file.py:function of the + # task's own concurrency: 4 timeout_min: null # a sandboxed task call that runs longer is stopped and recorded as an error; null: none params: {} # Layer 3: the Acting Agent's own settings (docs/framework/agent-layers.md) - base: null # Layer 2: codex | claude | pi | react | direct; its settings go in a section of its name + base: null # Layer 2: codex | claude | pi | opencode | react | direct; its settings go in a section + # of its name model: null # Layer 1: a / reference, or {ref | name, login, effort, price, ...} codex: null claude: null pi: null + opencode: null react: null direct: null pipeline: # the older spelling of `agent`: run -> name @@ -53,11 +56,12 @@ evolver: name: null resume: false params: {} # Layer 3: the method's settings - base: null # Layer 2: codex | claude | pi | direct (the Base Agent the method runs on) + base: null # Layer 2: codex | claude | pi | opencode | direct (the Base Agent the method runs on) model: null # Layer 1: as agent.model; with direct it is the run's `llm` codex: null claude: null pi: null + opencode: null direct: null evolver_access: environment: [] diff --git a/hermit/hosts/opencode.py b/hermit/hosts/opencode.py new file mode 100644 index 00000000..71a71af9 --- /dev/null +++ b/hermit/hosts/opencode.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Deploy an adapter into an OpenCode workspace: the whole adapter under hermit//, and its exports connected to +OpenCode's own places: AGENTS.md context, opencode.json tools, .opencode/skills. + +OpenCode reads AGENTS.md from the working directory (and its parents, up to a Git repository's root) and the +project's opencode.json and .opencode/ with no trust step. The tools are a local MCP server declared with `codemode: +false`, so the model is offered them as tools, not only through OpenCode's code mode (its default). OpenCode takes no +roles here and reads no hook file: an adapter's roles and hooks stay files of its copy, which AGENTS.md names with +what to do with them (hermit.hosts.inputs.resources), as it names the other files. Global OpenCode settings +(~/.config/opencode) are never changed. +""" +import argparse +import json +from pathlib import Path +import subprocess +import sys + +from hermit.adapter.loader import agent_tools, hook_definitions, load_manifest, not_portable +from hermit.hosts.context import PROJECT_CONTEXT, START, append_context +from hermit.hosts.inputs import (MARKER, PACKAGE_ROOT, adapter_files, adapter_folder, check_workspace, copy_adapter, + copy_skills, folder_note, render_exports, resources, server_name, source_label) + +NATIVE = {"skills"} +TOOL_TIMEOUT_MS = 120 * 1000 # Codex's tool_timeout_sec, not OpenCode's 30 s + + +def prepare(adapter: Path, output: Path, python: str, *, learning_material: Path | None = None, + context: str | None = None) -> dict: + """`context`: the adapter's context for one task, which the harness computed, in place of the one rendered + here; an adapter whose context is per task deploys only so.""" + adapter, output = adapter.resolve(), output.resolve() + refused = not_portable(load_manifest(adapter), "An OpenCode workspace") # before anything is written + if refused and context is None: + raise ValueError(refused) + previous = check_workspace(adapter, output, "opencode") + manifest = load_manifest(adapter) + files = adapter_files(adapter, output, manifest, previous) + exports = render_exports(adapter, python) + listed, placed = resources(adapter, output, manifest, exports, hook_definitions(adapter, manifest), NATIVE) + has_tools = bool(agent_tools(manifest)) # the context tool is the harness's, not served + if has_tools: + subprocess.run([python, "-c", "import mcp.server"], check=True, capture_output=True) + output.mkdir(parents=True, exist_ok=True) + context_path = output / "AGENTS.md" + existing = context_path.read_text() if context_path.exists() else PROJECT_CONTEXT + if existing.startswith(START): + existing = PROJECT_CONTEXT + "\n\n" + existing + context_text = append_context(existing, "\n\n".join(t for t in ( + folder_note(output, manifest), + exports["context"] if context is None else context, listed) if t), + source=source_label(manifest), + version=manifest["version"], adapter_id=manifest["id"]) + audit = output / "tool-calls.jsonl" + server = None + if has_tools: + server = {"type": "local", "codemode": False, "timeout": {"execution": TOOL_TIMEOUT_MS}, + "command": [python, "-m", "hermit.runtime.mcp_server", "--adapter", str(adapter), + "--audit-log", str(audit)], + "environment": {"PYTHONPATH": PACKAGE_ROOT}} + if learning_material is not None: + server["command"].extend(["--learning-material", str(Path(learning_material).resolve())]) + servers = {server_name(manifest): server} if has_tools else {} + (output / "opencode.json").write_text(json.dumps({"mcp": {"servers": servers}}, indent=2) + "\n") + context_path.write_text(context_text) + skills = copy_skills(adapter, manifest, output / ".opencode" / "skills") + copy_adapter(adapter, output, manifest, files, previous) + result = {"host": "opencode", "adapter_id": manifest["id"], "version": manifest["version"], + "adapter": str(adapter), "workspace": str(output), "context_injected_via": "AGENTS.md", + "server_name": server_name(manifest) if has_tools else None, "server": server, "roles": {}, + "role_name_map": {}, "skills_dir": str(output / ".opencode" / "skills") if skills else None, + "skills": skills, "hooks": None, "audit_log": str(audit) if has_tools else None, + "adapter_dir": str(adapter_folder(output, manifest)), "files": files, "placed": placed} + (output / MARKER).write_text(json.dumps(result, indent=2) + "\n") + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--adapter", type=Path, required=True) + parser.add_argument("--workspace", "--output", dest="workspace", type=Path, required=True) + parser.add_argument("--python", default=sys.executable) + args = parser.parse_args() + print(json.dumps(prepare(args.adapter, args.workspace, str(Path(args.python).absolute())), indent=2)) diff --git a/hermit/isolate.py b/hermit/isolate.py index 293d5c98..68f49296 100644 --- a/hermit/isolate.py +++ b/hermit/isolate.py @@ -165,8 +165,8 @@ def validate(config) -> None: login = params.get("login") if kind and login: # wherever the pipeline runs: else every session would be refused, one task at a time own = codex_login.LOGINS.get(login) - if kind == "pi": - raise ValueError("agent pi takes no login: its model is a / reference (agent.model)") + if kind in codex_login.NO_LOGIN: + raise ValueError(f"agent {kind} takes no login: its model is a / reference (agent.model)") if own is None: raise ValueError(f"agent.params.login is {' or '.join(sorted(codex_login.LOGINS))} or absent, not " f"{login!r}") diff --git a/tests/README.md b/tests/README.md index 4cbeb802..006c783f 100644 --- a/tests/README.md +++ b/tests/README.md @@ -34,8 +34,8 @@ Shared helpers: the repository root's `conftest.py` (the options and the groups) ChatGPT-login directory and Claude plan for every test, and no copy of the user's own sign-in), `fakes.py` (scripted models), `toy_task.py` (the toy task the Trainer tests run on), `claude_stand.py` (the stand-in `claude` that replays `fixtures/claude_streams/`, and the probe for a working bubblewrap, for core's and the methods' Claude tests), -`fixtures/` (`pi/`: Pi's recorded streams, read by -`core/test_pi_agent.py`). +`fixtures/` (`pi/`: Pi's recorded streams, read by `core/test_pi_agent.py`; `opencode/`: OpenCode's, read by +`core/test_opencode_agent.py`). A new or changed test follows the [test checklist](../.agents/skills/prepare-pr/references/test-checklist.md): where it goes, how it is named and documented, what it asserts, and what it may touch. diff --git a/tests/core/test_opencode_agent.py b/tests/core/test_opencode_agent.py new file mode 100644 index 00000000..e5393d07 --- /dev/null +++ b/tests/core/test_opencode_agent.py @@ -0,0 +1,401 @@ +"""The `opencode` Base Agent (hermit/agent/base/cli.py), its model binding (hermit/agent/model/backends.py) and the +Layer 3 code that runs it: the acting agent (hermit/agent/acting/workspace.py) and its deployment +(hermit/hosts/opencode.py), the config's `opencode` base, the `opencode` Evolver. + +Stand-ins: a fake `opencode` on PATH that replays a stream recorded from OpenCode 2.2.6 (tests/fixtures/opencode, +whose README says how) and records what it was given; and, for the tests marked integration, the installed +`opencode` against a scripted chat-completions model on the loopback (`serve_chat`), never a provider.""" +import json +import os +from pathlib import Path +import shutil +import stat +import sys +import threading + +import pytest + +from hermit.agent.base import cli as base_cli +from hermit.agent.base import trajectory +from hermit.agent.base.interface import Unsupported, make +from hermit.agent.base.tool import Tool +from hermit.agent.model.backends import bind_agent_params, registry + +ROOT = Path(__file__).resolve().parents[2] +STREAMS = ROOT / "tests" / "fixtures" / "opencode" +FILE_ADAPTER = ROOT / "docs" / "_examples" / "file_adapter" +SESSION = "ses_e40d3f481ffePQb8uaj39iK60v" # the recorded success stream's session +OUTAGES = ("failure_500.jsonl", "failure_429.jsonl", "failure_refused.jsonl") + +FAKE_OPENCODE = f'''#!{sys.executable} +"""A stand-in for `opencode run --format json ...`: records its arguments, OpenCode's variables, its home's files and +its stdin, then prints FAKE_OPENCODE_STREAM and exits FAKE_OPENCODE_EXIT.""" +import json, os, sys +from pathlib import Path +home = Path(os.environ["OPENCODE_CONFIG"]).parent +files = {{p.name: p.read_text() for p in sorted(home.iterdir()) if p.is_file() and p.suffix in (".json", ".md")}} +seen = {{"args": sys.argv[1:], "env": {{k: v for k, v in os.environ.items() + if k.startswith(("OPENCODE_", "XDG_")) or k in ("HOME", "PWD", "FAKE_KEY")}}, + "files": files, "stdin": sys.stdin.read()}} +with open(os.environ["FAKE_OPENCODE_SEEN"], "a") as f: + f.write(json.dumps(seen) + "\\n") +sys.stdout.write(Path(os.environ["FAKE_OPENCODE_STREAM"]).read_text()) +sys.exit(int(os.environ.get("FAKE_OPENCODE_EXIT", "0"))) +''' + + +@pytest.fixture +def fake(tmp_path, monkeypatch): + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + exe = bin_dir / "opencode" + exe.write_text(FAKE_OPENCODE) + exe.chmod(exe.stat().st_mode | stat.S_IEXEC) + monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ['PATH']}") + monkeypatch.setenv("FAKE_OPENCODE_SEEN", str(tmp_path / "seen.jsonl")) + monkeypatch.setenv("FAKE_OPENCODE_STREAM", str(STREAMS / "success.jsonl")) + monkeypatch.setenv("FAKE_KEY", "sk-fake") + return tmp_path + + +def replay(monkeypatch, name: str, code: int = 0) -> None: + monkeypatch.setenv("FAKE_OPENCODE_STREAM", str(STREAMS / name)) + monkeypatch.setenv("FAKE_OPENCODE_EXIT", str(code)) + + +def seen(tmp_path) -> list[dict]: + return [json.loads(line) for line in (tmp_path / "seen.jsonl").read_text().splitlines()] + + +def bound(**backend) -> dict: + """An `opencode` agent's params with its model bound to a backend of its own (`fake/m-1`).""" + spec = {"base_url": "http://127.0.0.1:9/v1/", "api_key_env": "FAKE_KEY", "apis": ["chat"], + "prices": {"m-1": {"input": 1.0, "cached_input": 0.1, "output": 2.0}}, **backend} + return bind_agent_params({"model": "fake/m-1"}, "opencode", registry({"fake": spec})) + + +def agent(fake, **settings): + return make("opencode", {**bound(), "web_search": False, "home": str(fake / "home"), **settings}) + + +def echo() -> Tool: + return Tool("echo", "Echo the text back.", lambda text="": {"echoed": text}, + input_schema={"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}) + + +def test_a_bound_model_is_opencodes_provider_with_its_key_as_a_variable(): + """The key reaches OpenCode only as `{env:VARIABLE}` (the records keep its name, never the key).""" + params = bound() + assert params["model"] == "m-1" and params["binding"]["ref"] == "fake/m-1" + assert params["provider"] == {"npm": "@ai-sdk/openai-compatible", "name": "hermit", + "options": {"baseURL": "http://127.0.0.1:9/v1", "apiKey": "{env:FAKE_KEY}"}, + "models": {"m-1": {"name": "m-1"}}} + assert bound(context_window=32000)["provider"]["models"]["m-1"]["limit"] == {"context": 32000} + free = bound(api_key_env="NO_SUCH_KEY_VAR", key_required=False)["provider"] + assert free["options"]["apiKey"] == "local" # a server that needs no key gets the placeholder + + +def test_opencode_runs_in_its_home_with_its_model_held_and_the_tools_offered_directly(fake, monkeypatch): + """What the session must hold (the provider, the permissions, no sharing) is the inline config, which outranks a + workspace's opencode.json; the call's tools are the home's config, offered directly; the caller's own OpenCode + settings do not reach the session.""" + monkeypatch.setenv("OPENCODE_CONFIG_DIR", str(fake / "elsewhere")) + monkeypatch.setenv("OPENCODE_PERMISSION", '{"*": "ask"}') + home, work = fake / "home", fake / "work" + work.mkdir() + result = agent(fake, effort="high", log=str(fake / "agent-opencode.jsonl")).run( + "-a prompt that starts with a dash", workspace=work, tools=[echo()]) + [call] = seen(fake) + # a server of its own (never OpenCode's background service, which other sessions would share) + assert call["args"][:7] == ["run", "--standalone", "--format", "json", "-m", "hermit/m-1", "--title"] + assert "--thinking" in call["args"] and call["args"][-2:] == ["--", "-a prompt that starts with a dash"] + env = call["env"] + assert env["HOME"] == str(home) and env["XDG_DATA_HOME"] == str(home / "data") + assert env["OPENCODE_CONFIG"] == str(home / "opencode.json") and env["OPENCODE_DISABLE_AUTOUPDATE"] == "1" + assert "OPENCODE_CONFIG_DIR" not in env and "OPENCODE_PERMISSION" not in env + assert "PWD" not in env # OpenCode works where PWD names, before where it is started + held = json.loads(env["OPENCODE_CONFIG_CONTENT"]) + assert held["model"] == "hermit/m-1" and held["enabled_providers"] == ["hermit"] and held["share"] == "disabled" + assert held["provider"]["hermit"]["options"]["apiKey"] == "{env:FAKE_KEY}" + assert held["provider"]["hermit"]["models"]["m-1"]["options"] == {"reasoningEffort": "high"} + assert {held["permission"][t] for t in ("question", "subagent", "execute", "webfetch", "websearch")} == {"deny"} + assert "sk-fake" not in env["OPENCODE_CONFIG_CONTENT"] + json.dumps(call["files"]) + [(server, entry)] = json.loads(call["files"]["opencode.json"])["mcp"]["servers"].items() + assert server == "hermit_tools" and entry["codemode"] is False and entry["url"].startswith("http://127.0.0.1:") + assert entry["timeout"] == {"execution": 1800000} # a Trainer tool runs longer than OpenCode's 30 s + assert result.reply == "the answer" and result.exit_code == 0 and result.extra["served"] + assert not result.extra["failed"] and result.session == SESSION + [usage] = result.usage + assert (usage.input_tokens, usage.cached_input_tokens, usage.output_tokens, usage.calls) == (4000, 1600, 80, 4) + assert usage.cost_usd == pytest.approx(0.00272) # the price's, not OpenCode's $0 for a custom model + assert [s.kind for s in result.trajectory] == ["command", "tool_call", "file_change", "reasoning", "message"] + command, tool = result.trajectory[0], json.loads(result.trajectory[1].text) + assert (command.command, command.exit_code, command.output) == ("echo hi && exit 3", 3, "hi\n") + assert tool == {"tool": "hermit_tools_echo", "input": {"text": "from opencode"}} + assert json.loads(result.trajectory[1].output) == {"echoed": "from opencode"} + + +@pytest.mark.parametrize("stream", OUTAGES) +def test_a_provider_that_could_not_serve_is_an_outage_read_from_opencodes_own_error(fake, monkeypatch, stream): + """A 5xx, a 429 and a connection that never reached the provider each end in OpenCode's error event, whose + `type` says so: `unavailable` (the acting agent runs the task again), never read from the error's wording.""" + replay(monkeypatch, stream, code=1) + work = fake / "work" + work.mkdir() + result = agent(fake).run("go", workspace=work) + assert result.exit_code == 1 and result.extra["failed"] and not result.extra["served"] + assert result.extra["unavailable"] and not result.extra["rejected"] + assert result.usage == [] and result.trajectory[-1].kind == "error" + + +def test_a_request_the_provider_refuses_is_rejected_not_an_outage(fake, monkeypatch): + """A 401 (a wrong key) fails the same way however often it is sent: no retry.""" + replay(monkeypatch, "failure_401.jsonl", code=1) + work = fake / "work" + work.mkdir() + result = agent(fake).run("go", workspace=work) + assert result.extra["failed"] and result.extra["rejected"] and not result.extra["unavailable"] + assert result.extra["failure"].startswith("provider.auth") + + +def test_the_acting_agent_runs_a_task_again_when_the_provider_could_not_serve_then_reports_an_error(fake, monkeypatch): + """Through the caller that reads `unavailable`: a provider down for every attempt is an error, not an answer.""" + from hermit.agent.acting import workspace as acting + replay(monkeypatch, "failure_500.jsonl", code=1) + params = {**bound(), "backend": "opencode", "web_search": False, "prompt": "go", "workspaces": "ws", + "retries": 2, "retry_wait_s": 0} + with pytest.raises(RuntimeError, match="could not be served after 2 attempts"): + acting.run({"id": "q1"}, None, params=params, base=fake) + assert len(seen(fake)) == 2 + + +def test_a_resumed_session_is_continued_by_its_id_and_counts_only_its_new_usage(fake, monkeypatch): + replay(monkeypatch, "resume.jsonl") + work = fake / "work" + work.mkdir() + opencode = agent(fake) + result = opencode.run("again", workspace=work, session=SESSION) + args = seen(fake)[0]["args"] + assert args[args.index("--session") + 1] == SESSION and result.session == SESSION + [usage] = result.usage + assert (usage.input_tokens, usage.calls) == (1000, 1) + opencode.run("again", workspace=work, session="../not-an-id") # no OpenCode session id: a new session + assert "--session" not in seen(fake)[1]["args"] + + +def test_opencode_runs_only_a_model_reference_and_refuses_roles_web_search_a_login_and_a_container(fake): + """Each is refused before OpenCode starts, never ignored: no sign-in of the user's is ever copied.""" + work = fake / "work" + work.mkdir() + with pytest.raises(Unsupported, match="runs a / reference"): + make("opencode", {"model": "some-model", "web_search": False, "home": str(fake / "home")}).run( + "go", workspace=work) + opencode = agent(fake) + role = {"name": "reviewer", "description": "Review.", "instructions": "Check it."} + with pytest.raises(Unsupported, match="no roles"): + opencode.run("go", workspace=work, roles=[role]) + with pytest.raises(Unsupported, match="no web search"): + opencode.configured(web_search=True).run("go", workspace=work) + with pytest.raises(Unsupported, match="login"): + opencode.configured(login="chatgpt").run("go", workspace=work) + with pytest.raises(Unsupported, match="takes isolation none or sandbox"): + opencode.configured(isolation="container").run("go", workspace=work) + assert not (fake / "seen.jsonl").exists() + from hermit.agent.acting.workspace import _check + with pytest.raises(ValueError, match="agent opencode takes no login"): + _check("opencode", {"login": "chatgpt", "web_search": False}) + + +def test_system_instructions_are_a_file_the_inline_config_names(fake): + """OpenCode has no flag for them: a file in the home, named by its path in the inline config (a variable, which + a sandbox spells as it is inside).""" + work = fake / "work" + work.mkdir() + opencode = agent(fake) + own, prompt = opencode.system_settings("Be exact.", "go") + assert own == {"append_system_prompt": "Be exact."} and prompt == "go" + opencode.configured(**own).run(prompt, workspace=work) + [call] = seen(fake) + assert call["files"]["system.md"] == "Be exact." + assert json.loads(call["env"]["OPENCODE_CONFIG_CONTENT"])["instructions"] == [str(fake / "home" / "system.md")] + + +def test_an_opencode_stream_is_read_back_by_its_name_or_by_its_events(tmp_path): + """The learning material keeps the acting agent's log: an Evolver reads OpenCode's steps from it like Codex's.""" + named = tmp_path / "log" + named.mkdir() + shutil.copy(STREAMS / "success.jsonl", named / trajectory.OPENCODE_STREAM) + other = tmp_path / "events.jsonl" + shutil.copy(STREAMS / "success.jsonl", other) + for log in (named, other): + assert [s.kind for s in trajectory.log_steps(log)] == ["command", "tool_call", "file_change", "reasoning", + "message"] + assert base_cli.served("opencode", (STREAMS / "success.jsonl").read_text()) + raw = (STREAMS / "failure_500.jsonl").read_text() + assert not base_cli.served("opencode", raw) and base_cli.notices("opencode", raw).startswith("provider.internal") + + +def test_the_opencode_acting_agent_deploys_the_adapter_where_opencode_reads_it(fake): + """The adapter's tools are the project's opencode.json, offered directly; its skills are .opencode/skills; its + roles stay files AGENTS.md names, as OpenCode takes none.""" + from hermit.agent.acting import workspace as acting + params = {**bound(), "backend": "opencode", "web_search": False, "prompt": "go", "workspaces": "ws"} + out = acting.run({"id": "q1"}, FILE_ADAPTER, params=params, base=fake) + work = Path(out.extra["workspace"]) + [call] = seen(fake) + assert out.output == "the answer" and out.extra["backend"] == "opencode" and "--approve" not in call["args"] + [server] = json.loads((work / "opencode.json").read_text())["mcp"]["servers"].values() + assert server["type"] == "local" and server["codemode"] is False + assert "hermit.runtime.mcp_server" in server["command"] + assert (work / ".opencode" / "skills" / "verify-output" / "SKILL.md").is_file() + assert "do it yourself" in (work / "AGENTS.md").read_text() + assert (out.log / "agent-opencode.jsonl").is_file() + + +def test_opencode_is_a_base_of_the_config_and_the_opencode_evolver_binds_its_model(): + from hermit.agent.base.login import evolver_problems + from hermit.agent.evolver.loader import find, instantiate + from hermit.config import layered + data = {"agent": {"base": "opencode", "model": {"ref": "fake/m-1", "effort": "high"}, + "opencode": {"timeout_s": 60}, "params": {"prompt": "go"}}, + "evolver": {"name": "opencode", "base": "opencode", "model": "fake/m-1", "params": {}}, "llm": None} + layered(data) + assert data["agent"]["name"] == "opencode" and data["agent"]["params"]["effort"] == "high" + assert data["agent"]["params"]["timeout_s"] == 60 and data["evolver"]["params"]["backend"] == "opencode" + backends = registry({"fake": {"base_url": "http://127.0.0.1:9/v1", "api_key_env": "FAKE_KEY", "apis": ["chat"]}}) + _, params = instantiate(find("opencode", ROOT), data["evolver"]["params"], backends=backends, + default_model="fake/m-1") + assert params["backend"] == "opencode" and params["home"] == [] and params["web_search"] is False + assert params["provider"]["options"]["apiKey"] == "{env:FAKE_KEY}" + assert evolver_problems({"backend": "opencode", "login": "chatgpt"}) + + +# ---------- the installed opencode (integration) ---------- + +def serve_chat(script, status: int | None = None): + """A chat-completions model on the loopback: `script(request body) -> (tool call (name, arguments) | None)`; + None answers `the answer`, with a reasoning text first. Every response is streamed, with usage (1000 prompt + tokens, 400 of them cached; 20 completion tokens). With `status`, every request is answered that error.""" + from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + def chunk(body): + return f"data: {json.dumps(body)}\n\n".encode() + + class Model(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers.get("content-length") or 0)) or b"{}") + if status is not None: + data = json.dumps({"error": {"message": "the model is down", "type": "server_error"}}).encode() + self.send_response(status) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + return + call = script(body) + deltas = [{"role": "assistant", "tool_calls": [{"index": 0, "id": f"call_{len(body['messages'])}", + "type": "function", + "function": {"name": call[0], + "arguments": json.dumps(call[1])}}]}] \ + if call else [{"role": "assistant", "reasoning_content": "The work is done."}, + {"content": "the answer"}] + data = b"".join([*(chunk({"choices": [{"index": 0, "delta": d, "finish_reason": None}]}) for d in deltas), + chunk({"choices": [{"index": 0, "delta": {}, "finish_reason": + "tool_calls" if call else "stop"}]}), + chunk({"choices": [], "usage": {"prompt_tokens": 1000, "completion_tokens": 20, + "prompt_tokens_details": {"cached_tokens": 400}}}), + b"data: [DONE]\n\n"]) + self.send_response(200) + self.send_header("content-type", "text/event-stream") + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + server = ThreadingHTTPServer(("127.0.0.1", 0), Model) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, f"http://127.0.0.1:{server.server_address[1]}/v1" + + +def _bwrap_works() -> bool: + import subprocess + return bool(shutil.which("bwrap")) and subprocess.run( + ["bwrap", "--ro-bind", "/", "/", "--unshare-net", "true"], capture_output=True).returncode == 0 + + +def mock_params(url: str) -> dict: + return bind_agent_params({"model": "mock/m-1"}, "opencode", + registry({"mock": {"base_url": url, "api_key_env": "MOCK_KEY", "apis": ["chat"]}})) + + +@pytest.mark.integration +@pytest.mark.skipif(not shutil.which("opencode"), reason="needs the opencode CLI") +@pytest.mark.parametrize("isolation", ["none", "sandbox"]) +def test_with_the_opencode_cli_a_session_reaches_its_model_and_its_tools(tmp_path, monkeypatch, isolation): + """The installed OpenCode, bound to a scripted model: it calls the call's MCP tool (offered directly), writes a + file, answers; in the run's sandbox (isolated network) only its model and the tool server are reached.""" + from hermit.sandbox import Sandbox + if isolation == "sandbox" and not _bwrap_works(): + pytest.skip("needs a working bubblewrap") + + def script(body): + done = sum(1 for m in body.get("messages") or [] if m.get("role") == "tool") + names = [t["function"]["name"] for t in body.get("tools") or []] + plan = [("hermit_tools_echo", {"text": "hi"}), ("write", {"path": "note.txt", "content": "ok\n"})] + assert plan[0][0] in names # the tool is offered directly, not through code mode + return plan[done] if done < len(plan) else None + + server, url = serve_chat(script) + monkeypatch.setenv("MOCK_KEY", "sk-mock") + (tmp_path / "caller").mkdir() + monkeypatch.setenv("PWD", str(tmp_path / "caller")) # where OpenCode would work if it went by PWD + work = tmp_path / "work" + work.mkdir() + settings = {**mock_params(url), "web_search": False, "home": str(tmp_path / "home"), "isolation": isolation, + "timeout_s": 300} + if isolation == "sandbox": + settings["sandbox"] = Sandbox(network="isolated", env_allow=[], writable=[work], role="agent", + record_dir=tmp_path / "records") + try: + result = make("opencode", settings).run("Do the task.", workspace=work, tools=[echo()]) + finally: + server.shutdown() + assert result.exit_code == 0 and result.extra["served"] and result.reply == "the answer" + assert (work / "note.txt").read_text() == "ok\n" and not any((tmp_path / "caller").iterdir()) + assert [s.kind for s in result.trajectory] == ["tool_call", "file_change", "reasoning", "message"] + assert json.loads(result.trajectory[0].output) == {"echoed": "hi"} + assert result.usage[0].calls == 3 + if isolation == "sandbox": + [record] = (tmp_path / "records").glob("agent-*.json") + data = json.loads(record.read_text()) + assert data["network"] == "isolated" and data["probe"]["passed"] + assert {"OPENCODE_CONFIG_CONTENT", "XDG_DATA_HOME", "MOCK_KEY"} <= set(data["environment"]) + + +@pytest.mark.integration +@pytest.mark.skipif(not shutil.which("opencode"), reason="needs the opencode CLI") +def test_with_the_opencode_cli_the_acting_agent_uses_the_deployed_adapters_tools(tmp_path, monkeypatch): + """The deployment as OpenCode reads it: the project's opencode.json starts the adapter's tool server, whose tool + the model is offered directly and calls.""" + from hermit.agent.acting import workspace as acting + calls = [] + + def script(body): + names = [t["function"]["name"] for t in body.get("tools") or []] + done = any(m.get("role") == "tool" for m in body.get("messages") or []) + calls.append(names) + return None if done else ("file_example_count_words", {"text": "a b c"}) + + server, url = serve_chat(script) + monkeypatch.setenv("MOCK_KEY", "sk-mock") + try: + out = acting.run({"id": "q1"}, FILE_ADAPTER, base=tmp_path, + params={**mock_params(url), "backend": "opencode", "web_search": False, "prompt": "Count.", + "workspaces": "ws", "timeout_s": 300, "retries": 1}) + finally: + server.shutdown() + assert out.output == "the answer" and "file_example_count_words" in calls[0] + audit = Path(out.extra["workspace"]) / "tool-calls.jsonl" + assert '"count_words"' in audit.read_text() diff --git a/tests/core/test_sandbox.py b/tests/core/test_sandbox.py index 3298a4c4..785c2ec6 100644 --- a/tests/core/test_sandbox.py +++ b/tests/core/test_sandbox.py @@ -362,7 +362,7 @@ def test_a_uv_alias_inside_a_granted_checkout_is_bound_once(tmp_path, monkeypatc @pytest.mark.integration # the CLI installed on the machine @pytest.mark.skipif(not _bwrap_works(), reason="needs a working bubblewrap (unprivileged user namespaces)") -@pytest.mark.parametrize("cli", ["codex", "claude", "pi"]) +@pytest.mark.parametrize("cli", ["codex", "claude", "pi", "opencode"]) def test_an_installed_cli_starts_with_only_its_own_paths(cli): """The built-in CLI agents: the CLI as installed (an nvm package, a ~/bin wrapper) starts inside, with no home.""" from hermit.sandbox import program_paths diff --git a/tests/core/test_selection.py b/tests/core/test_selection.py index 4a6d33aa..75749e7c 100644 --- a/tests/core/test_selection.py +++ b/tests/core/test_selection.py @@ -8,7 +8,7 @@ from selection import METHODS, READ_BY, NoBase, changed_paths, groups_for, select ROOT = Path(__file__).resolve().parents[2] -BUILT_IN = {"codex", "claude", "pi"} # the generic AgentEvolvers: tests/core +BUILT_IN = {"codex", "claude", "pi", "opencode"} # the generic AgentEvolvers: tests/core NO_METHOD = {"prompt_only", "lean_collab"} # templates without an Evolver of their own: tests/core diff --git a/tests/fixtures/opencode/README.md b/tests/fixtures/opencode/README.md new file mode 100644 index 00000000..1790ce4d --- /dev/null +++ b/tests/fixtures/opencode/README.md @@ -0,0 +1,17 @@ +# OpenCode streams + +Recorded from OpenCode 2.2.6 (the `opencode-linux-x64.tar.gz` release binary, checked against the release's +sha256 digest) run by hermit's `opencode` Base Agent (`make("opencode").run`, isolation none), against a scripted +chat-completions model on the loopback: the model of `tests/core/test_opencode_agent.py` (`serve_chat`), bound as a +`/` reference. + +- `success.jsonl`: a shell call that exits 3, a call of the call's MCP tool `echo` (`hermit_tools`, offered + directly as `hermit_tools_echo`), a write, then a reasoning text and the answer `the answer`; four requests of + 1000 prompt tokens (400 cached) and 20 completion tokens each. +- `resume.jsonl`: the same session resumed (`--session `): one request. +- `failure_500.jsonl`, `failure_429.jsonl`: every request answered that status; OpenCode retries (its `retry` + events), then ends with an `error` event (`provider.internal`, `provider.rate-limit`) and exits 1. +- `failure_refused.jsonl`: a model URL nothing listens on; the same, with `provider.transport`. +- `failure_401.jsonl`: every request answered 401; OpenCode ends at once with `provider.auth` and exits 1. + +The streams are OpenCode's output unchanged: they hold no path of the machine they were recorded on. diff --git a/tests/fixtures/opencode/failure_401.jsonl b/tests/fixtures/opencode/failure_401.jsonl new file mode 100644 index 00000000..68778e71 --- /dev/null +++ b/tests/fixtures/opencode/failure_401.jsonl @@ -0,0 +1,2 @@ +{"type":"step_start","timestamp":1794208875949,"sessionID":"ses_e40d13b27ffePQb0EflFCeLjWQ","part":{"id":"prt_1bf2ec5ad001YebBLLLCTTI8xn","sessionID":"ses_e40d13b27ffePQb0EflFCeLjWQ","messageID":"msg_1bf2ec596001qJrJXff8j21Gfd","type":"step-start"}} +{"type":"error","timestamp":1794208875964,"sessionID":"ses_e40d13b27ffePQb0EflFCeLjWQ","error":{"type":"provider.auth","message":"the model is down","status":401,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} diff --git a/tests/fixtures/opencode/failure_429.jsonl b/tests/fixtures/opencode/failure_429.jsonl new file mode 100644 index 00000000..5b9ac4eb --- /dev/null +++ b/tests/fixtures/opencode/failure_429.jsonl @@ -0,0 +1,12 @@ +{"type":"step_start","timestamp":1794208785386,"sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","part":{"id":"prt_1bf2d63ea001LNq0u03igYAEci","sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","messageID":"msg_1bf2d63e0001go4uaF2C4w5eMF","type":"step-start"}} +{"type":"retry","timestamp":1794208785388,"sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","messageID":"msg_1bf2d63e0001go4uaF2C4w5eMF","attempt":2,"nextRetryAt":1794208787306,"error":{"type":"provider.rate-limit","message":"the model is down","status":429,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208787329,"sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","messageID":"msg_1bf2d63e0001go4uaF2C4w5eMF","attempt":3,"nextRetryAt":1794208791787,"error":{"type":"provider.rate-limit","message":"the model is down","status":429,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208791804,"sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","messageID":"msg_1bf2d63e0001go4uaF2C4w5eMF","attempt":4,"nextRetryAt":1794208801245,"error":{"type":"provider.rate-limit","message":"the model is down","status":429,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208801261,"sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","messageID":"msg_1bf2d63e0001go4uaF2C4w5eMF","attempt":5,"nextRetryAt":1794208810778,"error":{"type":"provider.rate-limit","message":"the model is down","status":429,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208810800,"sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","messageID":"msg_1bf2d63e0001go4uaF2C4w5eMF","attempt":6,"nextRetryAt":1794208820808,"error":{"type":"provider.rate-limit","message":"the model is down","status":429,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208820826,"sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","messageID":"msg_1bf2d63e0001go4uaF2C4w5eMF","attempt":7,"nextRetryAt":1794208831837,"error":{"type":"provider.rate-limit","message":"the model is down","status":429,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208831855,"sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","messageID":"msg_1bf2d63e0001go4uaF2C4w5eMF","attempt":8,"nextRetryAt":1794208843654,"error":{"type":"provider.rate-limit","message":"the model is down","status":429,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208843671,"sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","messageID":"msg_1bf2d63e0001go4uaF2C4w5eMF","attempt":9,"nextRetryAt":1794208854909,"error":{"type":"provider.rate-limit","message":"the model is down","status":429,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208854934,"sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","messageID":"msg_1bf2d63e0001go4uaF2C4w5eMF","attempt":10,"nextRetryAt":1794208866277,"error":{"type":"provider.rate-limit","message":"the model is down","status":429,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208866293,"sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","messageID":"msg_1bf2d63e0001go4uaF2C4w5eMF","attempt":11,"nextRetryAt":1794208874670,"error":{"type":"provider.rate-limit","message":"the model is down","status":429,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"error","timestamp":1794208874709,"sessionID":"ses_e40d29ce6ffe0fSnWM3OUs9sWt","error":{"type":"provider.rate-limit","message":"the model is down","status":429,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} diff --git a/tests/fixtures/opencode/failure_500.jsonl b/tests/fixtures/opencode/failure_500.jsonl new file mode 100644 index 00000000..58e49b40 --- /dev/null +++ b/tests/fixtures/opencode/failure_500.jsonl @@ -0,0 +1,12 @@ +{"type":"step_start","timestamp":1794208700437,"sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","part":{"id":"prt_1bf2c18150015tr9jOgO1ZMiTL","sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","messageID":"msg_1bf2c17fb001na3TzG2QiCbDJg","type":"step-start"}} +{"type":"retry","timestamp":1794208700440,"sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","messageID":"msg_1bf2c17fb001na3TzG2QiCbDJg","attempt":2,"nextRetryAt":1794208702790,"error":{"type":"provider.internal","message":"the model is down","status":500,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208702809,"sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","messageID":"msg_1bf2c17fb001na3TzG2QiCbDJg","attempt":3,"nextRetryAt":1794208706620,"error":{"type":"provider.internal","message":"the model is down","status":500,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208706643,"sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","messageID":"msg_1bf2c17fb001na3TzG2QiCbDJg","attempt":4,"nextRetryAt":1794208715301,"error":{"type":"provider.internal","message":"the model is down","status":500,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208715319,"sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","messageID":"msg_1bf2c17fb001na3TzG2QiCbDJg","attempt":5,"nextRetryAt":1794208724880,"error":{"type":"provider.internal","message":"the model is down","status":500,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208724904,"sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","messageID":"msg_1bf2c17fb001na3TzG2QiCbDJg","attempt":6,"nextRetryAt":1794208736076,"error":{"type":"provider.internal","message":"the model is down","status":500,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208736101,"sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","messageID":"msg_1bf2c17fb001na3TzG2QiCbDJg","attempt":7,"nextRetryAt":1794208745643,"error":{"type":"provider.internal","message":"the model is down","status":500,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208745659,"sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","messageID":"msg_1bf2c17fb001na3TzG2QiCbDJg","attempt":8,"nextRetryAt":1794208757340,"error":{"type":"provider.internal","message":"the model is down","status":500,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208757356,"sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","messageID":"msg_1bf2c17fb001na3TzG2QiCbDJg","attempt":9,"nextRetryAt":1794208765747,"error":{"type":"provider.internal","message":"the model is down","status":500,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208765764,"sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","messageID":"msg_1bf2c17fb001na3TzG2QiCbDJg","attempt":10,"nextRetryAt":1794208775981,"error":{"type":"provider.internal","message":"the model is down","status":500,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"retry","timestamp":1794208775998,"sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","messageID":"msg_1bf2c17fb001na3TzG2QiCbDJg","attempt":11,"nextRetryAt":1794208784056,"error":{"type":"provider.internal","message":"the model is down","status":500,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} +{"type":"error","timestamp":1794208784085,"sessionID":"ses_e40d3e8f5ffeztJcHCunJDnats","error":{"type":"provider.internal","message":"the model is down","status":500,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} diff --git a/tests/fixtures/opencode/failure_refused.jsonl b/tests/fixtures/opencode/failure_refused.jsonl new file mode 100644 index 00000000..d18e8630 --- /dev/null +++ b/tests/fixtures/opencode/failure_refused.jsonl @@ -0,0 +1,12 @@ +{"type":"step_start","timestamp":1794208877313,"sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","part":{"id":"prt_1bf2ecb01001aWD2HQ7s3c9DGE","sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","messageID":"msg_1bf2ecaea001JHTAijEV0lnzl9","type":"step-start"}} +{"type":"retry","timestamp":1794208877316,"sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","messageID":"msg_1bf2ecaea001JHTAijEV0lnzl9","attempt":2,"nextRetryAt":1794208879414,"error":{"type":"provider.transport","message":"ECONNREFUSED: Unable to connect. Is the computer able to access the url?"}} +{"type":"retry","timestamp":1794208879434,"sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","messageID":"msg_1bf2ecaea001JHTAijEV0lnzl9","attempt":3,"nextRetryAt":1794208882854,"error":{"type":"provider.transport","message":"ECONNREFUSED: Unable to connect. Is the computer able to access the url?"}} +{"type":"retry","timestamp":1794208882873,"sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","messageID":"msg_1bf2ecaea001JHTAijEV0lnzl9","attempt":4,"nextRetryAt":1794208891597,"error":{"type":"provider.transport","message":"ECONNREFUSED: Unable to connect. Is the computer able to access the url?"}} +{"type":"retry","timestamp":1794208891617,"sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","messageID":"msg_1bf2ecaea001JHTAijEV0lnzl9","attempt":5,"nextRetryAt":1794208901259,"error":{"type":"provider.transport","message":"ECONNREFUSED: Unable to connect. Is the computer able to access the url?"}} +{"type":"retry","timestamp":1794208901275,"sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","messageID":"msg_1bf2ecaea001JHTAijEV0lnzl9","attempt":6,"nextRetryAt":1794208913107,"error":{"type":"provider.transport","message":"ECONNREFUSED: Unable to connect. Is the computer able to access the url?"}} +{"type":"retry","timestamp":1794208913140,"sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","messageID":"msg_1bf2ecaea001JHTAijEV0lnzl9","attempt":7,"nextRetryAt":1794208924504,"error":{"type":"provider.transport","message":"ECONNREFUSED: Unable to connect. Is the computer able to access the url?"}} +{"type":"retry","timestamp":1794208924521,"sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","messageID":"msg_1bf2ecaea001JHTAijEV0lnzl9","attempt":8,"nextRetryAt":1794208934565,"error":{"type":"provider.transport","message":"ECONNREFUSED: Unable to connect. Is the computer able to access the url?"}} +{"type":"retry","timestamp":1794208934582,"sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","messageID":"msg_1bf2ecaea001JHTAijEV0lnzl9","attempt":9,"nextRetryAt":1794208946201,"error":{"type":"provider.transport","message":"ECONNREFUSED: Unable to connect. Is the computer able to access the url?"}} +{"type":"retry","timestamp":1794208946216,"sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","messageID":"msg_1bf2ecaea001JHTAijEV0lnzl9","attempt":10,"nextRetryAt":1794208954259,"error":{"type":"provider.transport","message":"ECONNREFUSED: Unable to connect. Is the computer able to access the url?"}} +{"type":"retry","timestamp":1794208954275,"sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","messageID":"msg_1bf2ecaea001JHTAijEV0lnzl9","attempt":11,"nextRetryAt":1794208964418,"error":{"type":"provider.transport","message":"ECONNREFUSED: Unable to connect. Is the computer able to access the url?"}} +{"type":"error","timestamp":1794208964448,"sessionID":"ses_e40d136d1ffeM6Wd7pkJgq0Dou","error":{"type":"provider.transport","message":"ECONNREFUSED: Unable to connect. Is the computer able to access the url?"}} diff --git a/tests/fixtures/opencode/resume.jsonl b/tests/fixtures/opencode/resume.jsonl new file mode 100644 index 00000000..ae5beb71 --- /dev/null +++ b/tests/fixtures/opencode/resume.jsonl @@ -0,0 +1,4 @@ +{"type":"step_start","timestamp":1794208699017,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c1289001p13MjNBVQVxcRW","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c1267001xyDIMwUtqDeLAa","type":"step-start"}} +{"type":"reasoning","timestamp":1794208699030,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c12900012upyLHLewLOIIM","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c1267001xyDIMwUtqDeLAa","type":"reasoning","text":"The work is done.","metadata":{"reasoningField":"reasoning_content"},"time":{"start":1794208699024,"end":1794208699030}}} +{"type":"text","timestamp":1794208699032,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c1293002bUdYTcPxG3cWls","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c1267001xyDIMwUtqDeLAa","type":"text","text":"the answer","time":{"start":1794208699027,"end":1794208699032}}} +{"type":"step_finish","timestamp":1794208699035,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c129b001FbnVTg5Wy5GCT6","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c1267001xyDIMwUtqDeLAa","type":"step-finish","reason":"stop","cost":0,"tokens":{"input":600,"output":20,"reasoning":0,"cache":{"read":400,"write":0}}}} diff --git a/tests/fixtures/opencode/success.jsonl b/tests/fixtures/opencode/success.jsonl new file mode 100644 index 00000000..7a40dcba --- /dev/null +++ b/tests/fixtures/opencode/success.jsonl @@ -0,0 +1,13 @@ +{"type":"step_start","timestamp":1794208697695,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c0d5f001qKI5boa43CZOfZ","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0d54001MBdTQtnbNdq1Qj","type":"step-start"}} +{"type":"tool_use","timestamp":1794208697714,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"partID":"prt_1bf2c0d61001I4Xs336IexV9va","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0d54001MBdTQtnbNdq1Qj","type":"tool","id":"call_2","tool":"shell","state":{"status":"completed","input":{"command":"echo hi && exit 3","description":"Print hi and exit 3"},"output":"hi\n","title":"shell","metadata":{"metadata":{"status":"completed","truncated":false,"exit":3},"content":[{"type":"text","text":"hi\n"},{"type":"text","text":"Exited with code 3"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"command\": \"echo hi && exit 3\", \"description\": \"Print hi and exit 3\"}"},"time":{"start":1794208697697,"end":1794208697714}}}} +{"type":"step_finish","timestamp":1794208697716,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c0d74001qBrOm70wzcpmcp","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0d54001MBdTQtnbNdq1Qj","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":600,"output":20,"reasoning":0,"cache":{"read":400,"write":0}}}} +{"type":"step_start","timestamp":1794208697728,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c0d80001lQOpTiBGjpZnJm","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0d790017UR2P6Pg36ECzp","type":"step-start"}} +{"type":"tool_use","timestamp":1794208697740,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"partID":"prt_1bf2c0d81001VN6bH3MyxUcEJk","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0d790017UR2P6Pg36ECzp","type":"tool","id":"call_4","tool":"hermit_tools_echo","state":{"status":"completed","input":{"text":"from opencode"},"output":"{\"echoed\": \"from opencode\"}","title":"hermit_tools_echo","metadata":{"metadata":{"truncated":false},"content":[{"type":"text","text":"{\"echoed\": \"from opencode\"}"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"text\": \"from opencode\"}"},"time":{"start":1794208697729,"end":1794208697740}}}} +{"type":"step_finish","timestamp":1794208697742,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c0d8e0013YHCerJV2bisUP","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0d790017UR2P6Pg36ECzp","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":600,"output":20,"reasoning":0,"cache":{"read":400,"write":0}}}} +{"type":"step_start","timestamp":1794208697753,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c0d99001eaFuhwL5ZcC41X","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0d920019hE5I4JC44GZAO","type":"step-start"}} +{"type":"tool_use","timestamp":1794208697772,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"partID":"prt_1bf2c0d9a001RYqQuXjyx9Tmft","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0d920019hE5I4JC44GZAO","type":"tool","id":"call_6","tool":"write","state":{"status":"completed","input":{"path":"note.txt","content":"ok\n"},"output":"Created file successfully: note.txt","title":"write","metadata":{"metadata":{"truncated":false},"content":[{"type":"text","text":"Created file successfully: note.txt"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"path\": \"note.txt\", \"content\": \"ok\\n\"}"},"time":{"start":1794208697754,"end":1794208697772}}}} +{"type":"step_finish","timestamp":1794208697773,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c0dad0016kgNz4p3CwtNDH","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0d920019hE5I4JC44GZAO","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":600,"output":20,"reasoning":0,"cache":{"read":400,"write":0}}}} +{"type":"step_start","timestamp":1794208697784,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c0db8001VGFbkxS64XPDTE","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0db2001N1MGLt1YUMIU3V","type":"step-start"}} +{"type":"reasoning","timestamp":1794208697789,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c0db9001tCG0EGT8klPTAC","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0db2001N1MGLt1YUMIU3V","type":"reasoning","text":"The work is done.","metadata":{"reasoningField":"reasoning_content"},"time":{"start":1794208697785,"end":1794208697789}}} +{"type":"text","timestamp":1794208697790,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c0dbb002LhRe0enX5gKR56","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0db2001N1MGLt1YUMIU3V","type":"text","text":"the answer","time":{"start":1794208697787,"end":1794208697790}}} +{"type":"step_finish","timestamp":1794208697793,"sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","part":{"id":"prt_1bf2c0dc1001ayVsi79XPaRS0A","sessionID":"ses_e40d3f481ffePQb8uaj39iK60v","messageID":"msg_1bf2c0db2001N1MGLt1YUMIU3V","type":"step-finish","reason":"stop","cost":0,"tokens":{"input":600,"output":20,"reasoning":0,"cache":{"read":400,"write":0}}}} diff --git a/tests/selection.py b/tests/selection.py index 26a578b8..e2456b53 100644 --- a/tests/selection.py +++ b/tests/selection.py @@ -67,7 +67,8 @@ def fnmatch(path: str, pattern: str) -> bool: "tests/claude_stand.py", "tests/fixtures/claude_streams/*", # the Claude stand-in: core's and the methods' ".github/workflows/tests.yml"] # how CI runs them: a change to it runs them all # the rest of the framework, the templates no method group owns, the documentation's examples: the core group -CORE = ["hermit/*", "tests/core/*", "tests/fixtures/pi/*", "docs/_examples/*"] +CORE = ["hermit/*", "tests/core/*", "tests/fixtures/pi/*", "tests/fixtures/opencode/*", + "docs/_examples/*"] # nothing to run: documentation, and files no test reads NONE = ["docs/*", "*.md", "tests/README.md", "LICENSE", "NOTICE", ".github/*", ".agents/*", "assets/*", ".gitignore"] From ff6517336e34d35c86f1ed5930b7182b32d9e2f4 Mon Sep 17 00:00:00 2001 From: yizhuod Date: Mon, 9 Nov 2026 23:15:59 -0500 Subject: [PATCH 2/3] opencode integration bug fixed --- docs/framework/adapter.md | 13 ++++- docs/framework/commands.md | 2 +- docs/methods/ahe_adapter.md | 3 +- hermit/agent/acting/workspace.py | 4 +- hermit/agent/base/cli.py | 28 +++++++---- tests/core/test_opencode_agent.py | 61 ++++++++++++++++++----- tests/fixtures/opencode/README.md | 1 + tests/fixtures/opencode/failure_402.jsonl | 2 + 8 files changed, 87 insertions(+), 27 deletions(-) create mode 100644 tests/fixtures/opencode/failure_402.jsonl diff --git a/docs/framework/adapter.md b/docs/framework/adapter.md index a9f4ec17..a8101b74 100644 --- a/docs/framework/adapter.md +++ b/docs/framework/adapter.md @@ -140,6 +140,17 @@ pi-workspace/ # only for an adapter without roles .hermit-deploy.json ``` +```text +opencode-workspace/ # roles stay files under hermit//, named in AGENTS.md + AGENTS.md + opencode.json + hermit/file-example/ + ADAPTER.md exports.yaml tools.py agents/ skills/ README.md + .opencode/ + skills/verify-output/SKILL.md + .hermit-deploy.json +``` + Only declared exports are connected; every file is copied. A prompt-only adapter has no tool-server entry, skills, roles or hooks to install, and its copy holds `ADAPTER.md`, `exports.yaml` and `README.md`. The generated deployment report identifies the actual paths and role names, and lists every copied file with its digest. @@ -164,7 +175,7 @@ A redeployment replaces the copy under `hermit//`: files the new version no before writing anything, when a copied file was changed or replaced (by a directory or a link) since the last deployment or another file is in the way, and names the file; an adapter link that leads outside the adapter is refused too. -The generated `.codex/config.toml`, `.mcp.json` or `.pi/mcp.json` is rewritten on deployment; it is not a general configuration +The generated `.codex/config.toml`, `.mcp.json`, `.pi/mcp.json` or `opencode.json` is rewritten on deployment; it is not a general configuration merger. Global host configuration is not modified. ### Tools run from the adapter source diff --git a/docs/framework/commands.md b/docs/framework/commands.md index 0b51d98c..be224c46 100644 --- a/docs/framework/commands.md +++ b/docs/framework/commands.md @@ -169,7 +169,7 @@ It is not an HTTP preview server or the proposed standalone-service launcher. `- `evolver_access.environment`) and that no declared path holds the data, the judge or the runs. It does not check the pipeline's host: adapters are meant to be usable by any acting agent, and each pipeline deploys the exports (context, tools, roles, skills) in its own way. -- `hermit deploy --adapter DIR --workspace WORKSPACE --host codex|claude-code|pi` copies an adapter to +- `hermit deploy --adapter DIR --workspace WORKSPACE --host codex|claude-code|pi|opencode` copies an adapter to `hermit//` in a host workspace and connects its exports there (context block, MCP tools, native roles, skills, hooks). - `hermit convert --adapter DIR --output OUT --target ...` emits a plugin in the host's native format instead, diff --git a/docs/methods/ahe_adapter.md b/docs/methods/ahe_adapter.md index 07e7cff3..47669d29 100644 --- a/docs/methods/ahe_adapter.md +++ b/docs/methods/ahe_adapter.md @@ -35,7 +35,8 @@ example's `make_rows.py` writes them. The learners' CLI does not depend on the a deploy the adapter as `hermit deploy` does for its host, so that the host's hooks run the middleware (Codex: `.codex/hooks.json`; Claude Code: `hooks` in `.claude/settings.json`). Pi runs no hooks: its deployment lists the hook commands for the agent to run by hand, and run so, without an event's payload, only `session_start` has something to do -(it hands the memory over). +(it hands the memory over). OpenCode is not one of the template's hosts: its middleware refuses a copy deployed into +an OpenCode workspace. ## The template diff --git a/hermit/agent/acting/workspace.py b/hermit/agent/acting/workspace.py index 8f06b378..c50b2449 100644 --- a/hermit/agent/acting/workspace.py +++ b/hermit/agent/acting/workspace.py @@ -348,7 +348,9 @@ def _run(task: dict, adapter: Path | None, params: dict, base: Path) -> RunOutpu deployed, context_tool = _deploy(task, adapter, work, backend, params) session = agent.configured(args=[*(agent.settings.get("args") or []), *_session_args(backend, deployed, work)], **({"tools_name": deployed["harness_tools"].replace("-", "_")} - if deployed.get("harness_tools") else {})) + if deployed.get("harness_tools") else {}), + # OpenCode loads only the skills it is allowed: the deployment's + **({"skills": list(deployed.get("skills") or [])} if backend == "opencode" else {})) memory = _memory(work, deployed) for item in params.get("files") or []: source = Path(base) / item diff --git a/hermit/agent/base/cli.py b/hermit/agent/base/cli.py index 44ed3c7d..4f8ae6f5 100644 --- a/hermit/agent/base/cli.py +++ b/hermit/agent/base/cli.py @@ -72,8 +72,8 @@ and runs under isolation none or sandbox. OpenCode only: provider (its config's provider for the bound model, from the binding: Binding.opencode_provider; required: OpenCode runs a model reference and takes no login), append_system_prompt (an instructions file in the - home), effort (the model's reasoningEffort). OpenCode takes no roles, has no web search and runs under isolation - none or sandbox. + home), effort (the model's reasoningEffort), skills (the only skills the session may load: the deployment's; none + by default). OpenCode takes no roles, has no web search and runs under isolation none or sandbox. Limits are enforced by the isolation, or the call is refused (Unsupported): @@ -1471,15 +1471,15 @@ def _pi_session(home: Path, handle) -> Path | None: # Tools a session is not offered: questions for a person (no one answers), its own sub-agents (OpenCode takes no # roles), code mode (the call's tools are offered directly) and what reaches the network past the run's sandbox. OPENCODE_DENIED = ("question", "subagent", "execute", "webfetch", "websearch", "opencode_*") -# No update, catalog or language-server download; no Claude Code files (~/.claude) and no skills from .claude/ or -# .agents/ folders (an adapter's skills are deployed to .opencode/skills) +OPENCODE_AGENT = "build" # the agent a session runs: OpenCode's default, named so no config picks another +# No update or catalog requests, no Claude Code files (~/.claude, .claude/ and their skills). (2.2 reads no variable +# that keeps .agents/skills folders out: the skills a session may load are its permissions', `_held`.) OPENCODE_ENV = {"OPENCODE_DISABLE_AUTOUPDATE": "1", "OPENCODE_DISABLE_MODELS_FETCH": "1", - "OPENCODE_DISABLE_LSP_DOWNLOAD": "1", "OPENCODE_DISABLE_CLAUDE_CODE": "1", - "OPENCODE_DISABLE_EXTERNAL_SKILLS": "1"} + "OPENCODE_DISABLE_CLAUDE_CODE": "1"} # OpenCode's reports (its error event's `type`) of a provider that could not serve, which it retries itself first OPENCODE_OUTAGES = ("provider.rate-limit", "provider.internal", "provider.transport", "provider.timeout") -# ... and of a request that a retry would send to the same refusal -OPENCODE_REJECTED = ("provider.auth", "provider.invalid-request", "provider.content-filter", +# ... and of a request that a retry would send to the same refusal (a 402, the account's quota, included) +OPENCODE_REJECTED = ("provider.auth", "provider.quota", "provider.invalid-request", "provider.content-filter", "provider.unsupported-operation") OPENCODE_UNFINISHED = ("tool-calls", "length", "error", "content-filter") # a last step's reason that is no answer @@ -1533,7 +1533,10 @@ def _sign_in(self, home): def _held(self, home: Path) -> dict: """The inline config: the bound model (its reasoning effort), no other provider, the permissions, no update check, sharing or snapshots, and the call's system instructions (a file in the home, named by its path, which - a sandbox spells as it is inside, as it does every variable).""" + a sandbox spells as it is inside, as it does every variable). The permissions are given to the agent the + session runs too, which a workspace's (or, outside a sandbox, a parent folder's) config could otherwise give + its own; its skills are only the ones the `skills` setting names (the deployment's), never one a parent + folder's .agents/skills offers.""" s = self.settings provider = json.loads(json.dumps(s.get("provider") or {})) if s.get("effort") and s["effort"] != "off": @@ -1541,10 +1544,13 @@ def _held(self, home: Path) -> dict: if isinstance(entry, dict): entry.setdefault("options", {})["reasoningEffort"] = s["effort"] ref = f"{OPENCODE_PROVIDER}/{s.get('model') or ''}" + permission = {"*": "allow", "external_directory": "allow", "doom_loop": "allow", + **{tool: "deny" for tool in OPENCODE_DENIED}, + "skill": {"*": "deny", **{str(name): "allow" for name in s.get("skills") or ()}}} return {"provider": {OPENCODE_PROVIDER: provider}, "model": ref, "small_model": ref, "enabled_providers": [OPENCODE_PROVIDER], "autoupdate": False, "share": "disabled", "snapshot": False, - "permission": {"*": "allow", "external_directory": "allow", "doom_loop": "allow", - **{tool: "deny" for tool in OPENCODE_DENIED}}, + "default_agent": OPENCODE_AGENT, "permission": permission, + "agent": {OPENCODE_AGENT: {"permission": permission}}, **({"instructions": [str(home / "system.md")]} if s.get("append_system_prompt") else {})} def prepare_home(self, home, roles, tools_url, tools_name): diff --git a/tests/core/test_opencode_agent.py b/tests/core/test_opencode_agent.py index e5393d07..a7d566cc 100644 --- a/tests/core/test_opencode_agent.py +++ b/tests/core/test_opencode_agent.py @@ -119,6 +119,9 @@ def test_opencode_runs_in_its_home_with_its_model_held_and_the_tools_offered_dir assert held["provider"]["hermit"]["options"]["apiKey"] == "{env:FAKE_KEY}" assert held["provider"]["hermit"]["models"]["m-1"]["options"] == {"reasoningEffort": "high"} assert {held["permission"][t] for t in ("question", "subagent", "execute", "webfetch", "websearch")} == {"deny"} + # the agent the session runs holds them too (a workspace's config could give it its own), and no skill is allowed + assert held["default_agent"] == "build" and held["agent"]["build"]["permission"] == held["permission"] + assert held["permission"]["skill"] == {"*": "deny"} assert "sk-fake" not in env["OPENCODE_CONFIG_CONTENT"] + json.dumps(call["files"]) [(server, entry)] = json.loads(call["files"]["opencode.json"])["mcp"]["servers"].items() assert server == "hermit_tools" and entry["codemode"] is False and entry["url"].startswith("http://127.0.0.1:") @@ -148,14 +151,16 @@ def test_a_provider_that_could_not_serve_is_an_outage_read_from_opencodes_own_er assert result.usage == [] and result.trajectory[-1].kind == "error" -def test_a_request_the_provider_refuses_is_rejected_not_an_outage(fake, monkeypatch): - """A 401 (a wrong key) fails the same way however often it is sent: no retry.""" - replay(monkeypatch, "failure_401.jsonl", code=1) +@pytest.mark.parametrize("stream,kind", [("failure_401.jsonl", "provider.auth"), + ("failure_402.jsonl", "provider.quota")]) +def test_a_request_the_provider_refuses_is_rejected_not_an_outage(fake, monkeypatch, stream, kind): + """A 401 (a wrong key) or a 402 (the account's quota) fails the same way however often it is sent: no retry.""" + replay(monkeypatch, stream, code=1) work = fake / "work" work.mkdir() result = agent(fake).run("go", workspace=work) assert result.extra["failed"] and result.extra["rejected"] and not result.extra["unavailable"] - assert result.extra["failure"].startswith("provider.auth") + assert result.extra["failure"].startswith(kind) def test_the_acting_agent_runs_a_task_again_when_the_provider_could_not_serve_then_reports_an_error(fake, monkeypatch): @@ -244,6 +249,8 @@ def test_the_opencode_acting_agent_deploys_the_adapter_where_opencode_reads_it(f work = Path(out.extra["workspace"]) [call] = seen(fake) assert out.output == "the answer" and out.extra["backend"] == "opencode" and "--approve" not in call["args"] + held = json.loads(call["env"]["OPENCODE_CONFIG_CONTENT"]) + assert held["permission"]["skill"] == {"*": "deny", "verify-output": "allow"} # the deployment's skills only [server] = json.loads((work / "opencode.json").read_text())["mcp"]["servers"].values() assert server["type"] == "local" and server["codemode"] is False assert "hermit.runtime.mcp_server" in server["command"] @@ -252,6 +259,16 @@ def test_the_opencode_acting_agent_deploys_the_adapter_where_opencode_reads_it(f assert (out.log / "agent-opencode.jsonl").is_file() +def test_hermit_deploy_writes_an_opencode_workspace(tmp_path, capsys): + """`hermit deploy --host opencode`: the command a person runs, writing what OpenCode reads.""" + from hermit.cli import main + assert main(["deploy", "--adapter", str(FILE_ADAPTER), "--workspace", str(tmp_path / "ws"), + "--host", "opencode"]) == 0 + record = json.loads(capsys.readouterr().out) + assert record["host"] == "opencode" and record["skills"] == ["verify-output"] + assert set(json.loads((tmp_path / "ws" / "opencode.json").read_text())["mcp"]["servers"]) == {"file_example"} + + def test_opencode_is_a_base_of_the_config_and_the_opencode_evolver_binds_its_model(): from hermit.agent.base.login import evolver_problems from hermit.agent.evolver.loader import find, instantiate @@ -272,10 +289,11 @@ def test_opencode_is_a_base_of_the_config_and_the_opencode_evolver_binds_its_mod # ---------- the installed opencode (integration) ---------- -def serve_chat(script, status: int | None = None): +def serve_chat(script, status: int | None = None, seen: list | None = None): """A chat-completions model on the loopback: `script(request body) -> (tool call (name, arguments) | None)`; None answers `the answer`, with a reasoning text first. Every response is streamed, with usage (1000 prompt - tokens, 400 of them cached; 20 completion tokens). With `status`, every request is answered that error.""" + tokens, 400 of them cached; 20 completion tokens, 5 of them reasoning). With `status`, every request is answered + that error. `seen` gets each request's body and Authorization header.""" from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer def chunk(body): @@ -287,6 +305,8 @@ def log_message(self, *args): def do_POST(self): body = json.loads(self.rfile.read(int(self.headers.get("content-length") or 0)) or b"{}") + if seen is not None: + seen.append({"body": body, "authorization": self.headers.get("authorization")}) if status is not None: data = json.dumps({"error": {"message": "the model is down", "type": "server_error"}}).encode() self.send_response(status) @@ -306,7 +326,8 @@ def do_POST(self): chunk({"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls" if call else "stop"}]}), chunk({"choices": [], "usage": {"prompt_tokens": 1000, "completion_tokens": 20, - "prompt_tokens_details": {"cached_tokens": 400}}}), + "prompt_tokens_details": {"cached_tokens": 400}, + "completion_tokens_details": {"reasoning_tokens": 5}}}), b"data: [DONE]\n\n"]) self.send_response(200) self.send_header("content-type", "text/event-stream") @@ -335,10 +356,13 @@ def mock_params(url: str) -> dict: @pytest.mark.parametrize("isolation", ["none", "sandbox"]) def test_with_the_opencode_cli_a_session_reaches_its_model_and_its_tools(tmp_path, monkeypatch, isolation): """The installed OpenCode, bound to a scripted model: it calls the call's MCP tool (offered directly), writes a - file, answers; in the run's sandbox (isolated network) only its model and the tool server are reached.""" + file, answers; in the run's sandbox (isolated network) only its model and the tool server are reached. The key + reaches the model from its variable, the effort reaches the request, and a parent folder (a Git repository's + root, with a skill and a config that allows the denied tools again) gives the session nothing.""" from hermit.sandbox import Sandbox if isolation == "sandbox" and not _bwrap_works(): pytest.skip("needs a working bubblewrap") + requests = [] def script(body): done = sum(1 for m in body.get("messages") or [] if m.get("role") == "tool") @@ -347,14 +371,20 @@ def script(body): assert plan[0][0] in names # the tool is offered directly, not through code mode return plan[done] if done < len(plan) else None - server, url = serve_chat(script) + (tmp_path / ".git").mkdir() # the parent folder: a repository's root, as a checkout is + (tmp_path / "opencode.json").write_text(json.dumps( + {"agent": {"build": {"permission": {"webfetch": "allow", "question": "allow"}}}})) + (tmp_path / ".agents" / "skills" / "parent-skill").mkdir(parents=True) + (tmp_path / ".agents" / "skills" / "parent-skill" / "SKILL.md").write_text( + "---\nname: parent-skill\ndescription: A skill of the parent folder.\n---\nNot the adapter's.\n") + server, url = serve_chat(script, seen=requests) monkeypatch.setenv("MOCK_KEY", "sk-mock") (tmp_path / "caller").mkdir() monkeypatch.setenv("PWD", str(tmp_path / "caller")) # where OpenCode would work if it went by PWD work = tmp_path / "work" work.mkdir() settings = {**mock_params(url), "web_search": False, "home": str(tmp_path / "home"), "isolation": isolation, - "timeout_s": 300} + "timeout_s": 300, "effort": "high"} if isolation == "sandbox": settings["sandbox"] = Sandbox(network="isolated", env_allow=[], writable=[work], role="agent", record_dir=tmp_path / "records") @@ -366,7 +396,12 @@ def script(body): assert (work / "note.txt").read_text() == "ok\n" and not any((tmp_path / "caller").iterdir()) assert [s.kind for s in result.trajectory] == ["tool_call", "file_change", "reasoning", "message"] assert json.loads(result.trajectory[0].output) == {"echoed": "hi"} - assert result.usage[0].calls == 3 + assert (result.usage[0].calls, result.usage[0].output_tokens) == (3, 60) # the reasoning counted as output + assert {r["authorization"] for r in requests} == {"Bearer sk-mock"} + assert {r["body"].get("reasoning_effort") for r in requests} == {"high"} + offered = {t["function"]["name"] for r in requests for t in r["body"].get("tools") or []} + assert not offered & {"question", "subagent", "execute", "webfetch", "websearch"} + assert "parent-skill" not in json.dumps([r["body"] for r in requests]) if isolation == "sandbox": [record] = (tmp_path / "records").glob("agent-*.json") data = json.loads(record.read_text()) @@ -380,12 +415,13 @@ def test_with_the_opencode_cli_the_acting_agent_uses_the_deployed_adapters_tools """The deployment as OpenCode reads it: the project's opencode.json starts the adapter's tool server, whose tool the model is offered directly and calls.""" from hermit.agent.acting import workspace as acting - calls = [] + calls, bodies = [], [] def script(body): names = [t["function"]["name"] for t in body.get("tools") or []] done = any(m.get("role") == "tool" for m in body.get("messages") or []) calls.append(names) + bodies.append(body) return None if done else ("file_example_count_words", {"text": "a b c"}) server, url = serve_chat(script) @@ -397,5 +433,6 @@ def script(body): finally: server.shutdown() assert out.output == "the answer" and "file_example_count_words" in calls[0] + assert "verify-output" in json.dumps(bodies[0]) # the deployment's skill, the one the session may load audit = Path(out.extra["workspace"]) / "tool-calls.jsonl" assert '"count_words"' in audit.read_text() diff --git a/tests/fixtures/opencode/README.md b/tests/fixtures/opencode/README.md index 1790ce4d..f676713a 100644 --- a/tests/fixtures/opencode/README.md +++ b/tests/fixtures/opencode/README.md @@ -13,5 +13,6 @@ chat-completions model on the loopback: the model of `tests/core/test_opencode_a events), then ends with an `error` event (`provider.internal`, `provider.rate-limit`) and exits 1. - `failure_refused.jsonl`: a model URL nothing listens on; the same, with `provider.transport`. - `failure_401.jsonl`: every request answered 401; OpenCode ends at once with `provider.auth` and exits 1. +- `failure_402.jsonl`: every request answered 402; OpenCode ends at once with `provider.quota` and exits 1. The streams are OpenCode's output unchanged: they hold no path of the machine they were recorded on. diff --git a/tests/fixtures/opencode/failure_402.jsonl b/tests/fixtures/opencode/failure_402.jsonl new file mode 100644 index 00000000..80b4c1f0 --- /dev/null +++ b/tests/fixtures/opencode/failure_402.jsonl @@ -0,0 +1,2 @@ +{"type":"step_start","timestamp":1794214501228,"sessionID":"ses_e407b6608ffeOuOi51f1pvk1f5","part":{"id":"prt_1bf849b6c001spmw6X3CDKe281","sessionID":"ses_e407b6608ffeOuOi51f1pvk1f5","messageID":"msg_1bf849b580016J5ZFOkOYwOUwO","type":"step-start"}} +{"type":"error","timestamp":1794214501282,"sessionID":"ses_e407b6608ffeOuOi51f1pvk1f5","error":{"type":"provider.quota","message":"the model is down","status":402,"response":{"body":"{\"error\": {\"message\": \"the model is down\", \"type\": \"server_error\"}}"}}} From 80e04b19da6e7da5761e2765ac0868a0524e2850 Mon Sep 17 00:00:00 2001 From: Haizhong Zheng Date: Tue, 10 Nov 2026 11:15:47 -0500 Subject: [PATCH 3/3] opencode: tools from the first request, long prompts, extra_body, compaction usage - The adapter's tools reach an OpenCode acting agent through the Base Agent's tool server: OpenCode 2.2 waits at most 2 s for an MCP server it starts (STARTUP_GRACE_MS) and the adapter's takes ~3 s, so the first request often went without them. hosts/opencode.prepare takes serve_tools; docs say so. - The prompt is OpenCode's stdin, not an argument (E2BIG past 128 KiB). - A binding's extra_body becomes the OpenCode model's options; the effort setting outranks its reasoning_effort. - Usage counts compactions' model calls, which `run --format json` never streams: this call's share of the session's totals in OpenCode's database (read-only, immutable, nothing followed out of the home), a resumed session's earlier totals taken off (_this_call, now with `fields`). - parse_log reads OpenCode's stream by its name. - The AHE Evolver's texts name OpenCode's stream (agent-opencode.jsonl) as they name Pi's and mini-swe-agent's (#91). - The deployer's docstring gives AGENTS.md discovery's real boundary. Tests: the first request offers the adapter's tools (real binary); a prompt past ARG_MAX; extra_body and effort; compaction usage from a stand-in database and from the real binary (mid-run compaction, then a resume). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +- docs/framework/commands.md | 2 + docs/framework/task.md | 3 +- hermit/agent/acting/workspace.py | 10 +- hermit/agent/base/cli.py | 74 ++++++-- hermit/agent/base/records.py | 11 +- .../evolver/methods/ahe_adapter/debugger.py | 7 +- hermit/agent/model/backends.py | 5 +- hermit/hosts/opencode.py | 14 +- tests/core/test_opencode_agent.py | 162 ++++++++++++++++-- tests/methods/ahe/test_ahe_hosts.py | 8 +- 11 files changed, 246 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe4a7dbb..1d79ce76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,7 +51,8 @@ Changes are grouped by software version. Entries under Unreleased describe work (the provider, the permissions, no sharing) is its inline config, which outranks a workspace's `opencode.json`; the call's tools are an MCP server offered directly (not through code mode). Whether its provider could not serve is read from OpenCode's own error type (`provider.rate-limit`, `.internal`, `.transport`, `.timeout`), so the - acting agent runs such a task again. OpenCode takes no roles and has no web search. `hermit deploy --host opencode` + acting agent runs such a task again. Its usage counts the model calls of its compactions, which its stream leaves + out, from its session's totals. OpenCode takes no roles and has no web search. `hermit deploy --host opencode` writes `AGENTS.md`, the project's `opencode.json` and `.opencode/skills`. - Models in sandboxes as Harbor's agents get theirs: each sandbox gets its models' key variables and provider hosts (an isolated network becomes an allowlist) and forwards a model meter on the loopback; what a run keeps (the diff --git a/docs/framework/commands.md b/docs/framework/commands.md index fbb19567..cbb4b229 100644 --- a/docs/framework/commands.md +++ b/docs/framework/commands.md @@ -84,6 +84,8 @@ other files, and its tools as one bash command (`hermit-tool`) in the system tem mini-swe-agent.yaml` from the workspace ([tutorial](../tutorials/mini-swe-agent.md)). `--host opencode` writes `AGENTS.md`, the project's `opencode.json` (the tools, offered directly) and `.opencode/skills`, which OpenCode loads with no trust step; it names roles and hooks in `AGENTS.md`, as for Pi. +OpenCode 2.2 waits at most 2 s for the tools' server it starts, which takes about 3 s: an `opencode run` given its +prompt at once may send the first request without the adapter's tools (the `opencode` acting agent serves them itself). `--context-limit BYTES` (Codex) is the `project_doc_max_bytes` your Codex configuration sets, 32768 (Codex's default) when not given: a longer `AGENTS.md` is refused, since Codex would cut it; `0` skips the check. It is the per-project way to use an adapter; the per-agent way, `convert`, and how the two compare are in [What is a harness adapter?](what-is-a-harness-adapter.md#two-ways-to-use-an-adapter). The workspace must be an empty directory or one previously generated for the same host, separate from diff --git a/docs/framework/task.md b/docs/framework/task.md index 91fb85a1..2bebc82d 100644 --- a/docs/framework/task.md +++ b/docs/framework/task.md @@ -121,7 +121,8 @@ What the agent does for every task: the whole adapter under `hermit//` but its [`internal`](adapter-manifest.md#internal) files, each export connected to the CLI's own place, and the context naming the rest. Its tools are served by an MCP server on this machine; a container session, which cannot start one, gets them from the session's own tool server, which - the container reaches. An adapter's [`context_tool`](adapter-manifest.md#per-task-context) is rendered for each + the container reaches, and so does an OpenCode session (OpenCode waits only 2 s for a server it starts). An + adapter's [`context_tool`](adapter-manifest.md#per-task-context) is rendered for each task (the field `context_query`, else the task's question or prompt), deployed into the context and recorded in `RunOutput.extra["context_tool"]`; so is the context of any adapter whose template is not [`plugin-portable`](adapter-manifest.md#plugin-portable), which `hermit deploy` alone refuses. The session diff --git a/hermit/agent/acting/workspace.py b/hermit/agent/acting/workspace.py index 50404492..214b9bb6 100644 --- a/hermit/agent/acting/workspace.py +++ b/hermit/agent/acting/workspace.py @@ -152,7 +152,7 @@ def deploy(adapter: Path, workspace: Path, backend: str, *, context: str | None return prepare_mini(adapter, workspace, sys.executable, context=context, serve_tools=serve_tools) if backend == "opencode": from hermit.hosts.opencode import prepare as prepare_opencode - return prepare_opencode(adapter, workspace, sys.executable, context=context) + return prepare_opencode(adapter, workspace, sys.executable, context=context, serve_tools=serve_tools) from hermit.hosts.claude_code import prepare return prepare(adapter, workspace, sys.executable, context=context, serve_tools=serve_tools) @@ -165,9 +165,11 @@ def _deploy(task: dict, adapter: Path | None, work: Path, backend: str, params: from hermit.adapter.loader import agent_tools, load_manifest from hermit.adapter.manifest import PORTABLE manifest = load_manifest(adapter) - # A container session cannot start the tools' server on this machine, and mini-swe-agent reaches tools only - # through its Base Agent: the session's own tool server (the Base Agent's) serves them instead. - harness_tools = (params.get("isolation") == "container" or backend == "mini-swe-agent") and \ + # A container session cannot start the tools' server on this machine, mini-swe-agent reaches tools only + # through its Base Agent, and OpenCode waits 2 s at most for a starting server (STARTUP_GRACE_MS in 2.2; the + # adapter's takes longer, so its first request would go without them): the session's own tool server (the Base + # Agent's, running before the session starts) serves them instead. + harness_tools = (params.get("isolation") == "container" or backend in ("mini-swe-agent", "opencode")) and \ bool(agent_tools(manifest)) # An adapter only hermit runs (not plugin-portable: a context tool's per-task context, say) has no installed # workspace, so `hermit deploy` refuses it; here the task is known, so its context is deployed. diff --git a/hermit/agent/base/cli.py b/hermit/agent/base/cli.py index 587d8c6a..25594700 100644 --- a/hermit/agent/base/cli.py +++ b/hermit/agent/base/cli.py @@ -86,6 +86,7 @@ """ from __future__ import annotations +import contextlib import dataclasses import json import os @@ -1725,7 +1726,9 @@ def _held(self, home: Path) -> dict: if s.get("effort") and s["effort"] != "off": for entry in (provider.get("models") or {}).values(): if isinstance(entry, dict): - entry.setdefault("options", {})["reasoningEffort"] = s["effort"] + options = entry.setdefault("options", {}) + options.pop("reasoning_effort", None) # the effort setting outranks extra_body's + options["reasoningEffort"] = s["effort"] ref = f"{OPENCODE_PROVIDER}/{s.get('model') or ''}" permission = {"*": "allow", "external_directory": "allow", "doom_loop": "allow", **{tool: "deny" for tool in OPENCODE_DENIED}, @@ -1762,7 +1765,7 @@ def system_settings(self, system, prompt): return {"append_system_prompt": system}, prompt def on_stdin(self): - return False # the prompt is an argument, after `--` + return True # read to its end (no argument limit), as `opencode run` reads a piped message @classmethod def _finish(cls, objects) -> str | None: @@ -1803,9 +1806,23 @@ def outcome(self, raw, stream, last_file): "the session ended without an answer"))[-600:]} def adjust_usage(self, home, handle, usage, resumed): - """A bound model's cost is left to its price (price_usage): OpenCode counts a model whose config gives no - cost as free.""" - if self.settings.get("binding") or self.settings.get("provider"): + """With what the stream leaves out: the model calls of OpenCode's compactions (and of the summaries it writes + ahead of one), in its session's totals (its database) but in no `step_finish`. This call's share of those + totals (_this_call: a resumed session's earlier calls taken off) is counted where it is more than the + stream's; a compaction counts as one call (its retries only in its tokens). A bound model's cost is left to + its price (price_usage): OpenCode counts a model whose config gives no cost as free.""" + s = self.settings + totals = _opencode_totals(home, str(handle), (s.get("binding") or {}).get("ref") or s.get("model") or + self.backend) if handle else None + if totals is not None: + share = _this_call(home, str(handle), totals, resumed=resumed, + fields=("input_tokens", "cached_input_tokens", "output_tokens", "calls")) + counted = usage[0] if usage else type(share)(share.model) + for f in ("input_tokens", "cached_input_tokens", "output_tokens"): + setattr(counted, f, max(getattr(counted, f), getattr(share, f))) + counted.calls += share.calls + usage = [counted] if counted.calls or counted.input_tokens or counted.output_tokens else [] + if s.get("binding") or s.get("provider"): for u in usage: u.cost_usd = None return usage @@ -1834,13 +1851,44 @@ def command(self, prompt, workspace, last_file, *, session=None, roles=(), tools """`--standalone`: a server of the session's own, never OpenCode's background service, which other sessions (other homes, other workspaces) would share. `--title` names the session, so no request is spent on a title; `--thinking` keeps the model's reasoning in the stream. A session handle that is no OpenCode session id - starts a new session.""" + starts a new session. The prompt is its stdin (on_stdin), never an argument.""" s = self.settings resume = str(session) if session and re.fullmatch(r"ses_[A-Za-z0-9]+", str(session)) else None return [str(s.get("bin") or self.program), "run", "--standalone", "--format", "json", "-m", f"{OPENCODE_PROVIDER}/{s.get('model') or ''}", "--title", "hermit", "--thinking", *self.web_search_args(bool(s.get("web_search"))), - *(["--session", resume] if resume else []), *(s.get("args") or []), "--", prompt] + *(["--session", resume] if resume else []), *(s.get("args") or [])] + + +def _opencode_totals(home: Path, session: str, model: str): + """An OpenCode session's running totals as its database (in its home) keeps them: its tokens, counted as + records._opencode_event counts a request's, and its compactions as `calls`. None where there is none to read + (no database, no such session, or one OpenCode no longer keeps this way, which is said once). The session could + write its home: nothing is followed out of it, and the database is read as an immutable file, so SQLite neither + writes nor opens its -wal and -shm files (OpenCode leaves none when it exits: a session cut off may leave its + last totals there, and then counts as no more than its stream).""" + import sqlite3 + from hermit.agent.model.usage import Usage + db = Path(os.path.abspath(home)) / "data" / "opencode" / "opencode.db" + if not _regular(db) or not Path(os.path.realpath(db)).is_relative_to(os.path.realpath(home)): + return None + try: + with contextlib.closing(sqlite3.connect(f"{db.as_uri()}?mode=ro&immutable=1", uri=True)) as c: + row = c.execute("SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, " + "tokens_cache_write FROM session_v2 WHERE id = ?", (session,)).fetchone() + compactions = c.execute("SELECT count(*) FROM session_message WHERE session_id = ? AND " + "type = 'compaction'", (session,)).fetchone()[0] + if row is None: + return None + fresh, output, reasoning, read, write = (int(x or 0) for x in row) + return Usage(model, input_tokens=fresh + read + write, cached_input_tokens=read, + output_tokens=output + reasoning, calls=int(compactions)) + except (sqlite3.Error, OSError, ValueError, TypeError, OverflowError) as e: + if "opencode_db" not in _WARNED: + _WARNED.add("opencode_db") + print(f"hermit: OpenCode's session database could not be read ({e}): the model calls of its compactions " + "are not counted in the usage", file=sys.stderr, flush=True) + return None # Every CLI Base Agent, by each name make() takes for it. @@ -1848,11 +1896,12 @@ def command(self, prompt, workspace, last_file, *, session=None, roles=(), tools for n in (c.backend, *c.aliases)} -def _this_call(home: Path, handle: str, reported, resumed: bool): +def _this_call(home: Path, handle: str, reported, resumed: bool, + fields=("input_tokens", "cached_input_tokens", "output_tokens")): """This call's usage: Codex reports a thread's running total, so a resumed thread's report counts its earlier - calls again. The last total of each thread is kept in the home (`usage/.json`) and taken off.""" + calls again. The last total of each thread is kept in the home (`usage/.json`) and taken off. `fields`: + the running totals (OpenCode's session totals count its compactions too).""" from hermit.agent.model.usage import Usage - fields = ("input_tokens", "cached_input_tokens", "output_tokens") ledger = home / "usage" / f"{re.sub(r'[^A-Za-z0-9_.-]', '_', handle)}.json" # The session could write its home: a link it left there (the ledger's directory or the ledger) is removed, # never followed, and the ledger is written without following one. @@ -1868,8 +1917,9 @@ def _this_call(home: Path, handle: str, reported, resumed: bool): fd = os.open(ledger, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) with os.fdopen(fd, "w") as f: f.write(json.dumps({f_: getattr(reported, f_) for f_ in fields})) - return Usage(reported.model, **{f: max(0, getattr(reported, f) - int(before.get(f, 0))) for f in fields}, - calls=reported.calls, cost_usd=None if before else reported.cost_usd) + return Usage(reported.model, **{"calls": reported.calls, + **{f: max(0, getattr(reported, f) - int(before.get(f, 0))) for f in fields}}, + cost_usd=None if before else reported.cost_usd) def _overlap(a: Path, b: Path) -> bool: diff --git a/hermit/agent/base/records.py b/hermit/agent/base/records.py index b13fe342..6be74137 100644 --- a/hermit/agent/base/records.py +++ b/hermit/agent/base/records.py @@ -141,7 +141,8 @@ def _opencode_event(event: dict, usage: Usage, session): OpenCode's `input` leaves the cache out and its `output` the reasoning, so the input counted is input, cache reads and cache writes and the output is output and reasoning, as Codex and Claude Code count them; its cost is OpenCode's own (for a bound model, OpenCode.adjust_usage leaves it to the price). A request that failed has no - `step_finish` (its retries are `retry` events) and counts as no call.""" + `step_finish` (its retries are `retry` events) and counts as no call; nor has a compaction's (OpenCode.adjust_usage + counts those from the session's totals).""" session = session or event.get("sessionID") part = event.get("part") if isinstance(event.get("part"), dict) else {} if event.get("type") != "step_finish" or not isinstance(part.get("tokens"), dict): @@ -180,7 +181,7 @@ def parse_mini_swe_agent(log: Path, model: str) -> tuple[str | None, list[Usage] def parse_log(log: Path, backend: str, model: str) -> tuple[str | None, list[Usage]]: - """Session handle and usage from the agent's JSON event stream: Codex's, Pi's, mini-swe-agent's, else Claude - Code's.""" - return {"codex": parse_codex, "pi": parse_pi, "mini-swe-agent": parse_mini_swe_agent}.get(backend, parse_claude)( - log, model) + """Session handle and usage from the agent's JSON event stream: Codex's, Pi's, mini-swe-agent's, OpenCode's, else + Claude Code's.""" + return {"codex": parse_codex, "pi": parse_pi, "mini-swe-agent": parse_mini_swe_agent, + "opencode": parse_opencode}.get(backend, parse_claude)(log, model) diff --git a/hermit/agent/evolver/methods/ahe_adapter/debugger.py b/hermit/agent/evolver/methods/ahe_adapter/debugger.py index 24a93c05..e555db1c 100644 --- a/hermit/agent/evolver/methods/ahe_adapter/debugger.py +++ b/hermit/agent/evolver/methods/ahe_adapter/debugger.py @@ -190,7 +190,12 @@ def trace_source(log: Path | None) -> tuple[Path, str] | None: ("the raw Codex event stream", "the raw Claude Code event stream"), ("the Codex event stream", "the Claude Code event stream"), ("`codex exec --json` event stream", - "`claude -p --output-format stream-json` event stream"))} + "`claude -p --output-format stream-json` event stream")), + "agent-opencode.jsonl": (("agent-codex.jsonl", "agent-opencode.jsonl"), + ("the raw Codex event stream", "the raw OpenCode event stream"), + ("the Codex event stream", "the OpenCode event stream"), + ("`codex exec --json` event stream", + "`opencode run --format json` event stream"))} def stream_of(logs) -> str: diff --git a/hermit/agent/model/backends.py b/hermit/agent/model/backends.py index 2f8dd307..ad78a71a 100644 --- a/hermit/agent/model/backends.py +++ b/hermit/agent/model/backends.py @@ -332,11 +332,14 @@ def opencode_provider(self) -> dict: """OpenCode's provider entry for this model (a `provider` value of its config): the backend's chat-completions URL through OpenCode's OpenAI-compatible package, the key as `{env:VARIABLE}`, which OpenCode reads when it starts, so no config holds the key (a placeholder for a server that needs none), and the model with its - context window. The cost hermit records follows the price (OpenCode.adjust_usage).""" + context window and `extra_body` (a model's options, which OpenCode adds to every request). The cost hermit + records follows the price (OpenCode.adjust_usage).""" key_env = self.key_env_if_set() model: dict = {"name": self.model} if self.backend.context_window: model["limit"] = {"context": int(self.backend.context_window)} + if self.extra_body: + model["options"] = json.loads(json.dumps(self.extra_body)) return {"npm": OPENCODE_PACKAGE, "name": "hermit", "options": {"baseURL": self.base_url.rstrip("/"), "apiKey": f"{{env:{key_env}}}" if key_env else PLACEHOLDER_KEY}, diff --git a/hermit/hosts/opencode.py b/hermit/hosts/opencode.py index 71a71af9..23e822cb 100644 --- a/hermit/hosts/opencode.py +++ b/hermit/hosts/opencode.py @@ -2,9 +2,10 @@ """Deploy an adapter into an OpenCode workspace: the whole adapter under hermit//, and its exports connected to OpenCode's own places: AGENTS.md context, opencode.json tools, .opencode/skills. -OpenCode reads AGENTS.md from the working directory (and its parents, up to a Git repository's root) and the -project's opencode.json and .opencode/ with no trust step. The tools are a local MCP server declared with `codemode: -false`, so the model is offered them as tools, not only through OpenCode's code mode (its default). OpenCode takes no +OpenCode reads AGENTS.md from the working directory and its parents (up to the home directory for a workspace below +it, else up to the project's root, a Git repository's), and the project's opencode.json and .opencode/ with no trust +step. The tools are a local MCP server declared with `codemode: false`, so the model is offered them as tools, not +only through OpenCode's code mode (its default). OpenCode takes no roles here and reads no hook file: an adapter's roles and hooks stay files of its copy, which AGENTS.md names with what to do with them (hermit.hosts.inputs.resources), as it names the other files. Global OpenCode settings (~/.config/opencode) are never changed. @@ -25,9 +26,10 @@ def prepare(adapter: Path, output: Path, python: str, *, learning_material: Path | None = None, - context: str | None = None) -> dict: + context: str | None = None, serve_tools: bool = True) -> dict: """`context`: the adapter's context for one task, which the harness computed, in place of the one rendered - here; an adapter whose context is per task deploys only so.""" + here; an adapter whose context is per task deploys only so. `serve_tools`: false when the caller serves the + adapter's tools to the session itself (the `opencode` acting agent): opencode.json then names no server.""" adapter, output = adapter.resolve(), output.resolve() refused = not_portable(load_manifest(adapter), "An OpenCode workspace") # before anything is written if refused and context is None: @@ -37,7 +39,7 @@ def prepare(adapter: Path, output: Path, python: str, *, learning_material: Path files = adapter_files(adapter, output, manifest, previous) exports = render_exports(adapter, python) listed, placed = resources(adapter, output, manifest, exports, hook_definitions(adapter, manifest), NATIVE) - has_tools = bool(agent_tools(manifest)) # the context tool is the harness's, not served + has_tools = bool(agent_tools(manifest)) and serve_tools # the context tool is the harness's, not served if has_tools: subprocess.run([python, "-c", "import mcp.server"], check=True, capture_output=True) output.mkdir(parents=True, exist_ok=True) diff --git a/tests/core/test_opencode_agent.py b/tests/core/test_opencode_agent.py index a7d566cc..92934741 100644 --- a/tests/core/test_opencode_agent.py +++ b/tests/core/test_opencode_agent.py @@ -95,6 +95,31 @@ def test_a_bound_model_is_opencodes_provider_with_its_key_as_a_variable(): assert free["options"]["apiKey"] == "local" # a server that needs no key gets the placeholder +def test_the_bindings_extra_body_is_the_models_options_and_the_effort_outranks_it(fake): + """`extra_body` (fields for every chat request) becomes the model's options, which OpenCode adds to each request + body; the effort setting replaces an extra_body `reasoning_effort`.""" + params = bound(extra_body={"chat_template_kwargs": {"enable_thinking": False}, "reasoning_effort": "low"}) + assert params["provider"]["models"]["m-1"]["options"] == {"chat_template_kwargs": {"enable_thinking": False}, + "reasoning_effort": "low"} + work = fake / "work" + work.mkdir() + make("opencode", {**params, "web_search": False, "home": str(fake / "home"), "effort": "high"}).run( + "go", workspace=work) + held = json.loads(seen(fake)[0]["env"]["OPENCODE_CONFIG_CONTENT"]) + assert held["provider"]["hermit"]["models"]["m-1"]["options"] == { + "chat_template_kwargs": {"enable_thinking": False}, "reasoningEffort": "high"} + + +def test_a_prompt_past_the_argument_limit_reaches_opencode_on_stdin(fake): + """A prompt longer than one argument may be (E2BIG) still starts the session: it is OpenCode's stdin.""" + work = fake / "work" + work.mkdir() + prompt = "x" * (base_cli.ARG_MAX + 80_000) + result = agent(fake).run(prompt, workspace=work) + [call] = seen(fake) + assert result.extra["served"] and call["stdin"] == prompt and prompt not in call["args"] + + def test_opencode_runs_in_its_home_with_its_model_held_and_the_tools_offered_directly(fake, monkeypatch): """What the session must hold (the provider, the permissions, no sharing) is the inline config, which outranks a workspace's opencode.json; the call's tools are the home's config, offered directly; the caller's own OpenCode @@ -108,7 +133,8 @@ def test_opencode_runs_in_its_home_with_its_model_held_and_the_tools_offered_dir [call] = seen(fake) # a server of its own (never OpenCode's background service, which other sessions would share) assert call["args"][:7] == ["run", "--standalone", "--format", "json", "-m", "hermit/m-1", "--title"] - assert "--thinking" in call["args"] and call["args"][-2:] == ["--", "-a prompt that starts with a dash"] + assert "--thinking" in call["args"] and "--" not in call["args"] + assert call["stdin"] == "-a prompt that starts with a dash" # the prompt is stdin, never an argument env = call["env"] assert env["HOME"] == str(home) and env["XDG_DATA_HOME"] == str(home / "data") assert env["OPENCODE_CONFIG"] == str(home / "opencode.json") and env["OPENCODE_DISABLE_AUTOUPDATE"] == "1" @@ -188,6 +214,51 @@ def test_a_resumed_session_is_continued_by_its_id_and_counts_only_its_new_usage( assert "--session" not in seen(fake)[1]["args"] +def keep_totals(home: Path, compactions: int, **tokens) -> None: + """OpenCode's database in its home, as 2.2.6 keeps a session's totals (its tables' columns that are read): the + recorded session's `tokens` (input, output, reasoning, cache_read, cache_write) and its `compactions`.""" + import sqlite3 + db = home / "data" / "opencode" / "opencode.db" + db.parent.mkdir(parents=True, exist_ok=True) + with sqlite3.connect(db) as c: + c.execute("CREATE TABLE IF NOT EXISTS session_v2 (id text PRIMARY KEY, tokens_input integer, tokens_output " + "integer, tokens_reasoning integer, tokens_cache_read integer, tokens_cache_write integer)") + c.execute("CREATE TABLE IF NOT EXISTS session_message (id text PRIMARY KEY, session_id text, type text)") + c.execute("INSERT OR REPLACE INTO session_v2 VALUES (?, ?, ?, ?, ?, ?)", + (SESSION, *(tokens.get(k, 0) for k in ("input", "output", "reasoning", "cache_read", "cache_write")))) + c.execute("DELETE FROM session_message") + c.executemany("INSERT INTO session_message VALUES (?, ?, 'compaction')", + [(f"msg_{i}", SESSION) for i in range(compactions)]) + + +def test_a_compactions_model_calls_are_counted_from_the_sessions_totals(fake, monkeypatch, capsys): + """OpenCode streams no usage for a compaction's model calls; its session's totals (its database) count them. A + resumed session's earlier totals are taken off; a database OpenCode no longer keeps this way leaves the stream's + usage, said once.""" + work = fake / "work" + work.mkdir() + opencode = agent(fake) + # the stream's four requests (600 + 400 cached in, 15 + 5 reasoning out each) and a compaction of 2000 + 1000 + keep_totals(fake / "home", 1, input=4400, cache_read=2600, output=90, reasoning=30) + [usage] = opencode.run("go", workspace=work).usage + assert (usage.input_tokens, usage.cached_input_tokens, usage.output_tokens, usage.calls) == (7000, 2600, 120, 5) + assert usage.cost_usd == pytest.approx((4400 * 1.0 + 2600 * 0.1 + 120 * 2.0) / 1e6) + replay(monkeypatch, "resume.jsonl") # one request more, and a compaction like the first + keep_totals(fake / "home", 2, input=7000, cache_read=4000, output=135, reasoning=45) + [usage] = opencode.run("again", workspace=work, session=SESSION).usage + assert (usage.input_tokens, usage.cached_input_tokens, usage.output_tokens, usage.calls) == (4000, 1400, 60, 2) + monkeypatch.setattr(base_cli, "_WARNED", set()) + (fake / "home" / "data" / "opencode" / "opencode.db").unlink() + keep_totals(fake / "home", 0) + import sqlite3 + with sqlite3.connect(fake / "home" / "data" / "opencode" / "opencode.db") as c: + c.execute("ALTER TABLE session_v2 RENAME COLUMN tokens_input TO input") + replay(monkeypatch, "success.jsonl") + [usage] = agent(fake).run("go", workspace=work).usage + assert (usage.input_tokens, usage.calls) == (4000, 4) + assert "OpenCode's session database could not be read" in capsys.readouterr().err + + def test_opencode_runs_only_a_model_reference_and_refuses_roles_web_search_a_login_and_a_container(fake): """Each is refused before OpenCode starts, never ignored: no sign-in of the user's is ever copied.""" work = fake / "work" @@ -238,11 +309,15 @@ def test_an_opencode_stream_is_read_back_by_its_name_or_by_its_events(tmp_path): assert base_cli.served("opencode", (STREAMS / "success.jsonl").read_text()) raw = (STREAMS / "failure_500.jsonl").read_text() assert not base_cli.served("opencode", raw) and base_cli.notices("opencode", raw).startswith("provider.internal") + from hermit.agent.base.records import parse_log + session, [usage] = parse_log(STREAMS / "success.jsonl", "opencode", "m") # the generic reader, by its name + assert session == SESSION and (usage.input_tokens, usage.calls) == (4000, 4) def test_the_opencode_acting_agent_deploys_the_adapter_where_opencode_reads_it(fake): - """The adapter's tools are the project's opencode.json, offered directly; its skills are .opencode/skills; its - roles stay files AGENTS.md names, as OpenCode takes none.""" + """The adapter's skills are .opencode/skills; its roles stay files AGENTS.md names, as OpenCode takes none; its + tools are the session's own tool server (the home's opencode.json, running before OpenCode starts), not a server + the project's opencode.json would have OpenCode start: OpenCode waits 2 s at most for one, less than it takes.""" from hermit.agent.acting import workspace as acting params = {**bound(), "backend": "opencode", "web_search": False, "prompt": "go", "workspaces": "ws"} out = acting.run({"id": "q1"}, FILE_ADAPTER, params=params, base=fake) @@ -251,9 +326,10 @@ def test_the_opencode_acting_agent_deploys_the_adapter_where_opencode_reads_it(f assert out.output == "the answer" and out.extra["backend"] == "opencode" and "--approve" not in call["args"] held = json.loads(call["env"]["OPENCODE_CONFIG_CONTENT"]) assert held["permission"]["skill"] == {"*": "deny", "verify-output": "allow"} # the deployment's skills only - [server] = json.loads((work / "opencode.json").read_text())["mcp"]["servers"].values() - assert server["type"] == "local" and server["codemode"] is False - assert "hermit.runtime.mcp_server" in server["command"] + assert json.loads((work / "opencode.json").read_text())["mcp"]["servers"] == {} + [(name, server)] = json.loads(call["files"]["opencode.json"])["mcp"]["servers"].items() + assert name == "file_example" and server["type"] == "remote" and server["codemode"] is False + assert out.extra["deployed"]["harness_tools"] == "file-example" assert (work / ".opencode" / "skills" / "verify-output" / "SKILL.md").is_file() assert "do it yourself" in (work / "AGENTS.md").read_text() assert (out.log / "agent-opencode.jsonl").is_file() @@ -289,11 +365,12 @@ def test_opencode_is_a_base_of_the_config_and_the_opencode_evolver_binds_its_mod # ---------- the installed opencode (integration) ---------- -def serve_chat(script, status: int | None = None, seen: list | None = None): - """A chat-completions model on the loopback: `script(request body) -> (tool call (name, arguments) | None)`; - None answers `the answer`, with a reasoning text first. Every response is streamed, with usage (1000 prompt - tokens, 400 of them cached; 20 completion tokens, 5 of them reasoning). With `status`, every request is answered - that error. `seen` gets each request's body and Authorization header.""" +def serve_chat(script, status: int | None = None, seen: list | None = None, prompt_tokens=lambda body: 1000): + """A chat-completions model on the loopback: `script(request body) -> (tool call (name, arguments) | text | + None)`; None answers `the answer`, with a reasoning text first. Every response is streamed, with usage + (`prompt_tokens(body)` prompt tokens, 1000 by default, 400 of them cached; 20 completion tokens, 5 of them + reasoning). With `status`, every request is answered that error. `seen` gets each request's body and + Authorization header.""" from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer def chunk(body): @@ -320,12 +397,13 @@ def do_POST(self): "type": "function", "function": {"name": call[0], "arguments": json.dumps(call[1])}}]}] \ - if call else [{"role": "assistant", "reasoning_content": "The work is done."}, - {"content": "the answer"}] + if isinstance(call, tuple) else [{"role": "assistant", "content": call}] if call else \ + [{"role": "assistant", "reasoning_content": "The work is done."}, {"content": "the answer"}] data = b"".join([*(chunk({"choices": [{"index": 0, "delta": d, "finish_reason": None}]}) for d in deltas), chunk({"choices": [{"index": 0, "delta": {}, "finish_reason": - "tool_calls" if call else "stop"}]}), - chunk({"choices": [], "usage": {"prompt_tokens": 1000, "completion_tokens": 20, + "tool_calls" if isinstance(call, tuple) else "stop"}]}), + chunk({"choices": [], "usage": {"prompt_tokens": prompt_tokens(body), + "completion_tokens": 20, "prompt_tokens_details": {"cached_tokens": 400}, "completion_tokens_details": {"reasoning_tokens": 5}}}), b"data: [DONE]\n\n"]) @@ -412,8 +490,8 @@ def script(body): @pytest.mark.integration @pytest.mark.skipif(not shutil.which("opencode"), reason="needs the opencode CLI") def test_with_the_opencode_cli_the_acting_agent_uses_the_deployed_adapters_tools(tmp_path, monkeypatch): - """The deployment as OpenCode reads it: the project's opencode.json starts the adapter's tool server, whose tool - the model is offered directly and calls.""" + """The deployment as OpenCode reads it, the adapter's tools from the session's own tool server: the model is + offered them directly from its first request on, and calls one.""" from hermit.agent.acting import workspace as acting calls, bodies = [], [] @@ -432,7 +510,53 @@ def script(body): "workspaces": "ws", "timeout_s": 300, "retries": 1}) finally: server.shutdown() + # offered from the first request on (a server OpenCode started itself was often not ready for it) assert out.output == "the answer" and "file_example_count_words" in calls[0] assert "verify-output" in json.dumps(bodies[0]) # the deployment's skill, the one the session may load - audit = Path(out.extra["workspace"]) / "tool-calls.jsonl" - assert '"count_words"' in audit.read_text() + [result] = [m for m in bodies[-1]["messages"] if m.get("role") == "tool"] + assert json.loads(result["content"]) == {"count": 3} + + +@pytest.mark.integration +@pytest.mark.skipif(not shutil.which("opencode"), reason="needs the opencode CLI") +def test_with_the_opencode_cli_a_compactions_model_calls_are_counted(tmp_path, monkeypatch): + """OpenCode compacts a session that nears its context window, with model calls its stream never reports: they + are counted from its session's totals, each request's tokens once, also when the session is resumed (its earlier + calls not counted again).""" + requests, steps = [], [] + + def compacting(body): + return "Return only the structured summary" in json.dumps(body["messages"][-1]) + + def script(body): + if compacting(body): + return "## Objective\n- Read a.txt.\n\n## Next Move\n1. Answer." + steps.append(body) + return ("read", {"filePath": str(work / "a.txt")}) if len(steps) % 5 else None + + def tokens(body): + return 1000 * len(body["messages"]) # the conversation grows to the window: OpenCode compacts + + def counted(served): + return (sum(tokens(r["body"]) for r in served), 400 * len(served), 20 * len(served), len(served)) + + server, url = serve_chat(script, seen=requests, prompt_tokens=tokens) + monkeypatch.setenv("MOCK_KEY", "sk-mock") + work = tmp_path / "work" + work.mkdir() + (work / "a.txt").write_text("hello\n") + params = mock_params(url) + params["provider"]["models"]["m-1"]["limit"] = {"context": 8000, "output": 100} + opencode = make("opencode", {**params, "web_search": False, "home": str(tmp_path / "home"), "timeout_s": 300}) + try: + first = opencode.run("Read a.txt, then answer.", workspace=work) + before = len(requests) + second = opencode.run("Again.", workspace=work, session=first.session) + finally: + server.shutdown() + assert first.reply == "the answer" and sum(map(compacting, (r["body"] for r in requests[:before]))) == 1 + u = first.usage[0] + assert (u.input_tokens, u.cached_input_tokens, u.output_tokens, u.calls) == counted(requests[:before]) + assert second.session == first.session and second.reply == "the answer" + u = second.usage[0] + assert (u.input_tokens, u.cached_input_tokens, u.output_tokens, u.calls) == counted(requests[before:]) diff --git a/tests/methods/ahe/test_ahe_hosts.py b/tests/methods/ahe/test_ahe_hosts.py index 8fe78859..0118b11b 100644 --- a/tests/methods/ahe/test_ahe_hosts.py +++ b/tests/methods/ahe/test_ahe_hosts.py @@ -669,8 +669,9 @@ def test_a_state_with_an_unencodable_character_is_saved(tmp_path, capsys, monkey # --- the Evolver's texts ----------------------------------------------------------------------------------------- def test_the_evolvers_texts_name_every_acting_agents_stream_it_reads(): - """A Pi or mini-swe-agent acting agent's sessions keep their own stream (agent-pi.jsonl, agent-mini-swe-agent.jsonl), - which rollout_stream finds: the learners' texts name it, not Codex's file, which is not there.""" + """A Pi, mini-swe-agent or OpenCode acting agent's sessions keep their own stream (agent-pi.jsonl, + agent-mini-swe-agent.jsonl, agent-opencode.jsonl), which rollout_stream finds: the learners' texts name it, not + Codex's file, which is not there.""" from hermit.agent.base.trajectory import CODEX_STREAM, STREAMS from hermit.agent.evolver.methods.ahe_adapter import analysis as A, debugger as D import test_ahe_analysis as AN @@ -685,7 +686,8 @@ def test_the_evolvers_texts_name_every_acting_agents_stream_it_reads(): assert "codex exec --json" not in words, stream assert stream in D.for_stream(texts[0], stream) for stream, command in (("agent-pi.jsonl", "pi --mode json"), - ("agent-mini-swe-agent.jsonl", "python -m hermit.agent.base.mini_swe_agent_run")): + ("agent-mini-swe-agent.jsonl", "python -m hermit.agent.base.mini_swe_agent_run"), + ("agent-opencode.jsonl", "opencode run --format json")): assert f"`{command}` event stream" in D.for_stream(texts[1], stream)