E2B Provider
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:
For a package install, use:
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:
Pass the provider config beside the agent and model configs:
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:
SandboxSpec.provider_options.templatecreate.template_map[SandboxSpec.image]SandboxSpec.image, when it is an untagged name matching[A-Za-z0-9_-]+- The
create.templatefallback, only whenSandboxSpec.imageis 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:
The generated YAML contains an image-to-template mapping ready to place under create:
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
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:
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:
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:
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:
The SDK reads E2B_API_KEY, E2B_API_URL, and E2B_SANDBOX_URL from the environment, as
the provider does.
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:
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)).
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:
--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.