Repository navigation
feat(opencode): restrict the egress of agent-created sandboxes - #5555
Conversation
Benchmarks whose Resources server supplies no sandbox, such as HLE, have pi_agent create one per session. pi_sandboxed_agent ran those sandboxes with model-only egress; pi_agent could not, so a reasoning benchmark moved to agent sessions would gain open internet. - network_access (inherit, model_only, model_and_tools) sets an OpenSandbox egress policy on a sandbox the agent creates. A borrowed task sandbox keeps its owner's network, so a session that borrows one rejects any other value. The policy helper, restrict_sandbox_network, lives in nemo_gym.agents.utils.sandbox_network and is exported from nemo_gym.agents so other session agents can share it. - sandbox_runtime_dir points setup at a runtime baked into the image and checks its version, since a model-only sandbox cannot download Node or Pi. Signed-off-by: gwarmstrong <[email protected]>
Match pi_agent so reasoning benchmarks without task sandboxes can move off opencode_sandboxed_agent with the same model-only network: network_access (inherit, model_only, model_and_tools) sets the OpenSandbox egress policy on a sandbox OpenCode creates, and a session that borrows a task sandbox rejects any value other than inherit. It cannot be combined with sandbox_config.provider_options.network_policy. The policy comes from the shared restrict_sandbox_network helper, imported from nemo_gym.agents. The preinstalled runtime path already exists (sandbox_executable_path). Signed-off-by: gwarmstrong <[email protected]>
|
/ok to test 9d4ed33 |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE
RISK — Record representative Pi smoke-rollout evidence. The supplied rollouts exercise OpenCode, but this diff also changes Pi's sandbox network setup and adds a preinstalled-runtime branch. The new tests mock sandbox creation and supply the runtime's version output, so they don't establish that Pi actually completes inference and verification under these restrictions. This is a validation gap, not a confirmed runtime defect. Representative real smoke rollouts are required for behavior-changing agent work by the repository guidance.
Please add Pi results to the PR's validation record using an agent-owned OpenSandbox, an image with the installer-compatible runtime layout, an exact pi_version, sandbox_runtime_dir, and network_access: model_only. Record the configuration, completion and grading results, and inspection of agent/verifier behavior. The invariant to demonstrate is that the real offline runtime can complete the session without opening unrelated egress.
Proposed acceptance checks: A small text task should seed without downloading the runtime, reach the allowed model host, return a response that reaches verification, and destroy the owned sandbox on close; an unrelated network destination should be denied. A model_and_tools smoke should also complete one granted MCP call while unrelated egress remains denied. Preserve inherit behavior and the ownership distinction: existing ownership tests assert that owned close stops the sandbox, whereas borrowed close only disconnects. Borrowed sessions must continue rejecting restricted settings before execution.
I inspected all nine changed files, including the stacked Pi/shared-helper changes, and traced their affected runtime, model/tool URL, provider, and cleanup paths. I found no high-confidence code defect. One delegated report wasn't available, so I inspected its shared-policy topic directly. This was static review; I didn't execute tests or rollouts.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
restrict_sandbox_network raised ValueError when a restricted network_access could not be enforced: an explicit provider network policy as well, a provider without network policies, or an endpoint the sandbox cannot reach. The seed route answered it with a 500, which the Environment Server retries, though no attempt can fix the configuration. The helper now raises AgentSeedRejectedError, still a ValueError, so every adapter that calls it refuses the seed once with HTTP 422, before any sandbox is created. Pi also built its tool egress from every MCP grant, including an optional one it leaves out at activation, so such a grant at a loopback URL failed the seed. Egress now covers only the grants Pi keeps. Signed-off-by: gwarmstrong <[email protected]>
…de egress change Signed-off-by: gwarmstrong <[email protected]>
… with a 422 With NVIDIA-NeMo#5554's restrict_sandbox_network change, a restricted network_access the provider cannot enforce (here an explicit network_policy as well) refuses the seed with HTTP 422 before any sandbox is created, instead of a retried 500. Signed-off-by: gwarmstrong <[email protected]>
|
On the Pi smoke-evidence finding: the Pi changes in this diff are #5554's, which this PR is stacked on, and their rollout evidence is in #5554's description (the Rollouts section): #5554. It covers internal HLE runs of Pi on an agent-owned OpenSandbox with the preinstalled runtime ( This PR now also has #5554's review fix merged in (8412d17): |
|
/ok to test 65d8249 |
Both sides added public exports to nemo_gym.agents; both are kept. Signed-off-by: gwarmstrong <[email protected]>
…code egress change Signed-off-by: gwarmstrong <[email protected]>
|
/ok to test ed33fb6 |
Signed-off-by: gwarmstrong <[email protected]> NVIDIA-NeMo#5554 was squash-merged, so its files conflicted with this branch's copy of them; main's versions are kept. This PR's own changes are unchanged.
|
/ok to test a8675af |
Brings in main's latest four commits; this PR's own changes are unchanged. Signed-off-by: gwarmstrong <[email protected]>
|
/ok to test 175b111 |
yaoyu-33
left a comment
There was a problem hiding this comment.
Re-reviewed at 175b111 (the change is git diff main...head now that #5554 has merged). Everything from my earlier review is addressed, and CI is green on this head.
- Required MCP grants go to
restrict_sandbox_networkasrequired_tool_urls, somodel_onlyrefuses them at seed with a 422 instead of failing after the sandbox exists. - The README and the
network_accessdescription namesandbox_executable_path/sandbox_executable_sha256and thedns+nftcaveat; the profile setsmodel_onlyand requires both values. - The tests go through
/v1/agent_sessions, parametrize the borrowed refusal over both restricted values, and the egress test uses required, optional anddirect_httpgrants, so the mutations I listed now fail.
Not run here: I did not re-run the suites locally; I read the diff and relied on the green CI at this head.
Non-blocking: the local opencode_math and opencode_reasoning_gym presets run OpenCode on the Gym host with webfetch: allow (the /run path, where network_access does not apply); that belongs with #5552. The rollout evidence was taken before the review changes.
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42137143948 |
The egress PRs (NVIDIA-NeMo#5555-NVIDIA-NeMo#5559) added a network-policy test next to each adapter's HLE seed test. Keep this branch's seed test, which seeds HLE as shipped and with a direct_http grant, and the new egress test from main. Signed-off-by: gwarmstrong <[email protected]>
Main's egress change (NVIDIA-NeMo#5554, NVIDIA-NeMo#5555) builds an owned sandbox's network policy from the Gym model server's URL. With model_base_url set and no model_server, that read failed on None, so Pi and OpenCode could not seed a sandbox they create, whatever network_access was. The policy now takes the direct endpoint in that case, so model_only opens the endpoint's host. Each adapter's tests seed an owned sandbox with a direct endpoint under inherit and model_only; they fail without this change. Signed-off-by: gwarmstrong <[email protected]>
…andbox runs (NVIDIA-NeMo#5458) * feat(pi): opt-ins to run Pi in a task sandbox as a harness started there Benchmarks that grade a harness started inside the task container (Harbor's agents) need Pi to run with its own tools and prompt, call the benchmark's model endpoint, and leave logs where the verifier side collects them. Pi's sandbox sessions could only call a Gym model server with Gym's runtime guards, and they lost Pi's context-limit outcomes with Pi 0.80.10. All new settings are off or empty by default, so existing configs behave as before: - model_base_url and model_api_key: Pi calls an OpenAI-compatible endpoint directly from the sandbox instead of a Gym model server (set exactly one). Gym does not capture those calls. - thinking_level_map and provider_compat for the generated provider, so that `--thinking max` can send chat reasoning_effort "max"; settings merged recursively over Gym's settings.json (for example retry counts). - sandbox_env, and sandbox_runtime_guards: false to run Pi's own tools and system prompt without Gym's bash cap and prompt note. - session_prompt_cache_key: one prompt_cache_key per session on every call, so a gateway that routes on it keeps the session on one replica. - sandbox_logs_dir and log_requests: Pi's JSON events (pi.txt), its stderr and a per-request log without the conversation in a sandbox directory such as Harbor's /logs/agent. - raise_oom_score_adj: Pi and its tools become the memory-cgroup OOM killer's preferred victims, not the exec daemon or the supervisor. - verify_after_agent_error: a Pi run that failed while its sandbox still runs and answers is returned as a gradable failed response, as Harbor grades after any agent exit, unless its terminal error is a transient model-endpoint failure (after Pi's own retries) or cleanup is unconfirmed. The runner drops Pi's streaming message_update and tool_execution_update events, which repeat the whole partial message on every delta, so long turns no longer grow the event log quadratically. Pi 0.80.10 routes extension console output to stderr in JSON mode, so outcome.mjs writes its records to a session file that the runner appends to the event log; before, context-limit outcomes never reached the adapter in sandbox sessions. Local runs keep printing them. The task's HOME, the agent timeout from the task metadata and the runner's cleanup on capture errors are upstream behaviour and unchanged. Signed-off-by: gwarmstrong <[email protected]> * feat(opencode): opt-in direct model endpoint for sandbox sessions opencode_agent sandbox sessions could only call a Gym model server. A benchmark that grades a harness started in the task container, as Harbor runs OpenCode, has the harness call the model endpoint itself, and routing those calls through a Gym model server changes the requests the endpoint sees. model_base_url and model_api_key (both unset by default) point the session's OpenAI-compatible provider at an endpoint the sandbox reaches, sending `model` as the model ID; set exactly one of model_server and model_base_url. Gym does not capture those calls, so the model-call correlation plugin is not loaded for them. Sessions with a model server and local calls are unchanged. Signed-off-by: gwarmstrong <[email protected]> * feat(opencode): opt-in model request settings for sandbox sessions A sandbox session's provider sent no reasoning effort, replayed reasoning only as reasoning_content, capped every call at max_output_tokens and told OpenCode the model's size, so it compacted before the endpoint's real limit. A harness started in a task container with its own model config does none of that, and some endpoints read the replayed reasoning from another field. Four settings, whose defaults keep today's requests: - reasoning_effort: the model's reasoningEffort option, sent as chat reasoning_effort on every request. - interleaved_reasoning_field: the assistant-message field that replays each turn's reasoning (default reasoning_content). - output_token_policy: remaining_context loads a plugin that drops max_tokens from the session provider's requests, so the endpoint picks the output budget, as opencode_sandboxed_agent's policy of that name does. - declare_model_limits: false leaves the model's size unknown to OpenCode, which then compacts only when the endpoint reports an overflow. Signed-off-by: gwarmstrong <[email protected]> * feat(opencode): opt-in root workdir and argv prompt for sandbox sessions Two gaps kept a sandbox session from running OpenCode the way a harness started in the task container does: - Task images without a WORKDIR start in /, and sessions rejected that workdir because the adapter's runtime and session files under /tmp sit inside it. allow_root_workdir accepts exactly / (the files stay under /tmp, as a harness's own files do there); /tmp and the adapter's own directories are still rejected, and other workdirs keep the full overlap check. - A launcher that passes the instruction as one argument, as Harbor 0.24's opencode agent does, makes `opencode run` wrap it in double quotes (inner quotes escaped) before the model sees it. Sessions send the instruction on stdin, unquoted. argv_prompt_quoting sends the text OpenCode builds from that argument instead. Both are off by default. Signed-off-by: gwarmstrong <[email protected]> * feat(opencode): grade a failed run while its sandbox still runs Harbor runs the verifier after any agent exit that is not a timeout, so a trial whose agent died while its sandbox still answers is graded, not rerun. opencode_agent sessions raised an execution error for every failed OpenCode run (a nonzero exit, an error on an assistant turn, no terminal result), so the Environment Server skipped verification and retried the episode from scratch: an OpenCode the kernel's OOM kill hit, one whose own pkill hit it, or a request the endpoint rejected. verify_after_agent_error (off by default) returns such a run as a `failed` response (`incomplete` when it also hit its time limit), with the error in metadata.graded_agent_error, which Resources grades as a nonzero agent exit. It applies only when the supervisor confirmed cleanup, the run's session export was read, the last assistant turn's error is not a transient model-endpoint failure (OpenCode's retryable APIError: 429, 5xx, reset or lost connections, header and stream timeouts) and the sandbox still reports running and answers a probe command. Anything else stays an execution error and is retried. raise_oom_score_adj (off by default) makes OpenCode the OOM killer's preferred victim in its sandbox, as codex_agent's setting of that name does: the runner raises its own oom_score_adj, which OpenCode and its tools inherit, to 1000, or to 0 when the sandbox starts it below zero. The exec daemon and the supervisor keep the sandbox's own score. Signed-off-by: gwarmstrong <[email protected]> * feat(claude-code): opt-in instruction on stdin for sandbox sessions Sandbox sessions pass the instruction to `claude -p` as an argument after `--`. Harbor 0.24's claude-code agent pipes it on stdin instead, and on a command line the task's own words are a target: an agent that runs `pkill -f <word from its task>` stops its own Claude Code. instruction_on_stdin (off by default) leaves the instruction out of argv and has the runner feed it to the CLI on stdin from a session file. Without it, the runner keeps stdin empty, as before. Signed-off-by: gwarmstrong <[email protected]> * feat(claude-code): opt-in effort, output cap and client environment Running Claude Code against a self-hosted model the way its provider's Claude Code guide configures it needs three client settings the agent could not express: the reasoning effort (`--effort`, which Harbor passes from its reasoning_effort), the per-call output cap (CLAUDE_CODE_MAX_OUTPUT_TOKENS) and further client environment such as API_TIMEOUT_MS or CLAUDE_CODE_AUTO_COMPACT_WINDOW. A settings file on the agent host could carry environment, but not from a run config, and not the CLI flag. reasoning_effort, max_output_tokens and extra_env (all unset by default) apply to local and sandbox launches alike. extra_env rejects the variables the agent sets itself (endpoint, credentials, model, CLAUDE_CONFIG_DIR, the output cap), and YAML integers become strings. Signed-off-by: gwarmstrong <[email protected]> * feat(claude-code): opt-in root workdir for sandbox sessions A task image without a WORKDIR lends "/" as its working directory, and sandbox sessions refuse it because the runtime and session files under /tmp sit inside it, so every such trial fails at session start while a harness started in the container runs there. allow_root_workdir (off by default) accepts exactly "/". The runtime and session files stay under /tmp; /tmp itself, the adapter's own directories and relative or `..` paths are still refused. Signed-off-by: gwarmstrong <[email protected]> * feat(claude-code): opt-in Harbor system-dependency step for sandbox sessions Before Harbor 0.24 installs Claude Code in a task container, its claude-code agent runs ensure_system_dependencies for curl, bash, nodejs, npm and procps: each one whose commands are missing is installed as root with the first package manager found. Agents graded under Harbor therefore have node, npm, ps and pkill even where the task image lacks them, and a sandbox session that skips the step runs Claude Code in a different environment. harbor_system_dependencies (off by default) runs the same decisions as one POSIX sh script (system_dependencies.py: Harbor's checks, package names, manager order and install command lines, logged line by line) before the session installs Claude Code, bounded by system_dependencies_timeout_seconds (default 1800). Where Harbor errors the trial on a failed install, the session logs the failure and runs Claude Code anyway. The script's tests run it under real shells with stand-in package managers. Signed-off-by: gwarmstrong <[email protected]> * refactor(pi): read the outcome records from stdout, as main's outcome extension writes them Signed-off-by: gwarmstrong <[email protected]> * fix(agents): leave model errors the agent reported to the outcome policy Signed-off-by: gwarmstrong <[email protected]> * fix(agents): keep setup failures ungraded after an agent error With verify_after_agent_error, Pi and OpenCode graded any failed run while the sandbox still ran. A run the harness runner could not start (exit 125, 126 or 127), a Pi run whose Gym MCP tools did not load (exit 78), or an OpenCode run whose required Gym MCP tools did not connect or were never confirmed is a setup failure: it now stays an execution error and is retried, never graded as the agent's result. Signed-off-by: gwarmstrong <[email protected]> * fix(claude-code): keep extra_env from re-enabling background tasks Signed-off-by: gwarmstrong <[email protected]> * fix(agents): open a direct endpoint's host in an owned sandbox's egress Main's egress change (NVIDIA-NeMo#5554, NVIDIA-NeMo#5555) builds an owned sandbox's network policy from the Gym model server's URL. With model_base_url set and no model_server, that read failed on None, so Pi and OpenCode could not seed a sandbox they create, whatever network_access was. The policy now takes the direct endpoint in that case, so model_only opens the endpoint's host. Each adapter's tests seed an owned sandbox with a direct endpoint under inherit and model_only; they fail without this change. Signed-off-by: gwarmstrong <[email protected]> * fix(agents): drop the direct endpoint and grade only runs that reached the model Pi and OpenCode sandbox sessions drop the direct model endpoint (model_base_url, model_api_key). Their calls go through the Gym model server again, so Gym captures and correlates every call. That route now takes the settings the direct endpoint was added for: main's OpenAI 2.45 schemas (NVIDIA-NeMo#5464) accept chat reasoning_effort "max". The direct-endpoint egress fix goes with it; owned sandboxes open the model server's host as on main. verify_after_agent_error now treats more failed runs as setup failures, which stay execution errors and are retried, never graded, as Codex does on main for a run that never started a turn: - Pi: a nonzero exit before Pi ended its first assistant turn, unless the time limit stopped it. - OpenCode: a nonzero exit before any model step ran, unless the time limit stopped it; and a run whose required Gym MCP tools were never confirmed, also when OpenCode then exited nonzero for another reason. The READMEs no longer link to Terminal-Bench-Science sections that are not on main, and Pi's notes that `thinking: max` needs pi_version 0.80.6 or later (the default pin is 0.80.2). Signed-off-by: gwarmstrong <[email protected]> * docs(agents): say what an OOM-kill preference cannot protect prefer_oom_kill_setup's docstring implied that the supervisor and the exec daemon survive an OOM kill. Where the container's memory cgroup sets memory.oom.group=1 (cgroup v2, as some kubelets configure it), the kernel kills every process in it. The harness-runner tests now also check that an inherited events_exclude filters nothing when the params leave it unset; the test fails without the runner's unset. Signed-off-by: gwarmstrong <[email protected]> * fix(opencode): refuse the OpenCode 1 launch settings on OpenCode 2 reasoning_effort, interleaved_reasoning_field, output_token_policy, declare_model_limits and argv_prompt_quoting set OpenCode 1's provider configuration and launch. The OpenCode 2 session added on main builds its own and would ignore them, so its seed now refuses them, as it refuses plugin dependencies. raise_oom_score_adj is a harness runner setting and now reaches the OpenCode 2 runner too. Signed-off-by: gwarmstrong <[email protected]> * fix(opencode): keep an endpoint failure seen only on stdout retryable With verify_after_agent_error on, a timed-out continuation whose exported assistant message has no error but whose stdout carries an APIError 503 event was graded as a failed answer. The endpoint check now reads the first stdout error event as well as the last assistant message's error, so the run stays an execution error and the episode is retried. Signed-off-by: gwarmstrong <[email protected]> * fix(pi): check only Pi's provider error for endpoint failures The endpoint regex read one error string that could be either Pi's provider message or the adapter's own process text. Two cases went wrong with verify_after_agent_error on: - a tool-use turn then exit 0 produced "Pi ended without a terminal assistant result", which matched "ended without", so partial work was not graded; - a provider 503 with willRetry=true then exit 1 replaced the provider message with "Pi exited with code 1", so the outage was graded. Keep Pi's error for its last model call apart from the process exit and run the endpoint check on that provider evidence only. Signed-off-by: gwarmstrong <[email protected]> * fix(claude-code): fail session setup when Harbor's dependency install fails harbor_system_dependencies exists for Harbor parity, and Harbor 0.24 errors the trial when its system-dependency install fails. Gym logged the failure and started the task, so the verifier could score work done without procps or node. A nonzero package-manager exit (or the step's time limit) now fails session setup and the episode is retried. With no supported package manager, the step still only warns, as Harbor does. Signed-off-by: gwarmstrong <[email protected]> * test(claude-code): give the task-container seed stubs a sandbox_id Main (NVIDIA-NeMo#6020) records the sandbox's id at the end of Claude Code's seed, so a stub sandbox without sandbox_id fails setup. The stubs in test_sandbox.py gained one in that change; these two did not exist yet. Signed-off-by: gwarmstrong <[email protected]> --------- Signed-off-by: gwarmstrong <[email protected]> Signed-off-by: yaoyu-33 <[email protected]> Co-authored-by: gwarmstrong <[email protected]> Co-authored-by: yaoyu-33 <[email protected]>
What does this PR do?
opencode_agentgainsnetwork_access(defaultinherit) for the sandboxes it creates. The value comes from #5554'srestrict_sandbox_network, applied after the sandbox provider is created, with the Model Server's host and, formodel_and_tools, each MCP grant's host. A session that borrows a task sandbox rejects any value other thaninherit. A restricted sandbox uses the OpenCode executable already in the image (sandbox_executable_path), as the README's offline-runtime section describes. README: the setting.Why. The same reason as #5554, for OpenCode. Without this, a sandbox OpenCode creates has the provider's default network. The deprecated
opencode_sandboxed_agentprofile setsmodel_only. Stacked on #5554, whose branch this PR targets. Part of #5552.Validation
gym env test +entrypoint=responses_api_agents/opencode_agent +should_validate_data=true: 646 passed, 1 skipped. The skip already existed: it needs a C compiler.With each behavior disabled in turn, the new tests fail: the borrowed-sandbox rejection; model-only and model-and-tools egress; and the
network_policyconflict. Theinheritcontrol passes.Review follow-up: feat(pi): restrict the egress of agent-created sandboxes #5554's review fix merged in (8412d17), so this adapter's
restrict_sandbox_networkcall refuses an unenforceablenetwork_accesswith a terminal 422. the existingnetwork_policyconflict test now posts the seed over HTTP and checks the 422 (test_network_access_and_explicit_policy_conflict_is_a_terminal_seed_refusal). Suite in the adapter's own venv: 646 passed, 1 skipped.pre-commit run --all-files: clean.Follow-up to the feat(pi): restrict the egress of agent-created sandboxes #5554 review: merged its latest head; the helper call passes the provider; a borrowed sandbox with a restricted value is refused with
AgentSeedRejectedError; the README says a borrowed sandbox relies on its owner's policy. Its benchmark profile setsnetwork_access: model_onlyand requiressandbox_executable_pathandsandbox_executable_sha256, since a restricted sandbox cannot download OpenCode. The adapter's owntest_benchmark_profile.pyexpectsmodel_only(removing it fails the test). Suite: OpenCode: 650 passed, 1 skipped; profile and helper tests pass.Review follow-up (Yu Yao) at 5a958e4: required MCP grants are passed to the helper, so
model_onlyrefuses them at seed with a 422; the README and field description namesandbox_executable_pathand thedns+nftcaveat; the egress test uses required, optional anddirect_httpgrants, and the borrowed refusal covers both restricted values. OpenCode suite with the profile and helper tests: 685 passed, 1 skipped.Rollouts
On the internal OpenSandbox deployment used for #5554's egress checks, before this PR's review changes, the OpenCode science image (OpenCode 1.17.11 at
/usr/local/bin/opencode) ran with egress limited to the model and tool hosts, whilenodejs.org, the npm registry and GitHub's DNS name were blocked.Internal runs on the
georgea/nemo-gymfork at 7cf95c7f4 (HLE) and ee833ed (HLE Diamond), which carries this change before its review updates (Nemotron 3.5 Super on vLLM, 5 text tasks each, that image):model_only: 5/5 rollouts completed, graded and healthy.model_only: 5/5 healthy, with fix(opencode): keep a Gym reply's reasoning out of OpenCode's answer #5548's reasoning fix.Compatibility and benchmark impact
Default unchanged (
inherit).The adapter's own default stays
inherit. Its benchmark profile (from #5550) now setsnetwork_access: model_onlyand requiressandbox_executable_pathandsandbox_executable_sha256, so a run that uses the profile gets the restricted sandbox; open-network scores are not comparable.Checklist
pre-commit run --all-files).git commit -s).