refactor agent sandbox infrastructure with new agent backends + rework logprobs capture
Summary
The coding environment was hardwired to OpenCode. This PR pulls the sandbox and harness infrastructure into src/openenv/core/harness/ so it's shared, adds a declarative CLIAgentSpec + CLIAgentDriver that any agent adapter can plug into, ships OpenCode and Pi as the first two adapters, adds Docker and HF Sandbox backends alongside the existing E2B one, and renames opencode_env → coding_agent_env.
Changes
Sandbox protocols moved to core (src/openenv/core/harness/sandbox/). SandboxBackend, SandboxHandle, BgJob were locked inside opencode_env. They're now the shared seam. E2BSandboxBackend is unchanged and already works with CubeSandbox (E2B-compatible self-hosted MicroVM sandbox) by pointing E2B_API_URL at it.
Docker sandbox backend added (src/openenv/core/harness/sandbox/docker_backend.py). Runs sandboxes via docker run. Suitable for local development and CI.
HF Sandbox backend added (src/openenv/core/harness/sandbox/hf_backend.py). Wraps hf-sandbox.
CLIAgentSpec + CLIAgentDriver (src/openenv/core/harness/agents/). Per-agent knowledge is expressed as a declarative dataclass — install script, files to upload, env vars, MCP config format, artifacts to collect — with three small callables for the parts that can't be data (command builder, MCP config serializer, stdout event parser). The driver reads these fields and runs the lifecycle; it has no per-agent branches. Same pattern as verifiers (Prime Intellect). Adding a new agent is writing a spec, not touching the driver.
OpenCode refactored onto CLIAgentSpec. envs/coding_agent_env/harness.py is now a thin wrapper around CLIAgentSessionFactory.
Pi adapter added (src/openenv/core/harness/agents/pi.py). Runs Pi in print mode via --no-session -p @/instruction.txt, matching the verifiers Pi harness approach.
opencode_env → coding_agent_env. The environment is for coding tasks; the harness is a config parameter. run_rollout now takes agent: str = "opencode" and supports "opencode" and "pi". Gradio UI gets an agent selector. All imports, docs, pyproject.toml, openenv.yaml, and Dockerfile updated.
Tests
tests/core/test_cli_agent_driver.py — driver lifecycle via _FakeSandbox
tests/core/test_harness_adapters.py — per-adapter: MCP config, CLI flags, event parsing, registry
tests/core/test_docker_sandbox_backend.py — Docker backend
tests/core/test_hf_sandbox_backend.py — HF backend
tests/envs/test_coding_agent_env.py — end-to-end env tests (renamed, extended)
References
- verifiers
CLIHarness— declarative harness pattern this follows - CubeSandbox — E2B-compatible self-hosted sandbox
- HF Sandbox
- Pi
- Firehorse — studied for tool conflict and MCP failure patterns, not adopted (eval-only, no sandbox isolation, no training path)
- AReaL
remote_inf_engine.py— proxy-based logprob interception pattern
Type of Change
- [ ] Bug fix
- [x] New feature
- [x] Breaking change
- [x] Documentation
- [ ] New environment
- [x] Refactoring
Alignment Checklist
Before submitting, verify:
- [x] I have read
.claude/docs/PRINCIPLES.mdand this PR aligns with our principles - [x] I have checked
.claude/docs/INVARIANTS.mdand no invariants are violated - [x] I have run
/pre-submit-pr(orbash .claude/hooks/lint.shand tests) and addressed all issues
RFC Status
- [x] Not required (bug fix, docs, minor refactoring)
- [ ] RFC exists: #___
- [ ] RFC needed (will create before merge)
Claude Code Review
n/a
cc: @burtenshaw
Greptile Summary
This PR refactors the hardwired OpenCode environment into a shared CLIAgentDriver / CLIAgentSpec infrastructure in src/openenv/core/harness/, renames opencode_env → coding_agent_env, and ships Docker and HF Sandbox backends alongside the existing E2B one. It is a substantial architectural refactor with two new agent adapters (OpenCode and Pi) and a declarative spec pattern that makes adding future agents trivial.
- Core driver (
cli_driver.py): introducesCLIAgentDriver/CLIAgentSessionFactoryas the shared lifecycle engine; the_exec_with_retryhelper has a correctness bug (early break on any non-empty stderr) that defeats the advertised 3-attempt install retry. - Server layer (
coding_environment.py): lazy-imports viafrom coding_agent_env import ...which triggers__init__.py → client.py, violating the INVARIANTS client-server separation boundary; setup commands also run after the agent has already started, creating a correctness race for tasks that depend on setup completing first. - New backends (
docker_backend.py,hf_backend.py): correctly implement theSandboxBackendprotocol but are not wired into_build_session_factory, so they are unreachable via the MCPrun_rollouttool.
Confidence Score: 2/5
Not safe to merge as-is — the server layer imports client code through the package init, violating a hard architectural boundary, and there is a real correctness race between setup commands and the running agent.
The server indirectly pulls in client.py via coding_agent_env/init.py every time CodingAgentEnvironment initializes, crossing a boundary the repo treats as non-negotiable. The _exec_with_retry bug means install retries never fire for the most common failure mode (non-empty stderr), so cold sandbox installs will fail non-deterministically in CI. The setup/agent race is explicitly noted as a known compromise but affects any task that writes input files or installs dependencies before the agent's first model call.
envs/coding_agent_env/server/coding_environment.py (client-server violation + setup race), envs/coding_agent_env/init.py (root init imports client), src/openenv/core/harness/agents/cli_driver.py (retry logic bug)
Important Files Changed
| Filename | Overview |
|---|---|
| src/openenv/core/harness/agents/cli_driver.py | Core CLI driver for all agent harnesses; contains a retry bug in _exec_with_retry where any non-empty stderr immediately aborts retries, defeating 3-attempt install guarantees. |
| envs/coding_agent_env/server/coding_environment.py | New MCP environment server — has two issues: server lazy-imports coding_agent_env.__init__ which pulls in client.py (violates client-server separation); setup commands race with the already-running agent. |
| src/openenv/core/harness/sandbox/docker_backend.py | New Docker sandbox backend; protocol-correct and well-structured, but not wired into the server layer so unreachable via the MCP run_rollout tool. |
| src/openenv/core/harness/sandbox/hf_backend.py | New HF Sandbox backend; HFBgJob.wait() uses a blocking polling loop instead of a background thread — acceptable but the calling thread is blocked for the full agent duration with no interrupt path. |
| envs/coding_agent_env/init.py | Root package init unconditionally imports from .client import CodingAgentEnv, causing server code that does from coding_agent_env import ... to indirectly pull in client code — violates INVARIANTS client-server separation. |
| src/openenv/core/harness/agents/base.py | Declarative CLIAgentSpec dataclass and supporting protocols — clean, well-documented, no issues. |
| src/openenv/core/harness/agents/opencode.py | OpenCode adapter expressed as a declarative spec; _build_opencode_mcp_config intentionally returns empty string (config written via spec.files), which is correct. |
| src/openenv/core/harness/agents/pi.py | Pi adapter — maps api_key to both HF_TOKEN and OPENAI_API_KEY, which is correct for Pi's multi-provider support. |
| src/openenv/core/harness/sandbox/interception.py | Transparent forwarding proxy for logprob capture; streaming error-path handling (non-2xx returning JSON instead of empty SSE) is a correctness improvement over the prior version. |
| envs/coding_agent_env/harness.py | Thin wrapper around CLIAgentDriver; calls _driver._start_proxy() directly (private API) which is a coupling smell but functionally correct. |
Sequence Diagram
sequenceDiagram
participant Orch as Orchestrator
participant Env as CodingAgentEnvironment
participant Factory as SessionFactory
participant Driver as CLIAgentDriver
participant SB as SandboxBackend (E2B/Docker/HF)
participant Proxy as InterceptionProxy
Orch->>Env: run_rollout(agent, instruction, setup, verify)
Env->>Factory: create(task)
Factory->>Driver: create_session(task, config)
Driver->>SB: create(timeout_s)
SB-->>Driver: SandboxHandle
Driver->>Driver: _bootstrap_sandbox
alt "mode == transparent_proxy"
Driver->>SB: start_bg(interception.py)
SB-->>Driver: proxy BgJob
end
Driver->>SB: start_bg(agent CLI)
SB-->>Driver: agent BgJob
Driver-->>Factory: CLIAgentSession
Factory-->>Env: session (agent already running)
Note over Env: setup commands run HERE — races with agent
loop setup commands
Env->>SB: exec(cmd)
end
Env->>Factory: wait_for_completion()
loop verify commands
Env->>SB: exec(cmd)
end
Env->>SB: kill()
Env-->>Orch: RolloutResult (JSON)
Comments Outside Diff (2)
-
envs/coding_agent_env/server/coding_environment.py, line 693-711 (link)Setup commands race with running agent
The agent is launched inside
factory.create()viasession.start_agent()before this loop runs. For tasks that require setup to complete before the agent's first tool call (e.g., installing a dependency or writing an input file the agent reads on start), this is a silent correctness failure: the agent may attempt to importpandaswhile thepip install pandassetup command is still running. The inline comment acknowledges the race but frames it as "fine for typical work" — that assumption breaks for any task where the agent reads setup-created files or depends on pre-installed packages.Prompt To Fix With AI
This is a comment left during a code review. Path: envs/coding_agent_env/server/coding_environment.py Line: 693-711 Comment: **Setup commands race with running agent** The agent is launched inside `factory.create()` via `session.start_agent()` before this loop runs. For tasks that require setup to complete before the agent's first tool call (e.g., installing a dependency or writing an input file the agent reads on start), this is a silent correctness failure: the agent may attempt to import `pandas` while the `pip install pandas` setup command is still running. The inline comment acknowledges the race but frames it as "fine for typical work" — that assumption breaks for any task where the agent reads setup-created files or depends on pre-installed packages. How can I resolve this? If you propose a fix, please make it concise. -
envs/coding_agent_env/server/coding_environment.py, line 831-854 (link)ALIGNMENT FLAG: New Docker/HF sandbox backends are unreachable via the MCP tool
_build_session_factoryalways createsE2BSandboxBackend. TheDockerSandboxBackendandHFSandboxBackendadded in this PR tosrc/openenv/core/harness/sandbox/are only usable programmatically via the harness primitive, not through the deployedrun_rolloutMCP tool. There is nobackendparameter in the tool signature to select them. The PR description bills Docker as "suitable for CI" but CI agents can only reach the environment via MCP, so Docker is effectively unused in the primary run path.- Principle at stake: "Be hands-on: Provide ready-to-use implementations, not just specs" (PRINCIPLES.md)
- The concern: New backends shipped to core are disconnected from the server layer with no path to adoption
- Suggested reviewer:
@darktex
Context Used: .claude/docs/PRINCIPLES.md (source)
Prompt To Fix With AI
This is a comment left during a code review. Path: envs/coding_agent_env/server/coding_environment.py Line: 831-854 Comment: **ALIGNMENT FLAG: New Docker/HF sandbox backends are unreachable via the MCP tool** `_build_session_factory` always creates `E2BSandboxBackend`. The `DockerSandboxBackend` and `HFSandboxBackend` added in this PR to `src/openenv/core/harness/sandbox/` are only usable programmatically via the harness primitive, not through the deployed `run_rollout` MCP tool. There is no `backend` parameter in the tool signature to select them. The PR description bills Docker as "suitable for CI" but CI agents can only reach the environment via MCP, so Docker is effectively unused in the primary run path. - **Principle at stake**: "Be hands-on: Provide ready-to-use implementations, not just specs" (PRINCIPLES.md) - **The concern**: New backends shipped to core are disconnected from the server layer with no path to adoption - **Suggested reviewer**: `@darktex` **Context Used:** .claude/docs/PRINCIPLES.md ([source](https://app.greptile.com/review/custom-context?memory=67b96369-b31e-4918-84c9-a0a4e3c8aa97)) How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
Fix the following 4 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 4
src/openenv/core/harness/agents/cli_driver.py:446-465
**`_exec_with_retry` breaks on first non-empty stderr, defeating retries**
The `if last_stderr.strip(): break` exits the retry loop on the very first failure that produces any stderr output — which is exactly the case for transient network errors (e.g., `curl: (6) Could not resolve host` or a flaky apt mirror). The install stage advertises 3-attempt retries with exponential backoff, but in practice retries only fire when a command exits non-zero with _empty_ stderr or throws a Python exception, which covers almost no real-world install failures.
For example, `curl -fsSL https://opencode.ai/install | bash` failing with a DNS error or a 503 will immediately raise without retry, rather than being retried after 3s and 6s as intended.
```suggestion
last_stdout = r.stdout or ""
last_stderr = r.stderr or ""
last_exit = r.exit_code
```
### Issue 2 of 4
envs/coding_agent_env/server/coding_environment.py:693-711
**Setup commands race with running agent**
The agent is launched inside `factory.create()` via `session.start_agent()` before this loop runs. For tasks that require setup to complete before the agent's first tool call (e.g., installing a dependency or writing an input file the agent reads on start), this is a silent correctness failure: the agent may attempt to import `pandas` while the `pip install pandas` setup command is still running. The inline comment acknowledges the race but frames it as "fine for typical work" — that assumption breaks for any task where the agent reads setup-created files or depends on pre-installed packages.
### Issue 3 of 4
envs/coding_agent_env/server/coding_environment.py:425-432
**ALIGNMENT FLAG: Server imports client code via `coding_agent_env.__init__`**
The lazy import `from coding_agent_env import E2BSandboxBackend, CodingAgentConfig, CodingAgentSessionFactory, CodingAgentTask` triggers `coding_agent_env/__init__.py` which unconditionally executes `from .client import CodingAgentEnv`. This means `server/coding_environment.py` (server code) indirectly imports `client.py`, directly violating INVARIANTS.md §2 "Client-server separation": "Server code must never import client code."
The fix is to import from the specific sub-modules (`from coding_agent_env.config import CodingAgentConfig`, etc.) or split `__init__.py` into server-side and client-side exports.
- **Invariant at risk**: Client-server separation (INVARIANTS.md §2)
- **Suggested reviewer**: `@darktex`
### Issue 4 of 4
envs/coding_agent_env/server/coding_environment.py:831-854
**ALIGNMENT FLAG: New Docker/HF sandbox backends are unreachable via the MCP tool**
`_build_session_factory` always creates `E2BSandboxBackend`. The `DockerSandboxBackend` and `HFSandboxBackend` added in this PR to `src/openenv/core/harness/sandbox/` are only usable programmatically via the harness primitive, not through the deployed `run_rollout` MCP tool. There is no `backend` parameter in the tool signature to select them. The PR description bills Docker as "suitable for CI" but CI agents can only reach the environment via MCP, so Docker is effectively unused in the primary run path.
- **Principle at stake**: "Be hands-on: Provide ready-to-use implementations, not just specs" (PRINCIPLES.md)
- **The concern**: New backends shipped to core are disconnected from the server layer with no path to adoption
- **Suggested reviewer**: `@darktex`
Reviews (1): Last reviewed commit: "feat: hf sandbox backend" | Re-trigger Greptile
Thank you for the reviews @Darktex! I will be fixing them shortly. Also could you clean up the duplicated noise caused by claude so that the thread is cleaner?