nemo_gym.sandbox
nemo_gym.sandbox
Public sandbox API for NeMo Gym.
Subpackages
Submodules
nemo_gym.sandbox.accessnemo_gym.sandbox.agent_toolsnemo_gym.sandbox.apinemo_gym.sandbox.attributionnemo_gym.sandbox.confignemo_gym.sandbox.shellnemo_gym.sandbox.utils
Package Contents
Classes
Functions
Data
API
Async sandbox object backed by a runtime provider.
With owns_provider=False, the caller closes the shared provider after
all of its sandboxes have stopped.
Provider name for span attributes (docker, daytona, opensandbox, …).
Rebuild a sandbox in this process from a descriptor produced by
serialize, using provider (which must support connect).
Release this client without stopping a borrowed sandbox.
Use this only for a sandbox rebuilt with connect.
The component that created the sandbox remains responsible for stopping it.
Resolve a declared sandbox service port without exposing provider state.
Run a command, optionally preserving services needed by later commands.
preserve_background_services selects a provider’s service-preserving
execution when available; other providers use ordinary exec. Services
must redirect stdout and stderr. This mode does not accept per-command
env or user overrides on providers with a service-preserving path.
Pause this sandbox while preserving its state.
Open PTY sessions are detached; whether processes survive and sessions
can be re-attached after resume() depends on the provider backend.
Resume this sandbox and wait until it is ready.
On timeout the server-side state is unknown: reconnect and check
status() before retrying.
Return a JSON descriptor another process can rebuild this box from.
Requires a provider that supports the connect capability (the remote
provider, or an external-control-plane provider such as OpenSandbox). For
the remote provider, scope mints a co-lease (scope="operate").
Start the sandbox, then run setup against it.
If setup raises, the sandbox is stopped before the exception
propagates.
Start services from a Compose YAML file and own their sandbox lifecycle.
Deployment settings stay in the provider and optional service_specs.
Compose fields override the corresponding spec fields.
Connect to all members without provisioning or restarting services.
Like AsyncSandbox.connect, stop() closes the connected sandboxes using provider semantics. The creator retains ownership of managed-volume cleanup and running service/forwarding tasks and must also call stop().
Describe a running collection using provider connection descriptors.
The creating process must keep the collection alive: it owns service and forwarding tasks and managed-volume cleanup. Provider configuration and YAML are not included.
Optional capability: rebuild a handle in another process from a descriptor.
Providers whose sandboxes are reachable by id (external control plane, e.g.
OpenSandbox and Fargate, and the sandbox server’s remote provider) implement
this. A provider that does not implement it can only be shared by fronting it
with a sandbox server. Membership is checked with isinstance because the
protocol is runtime_checkable.
Rebuild a live handle in this process from a descriptor.
Return a JSON-serializable descriptor that connect can rebuild a
handle from. scope is honored by providers that mint leases (the
remote provider) and ignored by the rest.
Synchronous wrapper around AsyncSandbox.
pty, serialize and connect are async-only; use AsyncSandbox
for those.
Bases: RuntimeError
Raised when a provider cannot create a sandbox.
Bases: SandboxCreateError
Raised when a newly-created sandbox fails provider readiness checks.
Provider-neutral route to a long-lived service inside a sandbox.
endpoint is an absolute URL. headers carries provider-required
authentication or routing headers without exposing the provider’s opaque
handle to callers.
Provider-neutral process execution result.
return_code is the process exit code when the sandbox actually ran the
command. Providers may use a non-process sentinel with error_type set
when the sandbox runtime reports an execution failure without a process
exit code.
Provider-neutral handle to a created sandbox.
raw is provider-owned opaque state. Public code should pass it back to
the provider through this handle rather than inspecting or mutating it
directly.
Runtime/infra provider contract used by the public sandbox API.
Close provider-scoped resources such as SDK clients.
End the sandbox lifecycle and close provider resources for it.
Create a ready sandbox and return a provider-neutral handle.
Providers must return only after the sandbox is healthy enough to run
commands and transfer files. If the sandbox cannot become ready before
the configured timeout, providers should raise SandboxCreateError
or a provider-specific subclass.
Download one sandbox file to the local filesystem.
Run a command inside a sandbox.
Return the current sandbox lifecycle status.
Upload one local file into a sandbox.
PTY namespace of a sandbox: await sandbox.pty.create(...) for a live
session, await sandbox.pty.exec(...) for one-shot run-and-collect.
exec(detach=True): hand the command to the session’s detached
runner, which holds the socket only for brief completion polls.
Re-attach to a session opened earlier, here or in another process.
Sessions outlive the client that opened them, so session.session_id
is all another process needs. takeover evicts the current holder,
whose session then fails with SandboxPtyError; without it,
attaching to a held session fails. since replays retained output
from that byte offset first (0 replays all of it).
Open an interactive terminal; the returned session carries
read/read_stderr/write/resize/send_signal/
wait_exit/close and is an async context manager.
pty=False selects pipe mode: no TTY, stdout/stderr split across
read()/read_stderr(). rows/cols are applied right after
the terminal connects, because the backend has no spawn-time size, so a
command that reads the size in its first moments can still see the
80x24 default; programs that honor SIGWINCH pick up the real size.
Close the session before the sandbox stops: a session that outlives its
sandbox fails subsequent reads with SandboxPtyError. Async-only;
the sync Sandbox facade does not mirror it.
Run one command in a terminal session and collect its output.
Without session, the sandbox’s default-shell session — the oldest
live one opened by create() with no command — is reused,
provided the call sets none of the session-shaping arguments
(cwd/env/user, non-default rows/cols, or
pty=False), since those are fixed at create(). Custom-command
and attached sessions run arbitrary programs, so they are only used
when passed explicitly. When no default-shell session exists (or
shaping arguments are given) a private session is opened for the
command, drained and closed. Session-mode execs are serialized per
sandbox: concurrent calls into one shared stream would corrupt it.
With session the command runs in that live session, which stays open
and keeps its shell state. In a live session the output also contains
the shell’s echo of the command, stderr is best-effort (pipe mode
only), and a command that ends the shell (exit) raises
SandboxPtyError.
With detach=True the command runs without holding a connection
while it works: it starts in a session, the socket is dropped, and the
session is briefly re-attached every poll_interval_s to drain
output and check for completion, so a long command occupies a
connection for milliseconds per poll instead of its whole runtime
(completion latency is bounded by poll_interval_s). Nothing is
written to the sandbox filesystem; output rides the server’s retained
window (~1 MiB) between polls, comes back as one merged stream
(stderr is None), and exceeding the window raises rather than
returning truncated output — run bulk-output commands attached or via
the exec API instead. A detached exec never reuses the default-shell
session implicitly: without session it opens a private one. With
session, the session is detached while the command works, must
not be used concurrently, and is attached and reusable again when
this returns.
PTY mode returns all output on stdout and None stderr; pipe mode
splits the two. A command that outlives timeout_s returns
error_type="timeout" like sandbox.exec() rather than raising;
in an explicitly passed session that command keeps running and leaves
unread output behind, so discard the session rather than reusing it (an
implicitly reused session is retired automatically).
Bases: RuntimeError
Raised when a PTY session fails outside normal process exit.
One live interactive terminal. Async context manager; exit closes it.
Whether close() has run; a closed session cannot run commands.
"pty" or "pipe" once connected, None before that. Only pipe
mode splits stderr; in PTY mode all output arrives through read().
Yield output chunks until EOF.
Idempotent: release local resources; a session this client created is also ended, while an attached one is merely detached and lives on for its owner.
Return the next output chunk (all terminal output in PTY mode;
stdout only in pipe mode). b"" means the process exited and the
stream is drained. Raises TimeoutError on timeout and
SandboxPtyError if the session died without exiting.
Return the next stderr chunk. Only pipe mode (pty=False)
carries stderr separately; in PTY mode this stream is empty and
returns b"" once the process exits. Same timeout/error semantics
as read().
Resize the terminal.
Run one command holding the transport only for brief completion
polls; returns (merged output, exit code or None). The server
retains a bounded window of output between polls, and exceeding it
raises rather than returning truncated output.
Deliver a named signal, e.g. "SIGTERM", to the session’s process
group. Interactive shells run foreground jobs in their own group, so
signals reliably reach the process only for command sessions; whether
SIGINT interrupts at all also depends on the sandbox runtime’s
inherited signal dispositions.
Block until the process exits and return its exit code.
Send raw bytes to the terminal’s stdin.
Interactive PTY session request.
command runs under the backend’s interactive shell; None spawns the
shell itself. Backends without native env/user support may rewrite the
command (mirroring exec()’s user rewrite) and must raise ValueError
for values they cannot honor. pty=False selects pipe mode: no TTY,
stdout and stderr delivered as separate streams, rows/cols ignored.
Backends that cannot size a terminal at spawn apply rows/cols as
soon as it connects, so a command reading the size immediately may
observe the backend default.
Provider-neutral resource request.
Sandbox creation request.
Bases: enum.Enum
Provider-neutral sandbox lifecycle status.
Optional provider capability for resolving declared service ports.
Resolve a declared service port to a caller-reachable endpoint.
Optional direct networking between sandboxes, preserving service ports.
Optional provider capability to pause and resume a sandbox.
What survives a pause beyond the filesystem is backend-specific.
Pause a sandbox while preserving its state.
Resume a paused sandbox and refresh its handle.
Optional loopback TCP forwarding, running until cancellation.
Optional provider capability: interactive PTY sessions.
Open an interactive terminal inside a sandbox.
Optional provider capability: re-attach to a PTY session by id.
Separate from SupportsSandboxPty because it requires sessions that live
in the sandbox rather than in the client, so a provider may offer terminals
without offering re-attach.
Re-attach to an existing session by id.
takeover evicts the current holder, whose session then fails with
SandboxPtyError; without it, attaching to a held session fails.
since is a byte offset into the session’s retained output to replay
before live output (0 replays everything still retained).
Optional validation and setup of task-declared runtime requirements.
Validate support and return any required create-time metadata.
Optional shared filesystem provisioned by the operator’s provider config.
shared_volume_options returns provider options containing a volumes
list of opaque mount descriptors. Collections concatenate these lists.
source is relative to the configured shared root; None mounts that
root for initialization and cleanup. Metadata supplies placement settings.
Instantiate a provider from a single-key provider config.
Return a provider class by name (explicit > built-in > entry point).
List available provider names from all sources.
Register a sandbox provider class.
Resolve a sandbox_provider field into a single-key provider config dict.
Parameters:
Either the name of a top-level sandbox config block
(resolved from named_configs) or an inline single-key provider
mapping of the form {provider_name: {...}}.
Mapping of top-level config name to config block, typically
the merged global config dict. Required when sandbox_provider is a
name reference.
Returns: dict[str, Any]
A plain {provider_name: provider_kwargs} dict suitable for
Raises:
TypeError: Ifsandbox_provideris neither a string nor a mapping.ValueError: If a named reference cannot be found, or if the block does not hold exactly one provider key.
Return a sandbox block’s default_metadata.
These are provider-contributed defaults to merge into SandboxSpec.metadata.
Returns an empty dict when the block has no default_metadata key. See
resolve_provider_config for argument semantics.
Apply ordered image-prefix rewrites used by sandbox configs.