# Connect a Rust program

> Let your agent do it: Connect a Rust program to Hermitbox. Add the `hermitbox` crate from crates.io and `tokio` (`macros` and `rt-multi-thread` features) to the project with `cargo add`. On this machine `Hermitbox::new()` reads the saved credentials automatically; on another machine, set `HERMITBOX_API_URL` and `HERMITBOX_API_KEY` in the process's private environment, never in a file or this chat. Run the page's quickstart and snapshot-and-fork examples with `cargo run` and show me their output. Follow the exact steps in https://docs.hermitbox.dev/v0.3.2/get-started/rust.md.

Give your Rust program sandboxes: create one, run a command in it and delete it with the Hermitbox
SDK.

Add the crate from crates.io and Tokio, on Rust 1.99 or later:

```sh
cargo add hermitbox tokio --features tokio/macros,tokio/rt-multi-thread
```

## Quickstart

```rust
use hermitbox::Hermitbox;

#[tokio::main]
async fn main() -> hermitbox::Result<()> {
    let hb = Hermitbox::new()?;
    let sandbox = hb.sandbox().await?;
    println!("{}", sandbox.run("echo hello").await?.stdout.trim());
    sandbox.delete().await?;
    Ok(())
}
```

On the machine where you installed Hermitbox, `Hermitbox::new()` connects automatically. From
another machine, set `HERMITBOX_API_URL` and `HERMITBOX_API_KEY` in the process's private
environment.

## Snapshot and fork

Try a risky change without touching the original. Save a sandbox at a clean checkpoint, fork an
independent copy, change the fork and throw it away:

```rust
use hermitbox::Hermitbox;

#[tokio::main]
async fn main() -> hermitbox::Result<()> {
    let hb = Hermitbox::new()?;
    let sandbox = hb.sandbox().await?;
    let outcome = async {
        sandbox.write("config.json", r#"{"mode":"safe"}"#).await?;
        let snapshot = sandbox.snapshot().await?;
        let fork = snapshot.fork().await?;
        let forked = async {
            fork.write("config.json", r#"{"mode":"experimental"}"#).await?;
            println!("original: {}", sandbox.read("config.json").await?);
            println!("fork: {}", fork.read("config.json").await?);
            Ok::<(), hermitbox::HermitboxError>(())
        }
        .await;
        let _ = fork.delete().await;
        forked
    }
    .await;
    let _ = sandbox.delete().await;
    outcome
}
```

Output:

```txt
original: {"mode":"safe"}
fork: {"mode":"experimental"}
```

Handles are cloneable across Tokio tasks, and credentials stay out of `Debug` output and serialized
views. The host tier still controls [capabilities and isolation](https://docs.hermitbox.dev/v0.3.2/reference/tiers.md).
[SDK reference](https://docs.hermitbox.dev/v0.3.2/sdk/rust.md).
