> ## Documentation Index
> Fetch the complete documentation index at: https://usefused.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# harnest.sandbox

> Public Python signatures, fields, and methods.

[All Python modules](https://usefused.com/docs/harnest/reference/api/overview.md) · [Import and compatibility guidance](https://usefused.com/docs/harnest/build/python-imports.md)

## Provider data contracts

| Contract | Properties |
| - | - |
| `SandboxRequest` | `code`, `timeout_seconds`, `context`, `input_files`, `execution_id`, `metadata`, `network_policy` |
| `SandboxContext` | Optional `agent_name`, `invocation_id`, `user_id`, and `session_id` |
| `SandboxResult` | `status`, `exit_code`, `stdout`, `stderr`, `output_files`, `metadata` |
| `SandboxFile` | `name`, `content` as bytes or base64 text, and `mime_type` |

## Execution statuses

| Status | Meaning |
| - | - |
| `succeeded` | Execution completed successfully |
| `failed` | Nonzero exit or provider-reported failure |
| `timed_out` | Execution deadline expired |
| `output_limit_exceeded` | Combined output exceeded its budget |
| `cancelled` | Provider-reported cancellation; managed caller cancellation also propagates as an exception |

## Exports

| Name | Kind |
| - | - |
| [`Sandbox`](#sandbox) | Class |
| [`SandboxBackend`](#sandboxbackend) | Class |
| [`SandboxBudget`](#sandboxbudget) | Class |
| [`SandboxCancelledError`](#sandboxcancellederror) | Class |
| [`SandboxContext`](#sandboxcontext) | Class |
| [`SandboxExecutionError`](#sandboxexecutionerror) | Class |
| [`SandboxFile`](#sandboxfile) | Class |
| [`SandboxInputFilesUnsupportedError`](#sandboxinputfilesunsupportederror) | Class |
| [`SandboxNetworkMode`](#sandboxnetworkmode) | Class |
| [`SandboxNetworkPolicy`](#sandboxnetworkpolicy) | Class |
| [`SandboxPolicyUnsupportedError`](#sandboxpolicyunsupportederror) | Class |
| [`SandboxProvider`](#sandboxprovider) | Class |
| [`SandboxProviderCapabilities`](#sandboxprovidercapabilities) | Class |
| [`SandboxRequest`](#sandboxrequest) | Class |
| [`SandboxResult`](#sandboxresult) | Class |
| [`SandboxStatus`](#sandboxstatus) | Class |
| [`cleanup_control`](#cleanup_control) | Function |
| [`control`](#control) | Namespace |

## Sandbox

Declare one lazy sandbox usable by managed ADK and LangGraph agents.

A sandbox is a code-execution boundary, not a policy label. The backend
returned by `factory` implements `SandboxBackend.execute` and owns the
actual isolation guarantees. Legacy ADK executors remain ADK-only providers.
Compilation never connects to provider infrastructure.

Obtain this object from the owning Harnest API; its constructor includes runtime bindings.

Fields (`—` means no declared default):

| Field | Type | Default |
| - | - | - |
| `factory` | `Callable[[], Any]` | `—` |
| `backend` | `str` | `'custom'` |
| `timeout_seconds` | `int \| None` | `None` |
| `metadata` | `Mapping[str, Any]` | `dict()` |
| `network_policy` | `SandboxNetworkPolicy \| None` | `None` |

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import Sandbox
>
> sandbox: Sandbox  # returned by Harnest, not constructed directly
> ```

### Sandbox.provider

```python theme={null}
Sandbox.provider(
    factory: Callable[[], Any],
    *,
    name: str = 'custom',
    timeout_seconds: int | None = None,
    metadata: Mapping[str, Any] | None = None,
    network_policy: SandboxNetworkPolicy | None = None,
    adapter_options: Mapping[str, Any] | None = None,
) -> 'Sandbox'
```

Configure a portable provider; native ADK factories remain compatible.

Provider-specific SDK settings belong in the factory. `adapter_options`
configures only the native framework adapter, while JSON metadata and an
optional network policy are forwarded to each request. A policy requires
provider capability declarations.

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `factory` | `Callable[[], Any]` | Required |
> | `name` | `str` | `'custom'` |
> | `timeout_seconds` | `int \| None` | `None` |
> | `metadata` | `Mapping[str, Any] \| None` | `None` |
> | `network_policy` | `SandboxNetworkPolicy \| None` | `None` |
> | `adapter_options` | `Mapping[str, Any] \| None` | `None` |
>
> ```python theme={null}
> from harnest.sandbox import Sandbox
>
> sandbox = Sandbox.provider(factory=...)
> ```

### Sandbox.to\_adk\_executor

```python theme={null}
Sandbox.to_adk_executor() -> Any
```

Use ADK's code\_executor interface and native code/result event loop.

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import Sandbox
>
> sandbox: Sandbox
> result = sandbox.to_adk_executor()
> ```

### Sandbox.to\_langchain\_tool

```python theme={null}
Sandbox.to_langchain_tool() -> Any
```

Use LangGraph's native tool loop with a lazy, typed execution tool.

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import Sandbox
>
> sandbox: Sandbox
> result = sandbox.to_langchain_tool()
> ```

### Sandbox.build

```python theme={null}
Sandbox.build() -> Any
```

Construct and validate a provider only when explicitly requested.

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import Sandbox
>
> sandbox: Sandbox
> result = sandbox.build()
> ```

## SandboxBackend

Execute in an isolated provider, never by evaluating code on the host.

Implementations own isolation, deadlines, file handling, concurrency, resource
cleanup, and user/session separation. Compilation never invokes this method.

```python theme={null}
SandboxBackend(*args, **kwargs)
```

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import SandboxBackend
>
> class MySandboxBackend(SandboxBackend):
>     ...
> ```

### SandboxBackend.execute

```python theme={null}
SandboxBackend.execute(request: SandboxRequest) -> SandboxResult
```

Execute Python under provider-enforced policy and return its output.

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `request` | `SandboxRequest` | Required |
>
> ```python theme={null}
> from harnest.sandbox import SandboxBackend
>
> backend: SandboxBackend
> result = backend.execute(request=...)
> ```

## SandboxBudget

Request finite compute, memory, process, and scratch-space limits.

```python theme={null}
SandboxBudget(
    cpu: float = 1.0,
    memory_bytes: int = 536870912,
    pids: int = 64,
    scratch_bytes: int = 67108864,
) -> None
```

Fields (`—` means no declared default):

| Field | Type | Default |
| - | - | - |
| `cpu` | `float` | `1.0` |
| `memory_bytes` | `int` | `536870912` |
| `pids` | `int` | `64` |
| `scratch_bytes` | `int` | `67108864` |

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `cpu` | `float` | `1.0` |
> | `memory_bytes` | `int` | `536870912` |
> | `pids` | `int` | `64` |
> | `scratch_bytes` | `int` | `67108864` |
>
> ```python theme={null}
> from harnest.sandbox import SandboxBudget
>
> budget = SandboxBudget()
> ```

## SandboxCancelledError

An execution lost its caller or its managed invocation authority.

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import SandboxCancelledError
>
> try:
>     ...
> except SandboxCancelledError as error:
>     ...
> ```

## SandboxContext

Supply optional invocation identity without exposing a native runtime.

Providers may use this identity for tenant isolation. Direct adapter calls
outside a runtime have no identity; providers requiring it must reject them.

```python theme={null}
SandboxContext(
    agent_name: str | None = None,
    invocation_id: str | None = None,
    user_id: str | None = None,
    session_id: str | None = None,
) -> None
```

Fields (`—` means no declared default):

| Field | Type | Default |
| - | - | - |
| `agent_name` | `str \| None` | `None` |
| `invocation_id` | `str \| None` | `None` |
| `user_id` | `str \| None` | `None` |
| `session_id` | `str \| None` | `None` |

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `agent_name` | `str \| None` | `None` |
> | `invocation_id` | `str \| None` | `None` |
> | `user_id` | `str \| None` | `None` |
> | `session_id` | `str \| None` | `None` |
>
> ```python theme={null}
> from harnest.sandbox import SandboxContext
>
> context = SandboxContext()
> ```

## SandboxExecutionError

A provider failed without exposing its private exception payload.

```python theme={null}
SandboxExecutionError(message: str, *, status: SandboxStatus = <SandboxStatus.FAILED: 'failed'>) -> None
```

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import SandboxExecutionError
>
> try:
>     ...
> except SandboxExecutionError as error:
>     ...
> ```

## SandboxFile

Carry a file across an executor boundary without granting host access.

String content is base64-encoded; bytes are the original file content.
Providers own path validation and must never interpret names as host paths.

```python theme={null}
SandboxFile(name: str, content: str | bytes, mime_type: str = 'text/plain') -> None
```

Fields (`—` means no declared default):

| Field | Type | Default |
| - | - | - |
| `name` | `str` | `—` |
| `content` | `str \| bytes` | `—` |
| `mime_type` | `str` | `'text/plain'` |

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `name` | `str` | Required |
> | `content` | `str \| bytes` | Required |
> | `mime_type` | `str` | `'text/plain'` |
>
> ```python theme={null}
> from harnest.sandbox import SandboxFile
>
> file = SandboxFile(name=..., content=...)
> ```

## SandboxInputFilesUnsupportedError

A provider explicitly cannot materialize the requested input files.

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import SandboxInputFilesUnsupportedError
>
> try:
>     ...
> except SandboxInputFilesUnsupportedError as error:
>     ...
> ```

## SandboxNetworkMode

Describe the outbound network authority granted to one sandbox.

```python theme={null}
SandboxNetworkMode(*values)
```

| Member | Value |
| - | - |
| `NONE` | `'none'` |
| `UNRESTRICTED` | `'unrestricted'` |
| `ALLOWLIST` | `'allowlist'` |

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import SandboxNetworkMode
>
> value = SandboxNetworkMode.NONE
> ```

## SandboxNetworkPolicy

Declare provider-enforced outbound access without assuming its mechanism.

Allowlist entries are exact DNS names or IP literals. Providers must apply
the policy to every connection and resolution, not only to the initial URL.

```python theme={null}
SandboxNetworkPolicy(
    mode: <enum 'SandboxNetworkMode'> = <SandboxNetworkMode.NONE: 'none'>,
    allow_hosts: tuple[str, ...] = (),
    allow_ports: tuple[int, ...] = (),
    block_private_networks: bool = True,
) -> None
```

Fields (`—` means no declared default):

| Field | Type | Default |
| - | - | - |
| `mode` | `<enum 'SandboxNetworkMode'>` | `<SandboxNetworkMode.NONE: 'none'>` |
| `allow_hosts` | `tuple[str, ...]` | `()` |
| `allow_ports` | `tuple[int, ...]` | `()` |
| `block_private_networks` | `bool` | `True` |

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `mode` | `<enum 'SandboxNetworkMode'>` | `<SandboxNetworkMode.NONE: 'none'>` |
> | `allow_hosts` | `tuple[str, ...]` | `()` |
> | `allow_ports` | `tuple[int, ...]` | `()` |
> | `block_private_networks` | `bool` | `True` |
>
> ```python theme={null}
> from harnest.sandbox import SandboxNetworkPolicy
>
> policy = SandboxNetworkPolicy()
> ```

### SandboxNetworkPolicy.none

```python theme={null}
SandboxNetworkPolicy.none() -> SandboxNetworkPolicy
```

Deny all outbound network connections.

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import SandboxNetworkPolicy
>
> policy = SandboxNetworkPolicy.none()
> ```

### SandboxNetworkPolicy.unrestricted

```python theme={null}
SandboxNetworkPolicy.unrestricted(*, block_private_networks: bool = False) -> SandboxNetworkPolicy
```

Permit outbound access, optionally retaining a private-network ceiling.

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `block_private_networks` | `bool` | `False` |
>
> ```python theme={null}
> from harnest.sandbox import SandboxNetworkPolicy
>
> policy = SandboxNetworkPolicy.unrestricted()
> ```

### SandboxNetworkPolicy.allowlist

```python theme={null}
SandboxNetworkPolicy.allowlist(
    *hosts: str,
    ports: tuple[int, ...] = (),
    block_private_networks: bool = True,
) -> SandboxNetworkPolicy
```

Permit exact hosts and optional destination ports only.

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `*hosts` | `str` | Optional |
> | `ports` | `tuple[int, ...]` | `()` |
> | `block_private_networks` | `bool` | `True` |
>
> ```python theme={null}
> from harnest.sandbox import SandboxNetworkPolicy
>
> policy = SandboxNetworkPolicy.allowlist()
> ```

## SandboxPolicyUnsupportedError

A provider cannot enforce an explicitly requested sandbox policy.

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import SandboxPolicyUnsupportedError
>
> try:
>     ...
> except SandboxPolicyUnsupportedError as error:
>     ...
> ```

## SandboxProvider

A portable backend that declares its enforceable sandbox policy.

```python theme={null}
SandboxProvider(*args, **kwargs)
```

Fields (`—` means no declared default):

| Field | Type | Default |
| - | - | - |
| `sandbox_capabilities` | `SandboxProviderCapabilities` | `—` |

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import SandboxProvider
>
> class MySandboxProvider(SandboxProvider):
>     ...
> ```

### SandboxProvider.execute

```python theme={null}
SandboxProvider.execute(request: SandboxRequest) -> SandboxResult
```

Execute Python under provider-enforced policy and return its output.

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `request` | `SandboxRequest` | Required |
>
> ```python theme={null}
> from harnest.sandbox import SandboxProvider
>
> provider: SandboxProvider
> result = provider.execute(request=...)
> ```

## SandboxProviderCapabilities

Advertise network controls a provider enforces below agent code.

```python theme={null}
SandboxProviderCapabilities(
    network_modes: frozenset[harnest.sandbox.SandboxNetworkMode] = frozenset([]),
    host_allowlist: bool = False,
    port_allowlist: bool = False,
    private_network_blocking: bool = False,
) -> None
```

Fields (`—` means no declared default):

| Field | Type | Default |
| - | - | - |
| `network_modes` | `frozenset[harnest.sandbox.SandboxNetworkMode]` | `frozenset([])` |
| `host_allowlist` | `bool` | `False` |
| `port_allowlist` | `bool` | `False` |
| `private_network_blocking` | `bool` | `False` |

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `network_modes` | `frozenset[harnest.sandbox.SandboxNetworkMode]` | `frozenset([])` |
> | `host_allowlist` | `bool` | `False` |
> | `port_allowlist` | `bool` | `False` |
> | `private_network_blocking` | `bool` | `False` |
>
> ```python theme={null}
> from harnest.sandbox import SandboxProviderCapabilities
>
> capabilities = SandboxProviderCapabilities()
> ```

### SandboxProviderCapabilities.require

```python theme={null}
SandboxProviderCapabilities.require(policy: harnest.sandbox.SandboxNetworkPolicy) -> None
```

Fail closed when this provider cannot enforce requested authority.

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `policy` | `harnest.sandbox.SandboxNetworkPolicy` | Required |
>
> ```python theme={null}
> from harnest.sandbox import SandboxProviderCapabilities
>
> capabilities: SandboxProviderCapabilities
> capabilities.require(policy=...)
> ```

## SandboxRequest

Describe one Python execution; the provider enforces its timeout.

```python theme={null}
SandboxRequest(
    code: str,
    timeout_seconds: int | None = None,
    context: SandboxContext = ...,
    input_files: tuple[SandboxFile, ...] = (),
    execution_id: str | None = None,
    metadata: Mapping[str, Any] = ...,
    network_policy: SandboxNetworkPolicy | None = None,
) -> None
```

Fields (`—` means no declared default):

| Field | Type | Default |
| - | - | - |
| `code` | `str` | `—` |
| `timeout_seconds` | `int \| None` | `None` |
| `context` | `SandboxContext` | `SandboxContext()` |
| `input_files` | `tuple[SandboxFile, ...]` | `()` |
| `execution_id` | `str \| None` | `None` |
| `metadata` | `Mapping[str, Any]` | `dict()` |
| `network_policy` | `SandboxNetworkPolicy \| None` | `None` |

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `code` | `str` | Required |
> | `timeout_seconds` | `int \| None` | `None` |
> | `context` | `SandboxContext` | `...` |
> | `input_files` | `tuple[SandboxFile, ...]` | `()` |
> | `execution_id` | `str \| None` | `None` |
> | `metadata` | `Mapping[str, Any]` | `...` |
> | `network_policy` | `SandboxNetworkPolicy \| None` | `None` |
>
> ```python theme={null}
> from harnest.sandbox import SandboxRequest
>
> request = SandboxRequest(code=...)
> ```

## SandboxResult

Return execution output without coupling providers to ADK or LangChain.

```python theme={null}
SandboxResult(
    stdout: str = '',
    stderr: str = '',
    output_files: tuple[SandboxFile, ...] = (),
    metadata: Mapping[str, Any] = ...,
    status: SandboxStatus = <SandboxStatus.SUCCEEDED: 'succeeded'>,
    exit_code: int | None = None,
) -> None
```

Fields (`—` means no declared default):

| Field | Type | Default |
| - | - | - |
| `stdout` | `str` | `''` |
| `stderr` | `str` | `''` |
| `output_files` | `tuple[SandboxFile, ...]` | `()` |
| `metadata` | `Mapping[str, Any]` | `dict()` |
| `status` | `SandboxStatus` | `<SandboxStatus.SUCCEEDED: 'succeeded'>` |
| `exit_code` | `int \| None` | `None` |

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `stdout` | `str` | `''` |
> | `stderr` | `str` | `''` |
> | `output_files` | `tuple[SandboxFile, ...]` | `()` |
> | `metadata` | `Mapping[str, Any]` | `...` |
> | `status` | `SandboxStatus` | `<SandboxStatus.SUCCEEDED: 'succeeded'>` |
> | `exit_code` | `int \| None` | `None` |
>
> ```python theme={null}
> from harnest.sandbox import SandboxResult
>
> result = SandboxResult()
> ```

## SandboxStatus

Provider-reported outcome; stderr alone does not mean execution failed.

```python theme={null}
SandboxStatus(*values)
```

| Member | Value |
| - | - |
| `SUCCEEDED` | `'succeeded'` |
| `FAILED` | `'failed'` |
| `TIMED_OUT` | `'timed_out'` |
| `OUTPUT_LIMIT_EXCEEDED` | `'output_limit_exceeded'` |
| `CANCELLED` | `'cancelled'` |

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import SandboxStatus
>
> value = SandboxStatus.SUCCEEDED
> ```

## cleanup\_control

Admit resource release under a fresh finite deadline, never execution.

Provider I/O must use remaining() as its transport timeout and check() before
each side effect. This cooperative scope cannot interrupt arbitrary Python.
Nested cleanup inherits the original cleanup deadline and cannot renew it.

```python theme={null}
cleanup_control(timeout_seconds: int = 5) -> Iterator[SandboxControl]
```

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `timeout_seconds` | `int` | `5` |
>
> ```python theme={null}
> from harnest.sandbox import cleanup_control
>
> with cleanup_control():
>     ...
> ```

## control

Public provider controls, exported through harnest.sandbox.control.

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import control
> ```

### control.execute

```python theme={null}
control.execute(timeout_seconds: int | None) -> Iterator[SandboxControl]
```

Scope deadlines independently while preserving call-wide cancellation.

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `timeout_seconds` | `int \| None` | Required |
>
> ```python theme={null}
> from harnest.sandbox import control
>
> with control.execute(timeout_seconds=...):
>     ...
> ```

### control.cleanup

```python theme={null}
control.cleanup(timeout_seconds: int = 5) -> Iterator[SandboxControl]
```

Admit resource release under a fresh finite deadline, never execution.

Provider I/O must use remaining() as its transport timeout and check() before
each side effect. This cooperative scope cannot interrupt arbitrary Python.
Nested cleanup inherits the original cleanup deadline and cannot renew it.

> [accordion] Parameters and example
>
> | Parameter | Type | Default |
> | - | - | - |
> | `timeout_seconds` | `int` | `5` |
>
> ```python theme={null}
> from harnest.sandbox import control
>
> with control.cleanup():
>     ...
> ```

### control.current

```python theme={null}
control.current() -> SandboxControl | None
```

Return the execution token inherited by native framework worker threads.

> [accordion] Example
>
> ```python theme={null}
> from harnest.sandbox import control
>
> control = control.current()
> ```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.