Skip to navigation

Add or Update a Harness

View as MarkdownOpen in Claude

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

TermMeaning on this page
HarnessThe agent runtime (SDK or CLI) that runs the model and tool loop.
AdapterThe Gym Agent Server under responses_api_agents/<harness>/ that maps Gym requests to the harness. It runs outside the task sandbox.
Environment ServerThe Gym server that runs one episode in order: Resources Server seed, agent session, verification, and cleanup. The examples use single_agent_turn.
Resources ServerThe benchmark server. It prepares tasks, owns task sandboxes, verifies results, and can expose tools.
Task sandboxThe isolated environment that contains the task repository. The harness and its tools run here.
Borrowed or owned sandboxA sandbox is borrowed when the Resources Server creates it and passes it to the agent, and owned when the agent creates it. Only the owner destroys a sandbox.
Task serviceA background process that a completed tool call leaves running, such as a server that the verifier queries. It can outlive the harness.

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.

CapabilityWhat it enablesWhat the adapter must doHow to check it
EvaluationRewards from the benchmark’s verifier.Implement the session contract, return a NeMoGymResponse, and route model calls through a Gym Model Server so that the later levels need no rework.A real model and task with verification.
ObservabilityTrajectories for debugging, with tool timing and usage.Keep the rollout prefix on model calls, and return an AgentObservationBundle that records missing evidence as gaps. See Preserve inputs, outputs, and errors.Harness Conformance and inspection of saved rollouts.
Environment tools and task sandboxesThe same agent runs against environment-provided tools and sandboxes, across benchmarks.Map tool grants and SandboxAccess into the harness’s configuration. See Integration contracts.A second pairing that works through configuration changes alone.
TrainingExact token IDs and log probabilities for policy optimization.Send every model call that can return policy-generated text through the training-capture route. See Route every model call through the Model Server._ng_token_capture metrics on the collected rollouts, with mask_sample absent or false.

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:

  1. 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.
  2. 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 shared harness_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.
  3. 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 an AgentObservationBundle.
  4. 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 the mcp_servers section of its configuration.

What Gym provides

ComponentWhat it handles
Environment Server (single_agent_turn)The episode order: Resources Server seed, agent session, activation, agent close, verification, and cleanup.
SimpleResponsesAPIAgentThe HTTP endpoints, the agent-session contract, rollout URL helpers such as base_url_for_run(), resolve_model_base_url(), and model_endpoint(), and the partial-rollout checkpoint hooks. An adapter that does not declare checkpoint_mode = "exported" restarts unfinished rollouts from their input, and its checkpoint status reports mode: restart_only so a training framework can tell before any checkpoint. See Make a Harness Checkpointable.
Model ServerProvider normalization, rollout-prefixed routing, model-call capture, and training-token capture.
nemo_gym.sandboxSandbox providers, AsyncSandbox, and text file transfer.
nemo_gym.agents.utilsSupervised harness execution in a task sandbox: launch, termination, artifact capture, and release. See the nemo_gym.agents.utils section below.
nemo_gym.trajectory.trajectory_recordThe observation schemas. Rollout collection joins agent observations with captured model calls.
Harness ConformanceScripted probes and an evidence checker for trajectory evidence.

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 sets token_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.sh there, 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_session call reaches close_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 its finally block. Each verification attempt stops its own verifier sandbox in finally. The final /close_session call 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.

CallRequest bodyResponseAdapter hook
POST /v1/agent_sessionsAgentSeedSessionRequestAgentSeedSessionResponse and an agent_session_id session cookie_seed_agent_session_state()
POST /ng-rollout/<capture_key>[/training-token-capture]/v1/responsesThe task’s responses_create_paramsNeMoGymResponseSession branch of responses()
POST /v1/agent_sessions/closeAgentCloseSessionRequestAgentCloseSessionResponse_close_agent_session_state()
POST /rollouts/<capture_key>/stop (optional)RolloutStopRequest (an optional reason, and completed for a run whose task ended)RolloutStopResponse_rollout_sandbox_session()

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 refuses num_workers > 1 at startup.
  • Cookie binding. Seed stores agent_session_id in 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. In responses(), 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 string detail and 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 a detail that says does not support sandbox access; the Environment Server compliance check flags any other failure of a seed that lends a sandbox. Test each refusal with nemo_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, raise AgentSessionConflictError, which answers HTTP 409. For other errors that a retry cannot fix, such as an invalid request, raise an HTTPException with 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:

class SandboxAccess(BaseModel):
connection: DirectSandboxConnection # kind="direct", provider_config_ref, descriptor
workdir: str # task repository inside the sandbox

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:

from nemo_gym.sandbox import AsyncSandbox, create_provider
from nemo_gym.sandbox import resolve_provider_config
from nemo_gym.config import get_global_config_dict
connection = body.sandbox_access.connection
provider = create_provider(resolve_provider_config(connection.provider_config_ref, get_global_config_dict()))
try:
sandbox = await AsyncSandbox.connect(connection.descriptor, provider=provider)
except BaseException:
await provider.aclose() # no sandbox owns the provider yet
raise

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_HOME or PI_CODING_AGENT_DIR, instead of overriding HOME. Tool shells must keep the task’s HOME and XDG_* directories, because verification runs with the task’s home and agent close deletes the session directory. Otherwise, the effects of commands such as git config --global or pip 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 ~/.cache by default puts its files in the task’s HOME; for example, the GitHub Copilot CLI 1.0.103 binary unpacks about 236 MB of bundled files into $HOME/.cache on 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 sets UV_CACHE_DIR under 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 private HOME, and point the harness at that copy. In either case, leave the HOME and XDG_* 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.ready after 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:

ConnectionProtocol and responsibility
Environment Server to Agent Server or Resources ServerHTTP/JSON endpoints implemented with FastAPI: seed and close, the agent’s Responses API contract, and Resources Server verification.
Agent Server to task sandboxAsyncSandbox.exec(), upload(), and download() delegate to the configured provider. For command execution, OpenSandbox uses HTTP(S) with SSE or background polling, OpenShell uses streaming gRPC, Docker invokes its CLI, and Local uses a subprocess. File transfer follows each provider’s implementation. The supervisor client builds a shell-and-file protocol on top of these calls; it does not expose a Responses API endpoint.
Process supervisor to harnessThe supervisor starts the harness in a new process group, enforces its deadline, signals and reaps that group, and writes cleanup.json. For a pausable session it also pauses and continues the harness’s processes at a checkpoint. It does not send model requests or parse model responses.
Harness to Model ServerThe harness’s own model HTTP protocol, such as Chat Completions for Hermes and Pi or Responses for Codex. Preserve the rollout-qualified base URL that Gym passes in.
Harness to granted toolsHTTP or MCP, as described in the tool grant. See Tools.

Tools

A harness can get tools from two sources:

  1. 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.
  2. Tool grants from the Environment Server. These arrive in AgentSeedSessionRequest.tool_accesses. The Environment Server’s resources_tool_transports setting selects which grants it creates for the episode’s Resources Server, and its tool_servers setting adds a required MCP grant for each other listed Resources server, such as a search server, falling back to the agent configuration’s tool_servers:
TransportGrant typeWhat the adapter receives
direct_httpDirectHTTPToolAccessThe Resources Server base URL and session cookies, for trusted Python agents that call typed tool routes. The cookies identify the episode’s Resources Server session, so they also reach its routes other than tools.
mcpMCPToolAccessA streamable-HTTP MCP endpoint, usually the Resources Server’s /mcp, with the headers returned by the Resources Server’s seed.

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_http session 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:

AdapterBuilt-in toolsResources Server tool grantsModel API
BrowseCompupdate_progress when configured.At most one direct_http grant; required MCP grants are rejected. The research tools remain on the Resources Server, which isolates bash_command in its own sandbox.Responses
LangGraphReflection, orchestration, parallel thinking and ReWOO run in the Agent Server and call only the Model Server.No environment tools or sandbox access; required tool grants and sandbox grants are rejected. Keep resources_tool_transports: []. Evaluation sessions report missing native invocation and turn evidence.Responses
HermesHermes toolsets, selected with enabled_toolsets and disabled_toolsets, for example [terminal].mcp only. Each granted MCP server becomes a Hermes toolset with the same name. Required direct_http grants are rejected.Chat Completions
PiPi’s built-in sandbox tools. sandbox_bash_timeout_seconds limits each bash call.None in agent sessions. Required grants are rejected; keep resources_tool_transports: [].Chat Completions
CopilotCopilot CLI built-in shell, file, and task tools inside the task sandbox.None. Required grants are rejected; keep resources_tool_transports: [].Chat Completions (BYOK)
CodexCodex’s shell and file tools. Agent sessions require sandbox_mode: danger-full-access, because the task sandbox supplies isolation.mcp only. Each granted MCP server becomes a Codex mcp_servers entry with the same name. Required direct_http grants are rejected.Responses (streaming)
OpenCodeOpenCode’s built-in tools. Session opencode_config permits only permission, tools, snapshot (boolean), attachment, compaction.auto, the compaction buffer (compaction.reserved on OpenCode 1, compaction.buffer on OpenCode 2), agent.build.steps and subagents.mcp only. Each granted MCP server becomes an OpenCode remote MCP server with the same name; a required one that does not connect fails the activation. Required direct_http grants are rejected.Chat Completions
OpenClawread, write, edit, exec, and process.mcp only. Each granted MCP server becomes an OpenClaw mcp.servers entry with the same name, probed before the run; a required one that does not connect fails the activation. Required direct_http grants are rejected.Chat Completions
WildClawBench (wildclawbench_agent)Pinned original OpenClaw tools, image handling, search and task skills.None; required grants and borrowed sandbox access are rejected. Native Resources owns the task container. WildClawBench pairing only; no token IDs or continuation.Chat Completions
CrewAIshell, which runs each command in the task’s working directory. The crew runs in the task sandbox: the borrowed one, or an agent-owned one when none is lent.mcp only. Each tool of a granted MCP server becomes a CrewAI tool under its own name; a required server that does not list its tools fails the activation. Required direct_http grants are rejected.Chat Completions
DeepAgents (app.py, tool_profile: builtin)deepagents’ own tools: write_todos, ls, read_file, write_file, edit_file, glob, grep, execute, and task subagents. shell_timeout_seconds sets the default limit of each execute call.None in agent sessions. Required grants are rejected; keep resources_tool_transports: [].Responses
ClineCline’s built-in tools (shell commands, file reads and edits); command_permissions restricts its shell commands.None in agent sessions. Required grants are rejected and optional ones skipped; keep resources_tool_transports: [].Chat Completions
OpenHandsOpenHands’ terminal (subprocess backend), file editor, task tracker, finish and think, with its default condenser.None. Required grants are rejected; keep resources_tool_transports: [].Chat Completions
mini-SWEmini-SWE’s bash tool.mcp only. Each granted MCP server, and each MCP server a Harbor task declares, is reached through a task-local CLI that the bash tool calls; a required one that does not connect fails the activation before the first model call. The response carries each call after the bash call that made it, as mcp__<server>__<tool>. Required direct_http grants are rejected.Responses
DroidDroid’s built-in tools (Read, Execute, Edit, Create, Grep, Glob, LS, its Task subagents and others), run with --skip-permissions-unsafe because the task sandbox supplies isolation.None. Required grants are rejected; keep resources_tool_transports: [].Chat Completions (streaming)
GooseGoose’s default extensions, plus summon (delegate and load) unless delegate: false.None in agent sessions. Required grants are rejected, so keep resources_tool_transports: [].Chat Completions
Qwen CodeQwen Code’s built-in tools, including the agent tool unless subagents: false. exclude_tools turns off the web tools by default.None in agent sessions. Required grants are rejected, so keep resources_tool_transports: [].Chat Completions
Kimi CodeKimi Code’s built-in tools, including Agent and AgentSwarm unless subagents: false. disabled_tools turns off the cron and web tools by default.None in agent sessions. Required grants are rejected, so keep resources_tool_transports: [].Chat Completions
Terminus 2One tmux terminal. Terminus types the keystrokes it reads from the model’s JSON or XML reply; it uses no function calling.None. Required grants are rejected; keep resources_tool_transports: [].Chat Completions

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:

{
"kind": "mcp",
"name": "task_tools",
"required": true,
"connection": {
"transport": "streamable_http",
"url": "http://resources:8080/mcp",
"headers": {"Authorization": "Bearer <episode-tool-token>"}
}
}

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:

{
"responses_create_params": {"input": [{"role": "user", "content": "What does the figure show?"}]},
"verifier_metadata": {"answer": "a cat"},
"agent_context": {
"agent": {
"values": {"tag": "figqa2"},
"artifacts": {"media": {"path": "test_media/figqa2/7f3c"}}
}
}
}

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:

  • values holds small inline JSON fields. One role’s context, including its artifact references, is limited to 64 KiB as UTF-8 JSON.
  • artifacts names 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 values or in artifacts, 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.

class FigureContext(BaseModel):
model_config = ConfigDict(extra="forbid")
media: AgentContextArtifact
tag: str
@dataclass
class FigureSessionState(SimpleAgentSessionState):
media_dir: Path | None = None
class FigureAgent(SimpleAgent):
agent_context_model = FigureContext
def _new_session_state(self, body: AgentSeedSessionRequest) -> FigureSessionState:
state = super()._new_session_state(body)
context = self.parse_agent_context(body)
media_dir = resolve_agent_context_artifact(context.media, Path(self.config.media_base_dir), kind="directory")
# dataclasses.fields: copy Simple Agent's state and add the resolved directory.
inherited = {field.name: getattr(state, field.name) for field in fields(state)}
return FigureSessionState(**inherited, media_dir=media_dir)
async def _create_session_episode(self, state, body, **kwargs):
body = add_figure_images(body, state.media_dir) # the agent's own request builder
return await super()._create_session_episode(state, body, **kwargs)

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:

FieldPurpose
entrypointThe adapter’s server module, usually app.py.
resources_servernull for agent sessions, so that the Environment Server selects the benchmark. Set it only for the compatibility /run path.
model_serverThe Gym Model Server reference, for example {type: responses_api_models, name: policy_model}. The sandbox must be able to reach it.
modelThe model name that the harness sends.
num_workersSeveral workers are fine when all state lives in agent sessions; otherwise the server overrides multiple_workers_unsupported_reason().
Version pinThe exact harness version, for example pi_version: 1.5.2 or codex_version: 0.144.4. Pi, Codex, and OpenClaw reject a missing or inexact version. OpenCode defaults opencode_version to its pinned release and rejects an inexact value. Hermes defaults to the source revision in its pyproject.toml. Override it with hermes_version. See Select a harness release for the supported startup selectors.
sandbox_provider, sandbox_configUsed only for agent-owned sessions: a named provider block and the SandboxSpec fields. Leave sandbox_provider as null when the Resources Server supplies the sandbox.
network_accessEgress of an agent-owned sandbox: inherit (the provider’s network), model_only, or model_and_tools. See Restrict the egress of an owned sandbox.
sandbox_runtime_dirA harness runtime baked into the sandbox image, for a sandbox that cannot download one. Setup checks that it runs the pinned version instead of installing.
TimeoutsInstallation, execution, and per-phase close budgets, such as sandbox_install_timeout_seconds and session_close_timeout_seconds. Names differ by adapter; check its configuration class.
session_close_retry_window_secondsThe close retry window: how long a closed session stays fenced and a retried close gets the saved reply. Cover the caller’s retry horizon.
report_agent_sandbox_oomAnswer an activation whose sandbox was killed at its memory limit with a failed response, which the Environment Server’s agent_outcome_policy decides. The default is 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. See Report a sandbox killed at its memory limit.
tool_accessesStatic tool grants that are merged with each episode’s grants.
tool_serversResources servers whose MCP tools each episode grants, such as a search server. The Environment Server seeds them unless it sets its own list.
token_id_captureEnable for opaque external harnesses whose output has no token IDs, when collecting training data.

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.

Request pathWhere the harness runsWho cleans upWhen to use
Agent session seeded with SandboxAccessThe supplied task sandbox.The agent stops its harness work and disconnects. The Resources Server destroys the sandbox.Recommended. Use it whenever the benchmark’s Resources Server supplies a task sandbox.
Agent session without SandboxAccess, with sandbox_provider configuredA sandbox that the agent creates. Task requirements must be compatible with this mode.The agent stops the sandbox it created.The benchmark does not supply a task sandbox, or no shared sandbox service is available. Use a container provider such as Docker.
Agent session without SandboxAccess or sandbox_providerNowhere: seed rejects the request.Not applicable. Gym never falls back to host execution or a replacement environment.Never. This row is a configuration error.
/v1/responses with no agent-session bindingThe Agent Server host, if the adapter supports it.The adapter cleans up its local invocation and temporary files.Development and smoke tests only. The task is not isolated from the host.

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:

from nemo_gym.agents import restrict_sandbox_network
provider = create_provider(resolve_provider_config(self.config.sandbox_provider, get_global_config_dict()))
try:
spec = restrict_sandbox_network(
spec,
network_access=self.config.network_access,
provider=provider,
model_base_url=self.resolve_model_base_url(self.config.model_server.name, trace_context=False),
tool_urls=[str(access.connection.url) for access in mcp_grants_the_harness_uses],
)
except BaseException:
await provider.aclose() # no sandbox owns the provider yet
raise
sandbox = AsyncSandbox(provider)
  • inherit returns the spec unchanged. model_only allows only the host of the model endpoint. model_and_tools also 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 inherit before 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_network already raises it for a provider without network policies (only OpenSandbox enforces them), for an explicit sandbox_config.provider_options.network_policy combined with network_access, and for an endpoint that the sandbox cannot reach. Raise it yourself for a value that the adapter does not support, such as model_and_tools in 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 SandboxPythonRuntime do, or accept a sandbox_runtime_dir that 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, set absolute_ip_server_types: [responses_api_models] so that only the model server leaves loopback; with model_and_tools, also list resources_servers for the tool servers.
  • The policy is only as strong as the OpenSandbox server’s egress mode: dns filters only name resolution, so a hard-coded IP bypasses it, while dns+nft also 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.

Adapter fileResponsibility
app.pyGym endpoints and configuration; request validation and mapping; session hooks; response and observation conversion; dispatch to host or sandbox execution.
sandbox.pyA harness-specific session state class that composes SandboxSession. It installs the runtime at seed, stages input in stage_activation(), collects artifacts, and holds harness-specific state and diagnostics.
sandbox_runner.py (only when the shim needs Python)Reads the staged input, invokes the harness SDK, writes the harness’s output and optional process diagnostics, and keeps partial output where the harness supports it. Handles SIGTERM by stopping the harness and writing that partial output before it exits, because the supervisor sends SIGTERM at the deadline and on close. CLI harnesses use the shared harness_runner.sh instead, so the task image needs only bash.
install_<harness>_runtime.sh or an existing harness-specific installerInstalls the pinned harness and its private dependencies, then checks that they run. Keep installation out of the activation path.
pyproject.toml and uv.lockThe adapter’s isolated environment: nemo-gym[dev,sandbox] plus packages that run on the Agent Server, such as a framework or SDK. Without the sandbox extra, an SDK-backed provider such as OpenSandbox cannot import its SDK, and the first sandbox session fails.
tests/Host dispatch, session setup, request semantics, output parsing, installation, and lifecycle regressions.

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/.

Shared moduleResponsibility
agents/utils/sandbox_session.pySandboxSession owns the sandbox connection, the ownership flag, workdir, session_dir, the execution and finalization tasks, the termination receipt, artifacts, and retryable close state. It uploads the supervisor before launch. A session created with pausable=True can pause and continue its harness in place (pause_harness(), continue_harness()); checkpoint_state() and SandboxSession.rebind() re-bind a session to a sandbox restored from a snapshot. SandboxCommand carries the harness argv. shell_assignments() renders runner input as bash source.
agents/utils/supervisor_client.pyBuilds the launch, stop, pause and continue shell commands, defines control-file names and timeout budgets, validates termination receipts, and retires session directories safely.
agents/utils/process_supervisor.shRuns inside the Linux sandbox and needs only bash, a readable /proc, a sleep that accepts fractions of a second, and mv. It leaves the provider’s process group, enforces the harness deadline, which does not count time spent paused at a checkpoint, stops the harness process group and, after a forced stop, the processes described under Harness termination, confirms that none still runs, and writes the termination receipt. The sandbox needs neither Gym nor Python.
agents/utils/harness_runner.shRuns inside the sandbox with bash (built with programmable completion, for compgen), dirname, sleep, and, on bash older than 4.2, date. It sources the input that shell_assignments() wrote, applies the harness environment, runs the CLI with file-backed stdio, and optionally records each JSON line of stdout with the time it was seen. It exits with the CLI’s status, with 125 when it fails before starting the CLI (including an exit in its setup code), or with 126 or 127 when the CLI could not be started.
agents/utils/sandbox_python.pySandboxPythonRuntime gives a Python harness a private runtime that needs no network, uv, or Python in the sandbox. On the Agent Server, it downloads a pinned python-build-standalone CPython for the sandbox’s architecture and C library, checks its SHA-256, and installs the harness’s requirements from wheels for that platform with uv, pinned to the versions in the agent environment. Only requirements given as direct URLs, such as a harness pinned to a commit, are built from source. Both archives are cached on the host under sandbox_python in Gym’s cache_dir. In the sandbox, install_python_runtime.sh unpacks them under /tmp, checks the harness import, and publishes the runtime with an atomic rename, so concurrent seeds never see a partial runtime. Run an absolute harness script with the runtime’s python -E -s, because it is not a virtual environment: -E ignores the task’s PYTHON* settings and -s its user site-packages. is_installed() reuses a runtime built from the same inputs. A harness that differs from the one installed with the Agent Server passes its own lock as constraints, which then replaces the agent environment’s versions: mini-SWE’s runtime is locked by runtime/requirements.txt, because its server keeps an older fork for /run. Hermes, Stirrup and mini-SWE use it.
agents/utils/sandbox_network.pyrestrict_sandbox_network() applies an adapter’s network_access to the spec of a sandbox it creates: model_only allows the model endpoint’s host, and model_and_tools also allows the tool endpoints’ hosts. It refuses a setting it cannot enforce with AgentSeedRejectedError. See Restrict the egress of an owned sandbox. Pi uses it.
agents/utils/task_timeout.pyresolve_agent_timeout(metadata, ceiling=...) returns the harness time budget: a task’s positive metadata.agent_timeout_sec, which Harbor task rows carry, capped by the configured timeout. A missing or invalid value keeps the configured timeout. Hermes, Pi, Codex, OpenCode, OpenClaw, and mini-SWE use it.
sandbox/utils.pyupload_text() and read_text() transfer UTF-8 text, and upload_bytes() and download_bytes() transfer bytes unchanged, through AsyncSandbox.upload() and download(). stage_media() writes media files decoded from the prompt to paths named by their content and returns those paths.

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.

Agent Server: FastAPI endpointsand Python helpers Task sandbox HTTP/JSON: Responses API +session endpoints Provider exec/files: install or reuse Filesystem mount at creation Provider upload + exec: launch / stop Provider download: JSON receipt Provider download: harness artifacts HTTP/JSON: harness model API HTTP/JSON: harness model API Python SDK / subprocess; noagent session Agent session install runtime at seed execute with stage_activationand collect; close exec + upload: runtime setup upload: supervisor source exec: launch / stop shell command upload / download: file bytes Subprocess argv + OS signals CLI subprocess or Python SDK Provides executable and dependencies Local file I/O: JSON receipt Local file I/O: JSON output Environment Server or API client Common runtime mountconfiguration (planned) Gym Model Server: FastAPI app.py: HTTP/JSON endpoints,mapping and dispatch Host harness: SDK or CLI sandbox.py: harness-specificsession and hooks agents/utils/sandbox_session.py:SandboxSession lifecycle harness_install.py: ensureruntime (planned) agents/utils/supervisor_client.py:shell and file protocol sandbox/utils.py: text, byte andmedia transfer AsyncSandbox / providerExamples: OpenSandbox HTTP(S)OpenShell gRPCDocker CLI / Local subprocess Pinned harness runtime process_supervisor.sh: process lifetime harness_runner.sh orsandbox_runner.py: harness shim Harness SDK or CLI and its tools cleanup.json Harness output and optional diagnostics

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_activation uploads the activation input and returns SandboxCommand(argv=...). Install the runtime earlier, during seed. A CLI harness runs through the shared bash runner, whose name never mentions python, so a pkill -f python3 in the task cannot stop it.
  • collect copies 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.
@dataclass
class MyHarnessSession(AgentSessionState):
session: SandboxSession[str]
task: asyncio.Task[NeMoGymResponse] | None = None
activation_request: NeMoGymResponseCreateParamsNonStreaming | None = None
async def stage_activation(self, prompt: str) -> SandboxCommand:
directory = self.session.session_dir
await upload_text(self.session.sandbox, path=f"{directory}/prompt.txt", text=prompt)
params = shell_assignments(
{
"cwd": self.session.workdir,
"command": [f"{RUNTIME}/my-harness", "run", "--json"],
"env": {"MY_HARNESS_BASE_URL": self.base_url},
"stdin": f"{directory}/prompt.txt",
"stdout": f"{directory}/output.json",
"stderr": f"{directory}/stderr.log",
}
)
await upload_text(self.session.sandbox, path=f"{directory}/params.sh", text=params)
return SandboxCommand(argv=["bash", f"{directory}/{HARNESS_RUNNER_FILE}", f"{directory}/params.sh"])
async def collect(self) -> str:
return await read_text(self.session.sandbox, path=f"{self.session.session_dir}/output.json")

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.

state = MyHarnessSession(
request=body,
session=SandboxSession(
sandbox=sandbox,
session_dir=f"/tmp/nemo-gym-my-harness-sessions/{uuid4().hex}",
workdir=workdir,
owns_sandbox=body.sandbox_access is None,
harness="MyHarness",
),
)
try:
await install_runtime(state) # adapter-specific; also uploads harness_runner.sh
except BaseException as error:
try:
await state.session.close(timeout=self.config.session_close_timeout_seconds)
except BaseException:
raise AgentSessionSetupError(state, error=error) from error
raise
return state

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:

timeout = resolve_agent_timeout(body.metadata, ceiling=self.config.timeout)
async with self.sem: # asyncio.Semaphore(self.config.concurrency)
raw = await state.session.execute(
stage_activation=lambda: state.stage_activation(payload),
collect=state.collect,
timeout=timeout,
close_timeout=self.config.session_close_timeout_seconds,
)

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.

async def _close_agent_session_state(self, state: AgentSessionState) -> AgentCloseSessionResponse:
await state.session.close(timeout=self.config.session_close_timeout_seconds)
if state.task is not None and not state.task.done():
state.task.cancel()
...

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:

HelperPurpose
upload_text(sandbox, *, path, text) and read_text(sandbox, *, path)Transfer UTF-8 text through upload and download APIs without putting file contents into shell commands. read_text() replaces invalid UTF-8 and turns \r\n and \r into \n; the adapter validates the decoded payload. These are module functions in nemo_gym/sandbox/utils.py, not AsyncSandbox methods.
upload_bytes(sandbox, *, path, data) and download_bytes(sandbox, *, path)Transfer bytes unchanged, for binary files such as images.
split_text_and_media(content) and stage_media(sandbox, files)Pass prompt images to a harness that reads them from files. split_text_and_media(), in nemo_gym.core, decodes a message’s text and its base64 data-URI media, and raises UnsupportedContentError for content it cannot pass on; the adapter rejects the request. stage_media() writes each file to /tmp/nemo-gym-media/<sha256>.<extension> and returns the paths, so rollouts of one task get the same prompt; media_path(file) gives a file’s path before it is staged. Staged files are renamed into place atomically and never deleted, so sessions sharing a sandbox can read them. stage_media() raises SandboxUnavailableError for a provider outage, which the episode retries, and SandboxTransferError for a failure inside the sandbox.
supervised_launch_command()Checks that bash can parse the supervisor before claiming the launch. Builds a quoted command with an atomic launch claim that fences delayed execution.
stop_and_confirm_cleanup()Fences a pending launch or asks the supervisor to stop through stop.request, then requires an explicit termination receipt. It sends no signal, so a reused PID cannot be hit. Raises NgFailureEvent with boundary harness and kind harness_termination_unconfirmed for a well-formed negative receipt, which is final; missing or malformed evidence raises a retryable error.
remove_session_directory()Renames the session directory before deleting it, so its launch fence stays effective. Removes only adapter-owned session files, after the termination outcome is final and artifacts are collected.
parse_cleanup_receipt()Requires a literal cleanup_confirmed: true, and normalizes malformed optional diagnostics with a warning. A fenced launch that never ran has no harness exit code, so missing diagnostics never become a successful exit.
SandboxSession.stop_harness()Confirms harness termination before provider exec is cancelled. Normal execution and close both call it through shared finalization.
SandboxSession.read_output_log() and stop_request_pathExpose combined supervisor and harness diagnostics and the cancellation marker, so adapters do not hard-code control-file names. A missing log never masks the original error.
supervision_timeouts()Derives the per-phase cleanup budget and the provider exec timeout together. It reserves time for the TERM grace period, direct-process reaping, and process-group reaping, plus 30 seconds for startup, polling, and receipt I/O, plus pause_allowance for time paused at checkpoints.

All control files live under session_dir, and their names are defined in supervisor_client.py:

FileWriter and purpose
process_supervisor.shSandboxSession uploads it after staging input and before launch.
launch.claimThe launch or stop shell creates it atomically, either to claim execution or to fence a delayed launch.
supervisor.pidThe launch shell records the PID that becomes the supervisor when the shell executes it. If the provider did not make that shell a process group leader, this process instead starts the supervisor in a new process group, passes SIGTERM on to it and exits with its status.
stop.requestThe stop shell writes this cancellation marker; the supervisor polls for it. A signal is not used, so the harness keeps the default SIGTERM disposition.
expire.requestThe session writes it to end the harness as at its time limit; the supervisor polls for it.
cleanup.jsonThe supervisor records here whether the harness process group terminated. stopped is true when the stop request, not the harness’s own exit or the deadline, ended the harness or fenced its launch. pause_expired, present only when true, says a pause outlasted --max-pause and the supervisor ended the harness as at its time limit; timed_out is then true too. If a stop wins the launch claim, the stop shell writes the same receipt shape with return_code: null, timed_out: false and stopped: true.
output.logThe launch shell redirects supervisor and harness diagnostics here. Task output is a separate, adapter-owned artifact.
pause.requestPausable sessions only. The pause shell writes a sequence number N, greater than any earlier one; the supervisor polls for it and sends SIGSTOP to every process the harness reaches and every process that carries its marker. A pause written before the launch holds the launch until its continue.
paused.jsonThe supervisor acknowledges pause N here once every reached process is stopped: {"seq": N, "confirmed": BOOL, "pids": [...], "error": STRING|null}.
continue.requestThe continue shell writes N to continue after pause N; the supervisor sends SIGCONT to the same processes.
continued.jsonThe supervisor acknowledges continue N here, in the same shape as paused.json.

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=...) and supervised_launch_command(python=...) are removed. The supervisor runs with bash, so the task image needs bash; an adapter that installed python3 during setup only to run the supervisor or a runner no longer needs to.
  • SandboxCommand(stdlib_runner=...), supervised_launch_command(stdlib_runner=...), the bin/gym-runner interpreter link and RUNNER_FILE are removed. Run a CLI through harness_runner.sh; a Python shim must bring its own interpreter.
  • The receipt’s return_code is 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.sh reports 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 HOME and XDG_* 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.

  1. 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 that SandboxPythonRuntime uploads.
  2. 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.
  3. 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.
  4. 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.
  5. 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_access cannot 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:

OutcomeHandling
Model or configured execution limit reachedKeep partial work and mark it incomplete. It may still be gradable.
Provider or runtime failureKeep failure evidence. The Environment Server decides whether to verify or make the episode retryable from the reported cause.
Harness termination not confirmedFail the activation and skip verification. The sandbox owner tears the sandbox down.
Verification completedReport the score, including valid zeros.
Verification missing or inconclusiveReport the missing measurement separately from scored attempts.
Verification infrastructure failureFollow the repository masking rule. Keep an inconclusive result out of the session’s verification cache so verification can recover.

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:

Reported causeVerifyEligible for episode retry
agent_invalid_output, agent_limit, or model request errors 400/413/422YesNo
Model request errors 408/425/429/5xx, model_transport_error, or unknownNoYes
Transient sandbox provider failures classified for retry or model_server_queue_timeoutNoYes
provider_oom_killedYesNo
model_request_rejected (on a task-folder run, a 400 that names invalid run settings, such as an output limit above the model’s cap)NoNo
Other failures, including 401/403/404 or malformed metadataNoNo

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 failed with no output and no usage, because the harness’s events were lost with the sandbox. Its tools, tool_choice and parallel_tool_calls are the request’s. So is its model, which is empty when the request names none.
  • metadata.ng_agent_outcome holds the failure kind provider_oom_killed, so the Environment Server’s agent_outcome_policy decides the episode. The default of that policy verifies it.
  • metadata.ng_agent_sandbox_observation holds the sandbox’s observation: the role agent, the outcome oom, the provider and the sandbox ID of the failure, and the failure’s event ID as failure_id. Its stage is the failure’s, or agent when the failure names none.
  • failure_report and 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 AgentInvocation records that the kill left incomplete say failed with the error type server_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() raises NgFailureEvent with boundary harness and kind harness_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:

  1. Confirm harness termination.
  2. Collect artifacts once.
  3. 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:

python -m scripts.run_harness_conformance \
--harness pi --output results/pi-conformance

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:

python scripts/inspect_harness_conformance.py \
--bundle results/my-harness/rollouts.jsonl \
--output results/my-harness/evidence \
--require-sandbox

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 /run endpoint 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 SIGTERM and 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, because os.kill(pid, 0) also succeeds for a zombie. Run the sandbox-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_access value produces: inherit leaves the spec unchanged, model_only allows only the model host, and model_and_tools adds the hosts of the grants that the harness uses but not of grants that it skips. Post seeds to /v1/agent_sessions with an explicit network_policy and 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 with model_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 HOME and XDG_* 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 run gym eval run --no-serve --config <run.yaml> --input <tasks.jsonl> --output <run_dir>/rollouts.jsonl. Without --no-serve, gym eval run accepts 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.