# Sandboxes

A sandbox gives your code, or your agent, an isolated place to work. It runs commands, keeps its
files and serves ports, apart from your host and from other sandboxes. The box your agent works in
is one you can step into too: open a shell in it, read its files, open its ports.

Each sandbox has its own data directory, network policy and limits. It keeps one kind of isolation,
its tier, for its whole life; [Isolation tiers](https://docs.hermitbox.dev/v0.3.2/concepts/isolation.md) explains the choice.

```ts
import { Hermitbox } from 'hermitbox'

const hb = new Hermitbox()

// Create a sandbox on the host's default tier.
const box = await hb.sandbox()

// Run a command in it.
const result = await box.run('echo hello')
console.log(result.stdout) // hello

// Delete it when you're done.
await box.delete()
```

```python
from hermitbox import Hermitbox

hb = Hermitbox()

# Create a sandbox on the host's default tier.
box = hb.sandbox()

# Run a command in it.
result = box.run('echo hello')
print(result.stdout)  # hello

# Delete it when you're done.
box.delete()
```

```rust
use hermitbox::Hermitbox;

let hb = Hermitbox::new()?;

// Create a sandbox on the host's default tier.
let sandbox = hb.sandbox().await?;

// Run a command in it.
let result = sandbox.run("echo hello").await?;
println!("{}", result.stdout); // hello

// Delete it when you're done.
sandbox.delete().await?;
```

| Part | What it is |
| --- | --- |
| Commands | One-shot commands, streams, background processes, shells and terminals |
| Files | A persistent data directory; file paths are relative to it |
| Ports | Declared ports and spare ports, reached through the edge |
| Network | `internet` (the default) or `none`, plus egress rules where the node enforces them |
| Limits | Units of memory and CPU, timers and project quotas |
| Tier | `process`, `wasm`, `container`, `gvisor` or `vm`, fixed at creation |

## Run commands

Run a command and get its output back, watch it as it arrives, or leave it running. Every sandbox
runs a Hermitbox agent that starts commands and serves files: `box.run` waits for the result,
`box.stream` yields output as it arrives, and `box.spawn` starts a background process.

A string command runs with `sh -c`. An argument array, such as `['cat', 'app.py']`, skips the
shell. Commands start in the data directory unless `cwd` or the sandbox's `workdir` says otherwise.

Hermitbox never retries a command on its own; each one carries one idempotency key. If a stream
ends without an exit, the outcome is unknown, so inspect the sandbox before you run the command
again.

## Files and what persists

The data directory is where a sandbox keeps its work, and the part that lasts. Stop, sleep, rest
(an archive to the object store) and moves keep it, and snapshots and forks copy it.

On the `container`, `gvisor` and `vm` tiers the data directory is mounted at `/data`. On the
`process` tier it is a host directory: commands start there, and `HOME` and `TMPDIR` point to it.

```ts
// Write a file into the data directory, then read it back.
await box.write('notes/today.txt', 'hello')
console.log(await box.read('notes/today.txt')) // hello
```

```python
# Write a file into the data directory, then read it back.
box.write('notes/today.txt', 'hello')
print(box.read('notes/today.txt'))  # hello
```

```rust
// Write a file into the data directory, then read it back.
sandbox.write("notes/today.txt", "hello").await?;
println!("{}", sandbox.read("notes/today.txt").await?); // hello
```

Treat everything outside the data directory as temporary. By default a container's root
filesystem is read-only and its `/tmp` lives in memory.

You can read, write, list and check files while the sandbox is stopped or asleep: the node serves
them without starting compute. Searching, replacing, changing modes and uploading a directory run
in the sandbox, so they wake it. File paths are relative to the data directory on every tier.

## Ports and endpoints

A server running in a sandbox can get a URL, so you and your agent can open what it serves. A
sandbox has three spare ports by default, and `box.expose(port)` publishes one on demand and
returns its URL.

A sandbox can also declare ports at creation, each `public` or `private`. Public ports get an
address on the edge, the part of Hermitbox that faces clients. Private ones are reachable only on
the fleet's private network.

Workload ports are never bound to a public address on the host. Only the edge and control can dial
them, and a connection that arrives through the edge wakes a sleeping sandbox.

## Network and limits

You decide what a sandbox can reach and how much it can use. `network: 'none'` cuts a sandbox off
on every tier. With `internet`, egress rules for hostnames or addresses apply where the node
enforces them, and a node that can't refuses them by name. `box.network('none')` replaces a
running or stopped sandbox's compute with the new policy and keeps its data.

Resources come in units: one unit is 512 MiB and 250 CPU millis unless the operator sets other
values. How strictly a tier enforces them differs, and [Isolation tiers](https://docs.hermitbox.dev/v0.3.2/concepts/isolation.md) says how.

Timers put a sandbox to sleep or end it for you, so one nobody is using stops using compute.
`ttl` sets a deadline after which access stops and the sandbox is deleted. `idle` sleeps it after
that long without activity, or deletes it when `autoDelete` is set. `box.keepAlive(duration)`
extends access and counts as activity. Project ceilings bound all three.

## Projects and keys

A project groups sandboxes under their own keys and limits, out of reach of every other
project's keys. Every sandbox belongs to one project, and so does every API key. The key you use
chooses the project, and another project's sandbox IDs answer 404 to it.

An operator creates projects and keys on the private operator listener. The installer creates the
first key and saves it for the CLI and the SDKs.

```sh
# Create a project with limits, then a key for it. The key prints once.
hermitbox project create --max-units 5 --max-running 3
hermitbox key create --project <project-id>
```

Project limits cap units, running sandboxes, snapshots, timers and allowed images. A request over
a limit gets 403 `limit_exceeded` with the limit's name.

## Address a sandbox

Come back to a sandbox later by its ID, or find it among others by its labels. Each sandbox has an
ID, assigned at creation (`box.id`). It can also have a `name`, unique within its project, plus
`labels` and `metadata` you set.

```ts
// Find a sandbox again by its ID. A sleeping one wakes unless wake is false.
const box = await hb.sandbox('<sandbox-id>')

// List the project's sandboxes that carry a label.
const boxes = await hb.sandboxes({ labels: { team: 'ci' } })
```

```python
# Find a sandbox again by its ID. A sleeping one wakes unless wake is false.
box = hb.sandbox('<sandbox-id>')

# List the project's sandboxes that carry a label.
boxes = hb.sandboxes(labels={'team': 'ci'})
```

```rust
use hermitbox::SandboxFilters;

// Find a sandbox again by its ID. A sleeping one wakes unless wake is false.
let sandbox = hb.get_sandbox("<sandbox-id>").await?;

// List the project's sandboxes that carry a label.
let boxes = hb
    .sandboxes(SandboxFilters::new().label("team", "ci"))
    .await?;
```

The same ID works in the CLI (`hermitbox sandbox get <sandbox-id>`) and in the HTTP API
(`/v1/sandboxes/<sandbox-id>`).

## Next steps

- [Lifecycle](https://docs.hermitbox.dev/v0.3.2/concepts/lifecycle.md): what each verb keeps.
- [Isolation tiers](https://docs.hermitbox.dev/v0.3.2/concepts/isolation.md): how each tier separates a sandbox from the host.
- [Public API](https://docs.hermitbox.dev/v0.3.2/reference/api.md) and [The sandbox agent](https://docs.hermitbox.dev/v0.3.2/reference/sandbox-agent.md): every field and route.
