# Python SDK

> Install the Python 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/python

The Python SDK runs computers from Python code. It has two clients with the
same resources and methods. `Nevia` blocks and `AsyncNevia` awaits. 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:

* Python 3.11 or later.
* 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 install the SDK from it:

**uv**

```bash
uv add ./vendor/nevia-sdk-0.1.0/python/nevia-0.1.0-py3-none-any.whl
```

**pip**

```bash
pip install ./vendor/nevia-sdk-0.1.0/python/nevia-0.1.0-py3-none-any.whl
```

## 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 `quickstart.py`:

**Sync**

```python
from nevia import Nevia

with Nevia() as nevia:
    with nevia.computers.create(image='docker.io/library/python:3.13-slim') as computer:
        print(f'Computer: {computer.id}')

        result = computer.exec('python3 --version')
        print(f'Exit code: {result.exit_code}, output: {result.stdout.strip()}')

        computer.files.write('/tmp/hello.txt', 'Hello from Nevia!\n')
        print(computer.files.read_text('/tmp/hello.txt'), end='')
```

**Async**

```python
import anyio
from nevia import AsyncNevia


async def main():
    async with AsyncNevia() as nevia:
        async with nevia.computers.create(image='docker.io/library/python:3.13-slim') as computer:
            print(f'Computer: {computer.id}')

            result = await computer.exec('python3 --version')
            print(f'Exit code: {result.exit_code}, output: {result.stdout.strip()}')

            await computer.files.write('/tmp/hello.txt', 'Hello from Nevia!\n')
            print(await computer.files.read_text('/tmp/hello.txt'), end='')


anyio.run(main)
```

Run it:

```bash
python quickstart.py
```

The computer ID and Python version in the output vary:

```text
Computer: 01d69b2m9d26k14b244xjwmp9mb
Exit code: 0, output: Python 3.13.18
Hello from Nevia!
```

`computers.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.ok` to see whether it succeeded.

## 4. Clean up

The `with` block deletes the computer when it ends, also when the code inside
it raises. `nevia ls` confirms the computer is gone.

To keep a computer after the program ends, create it without `with` and save
its ID:

```python
computer = nevia.computers.create(image='docker.io/library/python:3.13-slim')
print(computer.id)
```

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

## Reference

### Sync and async clients

`Nevia` and `AsyncNevia` have the same resources, methods and arguments. The
tables on this page list each method once and apply to both. Pick one client
per program: `Nevia` for scripts and blocking code, `AsyncNevia` for code that
already runs an event loop, such as an async web server or agent framework.

Where the two differ:

|                                           | `Nevia` (sync)                                  | `AsyncNevia` (async)                                           |
| ----------------------------------------- | ----------------------------------------------- | -------------------------------------------------------------- |
| Calling a method                          | `computer.exec(...)`                            | `await computer.exec(...)`                                     |
| Scoped client                             | `with Nevia() as nevia:`                        | `async with AsyncNevia() as nevia:`                            |
| Closing the client                        | `nevia.close()`                                 | `await nevia.aclose()`                                         |
| Deleting a computer at the end of a block | `with nevia.computers.create(...) as computer:` | `async with nevia.computers.create(...) as computer:`          |
| When `create()` creates                   | At the call                                     | When awaited or entered                                        |
| Deleting a branch at the end of a block   | Not available, call `delete()`                  | `async with computer.branch() as branch:`                      |
| Listing                                   | `for computer in nevia.computers.list():`       | `async for computer in nevia.computers.list():`                |
| Workspace ID                              | `nevia.workspace()` returns a `str`             | `await nevia.workspace()`                                      |
| `credentials=` callable                   | A plain function                                | An async function                                              |
| Deadlines                                 | `with nevia.fail_after(30):`                    | `with anyio.fail_after(30):`                                   |
| Resource classes                          | `Computer`, `Files`, `Process`, `Database`      | `AsyncComputer`, `AsyncFiles`, `AsyncProcess`, `AsyncDatabase` |

Results and errors are the same classes in both: `ExecResult`, `ComputerInfo`,
`FileStat`, `DirEntry` and `NeviaError`.

The deadline helpers bound every blocking call the SDK makes. `fail_after`
raises `TimeoutError` when the time is up, `move_on_after` ends the block
without raising and `shield()` lets cleanup run past either one:

**Sync**

```python
import nevia

with nevia.fail_after(30):
    computer.exec('npm test')
```

**Async**

```python
import anyio

with anyio.fail_after(30):
    await computer.exec('npm test')
```

### Client

```python
Nevia(
    *,
    base_url=None,
    credentials=None,
    key_file=None,
    key=None,
    workspace=None,
)
```

| Argument      | Description                                    |
| ------------- | ---------------------------------------------- |
| `credentials` | Token string, or a callable that returns one   |
| `key_file`    | Path to a service-account key file             |
| `key`         | Service-account key as JSON text or a dict     |
| `workspace`   | Workspace ID (defaults to your only workspace) |
| `base_url`    | API base URL (defaults to production)          |

The client looks for credentials in this order:

1. The `credentials`, `key_file` or `key` argument.
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` argument, then `NEVIA_WORKSPACE`, then the
only workspace you belong to.

Use the client as a context manager, or call `close()` (`aclose()` on
`AsyncNevia`) when you are done. Closing the client 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()`   | ID of the selected workspace                                |
| `nevia.workspace(id)` | Client scoped to another workspace, on the same connections |

### Computers

| Method                                                                       | Description                                            |
| ---------------------------------------------------------------------------- | ------------------------------------------------------ |
| `computers.create(*, image, name=None, env=None, protected=None, wait=True)` | Create a computer and wait until it is ready           |
| `computers.get(id)`                                                          | Get a computer by ID                                   |
| `computers.find(name)`                                                       | First computer whose name is exactly `name`, or `None` |
| `computers.list()`                                                           | Iterate over every computer in the workspace           |

`create()` returns the computer. Inside a `with` block the SDK deletes the
computer when the block ends. If the computer fails to become ready, or the
wait times out or is interrupted, `create()` deletes it before raising.

On a computer:

| Member                 | Description                                                                              |
| ---------------------- | ---------------------------------------------------------------------------------------- |
| `id`, `name`, `state`  | Identity and [lifecycle state](https://nevia.cloud/docs/reference/computer-lifecycle.md) |
| `info`                 | Full record as a `ComputerInfo`                                                          |
| `refresh()`            | Fetch the latest record                                                                  |
| `sleep()`              | Sleep the computer and wait until it is sleeping                                         |
| `wake()`               | Wake the computer and wait until it is ready                                             |
| `branch(*, name=None)` | Create a branch of the computer and return it                                            |
| `delete()`             | Delete the computer (succeeds if it is already gone)                                     |

A branch is a new computer. `AsyncNevia` deletes it at the end of an
`async with` block. With `Nevia`, call `delete()` on the branch when you are
done.

### Exec

```python
computer.exec(command, *, cwd=None, env=None, stdin=None, timeout=None, transport='api', max_output_bytes=65536)
```

`exec()` runs a command to completion and returns an `ExecResult`.

| Argument           | Description                                               |
| ------------------ | --------------------------------------------------------- |
| `command`          | Shell string (runs under `sh -c`), or a list of arguments |
| `cwd`              | Working directory on the computer                         |
| `env`              | Extra environment variables for this command              |
| `stdin`            | Text sent to the command's standard input                 |
| `timeout`          | Seconds before the command is stopped                     |
| `transport`        | `'api'` (default) or `'direct'` for direct exec           |
| `max_output_bytes` | Bytes kept from the end of each stream with direct exec   |

When `timeout` passes, the SDK stops the command's process group and returns
the output so far with `timed_out=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=True` when it drops output. See [Limits and workarounds](https://nevia.cloud/docs/reference/sdk/limits.md).

| `ExecResult` field | Description                                                                 |
| ------------------ | --------------------------------------------------------------------------- |
| `exit_code`        | Exit code of the command                                                    |
| `signal`           | Signal that ended the command (0 when none)                                 |
| `stdout`, `stderr` | Output of the command                                                       |
| `timed_out`        | Whether `timeout` stopped the command                                       |
| `truncated`        | Whether direct exec dropped output                                          |
| `ok`               | `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)`                                    | File content as `bytes`, or `None` when there is no file              |
| `read_text(path, encoding='utf-8')`             | File content as `str`, or `None` when there is no file                |
| `write(path, data)`                             | Write a whole file from `str` or `bytes`, creating parent directories |
| `stat(path)`                                    | `FileStat` with type, size and times, or `None` when nothing is there |
| `list(path, *, recursive=False, max_depth=1)`   | Entries in a directory as `DirEntry` values, sorted by name           |
| `remove(path, *, recursive=False, force=False)` | Remove a file, or a directory tree with `recursive`                   |

`write()` replaces the file in one step, so a reader never sees it half
written. `list()` raises `FileNotFoundError` for a missing path and
`NotADirectoryError` for a file.

### Errors

The SDK raises every SDK and API error as a `NeviaError`. A command that exits
nonzero is a result, not an error.

**Sync**

```python
from nevia import Nevia, NeviaError

with Nevia() as nevia:
    try:
        computer = nevia.computers.get('01d4cnjk3xg90y576w8y6t4gdwm')
    except NeviaError as error:
        if error.code != 'not_found':
            raise
        print('No such computer')
```

**Async**

```python
import anyio
from nevia import AsyncNevia, NeviaError


async def main():
    async with AsyncNevia() as nevia:
        try:
            computer = await nevia.computers.get('01d4cnjk3xg90y576w8y6t4gdwm')
        except NeviaError as error:
            if error.code != 'not_found':
                raise
            print('No such computer')


anyio.run(main)
```

| Field         | Description                                                      |
| ------------- | ---------------------------------------------------------------- |
| `status`      | HTTP status (0 when the SDK refused the call before sending it)  |
| `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 dict                           |
| `request_id`  | API request ID to quote when you report a problem                |
| `retry_after` | Seconds to wait before retrying, when the API sent one           |
| `resource`    | What the call had created before it failed, so you can delete it |

New codes can appear, so treat a code you don't recognise as a generic
failure. `is_nevia_error(error, code)` checks the type and the code in one
call.
