Add or Update a Harness
A harness is an agent runtime, such as Hermes, Pi, or Codex, that runs the model and tool loop. A Gym adapter is the Agent Server that wraps the harness. This page explains how to integrate a harness that runs inside a task sandbox, and how to validate a new harness or an upgrade. The same contracts apply to an adapter for an agent framework, such as LangChain DeepAgents; that adapter loads the user’s agent instead of installing a CLI.
In sandbox execution, the adapter stays outside the sandbox, and the harness and its tools run inside it. If an adapter also supports host execution, keep that path working and test it separately.
Session support varies by adapter. Check the adapter’s README for supported features and limitations.
To run an agent that Gym already integrates, see Integrate Existing Agents.
Terminology
Plan the adapter
This page covers building and updating an adapter. To choose between Remote Agent, an adapter, and a custom Environment Server first, see Choose a Path.
Choose the capabilities you need
An adapter can stop at any level below. Each level adds work and enables a specific Gym capability. State the supported level in the adapter’s README, and reject or document anything it does not support.
An adapter that stops at Evaluation returns no invocation or turn records, so its rollouts are unobserved in rollout health and fail the evidence check. That is expected at that level. Its close still returns an AgentObservationBundle whose gaps name the missing evidence.
What you write
An adapter supplies the knowledge that is specific to the harness or framework:
- Install or load the agent. For example, a framework adapter lists the framework in its
pyproject.toml, while Pi and Codex install a pinned runtime into the task sandbox at seed. - Configure and invoke it. Build the harness configuration from the adapter configuration and the request, then call the SDK or start the CLI. For example, Hermes writes a
config.yaml, Pi starts its CLI through the sharedharness_runner.sh, and Codex starts its CLI through the same runner with a small Node launcher,sandbox_launcher.mjs, that also runs a sandbox-local retry proxy for model requests. - Map the harness’s inputs, results, and traces to Gym. Convert the request into the harness’s input, the harness’s output into a
NeMoGymResponse, and its model and tool activity into anAgentObservationBundle. - Map Gym connections into the harness’s own configuration. Set the rollout-prefixed Model Server URL as the harness’s model base URL, add tool grants to its tool configuration, and run it in
SandboxAccess.workdir. For example, Hermes adds each MCP grant to themcp_serverssection of its configuration.
What Gym provides
Gym does not provide adapter scaffolding or default conversion and usage accounting; each adapter implements them.
Architecture and ownership
Keep the benchmark and the harness independent
Keep task data, preparation, verification, and sandbox requirements in the benchmark’s Resources Server. Keep the execution loop, runtime, and harness settings in the adapter. Configure and launch each one independently.
An Environment Server binds the two by reference, and episodes are submitted to its /run endpoint. To pair a compatible benchmark and harness, you should only need to change the configuration. You should not need a launcher, adapter, or preset written for that specific pair.
Episode lifecycle
Architecture gives the general episode flow. The following diagram adds the sandbox and adapter details for one episode in which the Resources Server supplies the task sandbox. All Gym servers are FastAPI applications that exchange JSON over HTTP. Sandbox execution and file transfer use the configured provider’s transport. The model calls shown are those of Hermes, which uses Chat Completions.
The agent session must close successfully before verification starts. Agent close stops harness work and disconnects from the sandbox. It does not destroy a borrowed sandbox.
- The Environment Server orders the session calls and the final cleanup. The Resources Server implements the benchmark’s sandbox lifetime policy. It decides which sandbox to reuse, when to create a verifier sandbox, and when to stop each sandbox it owns.
- In agent and model routes,
...stands for Gym’s rollout prefix and the optional token-capture segment,/ng-rollout/<capture_key>[/training-token-capture]. Preserve this prefix when you forward requests. The segment decides capture: an agent activated without it captures none of that activation’s calls, even if the agent setstoken_id_capture, so an Environment Server that wants a rollout captured must include it. - If an episode is interrupted, close joins or retries finalization. It confirms harness termination, captures the available artifacts, and then releases resources. Finish collecting output before you delete session files or stop an agent-owned sandbox.
Sandbox lifetime policies
The two Resources Servers below implement different lifetime policies. Both descriptions cover the normal borrowed-session path with golden-patch mode disabled. The diagram above shows one verification attempt and leaves out validation, retries, and error handling.
Terminal Bench 2.1 (#3902 at 8bd25f372)
- Where verification runs: in the sandbox the agent used. Verification runs
bash /tests/test.shthere, so task services that the agent started remain available to the tests. The first verification result is cached for the session: an identical retry replays it instead of grading the already-modified task again. - When the sandbox stops: verification keeps the sandbox. The Environment Server’s final
/close_sessioncall reachesclose_resources_session(), which stops the sandbox and fences the session for the close retry window,session_close_retry_window_seconds. If stopping fails, the Resources Server keeps ownership so that close can retry. Close also marks a setup that is still in progress as closing, so a setup that finishes after a timed-out close tries to stop its own sandbox. If that stop fails after the Environment Server has cancelled its final close callback, nothing retries it automatically: the Resources Server keeps the session record and the sandbox handle for an explicit close retry or shutdown. The provider TTL can stop the abandoned sandbox, but it does not clear the Resources Server’s in-memory record.
SWE-bench Pro (revision 7f16ec541)
- Where verification runs: in a fresh verifier sandbox. Verification exports and downloads the patch from the task sandbox, then creates a verifier sandbox that receives the patch and the verification inputs.
- When the sandboxes stop:
_extract_model_patch()stops the original sandbox in itsfinallyblock. Each verification attempt stops its own verifier sandbox infinally. The final/close_sessioncall releases any remaining session resources. - What it relies on: patch extraction runs in the task sandbox after agent close, so the harness and its tool commands must have stopped. A build or watcher that is still writing can change the patch or hold
.git/index.lock. See Harness termination for the cases that the supervisor cannot stop.
The Terminal Bench 2.1 behavior and the process-group termination policy described in Harness termination landed in #3902, merge commit 8bd25f372, which the source links on this page pin. Checkouts from before that merge keep the earlier policy.
Neither policy changes the Resources Server’s session API or the SandboxAccess contract that the agent receives. Keep the choice between reusing the task sandbox and creating a verifier sandbox in the Resources Server, so that swapping the agent cannot change the benchmark’s ownership or verification policy. The final /close_session call is still required when verification has already stopped the original sandbox.
To choose a policy, first preserve the verification protocol of an existing benchmark. For a new benchmark, reuse the task sandbox when scoring depends on its final state, including changes that an exported artifact would not capture. Use a fresh verifier sandbox when the contract is to apply an exported artifact, such as a patch, to a clean baseline and score it there.
Integration contracts
An adapter implements three contracts: one with the Environment Server, one with the task sandbox, and one for tools. Settle all three before you write harness-specific code.
Agent Server and Environment Server
The Environment Server drives an agent session through three HTTP endpoints. SimpleResponsesAPIAgent registers all three; the adapter implements the hooks listed in the last column.
Implement these hooks and nothing more: the Environment Server runs the episode. The Environment Server compliance check flags an agent that does not implement them, or that keeps parts of the earlier design in which the agent ran the whole episode itself.
The stop route ends a running harness exactly as at its time limit, so the episode is still verified and graded as a timeout. It is for a caller that enforces its own budget (agent time, tokens, cost) or for an operator; cancelling the /run request instead discards the rollout. An agent whose harness runs in a SandboxSession supports it by returning that session from _rollout_sandbox_session() and passing its response through report_rollout_stop(), as Codex does; other agents answer HTTP 501. The stopped run’s response keeps the timeout’s incomplete status, which single_agent_turn verifies, and its metadata gains ng_rollout_stop, a JSON object with the caller’s reason (or null). A stop with completed: true, for a run whose task ended, gives the response the completed status instead, and its marker adds "completed": true; the session close reports the run’s top-level invocation as completed too, and the sandbox observation keeps the timeout. That marker tells a stop apart from a timeout or a cancellation. A stop is not a failure, so the response carries no ng_agent_outcome failure kind, and a rollout that was stopped and graded is an ordinary result. The caller keeps awaiting its /run request, which returns the graded result once verification finishes. Harness runners see the timeout path, not a cancellation: they find no stop.request marker. stopped: true means the stop was accepted; the run can still finish on its own before the stop takes effect. stopped is false when the run already ended or a stop was already requested. An unknown or closed rollout answers HTTP 404, and a stop that arrives while the session is still seeding takes effect when the harness would launch. Stopping a running harness writes a file its supervisor watches for, so it needs a sandbox provider whose uploads never wait for the capacity running commands hold (SupportsSandboxIndependentUploads): Local, bwrap, Docker, and OpenSandbox with operations.background_exec: true. On Apptainer, Daytona, E2B, ECS Fargate, Enroot and OpenShell, and on OpenSandbox in foreground mode, a stop of a running harness answers HTTP 501. A stop before launch works on every provider. With several server workers the request needs no session cookie: the worker running the rollout claims its /rollouts/<capture_key> path, and the others forward the stop to it. A stop applies to the rollout’s current agent session. An environment that opens a new session for each turn, such as Harbor’s multi-step tasks, still schedules the later turns, and a stop sent between sessions finds no open session and answers HTTP 404. A caller enforcing a budget for the whole episode must also keep the environment from starting further turns once the current one is graded.
Every Environment Server that drives sessions uses these endpoints, such as single_agent_turn for a Resources Server task and harbor for a task folder, where the Environment Server creates the sandbox itself and passes it in sandbox_access. See Design Agent-Environment Interactions.
AgentSeedSessionRequest carries agent_session_id, episode_id, task_id, tool_accesses, an optional sandbox_access, and an optional agent_context (see Agent context). AgentCloseSessionResponse returns agent_observations, an optional trajectory (the harness’s own turns, which the Environment Server forwards as ng_trajectory on the result and on a failure row alike), and an optional resources_cookies jar.
The base class in nemo_gym/agents/base_responses_api_agent.py enforces the seed, cookie, and close rules below. The adapter implements the activation rules in responses(), as Hermes, Pi, Codex, OpenCode, and OpenClaw do. Every adapter must preserve all of them:
- Idempotent seed. A repeated seed with the same ID and an identical body returns the existing session. A different body for the same ID returns HTTP 409. Agent sessions run with several workers when all of their state lives in the session, because session routing sends each session’s requests to the worker that holds it. A server that keeps state anywhere else overrides
multiple_workers_unsupported_reason(), and then refusesnum_workers > 1at startup. - Cookie binding. Seed stores
agent_session_idin the Agent Server’s signed session cookie. Activation and close requests with a mismatched cookie return HTTP 409. After close, the cookie stays set, so a stale activation cannot fall back to the sessionless host path. - Single activation. Bind the first activation request before the first
await. Identical retries join the same invocation, and a different request returns HTTP 409. Shield the shared task so that a disconnected HTTP client cannot cancel the harness; only close cancels it. Inresponses(), call_require_agent_session()to reject incomplete or closing sessions before execution. - Activation identity. Reject an activation whose rollout path does not match the seeded
episode_id.capture_key. - Saved reply. The first successful close’s response, including its observations, is saved and returned to a retried close for the close retry window,
session_close_retry_window_seconds(default 300). If harness termination cannot be confirmed yet, the session state is kept so that close can retry. After a final negative termination receipt, the session state is released instead; see Harness termination. - Setup failure. If seed fails and its cleanup cannot finish, raise
AgentSessionSetupError(state, error=...). The base class keeps the partial state for close and never activates it. - Deterministic errors. For a seed the agent cannot serve, such as an unsupported sandbox connection or an unusable required tool grant, raise
AgentSeedRejectedError(reason)from_seed_agent_session_state(). The seed returns HTTP 422 with a stringdetailand binds no session, so the episode fails once with the refusal reason. An adapter that cannot use a lent sandbox at all refuses it this way, with adetailthat saysdoes not support sandbox access; the Environment Server compliance check flags any other failure of a seed that lends a sandbox. Test each refusal withnemo_gym.agents.testing.agent_session_conformance.check_agent_seed_rejected. For a request that conflicts with the agent session, such as one for a closed session, raiseAgentSessionConflictError, which answers HTTP 409. For other errors that a retry cannot fix, such as an invalid request, raise anHTTPExceptionwith a 4xx status other than 409; it keeps its explicit status. Any other, unexpected exception answers HTTP 500. A deterministic 500 makes the episode eligible for another attempt on resume. See execution health and reward.
Close must return agent_observations even when activation failed, and the trajectory of the turns taken before the failure when the harness keeps one. When no observations were captured, return a bundle with an ObservationGap such as observation_capture_failed. Return resources_cookies only if the harness changed the Resources Server’s cookie jar through tool calls. None or an empty jar keeps the cookies from the Resources Server’s seed.
Agent Server and task sandbox
The Resources Server returns a SandboxAccess from its seed, and the Environment Server forwards it unchanged in AgentSeedSessionRequest.sandbox_access:
provider_config_ref names a top-level sandbox provider block in the merged Gym configuration, such as the sandbox block from opensandbox.yaml. descriptor identifies the running sandbox. Connect to the sandbox as a borrower:
Follow these rules for a borrowed sandbox:
- Reject connection kinds that the adapter cannot use. Hermes, Pi, Codex, OpenCode, and OpenClaw accept only
direct. - Require an absolute
workdir. Keep runtime files, session files, harness configuration, and caches outside it. For example, Pi and Codex keep session files under/tmp/nemo-gym-<harness>-sessions/<id>. - Isolate harness state with harness-specific variables, such as
CODEX_HOMEorPI_CODING_AGENT_DIR, instead of overridingHOME. Tool shells must keep the task’sHOMEandXDG_*directories, because verification runs with the task’s home and agent close deletes the session directory. Otherwise, the effects of commands such asgit config --globalorpip install --user, and files written under~, land in a throwaway home and can silently lower scores. - Keep harness caches out of the task’s home as well. A harness that writes to
~/.cacheby default puts its files in the task’sHOME; for example, the GitHub Copilot CLI 1.0.103 binary unpacks about 236 MB of bundled files into$HOME/.cacheon its first run. Redirect each cache with a tool-specific variable that you set only in the environment of the harness or its installer, as Stirrup’s installer setsUV_CACHE_DIRunder its runtime directory. If the harness has no such variable, unpack the files once during installation under the private runtime directory, for example by running the installer’s first launch with a privateHOME, and point the harness at that copy. In either case, leave theHOMEandXDG_*variables that tool shells inherit unchanged. - If correctness depends on a harness plugin or hook, make it fail closed. For example, OpenCode logs a plugin that fails to load and still exits 0, so the OpenCode adapter’s task-environment plugin writes
task-environment.readyafter validating the task directory settings and initializing the hook that restores them for each shell call. The adapter refuses to return a gradable result without that receipt. - Install only the harness runtime. The Resources Server has already prepared the task repository and its dependencies.
- If connection or setup fails, propagate the error. Never fall back to the host or to a different sandbox.
- On close, remove only adapter-owned files and disconnect. The Resources Server destroys the sandbox, and the Environment Server compliance check flags an agent that stops it.
The adapter reaches the sandbox only through AsyncSandbox. The harness reaches Gym only through the Model Server and any granted tool endpoints. Each connection has its own protocol:
Tools
A harness can get tools from two sources:
- Built-in harness tools. These run inside the task sandbox as part of the harness, such as a shell or a file editor. The adapter enables them through harness settings.
- Tool grants from the Environment Server. These arrive in
AgentSeedSessionRequest.tool_accesses. The Environment Server’sresources_tool_transportssetting selects which grants it creates for the episode’s Resources Server, and itstool_serverssetting adds a required MCP grant for each other listed Resources server, such as a search server, falling back to the agent configuration’stool_servers:
Grants in the agent configuration’s tool_accesses are merged with the episode’s grants by name. Call effective_tool_accesses(body) to get the merged list. The grant types are defined in nemo_gym/server_runtime/tool_access.py.
An adapter must handle grants as follows:
- At seed, reject any required grant that the harness cannot use, with HTTP 422. An optional grant can be skipped. Never silently ignore a required grant.
- Reject grant names that collide with the names of built-in tools or toolsets.
- Fail before the first model call if a required MCP server does not connect. The sandbox must be able to reach the granted URL.
- Return grant tool results to the model as tool output. Tool routes return JSON values, often objects: serialize any value the harness cannot take directly instead of validating it as tool arguments, so that a call that succeeded is not reported to the model as a failure.
- On close, disconnect tool clients without stopping the remote server.
- Assume that grant headers and tokens are readable inside the sandbox. A grant must only give access to that episode’s tools. When the harness runs inside the sandbox, keep
direct_httpsession cookies out of files the model can read, for example by deleting the staged input once the runner has loaded it.
The current adapters support the following tool sources:
When a tool belongs to the task, prefer a Resources Server tool grant over a built-in harness tool. Different agents can then share one implementation, and the adapter works across environments without benchmark-specific changes. Use built-in harness tools for behavior that belongs to the harness, such as its shell or file editor. See Tools in Agent vs. Resources Server.
Document the supported tool sources, the model API, and the rejected options in the adapter’s README.
MCP grant integration
With resources_tool_transports: [mcp], an episode’s tool_accesses can contain a grant like this:
Map the grant from effective_tool_accesses(body) into the pinned harness’s remote MCP client configuration. Preserve the supplied URL and headers: they carry the episode’s tool access, so a static URL or interactive login is not a substitute. Keep credentials out of diagnostics. Check server and tool names for collisions after any renaming the harness applies, including names from its static MCP configuration.
Accepting the seed or writing that configuration does not prove the harness consumes the grant. If the runtime has a required-server setting that stops the run before inference when a server does not connect, use it. If the runtime only logs an MCP failure and continues, add a bounded check that connects and lists the server’s tools without inference, such as a preflight during seed. When enforcement depends on a plugin or hook that the runtime skips silently if it fails to load, have it write a record that it ran, and fail the activation when that record is missing. Some runtimes apply one MCP timeout to both connecting and each tool call; there, a timeout sized for connecting also cuts long tool calls short.
MCP access and sandbox access are separate capabilities. A Resources Server can grant MCP tools without returning sandbox_access. An adapter that needs a sandbox must then use a configured agent-owned provider or reject the unsupported seed explicitly. Adding a provider does not add MCP or direct_http support. Close disconnects MCP clients; it stops an agent-owned sandbox and leaves a borrowed sandbox to its owner.
Validate grant support with an authenticated MCP fixture and a real harness run: confirm tool discovery, an actual tool call, and the tool result reaching the model. Also test unavailable required servers (no inference or gradable answer), optional-server failure, name collisions, cleanup, and, when enforcement depends on a plugin or hook, a run where it does not load. For a sandboxed adapter, exercise both borrowed and agent-owned sandboxes when both are supported. State which transports the adapter consumes; a successful sandbox-only rollout with resources_tool_transports: [] does not establish MCP support.
Agent context
Some harnesses need task data beyond the initial model input, such as a document to render, images to embed, or the prompt for a later stage. The task row carries that data in agent_context, next to verifier_metadata, keyed by participant role, because an episode can seed several agents. The Environment Server sends each role’s context to that role’s agent session in AgentSeedSessionRequest.agent_context, and keeps it out of the task data sent to the Resources Server. The initial conversation stays in responses_create_params.input. Do not use responses_create_params.metadata to carry task data to the harness.
The single_agent_turn Environment Server has one role, agent:
Each Environment Server names its roles. It refuses with HTTP 422 a row that names a role it does not have, and an Environment Server that sends no context, such as harbor, nemo_user_sim or swe_together, refuses the key altogether, so an episode never runs without task data it was given. The legacy_agent relay is the exception: it sends the whole row to the agent’s /run, where agent_context is one more row field.
Each role’s context has two maps:
valuesholds small inline JSON fields. One role’s context, including its artifact references, is limited to 64 KiB as UTF-8 JSON.artifactsnames files and directories by a path relative to a root the agent configures. The path cannot be absolute or contain..or a NUL byte. The content never travels in the seed.- A key appears in
valuesor inartifacts, not both. - An empty context counts as none: the seed then omits the key.
An agent declares the keys it reads as a Pydantic model in agent_context_model. A field typed AgentContextArtifact (or a subclass), optionally unioned with None, takes an artifact; any other field takes a value. Omit an optional artifact to use its default of None. Unions mixing artifact and value types are unsupported; declare separate fields instead. Before _seed_agent_session_state() runs, the base class checks the seed against that model and refuses it with HTTP 422 when:
- the agent declares no model and the seed carries any context,
- the seed carries a key the model does not declare,
- a required key is missing, a value has the wrong type, or a key is supplied through the wrong map.
No agent declares a model by default, so a task with context fails on an agent that cannot use it instead of running without it. Where the agent builds its session state, read the typed context with self.parse_agent_context(body) and resolve each artifact with resolve_agent_context_artifact(artifact, root, kind=...) from nemo_gym.agents. It refuses with HTTP 422 a path that leaves root, also through a symlink, that is not a file or directory as kind says, or that cannot be looked up, such as a name that is too long. The check runs on resolved paths, so a directory under root that is a symlink to other storage counts as outside it: configure the real directory as the root. For a directory artifact, only the directory itself is checked; files under it can be symlinks to anywhere, so resolve each file you read and check that it stays under the directory. Read or stage the content when the activation runs, and remove anything you staged, such as a temporary directory or a sandbox upload, when the session closes and in retire_agent_session when a checkpoint retires the session instead. Retirement does not call the close hook.
A SimpleAgent subclass resolves its context in _new_session_state(), which the seed and a checkpoint restore both call; context resolved only in _seed_agent_session_state() is lost when a restore rebuilds the session. It puts the context into the model request in _create_session_episode(), which creates each session activation’s episode. Override _create_session_episode(), never responses(): environment validation infers custom-gym-agent-loop for any agent that overrides responses(), while the agent loop is still Simple Agent’s.
On an agent’s legacy /run path, agent_context is one more field of the row the agent receives and may forward to the Resources Server. The agent-only routing described above applies to single_agent_turn.
Configure the adapter
Adapter configuration
Adapter configurations extend BaseResponsesAPIAgentConfig. Adapters that implement agent sessions use the following fields:
The Environment Server (single_agent_turn) binds the pair with resources_server, agent_server, resources_tool_transports, and tool_servers. Its base configuration also sets max_concurrent_episodes, queue_timeout_seconds, and the episode and cleanup timeouts.
The episode timeout, default_episode_timeout_seconds, covers the whole episode: Resources Server seed, runtime installation, the harness run, agent close, and verification. Set it above the harness’s own run timeout plus those budgets, or the deadline fires before verification. The task sandbox has its own lifetime: SWE-bench Pro and Terminal Bench 2.1 set sandbox_config.ttl_s: 18000, and OpenSandbox does not renew a sandbox by default. A harness that is still running when the sandbox expires fails the episode, so raise ttl_s in the benchmark declaration for runs that can last longer. Set max_concurrent_episodes and queue_timeout_seconds to admit episodes at the rate the agent can run them. Admission waits before the deadline starts; without it, every row starts its sandbox at once and waits inside its own deadline.
Since #3902, cleanup_timeout_seconds bounds each cleanup callback, such as agent close or Resources Server close, rather than the whole final cleanup. Agent close bounds each of its sequential steps by session_close_timeout_seconds: cancelling staging, stopping the harness, collection, exec release, and session-file removal with disconnect (or the owned-sandbox stop). Keep about five times that value, plus any adapter-side wait, within cleanup_timeout_seconds. A close that the Environment Server cancels leaves the sandbox to its owner’s teardown or the provider TTL.
During agent-server shutdown, the base lifespan closes that worker’s remaining sessions concurrently within one total session_close_timeout_seconds budget. It reuses the ordinary close operation, preserving checkpoint coordination and cached observations and cookies. Failed or timed-out cleanup keeps state for retry and is reported as unconfirmed. Configure the launcher’s server_shutdown_timeout_seconds above this drain plus request-cancellation overhead; see Server Shutdown for defaults and an aligned configuration.
To run an adapter on a benchmark with an Environment Server, see Run an integrated agent on a benchmark.
Select an execution mode
Use a borrowed sandbox by default. When the benchmark’s Resources Server supplies SandboxAccess, the benchmark keeps ownership of task setup, verification, and teardown, so swapping the agent cannot change how the task is scored. Use an agent-owned sandbox only when the Resources Server does not supply one, or when you run without a shared sandbox service. In that case, start with the Docker provider. The Local provider and the host path both run commands on the Agent Server host without isolation, so use them only for development and smoke tests.
Hermes, Pi, Codex, OpenCode, and OpenClaw select one of the following execution paths for each request. Check the adapter’s README and configuration before you rely on a path.
The compatibility /run endpoint requires an explicit resources_server binding and uses the adapter’s host path. Setting resources_server: null does not disable host execution through /v1/responses. Setting sandbox_provider enables agent-owned sessions, but it does not move sessionless calls into a sandbox. Reject a stale or invalid session binding instead of treating it as a host request.
When the Resources Server supplies a sandbox, propagate setup and connection failures. Never run the task on the host or in a different sandbox instead. Host execution is a separate mode that you select explicitly, and it does not isolate the task. Prepare the sandbox runtime during seed, and do not install an unused copy on the Agent Server host. An optional host path may install its runtime on first use instead of at server startup. If it does, document that first-call setup, share concurrent installation attempts, surface installation failures, and let a later call retry. Host tools that every path requires still install at server startup.
Restrict the egress of an owned sandbox
A sandbox that the adapter creates gets the provider’s default network unless the adapter restricts it. On a benchmark graded on what the model knows, such as HLE, open egress lets the harness look answers up: a web-fetch tool or a curl in a shell is enough. The deprecated *_sandboxed_agent profiles set network_access: model_only for these benchmarks, so an adapter that creates sandboxes must offer the same control.
Add a network_access: SandboxNetworkAccess field that defaults to inherit, and pass the spec of every owned sandbox through restrict_sandbox_network before you create the sandbox:
inheritreturns the spec unchanged.model_onlyallows only the host of the model endpoint.model_and_toolsalso allows the host of each MCP grant that the harness uses. Leave out grants that the adapter skips, so that an unused grant neither opens a host nor fails the seed. Each allowed host is open on every port.- Pass the endpoint that the harness actually calls. If the harness can call a model provider directly, without a Gym Model Server, pass that provider’s endpoint.
- The policy is fixed when the sandbox is created, so it applies only to an owned sandbox. A borrowed sandbox keeps the network that its owner gave it: in a borrowed session, reject any value other than
inheritbefore connecting. - Refuse a configuration that you cannot enforce with
AgentSeedRejectedError. The seed route returns it as a final HTTP 422 instead of a retryable 500, because another attempt cannot fix the configuration.restrict_sandbox_networkalready raises it for a provider without network policies (only OpenSandbox enforces them), for an explicitsandbox_config.provider_options.network_policycombined withnetwork_access, and for an endpoint that the sandbox cannot reach. Raise it yourself for a value that the adapter does not support, such asmodel_and_toolsin an adapter that takes no tool grants. - A restricted sandbox cannot download the harness runtime. Upload the runtime from the Agent Server, as Claude Code and
SandboxPythonRuntimedo, or accept asandbox_runtime_dirthat holds a runtime baked into the image, and check that it runs the pinned version instead of installing it, as Pi does. Document which of these the adapter supports. - Allowing the model endpoint’s host opens every Gym server bound to that address, not only the model server. With
model_only, setabsolute_ip_server_types: [responses_api_models]so that only the model server leaves loopback; withmodel_and_tools, also listresources_serversfor the tool servers. - The policy is only as strong as the OpenSandbox server’s egress mode:
dnsfilters only name resolution, so a hard-coded IP bypasses it, whiledns+nftalso enforces it at the IP layer. See Network Policy. - A profile that composes the adapter onto a benchmark graded on the model’s own knowledge should set
network_access: model_only, as the deprecated agents’ profiles do.
Build the adapter with nemo_gym.agents.utils
The nemo_gym/agents/utils package implements the sandbox execution lifecycle that Hermes, Pi, Codex, OpenCode, and OpenClaw share. The adapter provides the harness-specific parts: runtime installation, input staging, the harness command, and output parsing. nemo_gym.agents.utils launches, supervises, stops, and cleans up the harness process.
Code layout
Organize a new adapter under responses_api_agents/<harness>/. The adapter’s sandbox.py runs on the Agent Server. Inside the sandbox, the shared harness_runner.sh starts the harness CLI. A harness that is itself a Python program runs an adapter-specific sandbox_runner.py shim with a Python runtime that the Agent Server builds and uploads with SandboxPythonRuntime, as Hermes and Stirrup do. hermes_sandboxed_agent is being deprecated; use hermes_agent for new development and as the integration reference.
The shared modules have separate responsibilities. All of them run on the Agent Server, except process_supervisor.sh, harness_runner.sh, and install_python_runtime.sh, which are uploaded into the sandbox. Provider APIs and general file transfer stay in nemo_gym/sandbox/.
In the following diagram, dashed boxes are planned helpers that do not exist yet. Edges inside the Agent Server are Python calls unless labeled otherwise. Edges between processes are labeled with their protocol: HTTP/JSON, provider transport, subprocess and signals, or file I/O. A request without an agent session takes the host path.
The supervisor’s termination receipt and the harness’s output come back through separate contracts. A valid output file does not replace confirmation that the harness stopped before verification.
Wire an adapter to SandboxSession
Keep harness-specific response parsing and model and tool behavior in the adapter. The agent-session API in the base class owns session identity and each close’s saved reply; the adapter owns activation retries. SandboxSession handles the execution lifecycle underneath that API.
1. Define the session state. Subclass AgentSessionState and compose a SandboxSession. Implement two hooks:
stage_activationuploads the activation input and returnsSandboxCommand(argv=...). Install the runtime earlier, during seed. A CLI harness runs through the shared bash runner, whose name never mentions python, so apkill -f python3in the task cannot stop it.collectcopies artifacts to the Agent Server after harness termination is confirmed, including partial output from interrupted runs. It may run a bounded snapshot command, but it must not restart the harness. Bound the size of what it downloads: trim large logs inside the sandbox first and keep the tail with a truncation marker, for example the last 1 MiB of a runner log.
2. Seed the session. In _seed_agent_session_state(), validate tool grants and configuration, then connect to the borrowed sandbox or start an owned one. Create the SandboxSession with a session_dir that is separate from workdir, which is the task repository. Install the runtime and upload HARNESS_RUNNER_SCRIPT. If setup fails, close the session; if that close also fails, raise AgentSessionSetupError so that a later close can retry.
3. Run one activation. In responses(), self._agent_session_id_from_request(request) returns the session ID from the cookie, or None for a sessionless host call. In the session branch, load the state with self._require_agent_session(session_id), which returns HTTP 409 for an unknown, closing, or closed session. Check the rollout path against state.request.episode_id.capture_key, and bind the request to a single shared task as described in the session rules. That task resolves the time budget from the request metadata and calls execute() under the adapter’s concurrency limit:
execute() uploads process_supervisor.sh into session_dir after stage_activation returns, so adapters do not upload it themselves. It then launches the harness under the supervisor, confirms harness termination, collects artifacts, and releases the provider exec. Captured artifacts remain in session.artifacts even when execution raises. If the supervisor writes a final negative receipt, execute() raises NgFailureEvent with boundary harness and kind harness_termination_unconfirmed and does not capture artifacts. A nonzero harness exit code does not raise by itself, because the output can still be useful. Convert artifacts into a response and observations in the adapter.
An adapter that takes part in partial-rollout checkpoints creates its session with SandboxSession(pausable=True) and wraps the launch in run_with_checkpoint_pauses(session, activation, launch=..., on_parked=..., stop_timeout=...) from nemo_gym.agents. When a checkpoint asks the activation to park, it pauses the harness in place, parks the activation, and continues the harness when the checkpoint resumes. It returns LaunchFinished(result) when the launch ended on its own, with what launch returned. It returns LaunchStopped(receipt, error) when a pause or continue failed and the harness was stopped instead: the harness did not finish, and the adapter launches it again from the state the harness saved. Pass pause_allowance_s to execute(): it extends the provider’s deadline by the time the harness may spend paused, and it is the longest one pause may last. After a restore, SandboxSession.rebind(sandbox, state, ...) re-binds a session to the restored sandbox from the checkpoint_state() it exported. The re-bound session has no running launch; call begin_activation() with a fresh launch directory before the next execute().
4. Close the session. In _close_agent_session_state(), call session.close() first, then cancel the activation task if it is still running. Close joins any finalization in progress, never captures artifacts twice, and is safe to retry while termination evidence is missing. After a final negative receipt, close skips capture, releases a borrowed connection, and leaves teardown to the Resources Server; an owned sandbox is stopped through the provider. Build observations from session.artifacts if activation was interrupted before parsing them.
The Pi and Codex adapters are compact references for this pattern. Hermes adds MCP tool grants and runtime reuse.
Shared helpers
Adapters normally call SandboxSession instead of repeating its launch, stop, collect, and release sequence. The lower-level helpers are:
All control files live under session_dir, and their names are defined in supervisor_client.py:
To migrate an adapter that launches the process supervisor itself, move launch, termination, collection, and release into SandboxSession. For Hermes, use the existing hermes_agent integration; hermes_sandboxed_agent is being deprecated and should not receive new integration work. Receipt types and timeout helpers that used to live in process_supervisor.py are now in nemo_gym.agents.utils.supervisor_client. Update the imports, hook arguments, control-file assumptions, test doubles, and tests together. The adapter imports these modules at startup, so a stale import also breaks host calls.
Out-of-tree adapters written for the Python supervisor also need these changes:
SandboxCommand(python=...)andsupervised_launch_command(python=...)are removed. The supervisor runs with bash, so the task image needs bash; an adapter that installedpython3during setup only to run the supervisor or a runner no longer needs to.SandboxCommand(stdlib_runner=...),supervised_launch_command(stdlib_runner=...), thebin/gym-runnerinterpreter link andRUNNER_FILEare removed. Run a CLI throughharness_runner.sh; a Python shim must bring its own interpreter.- The receipt’s
return_codeis now the shell status of the harness command: 128+N when signal N killed it, where the Python supervisor reported -N. A harness that could not be started now gives a confirmed receipt with 126 or 127 instead of a negative receipt with a launch error. - A harness that runs through
harness_runner.shreports the runner’s own failures as 125, before the CLI starts, so 125, 126 and 127 do not come from the CLI itself.
Prepare the runtime during session setup
Implement the agent-session API on the supplied SandboxAccess:
- Pin the harness version and the task image digest. Check the image’s runtime, utilities, certificates, platform, and permissions.
- Install the harness in the supplied sandbox during seed, before activation. Do not also install it on the Agent Server host unless the host path uses it. Check bootstrap dependencies, and keep failed commands, exit codes, and stderr.
- Keep runtime files, harness configuration, and caches outside the task repository and the task’s home directory, without overriding the
HOMEandXDG_*directories that tool shells inherit. Preserve the task’s dependencies, and pass only the credentials and configuration the harness needs. - Publish the session only after setup succeeds. On failure, release connections and keep the state needed to retry unfinished cleanup.
- Never fall back to a host CLI or a replacement sandbox.
Installation contract
Run the installation check at every seed, and reuse a compatible runtime if one is already present. Keep reusable runtime files separate from per-session writable state: input, output, logs, private harness configuration, and caches. Session close must not remove a shared runtime.
- Detect the target sandbox’s OS, CPU architecture, libc, runtime prerequisites, and execution permissions. Select artifacts for that target, because an executable found on the Agent Server host may not run there. For example,
SandboxPythonRuntime.install()internally probes the architecture, C library, and glibc version, which select the Python build and the wheels thatSandboxPythonRuntimeuploads. - Check any preinstalled, mounted, or previously installed runtime against the pinned version and a health check that runs it. The existence of a directory does not prove the runtime is ready.
- Verify the checksums of pinned artifacts on the Agent Server host, upload them through the sandbox file API, and run the harness’s installer in a private directory outside the task repository. Preserve the task’s interpreters and libraries. If the installer resolves packages, constrain the harness’s dependencies to the versions the adapter is tested with, for example with a constraints file generated from the agent environment; an exact pin on the harness alone lets its dependencies change between episodes.
- Mark the runtime as ready only after installation and its health check succeed. Handle partial installations and concurrent setup without exposing an incomplete runtime. On failure, keep the commands, exit codes, and logs.
- For offline support, provide the complete dependency set, including bootstrap interpreters, package dependencies, and native libraries. Uploading a CLI or ripgrep alone is not enough if the installer still downloads other dependencies. If it does download them, document that the sandbox needs network access to the package index. A sandbox restricted with
network_accesscannot reach it; see Restrict the egress of an owned sandbox.
The supervisor and the shared runner need only bash in the task image. Do not require Python in the sandbox for a CLI harness: check paths, install runtimes, and post-process output with shell commands or on the Agent Server.
A harness that is itself a Python program needs a Python runtime that the adapter brings, never the task image’s. The launch command checks that bash can parse the supervisor before it claims the launch.
Launch the harness with an absolute interpreter and an absolute script path under its private runtime, without activating its environment. Hermes and Stirrup use python -E -s: the harness ignores task PYTHON* settings and user site-packages, while its tool subprocesses retain the task’s PATH, VIRTUAL_ENV, PYTHONPATH, and PYTHONHOME. The trusted script directory stays importable for sibling modules; the task’s current directory does not become the harness’s import root. Set harness-specific state before the first framework import: Hermes sets HERMES_HOME to the session’s private directory before importing Hermes, and its seed import checks use the runtime’s private home. Keep the task’s HOME unchanged for tools.
The proposed shared installer must not depend on system package managers or root access. Not all existing adapter installers meet this goal yet. Until they migrate, document the supported images and any remaining prerequisites.
For a Python harness, build the runtime on the Agent Server with SandboxPythonRuntime, as the Hermes seed does. The sandbox needs x86_64 or aarch64 Linux with glibc 2.17 or newer or musl, bash, tar with gzip, and space under /tmp, but no network access. The Agent Server needs uv and access to the package index and the python-build-standalone releases on GitHub; HTTPS_PROXY applies, and UV_PYTHON_INSTALL_MIRROR selects an HTTP(S) mirror (file:// mirrors are not supported). An offline host can prepopulate cache_dir/sandbox_python/ with the pinned Python archive; its checksum is still verified. Package dependencies must also be available to host uv through a local cache or index. Every dependency except a direct-URL requirement must publish a wheel for the sandbox’s platform, so a harness’s dependencies can narrow these platforms. On glibc-based images, Hermes v0.23.2 requires glibc 2.28 or newer for its Python 3.14 wheels; its Agent Server also needs git and access to the pinned Hermes repository on GitHub. Stirrup requires glibc 2.28 or newer and does not support musl.
The shared installation proposal would add an Agent Server helper, harness_install.py, with ensure_harness_installed(...). It would detect the platform, reuse or stage verified artifacts, run the adapter’s installer at seed, and return the runtime location. Neither the helper nor its package location exists yet.
A common runtime mount configuration across providers, with a convention such as /opt/nemo-gym-runtimes, is also planned. Enroot already supports its own exec.default_mounts. Mount defaults must be applied when the sandbox is created, with defined behavior for destination conflicts and unsupported providers. The installer then discovers the mounted runtime at seed. Read-only runtime mounts require separate writable session state.
Preserve inputs, outputs, and errors
Run the harness in SandboxAccess.workdir. Route model calls through a Gym endpoint that the sandbox can reach and that carries the rollout identity. The agent’s /v1/responses interface does not determine which model API the harness uses.
For Hermes, the adapter uploads the episode input to input.json and passes an argv with its private Python interpreter, sandbox_runner.py, and the input and output paths. The supervisor starts that command without reading the input. The shim reads the adapter-specific JSON, invokes Hermes, and writes output.json. This is a file exchange, not another Responses API call.
The Hermes shim creates the harness with model_base_url and points its auxiliary clients at the same Model Server. The adapter converts the harness output back into a NeMoGymResponse. This model traffic is independent of the supervisor’s cleanup files.
Route every model call through the Model Server
Point every model client in the harness at the rollout-prefixed Gym Model Server URL, built with base_url_for_run() or resolve_model_base_url(). This includes auxiliary calls that the harness or framework makes on its own, such as summarization, context compaction, title generation, and subagents. Hermes, for example, points its auxiliary clients at the same Model Server as its main loop.
A call sent directly to an external provider is not captured. For training, Gym does not guess at missing calls: if a call’s output reaches a later prompt but its chain cannot be proven, Gym sets mask_sample: true on the rollout. With token_id_capture.max_mask_fraction set, collection stops when too many rollouts are masked.
Set the x-session-id header on every model request to the invocation_id of the AgentInvocation that the adapter returns for that run. A failed attempt, such as an HTTP 429 or 500 reply, has no response ID, so the adapter cannot reference it with a ModelCallRef. With model-call capture enabled, the Model Server records the header with each captured call (_CLIENT_SESSION_HEADER in nemo_gym/models/model_call_capture.py), and rollout collection assigns each captured call to the invocation whose ID matches it (join_agent_model_calls() in nemo_gym/trajectory/trajectory_record.py). Without the header, a failed attempt has no owner: collection records a model_call_ownership_unavailable gap, and Harness Conformance fails ownership.call_owner and ownership.gap. Pi uses the episode’s capture key as its invocation ID and sets the header to the same value in _build_models_config() in responses_api_agents/pi_agent/app.py.
Send back the cookies that the Model Server returns on later calls of the same rollout, as SimpleAgent does. The vLLM Model Server keeps a rollout’s calls on one backend endpoint by using the rollout ID, or the session cookie when no rollout ID is present. A call with neither starts a new session and can land on a different endpoint.
For training, enable token_id_capture on an adapter whose responses carry no token IDs, together with the run-level token_id_capture.enabled setting. See Training on External Agent Harnesses for the model server configuration and the capture metrics. If the harness cannot route all of its policy-generating calls through the Model Server, mark the adapter as evaluation-only in its README and leave token_id_capture disabled.
Map configuration and request fields explicitly
Handle each configuration and request field in one of three ways: apply it, reject it with a clear error, or document that the adapter ignores it by design. Never drop a field silently. For example, Pi rejects request fields that it does not support with HTTP 422, except metadata.agent_timeout_sec, which it applies with resolve_agent_timeout(). Codex rejects max_output_tokens, temperature, top_p, and reasoning controls, because it cannot enforce them for a custom Gym provider.
Read only the settings that the harness actually supports. Do not forward a value from another part of the Gym configuration, such as a step limit, unless the harness has an equivalent setting with the same meaning.
After overrides, check the model requests that the harness actually sends. Distinguish per-call limits from episode budgets. Preserve prompt semantics, reasoning, and tool history across upgrades.
Some frameworks change their behavior based on a model or runtime profile. For example, DeepAgents reads max_input_tokens from the model profile to decide when to summarize, and the DeepAgents adapter sets that profile from its configuration. Expose such profiles as adapter configuration, pin them, and keep them fixed when you compare an upgrade.
Convert outputs without silent loss
Return a NeMoGymResponse with text, reasoning, tool calls and results, usage, and status where available. Collect rollout evidence: tool timing, model-call references, aggregated usage, and explicit evidence gaps.
Set the response status by the harness’s own rule for a failed run, read from its source at the pinned version. An error that the harness ignores or recovers from, such as a subagent’s error or a failed model call followed by a successful one, must not fail a run that finished.
Report aggregate usage only when every model call has a usage record. Collect model-call references from every record the harness writes, such as its event log and its telemetry, because each can miss calls the other has. When a call has no usage record, leave usage unknown and record an ObservationGap instead of reporting a subtotal.
Apply the same rule to each detail, such as input_tokens_details.cached_tokens (cache reads). Report the count the harness reported, summed over calls. When the harness reports no cache reads, or writes 0 for a count the backend did not report (as Pi, OpenCode and Kilo do), set None; never write a 0 that was not measured, because consumers read it as “no cache hits”. Use 0 only for a known zero, such as an oracle that calls no model, and say why in a comment that ends the line with # known-zero. tests/unit_tests/test_cached_tokens_contract.py rejects other literal zeros under responses_api_agents/. accumulate_response_usage and NeMoGymResponseUsage.sum_from_list keep an unknown detail unknown.
When a harness item has no exact Responses API equivalent, decide whether to convert it, drop it, or keep it only as an artifact. Record anything that is lost as an ObservationGap with a specific code, and never drop tool calls or their results. Keep the harness’s raw output and execution artifacts, including the ones available after a failure.
Derive each tool call’s status from what the tool did, not only from the harness’s success flag. Harness Conformance’s tools.witness_status check, in nemo_gym/rollouts/harness_capabilities/behavior.py, expects a shell command that exits nonzero to have ToolCallObservation.status set to failed, and one that exits 0 to have completed. Some harnesses report a nonzero exit as a successful tool call and record the exit code in a separate field; GitHub Copilot CLI 1.0.103 does this. Read that field and report the call as failed when the exit code is nonzero, without changing the tool output that the model saw.
Keep execution health separate from reward
Preserve the model’s HTTP status and error bodies, so that context-limit handling and retries can use them. Keep execution health separate from reward:
Local compatibility paths can have a different evidence contract. For example, Hermes’s local /run keeps terminal provider failures through verification. It then returns mask_sample: true and failure_kind: agent_request_failed, even if the verifier awards a positive reward. These failed rollouts are excluded from scores. Hermes agent sessions use the Environment Server policy below.
A reward of 1 or an HTTP 200 response alone does not prove that an episode was healthy.
Report a cause; let the environment decide
SimpleResponsesAPIAgent provides classify_outcome(native_result) -> AgentOutcome
and report_outcome(response, native_result). The default classifier returns
unknown; override it using native evidence when available. Call report_outcome
before returning a failed response; inheritance alone does not attach metadata.
Keep text parsing in the classifier and document the tested runtime version.
Check the selected agent server’s implementation when interpreting its reported cause.
On a run that sets forward_configuration_refusals, report_outcome reports a
model_request_error with status 400 as model_request_rejected when the response’s error
message says the run’s own settings are invalid: an output limit
above the model’s cap (“max_tokens is too large”, “maximum allowed number of output tokens”,
“cannot be greater than max_model_len”) or a parameter or value the model does not accept
(“Unsupported parameter”, “Unsupported value”, “is not supported with this model”). Such a
request is refused on every call, whatever the conversation holds. Any other 400 stays
model_request_error, and so does a refusal that names the context window: a prompt over
the window is the model’s own limit. Keep the provider’s error text in the response’s
error.message so the rule can read it. When the reply carries the Model Server’s
failure_report, report_outcome also adds a selected model_request_rejected event caused by
that 400 and keeps every original event, because an Environment Server fails a reply whose
selected failure disagrees with its outcome. Only a task-folder run on your machine (gym eval run <task folder>,
not --benchmark and not gym eval submit) sets forward_configuration_refusals, and only for OpenCode and Pi
(CONFIGURATION_REFUSAL_HARNESSES in nemo_gym/data/tasks/harbor/prepare.py), whose
report_outcome passes on the provider’s text; it also makes openai_model forward such a 400
instead of answering HTTP 500. On every other run, openai_model answers that 400 with HTTP 500, and a Model Server
that passes it on, such as vllm_model, has the harness report it as a graded model_request_error. OpenCode 2
(opencode_version 2 or later) can report a provider error with a generic message such as Bad request, which
report_outcome cannot read as a refusal, so such a refusal stays graded.
AgentOutcome.failure_kind accepts names registered in nemo_gym/core/failure_kinds.py
or unknown; unregistered names are rejected. The shared names describe causes,
not retry or grading policy.
Use model_context_limit only when a provider or harness explicitly reports that the
model’s context window was exceeded. HTTP 400 or 413 alone does not establish that
cause. Report a context-limit stop as status="incomplete" with this reason: the
partial work proceeds to verification without an automatic episode retry.
The helper writes JSON to response.metadata.ng_agent_outcome; status_code is the
upstream model request’s status, not the agent endpoint’s HTTP status. The
single_agent_turn and harbor Environment Servers apply this default policy to classified
failed responses after closing the agent:
The environment server classifies and closes one attempt. Failed attempts retain their partial
response and observations. On harbor, an excluded attempt whose cause is model_request_rejected
reports that failure_kind. Other excluded causes remain environment failures. Responses without
this metadata keep their existing grading behavior, and completed or incomplete responses remain gradable.
The collector can redispatch an eligible episode on resume within its rollout attempt budget. A
request retry inside a harness or the HTTP client has a separate scope. Dependency errors with
status 408, 425, 429 or 5xx and transient transport failures may be retried. Deterministic client
errors are terminal. The shared HTTP client returns HTTP error responses to its caller for this
decision. Internal calls use a 600-second transport retry budget by default. Setting the budget to
zero disables that bound. Explicit attempt or retry-window limits override the default. External
connection retries need a caller-supplied bound. Other external exceptions default to three attempts.
See the bounds in request.
For masked results, rollout recovery
can retry a namespaced failure when its owner records failure_outcome_action: retry, attribution
is not to the model, and the other eligibility checks pass. A saved answer is handled separately
from a fresh rollout.
For Pi, Codex, OpenCode and Hermes agent sessions, this changes some provider failures
that previously surfaced as retryable agent HTTP 500/502 errors: reported 401/403/404
errors, other unmatched failure kinds and malformed metadata now fail without
verification or episode retry by default. Unclassified failures reported as unknown
remain retryable.
Configure agent_outcome_policy inside the single_agent_turn or harbor Environment Server’s
config to choose verify, retry, or fail (ungraded and nonretryable) for classified
failed responses. These overrides do not apply to completed or incomplete responses.
HTTP status rules take precedence over failure-kind rules; unmatched failures use default_action
(default: fail). Supplied entries override matching defaults; omitted entries retain
their defaults. Failure names must be registered or unknown, and
HTTP status keys must be 400–599. Malformed outcome metadata always fails without retry.
For example, by_failure_kind: {model_request_error: fail} applies only when no HTTP
status rule matches; it does not override the default 400/408/413/422/425/429/5xx rules.
Use by_status_code: {503: fail} to change 503 handling. Adding
by_status_code: {404: retry} keeps the other default status rules, including 429 and 5xx.
model_request_rejected carries no HTTP status, so a by_status_code: {400: ...} rule does
not reach it; by_failure_kind: {model_request_rejected: verify} grades it again.
It applies to single_agent_turn, its legacy-response wrapper and harbor, not other
Environment Server implementations or agents’ own legacy /run methods.
Report a sandbox killed at its memory limit
A sandbox provider can confirm that an OOM kill took an agent’s whole sandbox. It then raises a
failure of the kind provider_oom_killed. SandboxSession records that failure in execution_oom
when it arrives while the harness runs: from the launch command, from a poll for the launch’s
cleanup receipt, or from the check that the supervisor started, which the session runs after a
launch command failed for another reason, such as an unavailable command status. execute() raises
the failure, and the adapter raises it from responses(). By default the /v1/responses route
answers HTTP 500, its failure header names the provider’s failure as the cause, and the Environment
Server does not verify the episode.
report_agent_sandbox_oom: true makes the base class answer that activation with a response. The
setting is a field of BaseResponsesAPIAgentConfig, so every adapter has it with the default
false. It acts for an adapter whose sandbox session the base class finds
(_find_sandbox_session) or that reports the kill itself; any other adapter raises the failure.
- The response is
failedwith no output and no usage, because the harness’s events were lost with the sandbox. Itstools,tool_choiceandparallel_tool_callsare the request’s. So is itsmodel, which is empty when the request names none. metadata.ng_agent_outcomeholds the failure kindprovider_oom_killed, so the Environment Server’sagent_outcome_policydecides the episode. The default of that policy verifies it.metadata.ng_agent_sandbox_observationholds the sandbox’s observation: the roleagent, the outcomeoom, the provider and the sandbox ID of the failure, and the failure’s event ID asfailure_id. Itsstageis the failure’s, oragentwhen the failure names none.failure_reportand the failure header hold the provider’s failure as an observed event. The response selects no failure.- A retried request gets the same response.
- The session’s close adds that observation to its observations. Its top-level
AgentInvocationrecords that the kill leftincompletesayfailedwith the error typeserver_error.
A kill outside the launch, such as during staging or artifact capture, is still raised. So are a sandbox failure of another kind and every failure without the setting.
The base class reads execution_oom from the SandboxSession that
_find_sandbox_session(state) returns. That method returns the session that the adapter returns
from _rollout_sandbox_session(state), so an adapter that supports rollout stops needs no code for
the setting. When that method returns no session, _find_sandbox_session returns the
SandboxSession that the session state keeps as state.session, if the adapter’s class declares
calls_model_from_sandbox. The seed reads the same method to name the sandbox that the adapter
started for its harness in the x-ng-agent-owned-sandbox-id header of its response. Rollout stops
read _rollout_sandbox_session alone.
Seven adapters without rollout stops keep their session as state.session, declare
calls_model_from_sandbox and raise the recorded failure from responses() unchanged, so the
setting acts for them without code of their own: browsecomp_agent, claude_code_agent,
copilot_agent, hermes_agent, kilocode_agent, openclaw_agent and pool_agent.
The method finds no session for three adapters that hold a SandboxSession, so the setting does
nothing for them. legal_agent_bench_native calls the model from the Agent Server, runs only its
tool commands in the session, and does not declare calls_model_from_sandbox. nooa_agent keeps
its session on its runner, as state.runner.session. simple_agent keeps its session on its
sandbox loop, as state.sandbox_loop.session. Such an adapter needs two things. The first is a
_find_sandbox_session of its own that returns the session, which the seed then reads too. The
second is a test of its own failure path, because the base class answers only when responses()
raises the recorded failure itself and not another failure raised from it.
An adapter that builds its own response for such a run calls observe_sandbox_oom(failure) and
then report_sandbox_oom(response, observation), which add the fields above to its response.
opencode_agent does so to keep its own metadata and, in a continuation session, the activation’s
observations. _find_sandbox_session also finds opencode_agent’s session, and nothing changes for
that adapter, which returns its own response. opencode_sandboxed_agent does so on its /run
path, which has no SandboxSession.
Make retries and close safe
Validate the session identity and cookies. In a single-activation session, identical retries join or replay the invocation, and conflicting requests are rejected. A disconnected client must not cancel shared work.
One Agent Server process serves concurrent sessions. Keep per-session state and credentials out of process-wide state, such as os.environ, module globals, or a shared home directory. Pass them per invocation instead, for example through the subprocess environment or the session directory.
Serialize close requests. Keep each successful close’s saved reply for session_close_retry_window_seconds, the close retry window, and reject stale activations. For a borrowed sandbox, remove only adapter-owned files and disconnect; the Resources Server destroys the sandbox.
Harness termination
The supervisor first leaves the provider’s process group, so a provider that kills the group of its exec cannot end the supervisor before the receipt. It starts the harness in a new process group and sets NEMO_GYM_SUPERVISOR in the harness’s environment to a value unique to this supervisor. When the harness exits by itself, the supervisor kills the harness process group. At the deadline or on a stop request it records what the stop reaches, sends SIGTERM to the harness and waits for the grace period, then kills everything reached and waits until none of it can still run. A forced stop reaches:
- the harness process group;
- every process that descends from the harness, from a member of its group, or from another reached process, such as tool commands started in their own sessions;
- every process that inherited the marker, such as a service that a tool daemonizes during the stop, unless it had already left the harness when the stop began, or descends from such a process.
The supervisor scans /proc when the stop begins and on every polling round until nothing it reached still runs. Two kinds of process are not reached: processes that had left the harness when the stop began, which are left for the sandbox owner, and a process that leaves the harness between two scans after dropping the marker from its environment. Keep NEMO_GYM_SUPERVISOR in the environment of tool commands; the Codex launcher passes it through its environment allowlist.
Shell-tool commands can run in their own sessions, so a harness-group kill alone may not reach them; a forced stop does. A background process left by a completed tool, even a plain server &, can then survive as a task service. Detachment depends on the harness and launch path: the child adapter of OpenClaw 2026.11.5, the adapter’s pin, starts commands in a process group of their own on POSIX, directly or, when OPENCLAW_SERVICE_MARKER is nonblank, through a service relay. Only a forced stop reaches those commands.
cleanup_confirmed: true means that no live harness-group processes remain and, after a forced stop, that nothing else the stop reached still runs. A zombie does not block confirmation, because it cannot run. The receipt does not mean the sandbox is idle, and it is not a security boundary: after a natural exit, a tool command still running in its own session can change task files after the receipt.
Services survive until the sandbox owner tears down the sandbox: the Resources Server after verification or episode failure, or the agent when it closes an owned sandbox.
Keep every harness process in the supervised process group. Disable modes in which the harness respawns or daemonizes itself. For example, OpenClaw restarts its agent as a detached process in its own session when stdio is not a TTY, so the OpenClaw adapter sets OPENCLAW_NO_RESPAWN=1. Without it, a forced stop can leave the agent running and calling the model while the receipt reports success.
A task service that must survive the harness needs to:
- Detach its process group and standard streams, for example with
subprocess.Popen(start_new_session=True), stdin from/dev/null, and stdout and stderr in task-owned log files.nohup ... &alone is not portable across harnesses, because a shell deadline or a process-group stop can still end the service. - Keep its data in task-owned files, not in the agent’s session directory, which agent close removes.
- Be reachable before the tool call that starts it finishes.
Redirect supervisor and harness output to a file, as supervised_launch_command() does with output.log. A surviving service that inherits the provider’s output pipe keeps provider exec open until its hard timeout.
Fence delayed launches, and handle the two kinds of termination failure differently:
- Missing or malformed evidence, such as an absent receipt or a stop that timed out, leaves the outcome unknown. Keep the retry state and block verification, because a later close can still confirm termination.
- A final negative receipt, a well-formed receipt with
cleanup_confirmed: false, cannot improve with retries.stop_and_confirm_cleanup()raisesNgFailureEventwith boundaryharnessand kindharness_termination_unconfirmed, the activation fails without verification, and artifacts are not captured. A borrowed close still releases the provider exec, removes the session directory, and disconnects, leaving teardown to the Resources Server. An owned close stops the sandbox through the provider.
Releasing a failed session does not make its activation gradable. Verification requires both a gradable activation and a successful agent close.
Finalization
Keep three contracts independent:
- The termination receipt (
cleanup.json) shows whether the harness process group stopped. - Process metadata identifies the harness process.
- Harness output carries task results and observations.
A valid output file does not confirm termination, and confirmed termination does not show task success. A parsing failure must not discard a confirmed receipt.
Process metadata is optional and adapter-local. Each adapter’s sandbox.py defines HarnessProcessInfo and parse_runtime_info(), which validate the hostname, harness PID, and interpreter, and return None with a warning when the input is malformed. Hermes records a runtime_info_unavailable gap in that case. Output errors still propagate independently. Artifact capture errors are recorded separately: they must not block resource release after termination is confirmed, and they must not replace the original execution error.
For both borrowed and owned sandboxes, finalize in this order:
- Confirm harness termination.
- Collect artifacts once.
- Release the provider exec.
Cancelling provider exec too early can kill the provider’s entire process group, including the supervisor when it is already the group leader, as with the local provider. Leaving the provider’s process group alone would not guarantee cleanup; the close ordering does. Concurrent close calls join the same finalization. A retry after missing termination evidence or a failed release keeps the handle and does not capture artifacts again. Each finalization step, from staging cancellation through session-file removal and disconnect, has its own timeout; the shared timeout is a per-step budget, not a deadline for the whole close.
For a borrowed sandbox, close retires the session paths and disconnects. For an owned sandbox, close tries the same graceful finalization before stopping the sandbox. If graceful termination fails, a confirmed provider teardown stands in for it, and unavailable artifacts are recorded as unavailable. If teardown fails, the state is kept for retry. In both modes, keep launch fences in place and reject late activations.
When execution completes, the sandbox is kept until an explicit close; closed means that resource release succeeded. In case the Agent Server crashes, arrange a provider-enforced expiry or an external cleanup mechanism for owned sandboxes. Allow enough time for installation, execution, and cleanup. For example, when sandbox_config omits ttl_s, Hermes sets it to sandbox_install_timeout_seconds + sandbox_runner_timeout_seconds + 600. An explicit value, including null, is kept. This default applies only to sandboxes that Hermes creates; borrowed sandboxes follow their owner’s lifetime policy. Check that the chosen provider actually enforces the configured lifetime.
These receipts coordinate lifecycle behavior. Files that the model can write are not a trusted channel for training trajectories, so validate training support separately.
Validate each supported pairing
Observability
Use Harness Conformance to validate trajectory evidence. To register a new harness and install its dependencies, follow the runner guide. Run the probes with a new output directory. This example uses Pi:
For sandboxed agent-session probes, the runner starts the harness through Gym’s local subprocess sandbox provider, so the process supervisor, which requires Linux, runs on the host. scripts/harness_conformance/episode.py therefore refuses to run these probes on any other OS. Simple Agent is exempt: its session probes use direct HTTP tools without the sandbox supervisor. On macOS or Windows, run the sandboxed probes on a Linux host or in a Linux container.
The runner uses scripted model replies and real local tools, then runs the evidence checker automatically. Review conformance_report.md, fix missing or inconsistent evidence, and rerun. The P0 gate passes only when every applicable P0 check passes, including ownership and call-to-step attribution. TE labels group results; they do not grant exemptions.
The scripted replies call the shell tool that the harness lists in its model request’s tools, so the probes apply only to a harness that offers the model a shell tool through function calling. The runner recognizes a fixed set of shell-tool names and argument shapes; the runner guide says how to extend it for a different shell tool. An adapter without a shell tool, such as a framework adapter that runs only its own tools inside the Agent Server, or a harness that runs commands it reads from the model’s text, cannot run them. Say so in the PR, and validate the adapter with its session tests, a real pairing, and the saved-rollout inspection below.
Also check saved rollouts from each target sandbox pairing:
Record evidence conformance and sandbox lifecycle validation separately, because the local probes do not exercise remote sandbox setup or cleanup.
Runtime and compatibility
- Execution modes. Test host calls with no sandbox access or provider, borrowed agent sessions, agent-owned sessions with a configured provider, and rejection of a seed with neither. Assert that host calls never create a sandbox and that sandbox failures never fall back to the host. Test the compatibility
/runendpoint with and without a Resources Server binding. - Installation. Test cold installation, runtime reuse, failed and partial installation, and unsupported platforms. Include an image without Python: a CLI harness must run there. Claim offline or read-only mounted-runtime support only after you test those deployments.
- Failures and races. Test setup failures, request mapping, unsupported controls, isolation, retries, cancellation, close races, and termination failures. Include supervisor upload failures, close during upload, interpreter or supervisor bootstrap failures before launch, termination before transport cancellation, artifact capture before teardown, capture failures, and malformed optional diagnostics. Check that a final negative receipt releases a borrowed connection without making the activation gradable.
- Process termination. Use real Linux processes. Cover tool commands in the harness group, with grandchildren, under a harness that exits on
SIGTERMand one that must be killed, for both a deadline and a close. A tool in the harness group, or in its own session while the harness still runs, must not change the task after a confirmed receipt, and a detached service must survive. Check that every harness process shares the supervised process group, and that a zombie does not block confirmation. Read the process state from/proc/<pid>/stat, becauseos.kill(pid, 0)also succeeds for a zombie. Run thesandbox-marked tests with the local provider, which exposes a surviving process that holds the exec output pipe open. - Test hygiene. Bound every wait in lifecycle tests, for example with
asyncio.wait_for(), so that a regression fails instead of hanging. Check that each new regression test fails when you revert the fix it covers. - Network access. For an adapter that creates sandboxes, test the policy that each
network_accessvalue produces:inheritleaves the spec unchanged,model_onlyallows only the model host, andmodel_and_toolsadds the hosts of the grants that the harness uses but not of grants that it skips. Post seeds to/v1/agent_sessionswith an explicitnetwork_policyand with a provider without network policies, and check the 422, that no sandbox is created, that the provider is closed, and that no session record remains. Check that a borrowed session rejects a restricted value before connecting, and that a preinstalled runtime of the pinned version skips installation while a mismatch fails setup. In the real smoke test withmodel_only, confirm that the harness completes and that an unrelated host is unreachable from the sandbox. - Task environment. Confirm that tool shells keep the task’s
HOMEandXDG_*directories, and that files a tool writes under~are visible to verification. Check that the harness does not unpack its runtime or caches into the task’s home. - Real smoke test. Run a real model on a real task with tools and verification. Confirm that the harness runs in the sandbox, that the agent closes before verification, and that the sandbox owner cleans it up. Inspect failures, traces, artifacts, and grading coverage. To collect rows you prepared as the benchmark’s README shows, start the servers with
gym env start --config <run.yaml>, then rungym eval run --no-serve --config <run.yaml> --input <tasks.jsonl> --output <run_dir>/rollouts.jsonl. Without--no-serve,gym eval runaccepts only the prepared dataset of the requested split. A configuration that resolves and validates can still fail when its servers start, so start them before you claim a pairing works. - Composition. Show a second compatible pairing that works through configuration changes alone. Record versions and unsupported combinations.
- Upgrades. Compare the same harness before and after the upgrade with a fixed model, tasks, prompts, sampling parameters, limits, images, verifier, and concurrency. Compare scores and failures. Different harnesses do not need to score the same.
- Isolation. Run concurrent sessions with different configurations and credentials, and check that no setting, credential, or file from one session reaches another.
- Scale. Measure setup time, memory, process count, and close latency before you scale up. Validate training support separately from inference.
- Environment Server compliance. CI runs the non-blocking Environment Server compliance check on every agent a PR changes and reports its findings as warnings. Run it locally with
python -m scripts.environment_server_compliance.ci check responses_api_agents/<agent>.
In the PR, include the commands, versions, evidence, limitations, tests, and pre-commit results.
Terminal-Bench 2.1 full evaluation
Before merging a new harness or a harness upgrade that claims Terminal-Bench 2.1 support, run the complete benchmark task set at a pinned revision with a real model. This applies at every capability level, including Evaluation. Small-sample smoke runs and scripted conformance probes do not satisfy this requirement.
Use the benchmark’s configuration and sandbox ownership, with golden-patch mode disabled. Include every task with 8 repeats (num_repeats: 8, as the benchmark’s OpenCode configuration sets); the README’s run configuration declares none, so set it yourself. Remove smoke-only task filters and limits. Record the following in the PR:
- The Gym commit, benchmark revision, harness and model versions, sandbox provider and images, resolved configuration, sampling settings, budgets, timeouts, repeats, and evaluation commands.
- The expected, attempted, graded, and missing task/repeat counts; aggregate score and its denominator; per-task rewards; and all failed or incomplete evaluations. Keep infrastructure failures separate from valid zero rewards, and explain exclusions and retries. Missing task/repeat outcomes mean the results are incomplete.
- Links to the retained rollouts, verifier outputs, failure sidecars, and
quality_summary.json. Include the saved-rollout evidence-check result: from Observability up it must pass; at Evaluation, record the failure and the gaps declared by the close bundle.
For an upgrade, provide full before/after results with the same model, tasks, prompts, sampling, limits, images, verifier, and concurrency. Every task must be accounted for; the harness does not have to solve every task.