# TypeScript SDK

> Install the TypeScript 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/typescript

The TypeScript SDK runs computers from Node.js code. One `Nevia` client holds
the credentials and the workspace, and every method returns a promise. 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:

* Node.js 22.23.4 or later on 22, or 24.22.1 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:

**npm**

```bash
npm init -y
npm pkg set type=module
npm install ./vendor/nevia-sdk-0.1.0/typescript/nevia-sdk-0.1.0.tgz
npm install --save-dev tsx
```

**pnpm**

```bash
pnpm init
pnpm pkg set type=module
pnpm add ./vendor/nevia-sdk-0.1.0/typescript/nevia-sdk-0.1.0.tgz
pnpm add --save-dev tsx
```

The quick start runs with [tsx](https://tsx.is). `type=module` lets the
example use top-level `await`.

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

```ts
import { Nevia } from '@nevia/sdk'

const nevia = new Nevia()
const computer = await nevia.computers.create({ image: 'docker.io/library/node:24-slim' })

try {
  console.log(`Computer: ${computer.id}`)

  const result = await computer.exec('node --version')
  console.log(`Exit code: ${result.exitCode}, output: ${result.stdout.trim()}`)

  await computer.files.write('/tmp/hello.txt', 'Hello from Nevia!\n')
  process.stdout.write(await computer.files.readText('/tmp/hello.txt'))
} finally {
  await computer.delete()
}
```

Run it:

```bash
npx tsx quickstart.ts
```

The computer ID and Node.js version in the output vary:

```text
Computer: 01d69b2m9d26k14b244xjwmp9mb
Exit code: 0, output: v24.22.2
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.exitCode` and `result.signal` to see whether it succeeded.

## 4. Clean up

The `finally` block deletes the computer when the code above it finishes, also
when that code throws. `nevia ls` confirms the computer is gone.

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

```ts
const computer = await nevia.computers.create({ image: 'docker.io/library/node:24-slim' })
console.log(computer.id)
```

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

## Reference

### Client

```ts
new Nevia(options?: {
  baseUrl?: string
  credentials?: string | (() => Promise<string>) | { keyFile: string } | { key: string | object }
  workspace?: string
  fetch?: typeof fetch
  validate?: boolean
})
```

| Option        | Description                                                 |
| ------------- | ----------------------------------------------------------- |
| `credentials` | Token, token provider, `{ keyFile }` path or `{ key }` JSON |
| `workspace`   | Workspace ID (defaults to your only workspace)              |
| `baseUrl`     | API base URL (defaults to production)                       |
| `fetch`       | `fetch` implementation for every request                    |
| `validate`    | Check each request before sending it (default `true`)       |

The client looks for credentials in this order:

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

The client holds no connections, so there is nothing to close. Computers
keep running until you delete them.

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

### Computers

| Method                      | Description                                            |
| --------------------------- | ------------------------------------------------------ |
| `computers.create(options)` | 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 `null` |
| `computers.list(filter?)`   | Async iterator over every computer in the workspace    |

`computers.list()` is an async generator, so read it with
`for await (const computer of nevia.computers.list())`.

| `create()` option | Description                                            |
| ----------------- | ------------------------------------------------------ |
| `image`           | Image to run, such as `docker.io/library/node:24-slim` |
| `name`            | Name of the computer (generated when omitted)          |
| `env`             | Environment variables stored on the computer           |
| `protected`       | Refuse deletion until unprotected                      |
| `wait`            | Wait until the computer is ready (default `true`)      |
| `signal`          | `AbortSignal` that cancels the call                    |

`create()` returns the computer. If the computer fails to become ready, or the
wait times out or is aborted, `create()` throws a `NeviaError` and leaves the
computer behind. The error's `resource` property holds it, so call
`error.resource.delete()` to clean up.

On a computer:

| Member             | Description                                                                        |
| ------------------ | ---------------------------------------------------------------------------------- |
| `id`, `state`      | ID and [lifecycle state](https://nevia.cloud/docs/reference/computer-lifecycle.md) |
| `info`             | Full record as a `ComputerInfo`, with `name` among its fields                      |
| `files`            | File methods, listed under [Files](#files)                                         |
| `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(options?)` | Create a branch of the computer and return it                                      |
| `delete(options?)` | Delete the computer (succeeds if it is already gone)                               |

`branch()` takes `name`, `wait` and `signal`. A branch is a new computer, and
the SDK never deletes it for you, so call `delete()` on the branch when you are
done.

### Exec

```ts
computer.exec(command: string | readonly string[], options?: ExecOptions): Promise<ExecResult>
```

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

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

When `timeoutSeconds` passes, the computer stops the command's process group
and `exec()` returns the output so far with `timedOut: 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                                  |
| ------------------ | -------------------------------------------- |
| `exitCode`         | Exit code of the command                     |
| `signal`           | Signal that ended the command (0 when none)  |
| `stdout`, `stderr` | Output of the command                        |
| `timedOut`         | Whether `timeoutSeconds` stopped the command |
| `truncated`        | Whether direct exec dropped output           |

A command succeeded when `exitCode` and `signal` are 0 and `timedOut` is
`false`.

### Files

`computer.files` reads and writes files on the computer. Every path is a path
on the computer. Each method takes an optional last argument with a `signal`.

| Method                   | Description                                                                   |
| ------------------------ | ----------------------------------------------------------------------------- |
| `read(path)`             | File content as `Uint8Array`, or `null` when there is no file                 |
| `readText(path)`         | File content as a UTF-8 `string`, or `null` when there is no file             |
| `write(path, data)`      | Write a whole file from `string` or `Uint8Array`, creating parent directories |
| `remove(path, options?)` | Remove a file, or a directory tree with `recursive`                           |

`write()` replaces the file in one step, so a reader never sees it half
written. `remove()` takes `recursive` and `force`, and throws a `NeviaError`
with the code `command_failed` when the removal fails. `readText()` throws when
the file is not valid UTF-8.

### Errors

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

```ts
import { Nevia, isNeviaError } from '@nevia/sdk'

const nevia = new Nevia()

try {
  await nevia.computers.get('01d4cnjk3xg90y576w8y6t4gdwm')
} catch (error) {
  if (!isNeviaError(error, 'not_found')) throw error
  console.log('No such computer')
}
```

| 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 an object                          |
| `op`         | Name of the API operation that failed                              |
| `requestId`  | API request ID to quote when you report a problem (`null` if none) |
| `retryAfter` | Seconds to wait before retrying (`null` if the API sent none)      |

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