Skip to content

feat(environment): require sandbox placement for tool-enabled sessions - #7146

Open
yaoyu-33 wants to merge 207 commits into
mainfrom
codex/sandbox-seed-guard
Open

yaoyu-33 wants to merge 207 commits into
mainfrom
codex/sandbox-seed-guard

Conversation

@yaoyu-33

@yaoyu-33 yaoyu-33 commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

What changes

Stacked on #6752, following Adam’s review. The Environment Server checks where an agent will execute tools before the first model call. Reviewed model-only pairings can continue on the host. Existing Simple Agent recipes with an unused direct HTTP grant warn and omit that grant for the turn.

The affected Simple Agent tool recipes, including AutomationBench, request a sandbox that can reach the model and the paired Resources Server. Deployments must supply a lending provider that enforces the recipe’s network rule. The placement check covers the agent loop. Individual Resources Server tools and graders retain their own execution contracts. OfficeEnv’s historical officeenv_sandboxless.yaml file keeps its saved instance names and now lends Simple Agent a sandbox. Each copy grants its own Resources Server. The compaction agent’s legacy relay cannot borrow that sandbox, so the recipe refuses that pairing at configuration time.

Conformance runs the Simple Agent loop and its scripted HTTP shell tool in the same borrowed Docker container. The other previously host-local, agent-owned probes use Docker with a per-episode marker directory. The synthetic interface-routing test exercises a model-only session.

Validation

  • 882 tests passed and 14 skipped across the Environment Servers, runtime, orchestration, Simple Agent rollout storage and conformance fixtures.
  • Full pre-commit completed on the Linux workstation. The private guardwords catalog was unavailable to the hook.
  • Resolved 20 affected recipes and three inherited configurations through gym env resolve with the OpenSandbox deployment configuration. Each resolved allowlist included its actual paired Resources Server and model.
  • The complete Simple Agent conformance suite met its P0 gate on Linux Docker (python -m scripts.run_harness_conformance --harness simple --output <new-dir>). All eleven harnesses moved to Docker passed --scenario tool_success with the scripted model. Simple Agent borrowed the container. Codex, CrewAI, Stirrup, Hermes, Pi, OpenCode, Claude Code, Copilot, KiloCode and OpenClaw each owned theirs. Each recorded two shell executions, both results reached the model, and the verifier returned 1.0.
  • GPQA Diamond completed with the shipped tool-free recipe, a real local model, and exactly one unused-grant warning. The answer scored 0.0 and the sample remained unmasked.
  • After the first CI run exposed OfficeEnv compatibility expectations, the OfficeEnv and shared conformance suites passed 253 tests with 14 skipped. With HARNESS=openclaw, all eight pinned-CLI fault regressions passed in 6m 42s. CrewAI’s CI warmup used the probe Docker image, followed by a passing tool-success run under the default 90s deadline.

CI on ff7fb6f

DCO, Lint check and Nemo_CICD_Test passed, including both previously failing OfficeEnv core shards.

  • The advisory conformance report measured nine P0 passes. Claude Code and Terminus 2 failed. OpenCode, Mini-SWE and OpenClaw did not produce usable suite results. On the hosted OpenClaw runner, six pinned-CLI failure cases failed their assertions. The saved failure records for stream-reset and context-precheck show a cleanup timeout; the former lost agent observations and the latter became retryable. The same eight cases passed on the workstation.
  • The Environment Server compliance report flagged existing run() overrides in Agentic MME, DeepAgents and Simple Agent, the DeepAgents sandbox refusal wording, and Simple Agent’s aggregate_metrics override.

ananthsub and others added 30 commits November 18, 2026 15:10
A client that disconnects cancels its request, and every later await in it.
An unshielded stop in the request's cleanup then raises before the provider
closes the sandbox, which runs on until its ttl_s.

nemo_gym.sandbox.stop_sandbox(), in the sandbox package's utils, shields the
stop from that cancellation and bounds it in time, so a hung provider
cannot hold the request either. A timed-out stop raises
TimeoutError, which owners treat like any other failed stop. It also accepts
a Compose group, which harbor owns.

LentSandboxes, the swebench sandbox session base and deepswe_external1 each
had a copy of this stop; they now use the shared one.

Signed-off-by: Ananth Subramaniam <[email protected]>
Every sandbox has one owner, the server that starts it, but each server
family owns its sandboxes through its own design. Gym already has a class
that tracks a server's sandboxes by key, stops them, lends them with operate
scope and snapshots them for checkpoints: SandboxSessionCheckpointer, which
no server uses yet.

It becomes the public nemo_gym.server_runtime.OwnedSandboxes, in its own
module (nemo_gym/server_runtime/owned_sandboxes.py) since it is no longer
checkpoint-only, and every SimpleServer holds one as self.sandboxes:

- created on first use from the server's sandbox_provider and
  checkpoint.state_dir, so a server without sandboxes builds nothing
- self.sandboxes.on("<field>") gives the instance for a second provider
  field, with its own server name for the snapshot index
- run_webserver wraps the app's lifespan so the shutdown stops what every
  instance still owns, after the server's own shutdown code
- access() lends through the provider block the instance was built from
- the instance owns the provider it creates and closes it once every
  sandbox is stopped; it reads the config the server was started with
- the shutdown sweep runs after the server's own shutdown, is bounded
  (150 s in all), refuses to build new instances once it began, and is
  documented next to server_shutdown_timeout_seconds

The glossary gains "sandbox owner" and "lend / borrow", and its existing
"Owner" (the worker that holds a session) points away from them.

The class is renamed directly without an alias: it merged on 2026-11-16 and
is in no release.

Signed-off-by: Ananth Subramaniam <[email protected]>
OwnedSandboxes becomes the one path for every sandbox start and stop, so it
takes on the jobs that servers copied into their own session code:

- One stop: stop() is shielded from the caller's cancellation and bounded
  by STOP_TIMEOUT_S from the moment it is called, its waits for the key's
  lock and for a stop slot included, so a client that disconnects cannot
  leave the sandbox running and nothing can hold the stop forever. A stop
  that fails or times out keeps the key, as before.
- Tracking before start: create() tracks the sandbox before it starts. A
  start that fails or is cancelled after the provider returned the sandbox
  is stopped, shielded. If that stop fails too, the key stays tracked for
  the next stop or aclose(), an export leaves the half-started sandbox out,
  and create() raises the start's error with the stop's as its context.
  AsyncSandbox.start now keeps the start's error the same way when its own
  rollback stop fails. A start cancelled before the provider returned the
  sandbox leaves nothing to stop; ttl_s reclaims it.
- Their own start and stop limits: parallelism (16 by default) bounded
  creates, stops, snapshots and deletes alike, which would let a server
  seeding 512 episodes start only 16 sandboxes at a time. Starts and forks
  now take max_concurrent_starts and stops take max_concurrent_stops, both
  unbounded by default and set per provider with the block's
  owner_concurrency, so a stop never waits behind starts. parallelism bounds
  only snapshot submits and deletes.
- Exclusion per key: a create, a stop, an export and a restore of one key
  hold that key's lock. An export snapshots a sandbox only once its start
  finished, a stop waits for the export or restore of its key and then
  stops what is there, and other keys go on. A restore takes its keys'
  locks in sorted order. A key's lock exists only while someone holds or
  waits for it.

Signed-off-by: Ananth Subramaniam <[email protected]>
Each sandbox's egress rule was set five different ways, and about 20
servers set none. A typed rule in its config block makes every sandbox's
egress visible, and the owner applies it when the sandbox starts.

- SandboxConfig gains network (inherit, no_network, model_only,
  model_and_tools, hosts_only), model_server, tool_servers and
  allowed_hosts, checked for consistency at load. A block that sets network
  and also a provider's own network option is refused. A subclass's own
  network setting, such as partner_if's tool sandbox, is left alone.
- SandboxConfig.spec() takes network_options, the provider options that
  apply the rule, and refuses a restricted rule without them: only the
  owner builds them, so a block that asks for restricted egress never
  starts a sandbox with the provider's default egress. network_options
  replaces Gym#6179's OpenSandbox-only network_policy parameter, which is
  in no release; whichever of the two lands second drops network_policy.
- Each provider class declares a frozen SandboxCapabilities: what its
  snapshots keep, the network rules it can apply, whether it reconnects
  always, only on the same host or never, and whether it closes by label.
  OpenSandbox applies every rule through its egress policy, built by the
  same helper as restricted_network_policy. Docker applies no_network as
  --network none, or leaves it to a provider block that already sets it.
- OwnedSandboxes.spec() turns model_server and tool_servers into reachable
  hosts, read from the config the server was started with, asks the provider for its options for the rule and builds the
  spec. A block without a rule keeps today's behavior and logs one
  deprecation warning naming the rule that keeps it.
- check_provider() refuses a rule the provider cannot apply, and lending on
  a provider that never reconnects. SimpleServer runs it at startup from the
  provider's class, for servers that set lends_sandboxes and, when
  sandbox_provider is the only provider field, for every typed block, whose
  model and tool servers it also resolves to hosts from the config, without
  connecting to them; access() refuses lending again at first use.
- The sandbox docs describe the rule.

Signed-off-by: Ananth Subramaniam <[email protected]>
An agent that is lent a sandbox connects to it through its own copy of the
borrow-or-own branch, and gets the sandbox to stop as easily as to run in.
Only an operate-scope descriptor kept it from stopping a sandbox the
environment still grades in, and no provider enforces that.

borrow(access) in nemo_gym.agents.utils is the one way to use a lent
sandbox. It resolves the provider, connects with the descriptor, and
returns a BorrowedSandbox:

- commands and terminal sessions run as the access's user in its workdir,
  with its env under each call's own
- stop, start, pause, resume and snapshot raise BorrowedSandboxError: they
  are the owner's
- serialize() gives only operate scope, and access() passes the lent access
  on for a harness that borrows the sandbox again in a subprocess
- disconnect(), and leaving an async-with block, release the client
  shielded from cancellation and bounded, as does a failed connect

AgentSandboxConfig types the sandbox an agent starts for itself when nothing
is lent, with the keys agent recipes set today (image, workdir, files,
entrypoint, user, ports and derive_cpu_env, off by default as in most
agents) on top of SandboxConfig and its network rule. Other SandboxSpec keys
a recipe may set, such as sidecars, are refused; each agent that moves onto
the config warns about them for one release first. No checked-in agent,
benchmark or environment recipe sets one today.

No agent moves onto them here: that is each agent family's own change, and
the harness guide changes with the first one.

Signed-off-by: Ananth Subramaniam <[email protected]>
Resolve against main:
- Drop this branch's earlier copy of the shielded stop (stop_sandbox() in
  nemo_gym.sandbox.utils and its test): #6410 merged a different version that
  puts the shield and limit in AsyncSandbox.stop(timeout_s=...). The sandbox
  package, LentSandboxes, the swebench session base and deepswe_external1
  take main's code; OwnedSandboxes stops through AsyncSandbox.stop.
- #5266 exports the checkpointer under its old name: its server, conformance
  helper and test move to OwnedSandboxes in owned_sandboxes, and the public
  API serves SandboxCheckpointConfig, SandboxCheckpointError and
  checkpoint_state_dir from there. No release shipped the old name.
- The glossary keeps main's sandbox lease and capabilities rows beside the
  owner and lend/borrow rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Brings in origin/main through the parent. Keeps this branch's stop: shielded
and bounded as a whole, the wait for a stop slot included. It passes
STOP_TIMEOUT_S to AsyncSandbox.stop, whose own shield (#6410) would otherwise
hold a stop for its 120 s default past a shorter configured limit. The
superseded-sandbox stop does the same. STOP_TIMEOUT_S now comes from
nemo_gym.sandbox.api.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…xes-network

Brings in origin/main through the parents. Main added SandboxCapabilities
with snapshot_keeps and provider_capabilities() in #5410; this branch added
its own SandboxCapabilities. They become one class: main's, with this
branch's network_rules, reconnect and close_by_label, its NetworkRule and
Reconnect defined before it. E2B and OpenSandbox declare one capabilities
each (E2B keeps main's files-and-processes snapshots). The owner's private
_capabilities() copy gives way to provider_capabilities().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Brings in origin/main through the parents; the glossary keeps main's sandbox
lease and capabilities rows beside this branch's lend/borrow row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…n attempt

When the Resources Server lends no sandbox, single_agent_turn can now start one
per attempt through its OwnedSandboxes, with a typed network rule such as
model_only. It lends the sandbox to the agent in the seed, lends the same
sandbox to /verify as ng_sandbox_access after the agent closes, and stops it in
the episode's cleanup on every path. A sandbox that cannot start fails the
attempt as a retryable infrastructure failure before the agent runs; nothing
falls back to the host. The feature is opt-in through sandbox_provider and
sandbox_config, so existing configs behave as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
OwnedSandboxes.for_server created the provider before it read
checkpoint.state_dir, so a refused config (checkpointing on without a
state_dir) left a provider nobody closes, and every later self.sandboxes
built another. The provider block and state_dir are now resolved first. An
owner on the local provider, which runs commands as host processes, logs a
warning.

The self.sandboxes docstring and the glossary say what is true today: no
server owns its sandboxes through it yet, it is used from the event loop, and
a borrower is an agent or a Resources Server grading in the sandbox. The
test imports names from their defining modules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
create() let a cancellation cut the provider's start short and relied on
ttl_s to reclaim what the provider had made. Not every provider applies
ttl_s: on Enroot a create cancelled half a second in left its container on
the node with nothing tracking it (seen in a lifecycle smoke). The start now
runs to its end, shielded and bounded by STOP_TIMEOUT_S, so the create's
rollback has a handle to stop; only a start still running after that is cut
short.

A main test of a stop that waits for its turn held the snapshot semaphore,
which stops no longer take since they got their own limit; it now holds the
stop limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
- stop() took STOP_TIMEOUT_S for its key's lock, again for a stop slot, and
  AsyncSandbox.stop, which shields itself from enclosing deadlines since
  #6410, took a third: up to three limits in all. One deadline now covers the
  whole stop, and the provider's stop gets only the time that is left.
- create() refuses a spec without ttl_s: the shutdown sweep is bounded and a
  crash runs none, so ttl_s is what ends a sandbox its owner never stops.
- access() lends only a running sandbox. A key is tracked from before its
  start, so a key still starting, or one whose start and stop both failed,
  raised a RuntimeError from the sandbox, or lent a broken one.
- An instance built with from_config, as swebench's checkpoint server builds
  it, keeps parallelism as the bound of its starts, forks and stops. They
  bounded them before they got limits of their own, and such a server has no
  owner_concurrency to set. swebench's close test holds the stop limit,
  which stops take now, instead of the snapshot semaphore.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…ent lends

With sandboxed: true, Simple Agent borrows the sandbox its agent session is
lent, installs a private Python runtime in it with this server's nemo_gym
sources, and runs each activation through sandbox_runner.py under Gym's
process supervisor. The runner builds the same SimpleAgent and calls the same
_create_episode loop as in process, calls only the model server, and returns
the output items unchanged. A seed that lends no sandbox is refused and a
sandboxed agent never runs the loop in its own process. In-process mode stays
the default.

reward_profile and the rollout timeout summary now import numpy, pandas and
scipy where they use them, so an agent server, and the sandbox runtime, no
longer load them on import.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
… after close

- A stop waiting for a stop slot no longer counts that wait against
  STOP_TIMEOUT_S. Every stop ahead holds its slot for at most that long, and
  cutting queued stops short under load (1000 sandboxes, 16 slots) left most
  of them running until their ttl_s. The wait for the key's lock and the
  provider's stop are each bounded by STOP_TIMEOUT_S, without the extra
  nested limits the previous commit removed.
- A create queued for a start slot when aclose() began now raises instead of
  starting a sandbox after the shutdown sweep has begun.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…xes-network

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…boxed loop

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…ry entry for the rule

- critpt's agentic execution server built its SandboxSpec from the whole
  SandboxConfig dump, which now also holds the network rule's fields, so its
  startup failed with an unexpected keyword. It takes only the fields a
  SandboxSpec has, and refuses a typed rule it would not apply.
- ECS reconnects through the owner's tunnel on the same host, so it declares
  same_host, not never; Daytona's connect takes a bare id, so it declares
  never; bwrap, added on main after this branch, declares same_host.
  Lending also refuses a provider with no serialize_handle and connect,
  whatever it declares. A test keeps every built-in provider's reconnect in
  step with its methods, and the design table lists every built-in provider.
- close_by_label is dropped: no provider sets it and nothing reads it.
- The startup check runs before the dry-run return, so a dry run reports a
  rule the provider cannot apply. It imports from the defining modules.
- The glossary gains "Network rule" (naming the network_access fields it
  replaces) and the capabilities entry names network_rules and reconnect.
  The sandbox page says which refusals happen at startup and which at the
  first spec(), and that a rule allows a server's whole host.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…egress at startup

- Declare the verify field once, as BaseVerifyRequest.sandbox_access
  (wire name ng_sandbox_access, excluded from dumps), and drop it from the
  verify reply, so a verifier that echoes its request never stores it.
- Refuse at startup a network rule that blocks the tools an episode grants,
  and build the provider at startup, so a bad block fails startup.
- Stop an attempt sandbox only where this server built a provider, so an
  episode whose Resources Server lent the sandbox builds none in cleanup.
- A sandbox that cannot be lent to the verifier is a retryable
  infrastructure failure.
- Require ttl_s to exceed the episode and cleanup timeouts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…w from server_runtime

- BorrowedSandbox.stop and disconnect dropped the timeout_s keyword that
  AsyncSandbox.stop and disconnect take since #6410. SandboxSession, which
  every sandboxed agent closes through, releases a sandbox it does not own
  with disconnect(timeout_s=...), so a borrowed sandbox raised TypeError at
  close and its client was never released. stop(timeout_s=...) now refuses
  like stop(), and the disconnect override is gone: AsyncSandbox.disconnect
  is shielded and bounded itself, and the override's own 60 s limit could
  not cut the inner shielded one short anyway.
- borrow(), BorrowedSandbox and BorrowedSandboxError move to
  nemo_gym.server_runtime, beside OwnedSandboxes, and its public API serves
  them: a Resources Server grading in a lent sandbox borrows it too, and
  server_runtime cannot import nemo_gym.agents. AgentSandboxConfig joins
  nemo_gym.agents' public API.
- A failed connect's client close no longer replaces the connect's error or
  a cancellation. access() passes on the access the sandbox was lent with
  instead of serializing it again. A command that keeps background services
  runs as the lent user: that provider call reads no sandbox default.
- Docstrings: a borrower installs its runtime as the lent user unless a
  command names another; the repository check is planned, not in place;
  the OpenCode and Pi sandboxed agents turn CPU caps on in code.
- Tests import from the defining modules; the AgentSandboxConfig tests sit
  beside their module in tests/unit_tests/agents/.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Running it before the dry-run return broke servers whose config a test
mocks (test_dry_run_skips_webserver_spinup); the check stays where the PR
put it. critpt's new test stubs the execution sessions instead of building
a Docker provider, so it runs on hosts without Docker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
- Retiring a sandboxed session closes it, so the loop stops and the
  borrowed client is released.
- A model server's HTTP error raised in the sandbox comes back with its
  status, headers and body, as the agent boundary reports one raised in
  process.
- Stage only the settings the loop reads; refuse a direct_http grant the
  sandbox cannot reach and a subclass that changes the agent loop.
- Write the harness archive in a private directory, rewrite it when it is
  gone or changed, and build it off the event loop; create each
  activation's directory; key the runtime only when it is used.
- Drop the rollout-stop hook until stops are enforced in the sandbox, and
  use the base session_close_timeout_seconds and the harnesses'
  sandbox_runner_timeout_seconds name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…attempt-sandbox

Signed-off-by: yaoyu-33 <[email protected]>

# Conflicts:
#	fern/versions/latest/pages/about/concepts/key-terminology.mdx
…mple-agent-sandbox-mode

Signed-off-by: yaoyu-33 <[email protected]>

# Conflicts:
#	responses_api_agents/simple_agent/app.py
@yaoyu-33

yaoyu-33 commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 2fc10e8

@yaoyu-33
yaoyu-33 marked this pull request as ready for review December 2, 2026 17:52
@copy-pr-bot

copy-pr-bot Bot commented Dec 2, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added risk:high Autobot PR risk: high feature New capabilities, enhancements, or enablement work area:sandbox Sandbox providers, isolation, and sandbox runtime contracts needs-review PR is ready for code review and waiting on a reviewer labels Dec 2, 2026
@nemo-pr-automation
nemo-pr-automation Bot requested review from a team December 2, 2026 18:24
@yaoyu-33
yaoyu-33 requested a review from a team as a code owner December 2, 2026 18:34
@yaoyu-33

yaoyu-33 commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test ff7fb6f

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:sandbox Sandbox providers, isolation, and sandbox runtime contracts feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer risk:high Autobot PR risk: high sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants