> ## Documentation Index
> Fetch the complete documentation index at: https://vms.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK reference

> The client options, the methods for each API route, the helpers, the errors, and the webhook check of @vms.dev/sdk.

For a first script, see [Use a sandbox from TypeScript](https://vms.dev/docs/sdk-quickstart.md).

## Install

```bash theme={null}
npm install @vms.dev/sdk
```

The package is an ES module with its TypeScript types. It runs on Node.js 22 or later and on Bun. The `ssh` helper also needs OpenSSH.

## Client

```typescript TypeScript theme={null}
import { Vms } from "@vms.dev/sdk";

const vms = new Vms({ apiKey: process.env.VMS_API_KEY });
```

| Option | Default | Value |
| - | - | - |
| `apiKey` | `VMS_API_KEY` | The API key. |
| `baseUrl` | `VMS_API_URL`, then `https://vms.dev/api` | The base URL of all routes. The command and file routes use the same base URL. |
| `fetch` | `globalThis.fetch` | The `fetch` function for each request. |
| `ssh` | `ssh.vms.dev`, port 22, and its host key | The `host`, `port`, and `hostKey` of the SSH proxy. |

## Methods for the API routes

The client has one method for each route of the [API reference](https://vms.dev/docs/api-reference/introduction.md). The method name is the operation ID of the route, such as `createSandbox` for `POST /v1/sandboxes`. The types come from the OpenAPI document.

Each method takes one object:

| Field | Value |
| - | - |
| Path parameters | By name, such as `id` and `commandId`. |
| Query parameters | By name, such as `limit`, `state`, and `path`. |
| Headers | In camel case, such as `idempotencyKey`. |
| `body` | The request body. For a file or a tar, a `string`, `Blob`, `ArrayBuffer`, `Uint8Array`, or `ReadableStream`. |

The second argument can have a `signal` to cancel the request.

```typescript TypeScript theme={null}
const page = await vms.listSandboxes({ state: ["running"], limit: 20 });

const sandbox = await vms.updateSandbox({
  id: page.data[0].id,
  body: { state: "stopped" },
});
```

| Answer | Return value |
| - | - |
| JSON | The parsed body. |
| NDJSON stream | An `NdjsonStream` that you read with `for await`. |
| File content | The `Response`. Read it with `text()`, `arrayBuffer()`, or `body`. |
| `204` | Nothing. |

## Helpers

| Helper | What it does | Return value |
| - | - | - |
| `waitUntilRunning(sandboxId, options?)` | Reads the sandbox until it is `running`. | The sandbox. |
| `exec(sandboxId, command, options?)` | Runs a command and streams its events. | A `CommandRun`. |
| `attach(sandboxId, commandId, options?)` | Reads the events of a command again, also a detached command. | A `CommandRun`. |
| `writeFiles(sandboxId, files, options?)` | Writes files in one tar upload. | The tar upload. |
| `ssh(sandboxId, options?)` | Adds your public key to the sandbox, then runs `ssh` through the SSH proxy. | The exit code, stdout, and stderr. |
| `fork(sandboxId, options?)` | Makes one or more forks of a sandbox. | A list of the forks. |
| `saveTemplate(sandboxId, name, options?)` | Saves the sandbox as a template, then reads the template until it is `ready`. | The template. |
| `waitUntilTemplateReady(templateId, options?)` | Reads the template until it is `ready`. | The template. |
| `latestSnapshot(sandboxId, options?)` | Reads the newest snapshot of a sandbox. | The snapshot, or `null` if the sandbox has no snapshot. |
| `readSnapshotFile(snapshotId, path, options?)` | Reads one file of a snapshot. For a folder, it reads a tar of the folder. | The bytes as a `Uint8Array`. |
| `desktop(sandboxId, options?)` | Makes a desktop link for a running sandbox. | The desktop session, with its `url`. |

### waitUntilRunning

| Option | Default | Value |
| - | - | - |
| `timeoutMs` | `120000` | The time to wait. |
| `intervalMs` | `1000` | The time between two reads. After a `429`, the wait doubles, up to 30 s, and is never shorter than `Retry-After`. |
| `signal` | | Cancels the wait. |

It throws a `SandboxWaitError` at the time limit, or when the sandbox is `stopped`, `error`, `failed`, `deleting`, or `deleted`. The error has the last `sandbox`.

### exec and attach

`command` is a string, which runs with `bash -lc`, or a list of the program and its arguments. The `exec` options are `cwd`, `env`, `timeoutSeconds`, `stdin`, and `signal`. The `attach` options are `after`, the last `seq` that you read, and `signal`.

| `CommandRun` member | Value |
| - | - |
| `commandId` | The ID of the command. |
| `for await (const event of run)` | Each event: `started`, `stdout`, `stderr`, and `exit`. You can read the events one time. |
| `wait()` | The `exitCode`, `signal`, `oomKilled`, `timedOut`, and the full `stdout` and `stderr` as text. |
| `writeStdin(data)` | Sends a string or bytes. Start the command with `stdin: true`. |
| `closeStdin()` | Closes stdin. |
| `kill(signal?)` | Kills the command. The default signal is `SIGKILL`. |
| `cancel()` | Closes the stream. A command that is not detached gets `SIGKILL`. |

### writeFiles

Each file has an absolute `path`, a `content` as a string or bytes, and an optional `mode`, such as `"0755"`. A new file gets `0644`. The SDK sends the files as one gzip tar to the deepest folder that holds all of them. Send `gzip: false` to send a tar without gzip. The tar can be up to 128 MiB.

### ssh

| Option | Default | Value |
| - | - | - |
| `identityFile` | `~/.ssh/id_ed25519` | The private key for `ssh -i`. |
| `publicKey` | The content of `<identityFile>.pub` | The public key to add to the sandbox. |
| `command` | | The command to run. Leave it out to open a shell. |
| `args` | | More `ssh` arguments, such as `["-L", "3000:localhost:3000"]`. |
| `stdio` | `inherit` | `pipe` collects stdout and stderr. |
| `keyTimeoutMs` | `30000` | The time to wait until the sandbox accepts a new key. |

The sandbox must be `running`. The user name is the name of the sandbox, or its ID if it has no name. `ssh` checks the host key of `ssh.vms.dev`, so you get no prompt to trust the host.

When `ssh` adds a new key, it throws `SshError` if the first connection fails:

| Message | Cause |
| - | - |
| `Could not connect to ssh.vms.dev. Check your network.` | Your computer cannot find or reach `ssh.vms.dev`. It throws at once. |
| `The sandbox did not accept the SSH key` | The sandbox refused the key for `keyTimeoutMs`. |
| `Could not open SSH to the sandbox` | A different failure. The message gives the `ssh` error. |

### fork

```typescript TypeScript theme={null}
const forks = await vms.fork(sandbox.id, { count: 3 });

await Promise.all(forks.map((fork) => vms.waitUntilRunning(fork.id)));
```

The options are the fields of `POST /v1/sandboxes`, without `fromSandbox` and `template`: such as `count`, `freshSnapshot`, `name`, `size`, and `labels`. Also `idempotencyKey` and `signal`. `fork` does not wait until the forks are `running`. See [Fork a sandbox](https://vms.dev/docs/sandboxes/fork.md).

### saveTemplate and waitUntilTemplateReady

```typescript TypeScript theme={null}
const template = await vms.saveTemplate(sandbox.id, "node-base");

await vms.createSandbox({ body: { size: "small", template: template.name } });
```

The options are `timeoutMs`, `intervalMs`, and `signal`, as for `waitUntilRunning`. The default time limit is 30 minutes. They throw a `TemplateWaitError` at the time limit, or when the template is `failed`. The error has the last `template`. See [Save a sandbox as a template](https://vms.dev/docs/sandboxes/templates.md).

### latestSnapshot and readSnapshotFile

```typescript TypeScript theme={null}
const snapshot = await vms.latestSnapshot(sandbox.id);

if (snapshot) {
  const bytes = await vms.readSnapshotFile(snapshot.id, "/home/user/notes.md");

  console.log(new TextDecoder().decode(bytes));
}
```

`latestSnapshot` needs the `sandboxes:read` scope. `readSnapshotFile` needs `snapshots:read`. To list a folder, use `getSnapshotTree`. To stream the whole snapshot as a tar, use `downloadSnapshot`. See [Read the files of a snapshot](https://vms.dev/docs/sandboxes/snapshot-files.md).

### desktop

```typescript TypeScript theme={null}
const session = await vms.desktop(sandbox.id);

console.log(session.url);
```

Open the `url` in a browser within 10 minutes. The option `mode` is `desktop`, the default, or `browser` to show only the Chrome window. See [See the desktop of a sandbox](https://vms.dev/docs/sandboxes/desktop.md).

## Errors

When the API answers with an error, the method throws a `VmsError`:

| Field | Value |
| - | - |
| `status` | The HTTP status, such as `409`. |
| `code` | The error code, such as `sandbox_not_running` or `no_capacity`. |
| `message` | The error message. |
| `requestId` | The ID of the request, or `null`. |
| `retryAfterSeconds` | The time to wait before a new try, or `null`. |
| `sandboxId` | The sandbox of the error, or `null`. |

```typescript TypeScript theme={null}
import { VmsError } from "@vms.dev/sdk";

try {
  await vms.createSandbox({ body: { size: "small" } });
} catch (error) {
  if (error instanceof VmsError && error.code === "no_capacity") {
    console.log("Try again in", error.retryAfterSeconds, "seconds");
  }
}
```

See the [error codes](https://vms.dev/docs/api-reference/introduction.md#errors).

## Webhooks

`readWebhook(request, secret)` checks the signature and the time of a webhook request, and returns the event. It throws a `WebhookSignatureError` if the signature is not correct or the request is older than 5 minutes. `verifyWebhook()` and `WEBHOOK_HEADERS` are also exported.

```typescript TypeScript theme={null}
import { readWebhook } from "@vms.dev/sdk";

export async function POST(request: Request) {
  const event = await readWebhook(request, process.env.VMS_WEBHOOK_SECRET!);

  console.log(event.type, event.data.sandbox.id);

  return new Response(null, { status: 204 });
}
```

See [Webhook events](https://vms.dev/docs/reference/webhook-events.md).

Read the [changelog.](https://vms.dev/docs/changelog.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.