Skip to navigation

The e2b provider creates isolated cloud sandboxes through the E2B Python SDK. It supports the hosted E2B service and E2B-compatible gateways with custom API and sandbox URLs.

Setup

Install the sandbox extra in the environment that creates sandboxes:

uv sync --extra sandbox

For a package install, use:

pip install "nemo-gym[sandbox]"

The provider requires e2b>=2.36.0,<3.0.0.

Get service access

For hosted E2B, follow the API-key quickstart and get a key from the E2B console. For shared accounts, confirm membership and template access with the administrator. Check sandbox creation/cleanup permissions, template-build permissions if needed, and plan limits for concurrency, lifetime, and cost.

Set E2B_API_KEY in the host environment through your secret manager; it is separate from model and registry credentials. Leave E2B_API_URL and E2B_SANDBOX_URL unset for hosted E2B unless instructed otherwise.

For an E2B-compatible gateway, obtain credentials, API/sandbox URLs, network requirements, template permissions, and quota from its operator. Gateway access uses the operator’s authentication settings. Set E2B_API_URL and E2B_SANDBOX_URL to the supplied endpoints; the operator may also require connection.api_headers. Keep secret values out of checked-in YAML. Gateway-specific create parameters go in create.custom_extension_params and are sent as the API’s customExtensionParams. The E2B SDK cannot send that field, so setting it makes the provider create each sandbox with one POST {api_url}/sandboxes and then attach with connect. That request sends the same timeout lifecycle (create.auto_resume) as the SDK create.

Provider Config

NeMo Gym ships an E2B config at nemo_gym/sandbox/providers/e2b/configs/e2b.yaml. It defines a top-level sandbox block that agents reference with sandbox_provider: sandbox:

sandbox:
default_metadata:
sandbox-api: e2b
e2b:
connection:
api_key: ${oc.env:E2B_API_KEY,null}
api_url: ${oc.env:E2B_API_URL,null}
sandbox_url: ${oc.env:E2B_SANDBOX_URL,null}
request_timeout_s: 120.0
create:
template: null
template_map: {}
timeout_s: 3600.0
auto_resume: false
renew_ttl_s: null
reachable_timeout_s: null
restore_login_env: false
secure: true
allow_internet_access: true
network: null
custom_extension_params: null
strict_resources: false
exec:
default_timeout_s: 180.0
user: null
request_timeout_s: null
background: true
reconnect_attempts: 2
snapshots:
send_names: false
list_by_name: false
keep_guest_clock: false
operations:
retries: 2
retry_delay_s: 0.5
retry_max_delay_s: 8.0
new_sandbox_grace_s: 15.0
snapshot_list_timeout_s: 300.0
attribution:
enabled: true
key_prefix: nemo-gym.nvidia.com/

Pass the provider config beside the agent and model configs:

gym env start \
--config responses_api_agents/mini_swe_agent_2/configs/mini_swe_agent_2.yaml \
--config nemo_gym/sandbox/providers/e2b/configs/e2b.yaml \
--config responses_api_models/vllm_model/configs/vllm_model.yaml

Prepare Templates

E2B starts a sandbox from a template name or ID rather than an OCI image reference. Because tagged template names and OCI references can both contain :, the provider resolves a template conservatively:

  1. SandboxSpec.provider_options.template
  2. create.template_map[SandboxSpec.image]
  3. SandboxSpec.image, when it is an untagged name matching [A-Za-z0-9_-]+
  4. The create.template fallback, only when SandboxSpec.image is omitted

Use provider_options.template for a tagged template name or template ID. A non-empty, unmapped image raises instead of silently selecting an unrelated fallback template.

Build templates from OCI images as a separate provisioning step:

python -m nemo_gym.sandbox.providers.e2b.build \
--image ghcr.io/acme/task:1.0 \
--cpu-count 8 \
--memory-mb 16384 \
--output template_map.yaml

The generated YAML contains an image-to-template mapping ready to place under create:

template_map:
"ghcr.io/acme/task:1.0": task-1-0__f00ee9d593d9

Template building can create E2B resources and is never performed implicitly by sandbox creation. Generated names are deterministic for the image, CPU count, and memory size, so a matching existing template can be reused. The helper’s local timeout stops waiting but cannot cancel a remote build that E2B has already accepted; check E2B before retrying after a timeout. By default a batch failure prevents queued siblings from starting and waits for already-started builds to finish; pass --continue-on-error to keep building the remaining images.

Relevant SandboxSpec Fields

FieldE2B behavior
imageUntagged names matching [A-Za-z0-9_-]+ are direct; tagged names, IDs, and OCI references require provider_options.template or create.template_map.
ttl_sSandbox lifetime; overrides create.timeout_s and must be positive.
ready_timeout_sPositive per-sandbox override for the E2B create request timeout. Omitted values use the connection timeout.
workdirUsed by the NeMo Gym facade as the default command working directory.
envPassed to E2B when the sandbox is created.
filesUploaded after creation and before start() returns.
metadataPassed to E2B as string metadata, merged over the job attribution keys.
resourcesFixed by the template rather than applied per sandbox. Requests warn, or raise when create.strict_resources is true.
entrypointUnsupported and rejected before allocation; define it in the E2B template.
provider_optionsSupports template and resource_requests (a mapping or "limits"). Scheduling resource_requests (for example from OpenSandbox-oriented agent configs) are treated like resources: they warn, or raise when create.strict_resources is true. Other keys and invalid values are rejected before allocation.

The bundled builder controls template CPU count and memory. Disk and GPU requirements need a suitable template prepared through E2B tooling.

Image Environment in Login Shells

The E2B SDK starts every command as bash -l -c and every terminal as bash -i -l. A sandbox process does start with its image’s environment (the image’s ENV and working directory), but a login shell reads /etc/profile first, and on Debian-based images that file resets PATH. Tools the image installed outside the default PATH, such as /usr/local/go/bin, /usr/local/cargo/bin or /opt/conda/bin, are then not found by name, both in a grader’s test command and in an agent’s tool calls.

With create.restore_login_env: true (the default), the provider writes /etc/profile.d/zz-nemo-gym-env.sh into each new sandbox, including one created from a snapshot. Every login shell sources it last, and it gives the shell back the environment it started with: its variables as they were, and PATH with its starting entries first, followed by any the profile added. Shells other than bash return from it at once. If the hook cannot be written, the sandbox is killed and the create fails. Set restore_login_env: false to leave login shells as the template has them.

Timeouts and Reconnection

SandboxSpec.ttl_s controls the remote sandbox lifetime. With the default create.auto_resume: false, the sandbox is deleted when it elapses: treat it as a cleanup backstop and still call stop() or use a context manager so the sandbox is killed as soon as work finishes. With auto_resume: true it pauses instead; see AgentENV auto-pause and auto-resume.

SandboxSpec.ready_timeout_s overrides the E2B create request timeout. The SDK retains an explicit create timeout on the returned sandbox connection; the shipped connection.request_timeout_s is reapplied to later calls, while a programmatic config that leaves it unset inherits ready_timeout_s for that sandbox object.

With E2B 2.36+, the connection or exec request_timeout_s only bounds opening command and reconnect streams. Command timeout_s is NeMo Gym’s total wait/stream budget across the initial connection and any reconnects. The public facades normally supply 180 seconds, so pass a larger value explicitly for long builds or test suites. A command that runs out its timeout returns exit code 124, and the processes it left running are killed by an environment marker, on a best-effort basis; close the sandbox before reuse when a lingering process would be unsafe.

Background execution lets the provider reconnect to a running process by PID after an output stream interruption. Output emitted before reconnection is not replayed. If the process exits during the gap, its result cannot be recovered. Reconnects consume the original wait budget rather than starting a new one.

Create is not automatically retried because an ambiguous failure could allocate two billable sandboxes. Rate-limit responses are returned without automatic retries so callers can choose their backoff window. Close retries transient kill failures, deletes paused sandboxes, treats a sandbox that is already gone as closed, and clears the local handle only after confirmed cleanup. Serialized handles carry the E2B sandbox ID for reconnection through another configured provider instance. E2B’s public connect operation may extend a near-expiry sandbox to its SDK-default connection lifetime (300 seconds in E2B 2.36).

status() reads the sandbox record from E2B’s control plane (GET /sandboxes/{id}): RUNNING means the service reports the sandbox as running, not that the guest passed a health check. An E2B-compatible gateway must serve that endpoint, or status cannot report the real state.

Pause and Resume

The E2B provider supports the public async and sync sandbox lifecycle methods:

from nemo_gym.sandbox import SandboxStatus
await sandbox.pause()
assert await sandbox.status() == SandboxStatus.PAUSED
await sandbox.resume()
result = await sandbox.exec("cat /tmp/checkpoint.txt")

For the synchronous Sandbox, call the same methods without await. Pause uses E2B’s default memory-preserving snapshot. Resume connects to the same sandbox ID and refreshes the SDK handle so subsequent commands and file operations use the resumed connection. Resume restarts the sandbox lifetime at create.timeout_s, the provider default; a per-sandbox SandboxSpec.ttl_s is not reapplied. Pause raises on a 409 Conflict. E2B cloud sends one for an already-paused sandbox or one in a transitional state, and AgentENV during a snapshot or fork, which status reports as paused although the sandbox then runs again.

Status reads the control plane without waking the guest. The provider does not retry failed pause/resume calls; a timeout or transport failure can leave the remote state unknown. Check status before retrying. Closing a paused sandbox still deletes it. This capability requires a service that implements E2B’s public pause/connect endpoints.

A paused sandbox does not count down its timeout, so pausing turns off the ttl_s cleanup backstop: if the process exits between pause() and close(), nothing deletes the sandbox (AgentENV never evicts paused sandboxes). Close paused sandboxes in a finally block.

Security and Isolation

E2B supplies the sandbox isolation boundary; when using a compatible gateway, its operator is responsible for the deployment’s security posture. The shipped config uses secure: true, so the sandbox envd service requires an access token.

Outbound internet access is enabled by default for workloads that install dependencies. Set create.allow_internet_access: false for offline or untrusted workloads. To allow only some destinations, set create.network with allow_out/deny_out lists of CIDRs, IPs or hostnames. For example, this permits only the listed package registries:

create:
network:
deny_out: ["0.0.0.0/0"]
allow_out: [pypi.org, files.pythonhosted.org, deb.debian.org, security.debian.org]

Values in SandboxSpec.env are injected into the remote sandbox, so pass only secrets required by the workload and keep E2B credentials in the provider connection config or host environment.

mini_swe_agent_2 removes e2b.connection.api_key, headers, and api_headers from generated per-instance worker YAML. It passes them through the worker environment, then reconstructs the header mappings only in worker memory. The API key stays out of the serializable provider config and is read directly from E2B_API_KEY by the E2B SDK.

Job Attribution

The provider merges nemo-gym.nvidia.com/team, nemo-gym.nvidia.com/user, nemo-gym.nvidia.com/workload, and nemo-gym.nvidia.com/run keys into each sandbox’s metadata when they can be resolved. E2B and AgentENV return sandbox metadata from their list API and filter on it with GET /v2/sandboxes?metadata=k=v (AgentENV’s gateway applies the filter across its clusters), so running sandboxes are attributable to the team, user, and workload that created them:

curl -sG "${E2B_API_URL:-https://api.e2b.app}/v2/sandboxes" \
-H "X-API-KEY: $E2B_API_KEY" \
--data-urlencode "metadata=nemo-gym.nvidia.com/team=my-team"

A gateway may need its own authentication headers instead (see connection.api_headers).

Each field resolves in order: the provider’s attribution config, then NEMO_GYM_TEAM / NEMO_GYM_USER / NEMO_GYM_WORKLOAD environment variables, then Slurm job environment variables (SLURM_JOB_ACCOUNT / SLURM_JOB_USER / SLURM_JOB_NAME). user additionally falls back to the OS login name (root is ignored — containers run as root by default, so it would attribute the image, not a person), and workload to NEMO_GYM_CONFIG_PATH, the server instance name the gym CLI sets on every server process it spawns. Fields that cannot be resolved are omitted. Explicit sandbox_spec.metadata and default_metadata keys always take precedence over attribution keys.

run identifies one launch of the creating process: NEMO_GYM_RUN_ID if set, else an id generated per process. The resolved attribution is logged once at the first sandbox create — note the run value from the logs to list or clean up exactly that run’s sandboxes (for example after killing a run partway through), which team / user / workload cannot do when the same user launches the same workload twice:

from e2b import AsyncSandbox, SandboxQuery
paginator = AsyncSandbox.list(query=SandboxQuery(metadata={"nemo-gym.nvidia.com/run": "<run-id>"}))
while paginator.has_next:
for info in await paginator.next_items():
await AsyncSandbox.kill(info.sandbox_id)

The SDK reads E2B_API_KEY, E2B_API_URL, and E2B_SANDBOX_URL from the environment, as the provider does.

sandbox:
e2b:
attribution:
enabled: true # set false to disable automatic attribution
key_prefix: nemo-gym.nvidia.com/ # key namespace; "" for bare team/user/workload/run keys
# team: my-team # override auto-detection
# user: my-user
# workload: my-benchmark
# run: my-run-id

When the gym servers themselves run in Kubernetes, none of the automatic sources resolve: there are no Slurm variables, and the container’s OS login is typically root, which is ignored. Set the NEMO_GYM_* variables on the pod spec, as described in Attribution in Kubernetes deployments.

Integration Attribution

NeMo Gym appends nemo-gym/<version> to the E2B SDK User-Agent for both runtime sandbox requests and template provisioning. This lets E2B distinguish NeMo Gym traffic; it is separate from the job attribution metadata on each sandbox. An explicit custom User-Agent in connection headers takes precedence in the E2B SDK and can hide this attribution.

Sandbox and template operations use the E2B SDK’s public high-level APIs; attribution uses E2B’s set-once integration hook. Because E2B 2.x does not expose transport injection on those APIs, NeMo Gym replaces its module-level HTTP transport factories with an aiohttp adapter backed by Gym’s shared client session. The adapter accepts HTTP and HTTPS proxies; SOCKS proxies are rejected explicitly. E2B’s ConnectRPC command streams keep their SDK-owned pyqwest transport.

AgentENV auto-pause and auto-resume

e2b.create.auto_resume selects what happens when a sandbox reaches its timeout:

ValueTimeout action
false (default)Delete the sandbox.
truePause the VM, keeping its files and processes; the next sandbox request resumes it (AgentENV).
nullSend no lifecycle and leave the action to the SDK and server.

Avoid null on AgentENV. E2B 2.36–2.41 send kill-on-timeout when no lifecycle is given, but 2.42 and later (including the locked 2.46) omit the fields. AgentENV then pauses the sandbox without auto-resume and never evicts it, so a crashed or cancelled run leaks paused VMs. The lifecycle settings require a deployment that supports the E2B lifecycle API.

create.timeout_s controls the initial timeout, and SandboxSpec.ttl_s overrides it per sandbox. It is a lifetime deadline, not an idle-traffic timer: choose a value appropriate for long-running commands. With auto_resume: true, note these AgentENV behaviors (see the proxy contract):

  • After an automatic resume, the sandbox gets at least the operator’s minimum timeout (default 300 seconds), counted from the resume. A shorter initial timeout does not change it.
  • Requests that arrive while the VM is pausing or resuming fail immediately with HTTP 410, so a call at the timeout boundary can fail even with auto-resume enabled.
  • Attaching to a sandbox wakes it: connect() sends the SDK’s 300-second default timeout, which replaces the stored timeout, so later automatic resumes also get only 300 seconds.

Status checks use the control plane and report paused without waking the VM. Explicit close still deletes the sandbox, including paused sandboxes. Auto-pause preserves storage; it does not replace cleanup after a completed or crashed run.

Snapshots and AgentENV checkpoints

Sandbox checkpointing snapshots the sandboxes a server owns and restores them after a crash. On E2B and AgentENV a snapshot saves the whole VM — memory, running processes and disk — and is usable when create_snapshot returns; the source sandbox keeps running. A sandbox created from it continues the processes it was running, so the provider declares capabilities.snapshot_keeps as {"files", "processes"} (read it with provider_capabilities(provider)).

SettingEffect
snapshots.send_names: false (default)Snapshots are unnamed: E2B files a named snapshot as a team-wide template alias. This departs from the snapshot contract. agentenv.yaml turns it on: a snapshot whose request fails or is cancelled is then deleted by its name, so one the service took without Gym learning its id does not stay. A request the service refused (HTTP 4xx), such as one for a name already taken, is left alone.
snapshots.list_by_name: false (default)Listing snapshots by a name prefix finds nothing and does not ask the service, which departs from the snapshot contract. The listing reads every snapshot the key can see and a checkpoint release waits for it, so it stays off where the service’s listing may not answer, as in agentenv.yaml. A release still deletes every snapshot the checkpointer indexed, by id. With it on, a listing not complete within operations.snapshot_list_timeout_s fails.
snapshots.keep_guest_clock: trueAgentENV only. A sandbox created from a snapshot keeps the wall clock the snapshot was taken at (customExtensionParams: {keepGuestClock: true}, sent with create.custom_extension_params), so a harness that continues in it sees no jump in time. The clock then lags real time by the time the snapshot sat unused: after a long gap, TLS checks and requests signed with the time (S3 allows 15 minutes) can fail in the sandbox. Creates from a template never send it.
create.renew_ttl_sThe sandbox lease, under the key OpenSandbox uses: create with this timeout and renew it every third of a lease, so the sandboxes of a process that died end one lease later. Needs create.timeout_s.
create.restore_login_env: trueWrite a login-shell hook into each new sandbox so commands keep the PATH their image declares (a Debian image’s /etc/profile resets it). Off by default, on in agentenv.yaml.
create.reachable_timeout_sAfter a create, run a no-op command until the gateway reaches the new sandbox (it can answer 502 “could not be reached” or 404 at first), for up to this many seconds; a sandbox still unreachable is killed and the create fails. Unset hands the sandbox over at once.
create.auto_resume: falseKill at timeout. Required on AgentENV, which otherwise keeps timed-out sandboxes paused.

nemo_gym/sandbox/providers/e2b/configs/agentenv.yaml is a ready config for an AgentENV cell. It holds only what AgentENV changes and pulls in e2b.yaml for the rest, so pass it alone: set E2B_API_KEY, E2B_API_URL and E2B_SANDBOX_URL. If the cell serves a certificate the system does not trust, set SSL_CERT_FILE and REQUESTS_CA_BUNDLE to a bundle of the system CAs plus the cell’s certificate rather than turning verification off.

provider_options.resource_requests, which OpenSandbox task configs often set, is reported once and not applied: E2B fixes resources when a template is built. provider_options.network_policy in OpenSandbox’s shape maps onto E2B’s network option.

After a run, list the sandboxes it left behind by its run label, and add --apply to delete them:

python scripts/agentenv_cleanup.py --metadata nemo-gym.nvidia.com/run=$NEMO_GYM_RUN_ID

--snapshot-ids <file> and --snapshot-prefix ng-<state dir id>- select snapshots the same way. A prefix is found by listing every snapshot the key can see; when the cell’s listing does not answer, --snapshot-ids is what still works.