# Rust SDK

> Install the Rust SDK, run a command on a computer and look up the client, computers, exec, files and errors

> Nevia is in early access for selected teams. The CLI installs with `curl -fsSL https://get.nevia.cloud | sh`, and the MCP server is at https://api.nevia.cloud/mcp. A person signs in once in the browser.
> Setup, sign-in and requesting access: [SKILL.md](https://nevia.cloud/SKILL.md). When Nevia fits and when it doesn't: [why.md](https://nevia.cloud/why.md).

> For the complete documentation index, see [llms.txt](https://nevia.cloud/llms.txt). This page's HTML version: https://nevia.cloud/docs/reference/sdk/rust

The Rust SDK runs computers from Rust code. It is async on tokio, and every
call returns a `nevia::Result`, with `nevia::Error` as the one error type. The
SDK is in early access, so names and behaviour can change.

The quick start creates a computer, runs a command on it, writes and reads a
file and deletes the computer. The [reference](#reference) after it covers the
client, computers, exec, files and errors.

## Prerequisites

You need:

* Rust 1.97.1 or later, with the 2024 edition.
* A Nevia workspace where you have the **admin** or **editor** role.
* The `nevia` CLI, signed in with `nevia login`. The
  [Quickstart](https://nevia.cloud/docs/get-started/quickstart.md) shows how to install it.

## 1. Install the SDK

> **Invited testers only**
>
> The SDKs are in early access for invited testers. To ask for access, see
> [Request access to Nevia](https://nevia.cloud/docs/get-started/request-access.md).

From your project's root, download the SDK bundle. It unpacks to
`vendor/nevia-sdk-0.1.0/`:

```bash
curl -fsSL --oauth2-bearer "$(nevia auth access-token)" https://sdk.nevia.cloud/0.1.0.tar.gz | tar -xz
```

Then add the SDK from it:

**cargo add**

```bash
cargo add --path vendor/nevia-sdk-0.1.0/rust/sdk-rust
cargo add tokio --features macros,rt-multi-thread
```

**Cargo.toml**

```toml
[dependencies]
nevia = { path = "vendor/nevia-sdk-0.1.0/rust/sdk-rust" }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
```

If your `Cargo.toml` has a `[workspace]` table, add `exclude = ["vendor"]` to
it.

## 2. Authenticate

The SDK uses your `nevia login` session, so a signed-in machine needs nothing
more. A server or CI job uses a service-account key instead:

```bash
export NEVIA_KEY_FILE="$HOME/path/to/key.json"
```

[Use an automation key file](https://nevia.cloud/docs/guides/automation-key-file.md) shows how to
create one. If you belong to more than one workspace, set `NEVIA_WORKSPACE` to
the workspace ID too.

## 3. Create a computer and run a command

Save this as `src/main.rs`:

```rust
use nevia::{Client, Nevia};

#[tokio::main]
async fn main() -> nevia::Result<()> {
    let nevia = Nevia::new(Client::from_env()?);
    let computer = nevia
        .computers()
        .create()
        .image("docker.io/library/debian:12-slim")
        .await?;
    println!("Computer: {}", computer.id());

    let result = computer.exec("uname -sr").await?;
    println!("Exit code: {}, output: {}", result.exit_code, result.stdout.trim());

    computer.files().write("/tmp/hello.txt", "Hello from Nevia!\n").await?;
    if let Some(text) = computer.files().read_text("/tmp/hello.txt").await? {
        print!("{text}");
    }

    computer.delete().await?;
    Ok(())
}
```

Run it:

```bash
cargo run
```

The computer ID and kernel version in the output vary:

```text
Computer: 01d69b2m9d26k14b244xjwmp9mb
Exit code: 0, output: Linux 6.1.191
Hello from Nevia!
```

Awaiting `create()` returns once the computer is ready, so the first command
runs at once. A command that exits nonzero still returns a result. Check
`result.exit_code` or `result.success()` to see whether it succeeded.

## 4. Clean up

The SDK never deletes a computer for you. `computer.delete()` deletes it and
waits until it is gone, and succeeds if it is already gone. The `?` operator
returns early on an error, so a failure between `create()` and `delete()`
leaves the computer running. Call `delete()` on the error path too, or run
`nevia ls` afterwards to find and remove leftovers.

To keep a computer after the program ends, skip `delete()` and save its ID:

```rust
let computer = nevia
    .computers()
    .create()
    .image("docker.io/library/debian:12-slim")
    .await?;
println!("{}", computer.id());
```

A later program reconnects with `nevia.computer(saved_id)` and calls
`computer.delete()` when it is done.

## Reference

### Client

```rust
Client::builder()
    .base_url(url)
    .workspace(id)
    .token(token)
    .key_file(path)
    .credentials(credentials)
    .build()?
```

`Client::from_env()` is `Client::builder().build()`. `Nevia::new(client)`
wraps a client in the resources used on this page, and `Nevia::from_env()` does
both steps.

| Builder method             | Description                                                             |
| -------------------------- | ----------------------------------------------------------------------- |
| `token(token)`             | Bearer token string                                                     |
| `key_file(path)`           | Path to a service-account key file                                      |
| `credentials(credentials)` | Any `Credentials` value (defaults to `Credentials::from_env()`)         |
| `workspace(id)`            | Workspace ID (defaults to your only workspace)                          |
| `base_url(url)`            | API base URL (defaults to production)                                   |
| `http_client(client)`      | Your own `reqwest::Client`, for proxies or custom TLS                   |
| `validate(on)`             | Check requests against the API contract before sending (default `true`) |
| `build()`                  | Build the `Client`, returning a `Result`                                |

The client looks for credentials in this order:

1. The `token`, `key_file` or `credentials` builder method.
2. `NEVIA_TOKEN`.
3. `NEVIA_KEY_FILE`, or `NEVIA_KEY` with the key's JSON.
4. Your `nevia login` session.

The workspace is the `workspace` builder method, then `NEVIA_WORKSPACE`, then
the only workspace you belong to. `NEVIA_API_URL` sets the base URL when
`base_url` is not called.

`Client` and `Nevia` are cheap to clone, and clones share connections and
credentials. Neither needs closing, and dropping them leaves your computers
running.

| Member                    | Description                                                  |
| ------------------------- | ------------------------------------------------------------ |
| `nevia.computers()`       | Create, get, find and list computers                         |
| `nevia.computer(id)`      | Handle to an existing computer, without a request            |
| `nevia.workspace().await` | ID of the selected workspace                                 |
| `nevia.in_workspace(id)`  | `Nevia` scoped to another workspace, on the same connections |

### Computers

| Method                         | Description                                                 |
| ------------------------------ | ----------------------------------------------------------- |
| `computers().create()`         | Builder for a new computer, created when awaited            |
| `computers().get(id).await`    | Get a computer by ID                                        |
| `computers().find(name).await` | First computer whose name is exactly `name`, as an `Option` |
| `computers().list()`           | `Stream` over every computer in the workspace               |

The `create()` builder takes these methods before you await it:

| Builder method        | Description                                              |
| --------------------- | -------------------------------------------------------- |
| `image(image)`        | OCI image the computer runs                              |
| `name(name)`          | Name, unique in the workspace                            |
| `env(name, value)`    | Stored environment variable (call it once per variable)  |
| `from_checkpoint(id)` | Start from a checkpoint instead of an image              |
| `wait(bool)`          | Wait until the computer is ready (default `true`)        |
| `key(key)`            | Idempotency key, so repeated creates return one computer |

`list()` narrows with `.field("state", "sleeping")` and yields
`Result<Computer>` items, so import `futures::TryStreamExt` to collect it.

Awaiting `create()` returns a `Computer`. If the wait for the computer to
become ready fails, the computer still exists. The error's `resource()` holds
its record, and `computers().left_by(&error)` returns a `Computer` to delete.

On a computer:

| Member            | Description                                                        |
| ----------------- | ------------------------------------------------------------------ |
| `id()`            | Computer ID                                                        |
| `info()`          | `Option<&ComputerInfo>`, the record as last read                   |
| `refresh().await` | Fetch the latest `ComputerInfo`                                    |
| `sleep().await`   | Sleep the computer and wait until it is sleeping                   |
| `wake().await`    | Wake the computer and wait until it is ready                       |
| `ready().await`   | Wake it if asleep and wait until it can run commands               |
| `branch(name)`    | Builder for a branch of the computer (`name` is an `Option<&str>`) |
| `delete().await`  | Delete the computer (succeeds if it is already gone)               |

`ComputerInfo` has `id`, `name`, `state`, `image`, `url`, `protected` and more.
`state` is a `ComputerState` that maps to a
[lifecycle state](https://nevia.cloud/docs/reference/computer-lifecycle.md).

A branch is a new computer. Awaiting `branch(name)` creates it, and it takes
`wait(bool)` and `key(key)` like `create()`. The SDK does not delete it for
you, so call `delete()` on the branch when you are done.

### Exec

```rust
computer.exec(command)
    .cwd(dir)
    .env(name, value)
    .envs(vars)
    .stdin(text)
    .timeout(duration)
    .direct()
    .await?
```

`exec()` runs a command to completion and returns an `ExecOutput` when
awaited.

| Argument or method        | Description                                                          |
| ------------------------- | -------------------------------------------------------------------- |
| `command`                 | Shell string (runs under `sh -c`), or a list of arguments            |
| `cwd(dir)`                | Absolute working directory on the computer                           |
| `env(name, value)`        | Extra environment variable for this command                          |
| `envs(vars)`              | Extra environment variables from an iterator of pairs                |
| `stdin(text)`             | Text sent to the command's standard input (up to 1 MiB)              |
| `timeout(duration)`       | `Duration` before the command is stopped (whole seconds, rounded up) |
| `direct()`                | Run with direct exec instead of through the API                      |
| `max_output_bytes(bytes)` | Bytes kept from the end of each stream with direct exec              |

When the timeout passes, the SDK stops the command's process group and returns
the output so far with `timed_out` set to `true`.

Exec runs through the API by default, which ends a request after about 50
seconds. Direct exec sends the command straight to the computer instead, so it
suits longer commands. It keeps the last 64 KiB of each output stream and sets
`truncated` when it drops output. See [Limits and workarounds](https://nevia.cloud/docs/reference/sdk/limits.md).

| `ExecOutput` field | Description                                 |
| ------------------ | ------------------------------------------- |
| `exit_code`        | Exit code of the command                    |
| `signal`           | Signal that ended the command (0 when none) |
| `stdout`, `stderr` | Output of the command, as `String`          |
| `timed_out`        | Whether `timeout` stopped the command       |
| `truncated`        | Whether direct exec dropped output          |

`ExecOutput::success()` returns `true` when `exit_code` and `signal` are 0 and
the command did not time out.

### Files

`computer.files()` reads and writes files on the computer. Every path is a path
on the computer.

| Method                    | Description                                                            |
| ------------------------- | ---------------------------------------------------------------------- |
| `read(path).await`        | File content as `Option<Vec<u8>>`, `None` when there is no file        |
| `read_text(path).await`   | File content as `Option<String>`, `None` when there is no file         |
| `write(path, data).await` | Write a whole file from any `AsRef<[u8]>`, creating parent directories |
| `remove(path)`            | Builder that removes a file when awaited                               |

`remove(path)` takes `recursive()` for a directory tree and `force()` to ignore
a path that is not there.

`write()` replaces the file in one step, so a reader never sees it half
written. `read_text()` fails with the code `not_text` when the file is not
UTF-8. A failed read, write or remove fails with the code `command_failed`.

### Errors

Every SDK and API error is a `nevia::Error`. A command that exits nonzero is a
result, not an error.

```rust
use nevia::{Client, Nevia};

#[tokio::main]
async fn main() -> nevia::Result<()> {
    let nevia = Nevia::new(Client::from_env()?);
    match nevia.computers().get("01d4cnjk3xg90y576w8y6t4gdwm").await {
        Ok(computer) => println!("Found {}", computer.id()),
        Err(error) if error.is("not_found") => println!("No such computer"),
        Err(error) => return Err(error),
    }
    Ok(())
}
```

| Method           | Description                                                       |
| ---------------- | ----------------------------------------------------------------- |
| `status()`       | HTTP status (0 when the call failed before an answer)             |
| `code()`         | Error code, such as `not_found` or `invalid_state`                |
| `message()`      | Message for a person to read                                      |
| `details()`      | Extra facts about the error, as a JSON map                        |
| `op()`           | Name of the operation that failed                                 |
| `request_id()`   | `Option<&str>` API request ID to quote when you report a problem  |
| `retry_after()`  | `Option<f64>` seconds to wait before retrying                     |
| `resource()`     | `Option<&Value>` record of what the call created before it failed |
| `is(code)`       | Whether the code is `code`                                        |
| `is_transport()` | Whether the request may not have reached the API                  |

New codes can appear, so treat a code you don't recognise as a generic
failure.
