# Chalk Compute Reference: Sandbox
source: https://docs.chalk.ai/compute-docs#section-sandbox

Low-level sandbox management backed by the Chalk SandboxService (gRPC).

Provides bidirectional streaming exec, interactive stdin/signal control, and fine-grained process lifecycle management.

## `SandboxClient`
source: https://docs.chalk.ai/compute-docs#SandboxClient

Class

Client for the Sandbox service.

### `SandboxClient.__init__(target, credentials, use_tls, metadata, _connect)`
source: https://docs.chalk.ai/compute-docs#SandboxClient.__init__

Initialize the RPC client.

**Parameters**

- `target`: `str` = `'localhost:50051'`
  RPC server address (e.g. `"localhost:50051"` or `"https://sandbox.example.com"`).
- `credentials`: `object | None` = `None`
  Backward-compatible TLS signal. The object is not inspected; prefer `use_tls` for new code.
- `use_tls`: `bool | None` = `None`
  Whether to use HTTPS for the ConnectRPC transport. When omitted, this remains compatible with the old behavior: passing any `credentials` object enables TLS.
- `metadata`: `_GrpcMetadata | None` = `None`
  Optional default metadata to send with every RPC call.
- `_connect`: `ConnectClient | None` = `None`

### `SandboxClient.from_env(chalk_client)`
source: https://docs.chalk.ai/compute-docs#SandboxClient.from_env

Create a [`SandboxClient`](https://docs.chalk.ai/compute-docs#SandboxClient) from ambient Chalk credentials.

### `SandboxClient.close()`
source: https://docs.chalk.ai/compute-docs#SandboxClient.close

Close the underlying HTTP clients.

### `SandboxClient.create(image, name, cpu, memory, gpu, env, secrets, volumes, port, entrypoint, lifetime, security_policy, network_policy, compute_class, runtime, execution_target, resource_detectors, host_pool_id, tags, restart_policy, chalk_identity, group_limits, managed_ssh, tracing, trace_syscalls, wait, poll_interval, timeout)`
source: https://docs.chalk.ai/compute-docs#SandboxClient.create

Construct and run a sandbox in one call.

If `image` is an [`Image`](https://docs.chalk.ai/compute-docs#Image) spec, this method builds it first and sends the resulting image URI to the sandbox service. If `wait` is [`True`](https://docs.python.org/3/library/constants.html#True) (the default), this method polls `GetSandbox` until the sandbox reaches "ready" (or "error").

**Parameters**

- `image`: `str | Image | None` = `None`
  Container image to use — either a string reference (e.g. `"ubuntu:latest"`) or a declarative [`Image`](https://docs.chalk.ai/compute-docs#Image) builder. If omitted, uses `sandbox`.
- `name`: `str | None` = `None`
  Optional name for the sandbox.
- `cpu`: `str | None` = `None`
  Optional CPU limit (e.g. `"1"`, `"500m"`).
- `memory`: `str | None` = `None`
  Optional memory limit (e.g. `"512Mi"`, `"1Gi"`).
- `gpu`: `str | None` = `None`
- `env`: `Mapping[str, str | Secret] | None` = `None`
  Environment variables as strings or single-value Secret references. The mapping key sets the injected name.
- `secrets`: `_SecretList | None` = `None`
- `volumes`: `_VolumeList | None` = `None`
  Optional [`Volume`](https://docs.chalk.ai/compute-docs#Volume) handles, [`VolumeMount`](https://docs.chalk.ai/compute-docs#VolumeMount) specifications, or `(name_or_volume, mount_path)` pairs to mount into the sandbox. Volume handles preserve their selected ref or pinned version.
- `port`: `int | None` = `None`
- `entrypoint`: `_StrList | None` = `None`
  Optional command to run as the sandbox container's main process.
- `lifetime`: `str | None` = `None`
- `security_policy`: `ContainerSecurityPolicy | None` = `None`
- `network_policy`: `NetworkPolicy | None` = `None`
  Optional network egress policy. Reuses the same [`NetworkPolicy`](https://docs.chalk.ai/compute-docs#NetworkPolicy) type accepted by containers.
- `compute_class`: `ComputeClass | None` = `None`
- `runtime`: `Runtime | None` = `None`
- `execution_target`: `ExecutionBackend | None` = `None`
- `resource_detectors`: `Sequence[ResourceDetector] | None` = `None`
  Optional [`ResourceDetector`](https://docs.chalk.ai/compute-docs#ResourceDetector) values. Each detector inspects egress traffic to the hosts it recognizes and records resources the sandbox creates, such as GitHub pull requests, against the sandbox. The hosts a detector recognizes (for example `api.github.com`) are implicitly added to the sandbox's network policy.
- `host_pool_id`: `str | None` = `None`
  Optional host pool ID to restrict placement of host compute class sandboxes. Unstable; subject to change.
- `tags`: `dict[str, str] | None` = `None`
- `restart_policy`: `RestartPolicy | None` = `None`
  Optional restart behavior. Use `RestartPolicy.NEVER` or `RestartPolicy.ALWAYS`.
- `chalk_identity`: `bool | ChalkIdentity | None` = `None`
  Whether to give the sandbox a platform-managed Chalk identity. The identity is exposed inside the sandbox through the standard `CHALK_WEB_IDENTITY_TOKEN_FILE` environment variable. When omitted, enables creator identity unless `CHALK_REMOTE_FUNCTION` is set to a nonempty value. Set [`True`](https://docs.python.org/3/library/constants.html#True) to explicitly enable creator identity or [`False`](https://docs.python.org/3/library/constants.html#False) to disable managed Chalk identity. Pass `ChalkIdentity(mode="sandbox")` for credentials that identify the sandbox itself, which [`OIDCTokenFile`](https://docs.chalk.ai/compute-docs#OIDCTokenFile) requires.
- `group_limits`: `SandboxGroupLimits | None` = `None`
  Root sandbox group limits. Requires `ChalkIdentity(mode="sandbox")`.
- `managed_ssh`: `Mapping[str, SSHDest] | Sequence[SSHDest] | None` = `None`
  Optional SSH destinations, as a list of [`SSHDest`](https://docs.chalk.ai/compute-docs#SSHDest) or a mapping of aliases to them. See [`Sandbox`](https://docs.chalk.ai/compute-docs#Sandbox).
- `tracing`: `TracingPolicyConfig | None` = `None`
  [`True`](https://docs.python.org/3/library/constants.html#True) traces every request inside the sandbox, a `TracingPolicy` sets the root sample rate, [`False`](https://docs.python.org/3/library/constants.html#False) turns tracing off. See [`Sandbox`](https://docs.chalk.ai/compute-docs#Sandbox).
- `trace_syscalls`: `Sequence[str]` = `()`
  Exact names of Linux syscalls to trace. An empty sequence disables syscall tracing.
- `wait`: `bool` = `True`
  If [`True`](https://docs.python.org/3/library/constants.html#True), poll until the sandbox is ready (default [`True`](https://docs.python.org/3/library/constants.html#True)).
- `poll_interval`: `float | None` = `None`
  Initial delay between readiness polls. When omitted, polling starts at 25ms and backs off by 50% to 250ms.
- `timeout`: `float` = `600.0`
  Maximum seconds to wait for the sandbox to become ready (default 600).

**Returns**

`Sandbox`

A sandbox handle.

### `SandboxClient.run(sandbox, wait, poll_interval, timeout)`
source: https://docs.chalk.ai/compute-docs#SandboxClient.run

Create a configured sandbox using this client.

**Parameters**

- `sandbox`: `Sandbox`
  A configured sandbox that has not been run.
- `wait`: `bool` = `True`
  If [`True`](https://docs.python.org/3/library/constants.html#True), poll until the sandbox is ready (default [`True`](https://docs.python.org/3/library/constants.html#True)).
- `poll_interval`: `float | None` = `None`
  Initial delay between readiness polls. When omitted, polling starts at 25ms and backs off by 50% to 250ms.
- `timeout`: `float` = `600.0`
  Maximum seconds to wait for the sandbox to become ready.

**Returns**

`Sandbox`

The created sandbox.

### `SandboxClient.get(id)`
source: https://docs.chalk.ai/compute-docs#SandboxClient.get

Get a sandbox handle by ID.

Does not validate the sandbox exists until you call a method on it.

**Parameters**

- `id`: `str`
  Sandbox identifier.

**Returns**

`Sandbox`

A sandbox handle.

### `SandboxClient.list(limit)`
source: https://docs.chalk.ai/compute-docs#SandboxClient.list

List sandboxes, fetching pages until exhausted or `limit` is reached.

**Parameters**

- `limit`: `int | None` = `None`
  Maximum number of results. [`None`](https://docs.python.org/3/library/constants.html#None) fetches all pages; zero returns an empty list without making a request. Must be nonnegative.

**Returns**

`_SandboxInfoList`

One entry per sandbox.

**Raises**

- `SandboxError`: The service repeats a pagination cursor before reaching the limit.

### `SandboxClient.get_snapshot(snapshot_id, timeout)`
source: https://docs.chalk.ai/compute-docs#SandboxClient.get_snapshot

Get a snapshot handle by ID through a bounded status request.

### `SandboxClient.list_snapshots(sandbox_id)`
source: https://docs.chalk.ai/compute-docs#SandboxClient.list_snapshots

List every snapshot captured from `sandbox_id`.

### `SandboxClient.delete_snapshot(snapshot_id)`
source: https://docs.chalk.ai/compute-docs#SandboxClient.delete_snapshot

Delete a saved snapshot by ID.

## `Sandbox`
source: https://docs.chalk.ai/compute-docs#Sandbox

Class

A managed sandbox backed by the Chalk `SandboxService`.

`create` constructs and immediately runs a sandbox. To configure a [`Sandbox`](https://docs.chalk.ai/compute-docs#Sandbox) before running it, construct one and pass it to `run`. Use `exec` to run commands and `terminate` to shut the sandbox down when you're done.

**Examples**

```python
from chalkcompute import Image, SandboxClient
with SandboxClient.from_env() as client:
    sandbox = client.create(
        Image.debian_slim().pip_install(["numpy"]),
    )
    result = sandbox.exec(
        "python",
        "-c",
        "import numpy; print(numpy.__version__)",
    )
    sandbox.terminate()
result.stdout_text.strip()
```

```python
'2.5.1'
```

**Attributes**

- `id`: `str | None`
  Opaque sandbox identifier assigned by the service.

  [`None`](https://docs.python.org/3/library/constants.html#None) until `run` has created the sandbox.
- `info`: `SandboxInfo | None`
  The most recently fetched [`SandboxInfo`](https://docs.chalk.ai/compute-docs#SandboxInfo) snapshot.

  [`None`](https://docs.python.org/3/library/constants.html#None) until the sandbox has been started or attached to. If `run` created the sandbox but failed before a snapshot was fetched (for example, a readiness check that errored), this fetches one now and raises if that fetch itself fails.

  After `terminate`, the next access fetches the stopped sandbox's metadata from the server. Subsequent accesses use that cached snapshot; call `refresh` to fetch it again.
- `image_uri`: `str | None`
  The fully qualified registry URI of the image the sandbox uses.

  Set after `run` finishes the image build (or, if the sandbox was constructed with a string image reference, equal to that reference). [`None`](https://docs.python.org/3/library/constants.html#None) before the sandbox has been started.
- `git`: `SandboxGit`
  Access Git operations inside this running sandbox.

  **Returns**

  SandboxGit Helpers for cloning, staging, committing, branches, remotes, and repository-local configuration. Paths refer to the sandbox filesystem, relative to the image working directory or absolute. Custom images must include Git; the default sandbox image already includes it.

  **Examples**

  ```python
  sandbox.git.clone("https://github.com/octocat/Hello-World.git", "repo")
  status = sandbox.git.status("repo")
  ```
- `fs`: `SandboxFileSystem`
  Transfer files to and from this running sandbox.

### `Sandbox.__chalk_pyarrow_type__()`
source: https://docs.chalk.ai/compute-docs#Sandbox.__chalk_pyarrow_type__

### `Sandbox.__chalk_serialize__()`
source: https://docs.chalk.ai/compute-docs#Sandbox.__chalk_serialize__

Transport the existing sandbox ID, never its credentials or spec.

### `Sandbox.__chalk_deserialize__(value)`
source: https://docs.chalk.ai/compute-docs#Sandbox.__chalk_deserialize__

Restore a handle without I/O; operations use the receiver's identity.

### `Sandbox.__init__(image, name, cpu, memory, gpu, env, secrets, volumes, port, entrypoint, lifetime, security_policy, network_policy, compute_class, runtime, execution_target, resource_detectors, host_pool_id, tags, restart_policy, chalk_identity, group_limits, managed_ssh, tracing, trace_syscalls, chalk_client, sandbox_client, client, sandbox_id)`
source: https://docs.chalk.ai/compute-docs#Sandbox.__init__

Configure a sandbox to be created by `run`.sandbox_id Existing sandbox ID. With no client, authentication is resolved lazily from the receiver's environment on the first operation. This form never creates a sandbox and cannot be mixed with image configuration.

**Notes**

Calling `run` without a client creates one from the environment. Prefer using an explicit [`SandboxClient`](https://docs.chalk.ai/compute-docs#SandboxClient). Its `create` method is a shortcut for constructing and immediately running a sandbox. For other setup, construct a [`Sandbox`](https://docs.chalk.ai/compute-docs#Sandbox) and pass it to `run`.

**Parameters**

- `image`: `str | Image | None` = `None`
  Container image to use, either a string reference such as `"ubuntu:latest"` or a declarative [`Image`](https://docs.chalk.ai/compute-docs#Image). If omitted, uses `sandbox` (Python, Git, SSH, and /workspace).
- `name`: `str | None` = `None`
  Optional DNS-safe sandbox name.
- `cpu`: `str | None` = `None`
  Optional CPU limit, for example `"2"` or `"500m"`.
- `memory`: `str | None` = `None`
  Optional memory limit, for example `"4Gi"` or `"512Mi"`.
- `gpu`: `str | None` = `None`
  Optional GPU request, for example `"nvidia-l4"`.
- `env`: `Mapping[str, str | Secret | OIDCTokenFile] | None` = `None`
  Environment variables as strings or single-value Secret references. The mapping key sets the injected name, overriding aliases and prefixes. A value may also be an [`OIDCTokenFile`](https://docs.chalk.ai/compute-docs#OIDCTokenFile), which sets the variable to the path of a platform-managed OIDC token file. That requires `chalk_identity=ChalkIdentity(mode="sandbox")`.
- `secrets`: `list[Secret] | None` = `None`
  Optional `Secret` references to inject.
- `volumes`: `_VolumeList | None` = `None`
  Optional [`Volume`](https://docs.chalk.ai/compute-docs#Volume) handles, [`VolumeMount`](https://docs.chalk.ai/compute-docs#VolumeMount) specifications, or `(name_or_volume, mount_path)` pairs to mount into the sandbox. Volume handles preserve their selected ref or pinned version. Each volume must already exist; `run` fails if one is missing.
- `port`: `int | None` = `None`
  Optional published port.
- `entrypoint`: `list[str] | None` = `None`
  Optional command to run as the sandbox container's main process.
- `lifetime`: `str | None` = `None`
  Optional max lifetime as a protobuf duration string (for example `"30s"` or `"300s"`).
- `security_policy`: `ContainerSecurityPolicy | None` = `None`
  Optional [`ContainerSecurityPolicy`](https://docs.chalk.ai/compute-docs#ContainerSecurityPolicy).
- `network_policy`: `NetworkPolicy | None` = `None`
  Optional network egress policy. Reuses the same [`NetworkPolicy`](https://docs.chalk.ai/compute-docs#NetworkPolicy) type accepted by `Container`.
- `compute_class`: `ComputeClass | None` = `None`
  Optional [`ComputeClass`](https://docs.chalk.ai/compute-docs#ComputeClass) (`K8S` or `HOST`).
- `runtime`: `Runtime | None` = `None`
  Runtime for host sandboxes. Not supported for Kubernetes workloads.
- `execution_target`: `ExecutionBackend | None` = `None`
  Optional [`ExecutionBackend`](https://docs.chalk.ai/compute-docs#ExecutionBackend); defaults to the environment cluster.
- `resource_detectors`: `Sequence[ResourceDetector] | None` = `None`
  Optional [`ResourceDetector`](https://docs.chalk.ai/compute-docs#ResourceDetector) values. Each detector inspects egress traffic to the hosts it recognizes and records resources the sandbox creates, such as GitHub pull requests, against the sandbox. The hosts a detector recognizes (for example `api.github.com`) are implicitly added to the sandbox's network policy.
- `host_pool_id`: `str | None` = `None`
  Optional host pool ID to restrict placement of host compute class sandboxes. Unstable; subject to change.
- `tags`: `dict[str, str] | None` = `None`
  Optional labels attached to the sandbox spec.
- `restart_policy`: `RestartPolicy | None` = `None`
  Optional restart behavior. Use `NEVER` or `ALWAYS`.
- `chalk_identity`: `bool | ChalkIdentity | None` = `None`
  Whether to give the sandbox a platform-managed Chalk identity. The identity is exposed inside the sandbox through the standard `CHALK_WEB_IDENTITY_TOKEN_FILE` environment variable. When omitted, enables creator identity unless `CHALK_REMOTE_FUNCTION` is set to a nonempty value. Set [`True`](https://docs.python.org/3/library/constants.html#True) to explicitly enable creator identity or [`False`](https://docs.python.org/3/library/constants.html#False) to disable managed Chalk identity. Pass `ChalkIdentity(mode="sandbox")` for credentials that identify the sandbox itself, which [`OIDCTokenFile`](https://docs.chalk.ai/compute-docs#OIDCTokenFile) requires.
- `group_limits`: `SandboxGroupLimits | None` = `None`
  Root sandbox group limits. Requires `ChalkIdentity(mode="sandbox")`.
- `managed_ssh`: `Mapping[str, SSHDest] | Sequence[SSHDest] | None` = `None`
  Optional SSH destinations: a list of [`SSHDest`](https://docs.chalk.ai/compute-docs#SSHDest), each reachable by its `alias` (default: its `host`), or a mapping of aliases to [`SSHDest`](https://docs.chalk.ai/compute-docs#SSHDest). `SSHDest.github(...)` sets up GitHub. Managed SSH sandboxes run on host compute.
- `tracing`: `TracingPolicyConfig | None` = `None`
  Trace sampling for processes inside the sandbox. [`True`](https://docs.python.org/3/library/constants.html#True) traces every request; a `TracingPolicy` sets the root sample rate; [`False`](https://docs.python.org/3/library/constants.html#False) turns tracing off.
- `trace_syscalls`: `Sequence[str]` = `()`
  Exact names of Linux syscalls to trace. An empty sequence disables syscall tracing.
- `chalk_client`: `Any | None` = `None`
- `sandbox_client`: `SandboxClient | None` = `None`
- `client`: `Any | None` = `None`
- `sandbox_id`: `str | None` = `None`

**Examples**

Use the default image with Python, Git, SSH, and `/workspace`:

```python
from chalkcompute import Sandbox
Sandbox()
```

Add Python dependencies and upload a local project when the sandbox starts:

```python
from chalkcompute import Image
Sandbox(
    image=Image.debian_slim("3.12")
        .pip_install(["pandas", "requests"])
        .add_local_dir("./src", "/workspace/src")
        .workdir("/workspace"),
    cpu="2",
    memory="8Gi",
)
```

Configure an API client with a secret and restricted outbound access:

```python
from chalkcompute import NetworkPolicy, Secret
Sandbox(
    image=Image.debian_slim().pip_install(["openai"]),
    env={"LOG_LEVEL": "INFO"},
    network_policy=NetworkPolicy(allowed_hosts=["api.openai.com"]),
).add_credentials("api.openai.com", Secret.from_chalk_env("OPENAI_API_KEY"))
```

Mount existing volumes for durable inputs and outputs:

```python
Sandbox(
    volumes=[("training-data", "/data"), ("results", "/results")],
    cpu="4",
    memory="16Gi",
    lifetime="3600s",
)
```

Prepare a coding agent with Claude Code, GitHub CLI, and tmux. Managed SSH uses a stored deploy key; resource detection records pull requests:

```python
from chalkcompute import ComputeClass, ResourceDetector, SSHDest
Sandbox(
    image=Image.sandbox().with_claude_code().with_gh().with_tmux(),
    compute_class=ComputeClass.HOST,
    managed_ssh=[SSHDest.github("GITHUB_DEPLOY_KEY")],
    resource_detectors=[ResourceDetector.GITHUB_PULL_REQUESTS],
    cpu="2",
    memory="16Gi",
).add_credentials("api.github.com", "GITHUB_TOKEN").add_credentials(
    "api.anthropic.com", "CLAUDE_CODE_OAUTH_TOKEN",
)
```

Request a GPU on a host pool configured with NVIDIA L4 GPUs:

```python
Sandbox(
    image="nvcr.io/nvidia/pytorch:24.01-py3",
    gpu="nvidia-l4",
    cpu="8",
    memory="64Gi",
    compute_class=ComputeClass.HOST,
)
```

Give code inside the sandbox a Chalk identity and trace its requests:

```python
Sandbox(
    chalk_identity=True,
    tracing=True,
    tags={"project": "agent-evals", "stage": "development"},
)
```

These expressions configure sandboxes. Call `run` on a configured sandbox, or pass it to `run`, to start it.

### `Sandbox.from_id(sandbox_id, chalk_client)`
source: https://docs.chalk.ai/compute-docs#Sandbox.from_id

Attach to an existing sandbox by ID.

### `Sandbox.from_name(name, chalk_client)`
source: https://docs.chalk.ai/compute-docs#Sandbox.from_name

Attach to an existing sandbox by name.

### `Sandbox.list_all(chalk_client, limit)`
source: https://docs.chalk.ai/compute-docs#Sandbox.list_all

List sandboxes in the current environment, optionally capped by `limit`.

### `Sandbox.refresh()`
source: https://docs.chalk.ai/compute-docs#Sandbox.refresh

Force-refresh sandbox info from the server, including after termination.

### `Sandbox.mount_volume(name, mount_path)`
source: https://docs.chalk.ai/compute-docs#Sandbox.mount_volume

Mount a named volume or volume handle into the sandbox.

Must be called before the sandbox is run. Returns `self` for chaining.

**Examples**

```python
from chalkcompute import Sandbox, SandboxClient
sandbox = Sandbox(image="ubuntu:latest")
sandbox.mount_volume("my-data", "/data")
with SandboxClient.from_env() as client:
    client.run(sandbox)
```

### `Sandbox.add_credentials(hosts, credentials)`
source: https://docs.chalk.ai/compute-docs#Sandbox.add_credentials

Expose credentials to requests bound for specific hosts.

String credentials name existing Chalk secrets. Use `from_local_env` to read a credential from the local environment when the sandbox starts.

The sandbox receives a placeholder in each credential's environment variable. Its network policy replaces that placeholder when it appears in headers on requests to the supplied hosts.

Must be called before the sandbox is run. Returns `self` for chaining.

**Parameters**

- `hosts`: `str | Sequence[str]`
  A host pattern or sequence of host patterns allowed to use the credentials.
- `credentials`: `str | Secret` = `()`
  Existing Chalk secret names or explicit [`Secret`](https://docs.chalk.ai/compute-docs#Secret) references.

**Examples**

```python
sandbox = (
    Sandbox(image="ubuntu:latest")
    .add_credentials("api.openai.com", "OPENAI_API_KEY")
    .add_credentials(
        ["api.slack.com", "*.slack.com"],
        Secret.from_local_env("SLACK_BOT_TOKEN"),
    )
)
with SandboxClient.from_env() as client:
    client.run(sandbox)
```

### `Sandbox.run(wait, poll_interval, timeout)`
source: https://docs.chalk.ai/compute-docs#Sandbox.run

Create the sandbox and optionally wait until it is ready.

**Parameters**

- `wait`: `bool` = `True`
  If [`True`](https://docs.python.org/3/library/constants.html#True), poll until the sandbox is ready (default [`True`](https://docs.python.org/3/library/constants.html#True)).
- `poll_interval`: `float | None` = `None`
  Initial delay between readiness polls. When omitted, polling starts at 25ms and backs off by 50% to 250ms. Image builds retain their 500ms default polling interval.
- `timeout`: `float` = `600.0`
  Maximum seconds to wait for the sandbox to become ready.

**Returns**

`Sandbox`

`self`, to allow chaining.

### `Sandbox.exec(command, args, timeout_secs, workdir, env, auto_reattach)`
source: https://docs.chalk.ai/compute-docs#Sandbox.exec

Execute a command and wait for it to complete.

**Parameters**

- `command`: `str`
  Command binary or script to execute.
- `args`: `str` = `()`
- `timeout_secs`: `int | None` = `None`
  Optional timeout in seconds.
- `workdir`: `str | None` = `None`
  Optional working directory inside the sandbox.
- `env`: `dict[str, str] | None` = `None`
  Optional environment variables to set for the command.
- `auto_reattach`: `bool` = `True`
  Reattach and replay buffered output after transient transport disconnects for HOST sandboxes. K8S commands use one-shot execution and cannot be reattached.

**Returns**

`ExecResult`

Result with stdout/stderr and exit code.

### `Sandbox.exec_stream(command, args, timeout_secs, workdir, env)`
source: https://docs.chalk.ai/compute-docs#Sandbox.exec_stream

Execute a command and stream events as they arrive.

**Parameters**

- `command`: `str`
  Command binary or script to execute.
- `args`: `str` = `()`
- `timeout_secs`: `int | None` = `None`
  Optional timeout in seconds.
- `workdir`: `str | None` = `None`
  Optional working directory inside the sandbox.
- `env`: `dict[str, str] | None` = `None`
  Optional environment variables to set for the command.

### `Sandbox.exec_start(command, args, timeout_secs, workdir, env)`
source: https://docs.chalk.ai/compute-docs#Sandbox.exec_start

Start a command and return an [`ExecProcess`](https://docs.chalk.ai/compute-docs#ExecProcess) handle for interactive use.

The caller can write to stdin, send signals, and iterate output.

**Parameters**

- `command`: `str`
  Command binary or script to execute.
- `args`: `str` = `()`
- `timeout_secs`: `int | None` = `None`
  Optional timeout in seconds.
- `workdir`: `str | None` = `None`
  Optional working directory inside the sandbox.
- `env`: `dict[str, str] | None` = `None`
  Optional environment variables to set for the command.

**Returns**

`ExecProcess`

Handle for interacting with the running process.

### `Sandbox.execute_python(source, timeout_secs, workdir, env, capture_charts, max_artifact_bytes)`
source: https://docs.chalk.ai/compute-docs#Sandbox.execute_python

Run Python source in the sandbox with structured output capture.

The server wraps `source` in a capture harness that injects a `save_artifact(obj, *, name=None, kind=None, content_type=None)` helper into the namespace and, after the source finishes, inspects the namespace for plotly/altair figures bound to variables. Everything saved or captured is persisted to the Chalk artifact store server-side — the sandbox itself never receives credentials — and returned as [`Artifact`](https://docs.chalk.ai/compute-docs#Artifact) handles.

**Parameters**

- `source`: `str`
  Python source to execute. Bare final expressions do not print; charts are captured regardless of printing.
- `timeout_secs`: `int | None` = `None`
  Optional timeout in seconds for the python process.
- `workdir`: `str | None` = `None`
  Optional working directory inside the sandbox.
- `env`: `dict[str, str] | None` = `None`
  Optional environment variables for the process.
- `capture_charts`: `bool` = `True`
  Inspect the namespace for plotly/altair figures after execution (default [`True`](https://docs.python.org/3/library/constants.html#True)).
- `max_artifact_bytes`: `int | None` = `None`
  Byte budget across all artifacts from this execution; artifacts past it are reported in `skipped_artifacts`.

**Returns**

`PythonExecution`

Buffered stdout/stderr, exit status, and persisted artifacts.

### `Sandbox.snapshot()`
source: https://docs.chalk.ai/compute-docs#Sandbox.snapshot

Capture sandbox state and return a snapshot ready to restore.

Wait until capture and durable publication complete. Individual requests use short deadlines and retry transient failures internally.

### `Sandbox.refresh_credentials(timeout)`
source: https://docs.chalk.ai/compute-docs#Sandbox.refresh_credentials

Refresh proxy credentials from the current scoped secret values.

Poll until Envoy activates the update. Raise [`SandboxError`](https://docs.chalk.ai/compute-docs#SandboxError) if the update fails or is superseded, or `TimeoutError` if `timeout` seconds elapse. A timeout does not cancel the submitted refresh. Already-open connections may continue using the previous credentials.

### `Sandbox.suspend()`
source: https://docs.chalk.ai/compute-docs#Sandbox.suspend

Suspend this sandbox while preserving its identity for later restore.

### `Sandbox.restore()`
source: https://docs.chalk.ai/compute-docs#Sandbox.restore

Restore this suspended sandbox in place, preserving its identity.

### `Sandbox.terminate(grace_period_seconds)`
source: https://docs.chalk.ai/compute-docs#Sandbox.terminate

Terminate this sandbox.

Metadata remains available through `info` and `refresh`. Termination does not fetch metadata or require read permission.

**Parameters**

- `grace_period_seconds`: `int | None` = `None`
  Optional grace period to allow running processes to shut down.

## `SandboxInfo`
source: https://docs.chalk.ai/compute-docs#SandboxInfo

Class

Information about a sandbox.

**Attributes**

- `id`: `str`
  Sandbox identifier.
- `status`: `str`
  Current lifecycle status of the sandbox.
- `created_at`: `str`
  Timestamp when the sandbox was created.
- `name`: `str | None`
  Optional human-readable name for the sandbox.
- `build_id`: `str | None`
  Optional identifier of the image build associated with this sandbox.
- `status_message`: `str | None`
  Backend-provided explanation for the current lifecycle status.
- `status_details`: `str | None`
  Additional diagnostic output for the current lifecycle status.
- `compute_class`: `ComputeClass | None`
  Backend compute class reported by the sandbox specification.

## `ExecResult`
source: https://docs.chalk.ai/compute-docs#ExecResult

Class

Result of a completed command execution.

**Attributes**

- `stdout`: `bytes`
  Raw bytes written to standard output by the command.
- `stderr`: `bytes`
  Raw bytes written to standard error by the command.
- `exit_code`: `int | None`
  Exit code of the process, if it exited normally.
- `signal`: `int | None`
  Signal number that terminated the process, if any.
- `error`: `str | None`
  Error string if execution failed.
- `session_id`: `str | None`
  Execution session ID, when available.
- `stdout_text`: `str`
  `stdout` decoded as UTF-8 (with `errors="replace"`).
- `stderr_text`: `str`
  `stderr` decoded as UTF-8 (with `errors="replace"`).

## `ExecEvent`
source: https://docs.chalk.ai/compute-docs#ExecEvent

Class

A single event from a streaming exec call.

**Attributes**

- `session_id`: `str | None`
  V2 session identifier, set when the process session starts.
- `stdout`: `str | None`
  Stdout text chunk, if this event carries stdout output.
- `stderr`: `str | None`
  Stderr text chunk, if this event carries stderr output.
- `exit_code`: `int | None`
  Exit code of the process, set on the process-exited event.
- `exit_signal`: `int | None`
  Signal number that terminated the process, if any.
- `error_code`: `str | None`
  Error code string, set on error events.
- `error_message`: `str | None`
  Error message string, set on error events.
- `is_started`: `bool`
- `is_output`: `bool`
- `is_exited`: `bool`
- `is_error`: `bool`

## `ExecProcess`
source: https://docs.chalk.ai/compute-docs#ExecProcess

Class

Handle to a running exec stream, allowing stdin writes and signal sends.

**Attributes**

- `session_id`: `str | None`
  V2 session identifier once the process session starts.

### `ExecProcess.write_stdin(data)`
source: https://docs.chalk.ai/compute-docs#ExecProcess.write_stdin

Send data to the process's stdin.

**Parameters**

- `data`: `str | bytes`
  Bytes or string to write to stdin. Strings are UTF-8 encoded.

### `ExecProcess.close_stdin()`
source: https://docs.chalk.ai/compute-docs#ExecProcess.close_stdin

Signal EOF on stdin.

### `ExecProcess.send_signal(sig)`
source: https://docs.chalk.ai/compute-docs#ExecProcess.send_signal

Send a signal to the process.

**Parameters**

- `sig`: `int` = `signal.SIGTERM`
  Signal number to send. Defaults to `SIGTERM`.

### `ExecProcess.output()`
source: https://docs.chalk.ai/compute-docs#ExecProcess.output

Iterate over output events from the process.

### `ExecProcess.wait(auto_reattach)`
source: https://docs.chalk.ai/compute-docs#ExecProcess.wait

Consume all output and return the final result.

If the response stream is interrupted after the session starts, reconnect and replay buffered events by default. Set `auto_reattach=False` to handle transport disconnects yourself.

**Returns**

`ExecResult`

Aggregated stdout, stderr, exit code, and signal information.

## `SandboxError`
source: https://docs.chalk.ai/compute-docs#SandboxError

Exception (bases: `Exception`)

Base exception for sandbox errors.

## `SandboxNotFoundError`
source: https://docs.chalk.ai/compute-docs#SandboxNotFoundError

Class (bases: `SandboxError`)

Raised when a sandbox is not found.

## `SandboxTerminatedError`
source: https://docs.chalk.ai/compute-docs#SandboxTerminatedError

Class (bases: `SandboxStatusError`)

Raised when a sandbox has terminated.

## `SandboxBuildError`
source: https://docs.chalk.ai/compute-docs#SandboxBuildError

Class (bases: `SandboxStatusError`)

Raised when a custom sandbox image build fails.

## `ExecError`
source: https://docs.chalk.ai/compute-docs#ExecError

Class (bases: `SandboxError`)

Raised when command execution fails.
