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

# TypeScript SDK Reference

> Classes, methods, options, and response types in the latest @run-cloud/sdk release.

This is the reference for the latest `@run-cloud/sdk` release. The SDK controls
iOS simulator sessions, Android emulator sessions, microVM sandboxes,
snapshots, reusable app assets, usage, and run.cloud account state from Node.js
20 or newer.

```bash theme={null}
npm install @run-cloud/sdk
```

For an end-to-end introduction, see the
[TypeScript SDK guide](/cli/typescript-sdk).

## Client

```ts theme={null}
import { Client } from "@run-cloud/sdk";

const cloud = new Client();
```

### Constructor

```ts theme={null}
new Client(options?: ClientOptions)
```

| Option   | Type           | Default                                         |
| -------- | -------------- | ----------------------------------------------- |
| `apiKey` | `string`       | `RUN_CLOUD_API_KEY`, then `RUN_CLOUD_API_TOKEN` |
| `apiUrl` | `string`       | `RUN_CLOUD_API_URL`, then the production API    |
| `fetch`  | `typeof fetch` | The runtime's global `fetch` implementation     |

The client exposes:

| Property or method  | Type                   | Description                                                      |
| ------------------- | ---------------------- | ---------------------------------------------------------------- |
| `ios`               | `SimulatorClient`      | Operate iOS simulator sessions.                                  |
| `android`           | `SimulatorClient`      | Operate Android emulator sessions.                               |
| `simulators`        | `SimulatorsClient`     | Select the platform at runtime.                                  |
| `sandboxes`         | `SandboxClient`        | Create and operate microVM sandboxes.                            |
| `snapshots`         | `SnapshotsClient`      | List, restore, and delete snapshots.                             |
| `assets`            | `AssetsClient`         | Upload, list, and delete app assets.                             |
| `account()`         | `Promise<Account>`     | Read account access, organizations, balance, and metering state. |
| `usage({ orgId? })` | `Promise<UsageReport>` | Read usage totals, optionally for one organization.              |

## Compatibility adapters

Compatibility adapters are subpath exports of `@run-cloud/sdk`; no second npm
package or scope is required.

| Provider           | Import                              |
| ------------------ | ----------------------------------- |
| Modal              | `@run-cloud/sdk/compat/modal`       |
| E2B                | `@run-cloud/sdk/compat/e2b`         |
| Daytona            | `@run-cloud/sdk/compat/daytona`     |
| Vercel Sandbox     | `@run-cloud/sdk/compat/vercel`      |
| Blaxel             | `@run-cloud/sdk/compat/blaxel`      |
| Fly Sprites        | `@run-cloud/sdk/compat/sprites`     |
| Cloudflare Sandbox | `@run-cloud/sdk/compat/cloudflare`  |
| CodeSandbox        | `@run-cloud/sdk/compat/codesandbox` |
| Fly Machines       | `@run-cloud/sdk/compat/fly`         |

Adapters preserve the provider's familiar entry point for core sandbox
creation, lookup/listing, synchronous command execution, lifecycle, and
destruction. Provider-specific functionality without a public run.cloud
equivalent throws `UnsupportedCompatibilityFeatureError`; unsupported methods
never return a fabricated success.

## SimulatorClient

`cloud.ios` and `cloud.android` expose the same methods:

| Method             | Returns                            | Description                                                              |
| ------------------ | ---------------------------------- | ------------------------------------------------------------------------ |
| `create(options?)` | `Promise<SimulatorSession>`        | Create a session for the client's platform.                              |
| `list(options?)`   | `Promise<SimulatorSession[]>`      | List active sessions; pass `{ all: true }` to include released sessions. |
| `get(id)`          | `Promise<SimulatorSession>`        | Get the latest state for one session.                                    |
| `openUrl(id, url)` | `Promise<Record<string, unknown>>` | Open an HTTP URL or app deep link.                                       |
| `delete(id)`       | `Promise<SimulatorSession>`        | Release the session and stop future metering.                            |

`cloud.ios` additionally exposes:

| Method                                       | Returns                          | Description                                                           |
| -------------------------------------------- | -------------------------------- | --------------------------------------------------------------------- |
| `screenshot(id)`                             | `Promise<Uint8Array>`            | Capture the current simulator display.                                |
| `uploadVideo(id, video, options?)`           | `Promise<VideoUploadResult>`     | Upload MP4 or QuickTime video and make it available to the simulator. |
| `uploadMicrophoneAudio(id, audio, options?)` | `Promise<MicrophoneAudioResult>` | Upload AAC, M4A, MP3, MP4 audio, or WAV for microphone playback.      |

### CreateSessionOptions

| Property            | Type                            | Description                                                 |
| ------------------- | ------------------------------- | ----------------------------------------------------------- |
| `model`             | `string`                        | Requested device model.                                     |
| `region`            | `string`                        | Requested fleet region.                                     |
| `displayName`       | `string`                        | Human-readable session name.                                |
| `labels`            | `Record<string, string>`        | Session metadata.                                           |
| `installAssets`     | `string[]`                      | Asset IDs to install during creation.                       |
| `inactivityTimeout` | `string \| null`                | Idle timeout such as `"60s"` or `"3m"`; `null` disables it. |
| `hardTimeout`       | `string \| null`                | Maximum lifetime such as `"10m"` or `"1h"`.                 |
| `codec`             | `"auto" \| "mjpeg" \| "webrtc"` | Viewer stream preference.                                   |

Always release metered sessions in `finally`:

```ts theme={null}
const session = await cloud.ios.create({ inactivityTimeout: "60s" });

try {
  await cloud.ios.openUrl(session.id, "https://run.cloud");
  console.log(session.url);
} finally {
  await cloud.ios.delete(session.id);
}
```

## SimulatorsClient

Use `cloud.simulators` when the platform is chosen at runtime.

| Method                             | Description                       |
| ---------------------------------- | --------------------------------- |
| `create({ platform, ...options })` | Create an iOS or Android session. |
| `list({ platform, all })`          | List sessions for one platform.   |
| `get(id, { platform })`            | Get a session.                    |
| `openUrl(id, url, { platform })`   | Open a URL or deep link.          |
| `delete(id, { platform })`         | Release a session.                |

`platform` is `"ios" | "android"` and defaults to `"ios"`.

## SandboxClient

Use `cloud.sandboxes` to create and operate microVM sandboxes through the same
run.cloud API key as the CLI.

| Method                        | Returns               | Description                                   |
| ----------------------------- | --------------------- | --------------------------------------------- |
| `create(options?)`            | `Promise<Sandbox>`    | Create a sandbox.                             |
| `list({ state? })`            | `Promise<Sandbox[]>`  | List sandboxes, optionally filtered by state. |
| `get(id)`                     | `Promise<Sandbox>`    | Get the latest sandbox state.                 |
| `exec(id, command, options?)` | `Promise<ExecResult>` | Run a shell string or argument array.         |
| `readFile(id, path)`          | `Promise<Uint8Array>` | Download a file without text conversion.      |
| `snapshot(id, { label? })`    | `Promise<Snapshot>`   | Capture a restorable snapshot.                |
| `destroy(id)`                 | `Promise<void>`       | Destroy a sandbox.                            |
| `delete(id)`                  | `Promise<void>`       | Alias for `destroy(id)`.                      |

### CreateSandboxOptions

| Property           | Type     | Description                                                           |
| ------------------ | -------- | --------------------------------------------------------------------- |
| `image`            | `string` | Base image reference.                                                 |
| `cpu`              | `number` | Fractional vCPU allocation.                                           |
| `memory`           | `number` | Memory allocation in MiB.                                             |
| `disk`             | `number` | Writable disk quota in GiB.                                           |
| `idlePauseSeconds` | `number` | Automatically pause after this many idle seconds.                     |
| `region`           | `string` | Requested placement region.                                           |
| `name`             | `string` | Human-readable name.                                                  |
| `orgId`            | `string` | Owning and billing organization.                                      |
| `idempotencyKey`   | `string` | Retry-safe create key; repeated requests return the original sandbox. |

### ExecOptions

| Property         | Type                     | Description                            |
| ---------------- | ------------------------ | -------------------------------------- |
| `cwd`            | `string`                 | Working directory inside the sandbox.  |
| `env`            | `Record<string, string>` | Environment variables for the command. |
| `timeoutSeconds` | `number`                 | Command timeout in seconds.            |

A string command runs through `/bin/sh -c`; pass a string array to execute the
arguments directly:

```ts theme={null}
import { writeFile } from "node:fs/promises";

const sandbox = await cloud.sandboxes.create({
  image: "runcloud/agent-base",
  cpu: 4,
  memory: 8192,
  disk: 40,
});

try {
  const result = await cloud.sandboxes.exec(
    sandbox.id,
    ["npm", "run", "build"],
    { cwd: "/workspace" },
  );
  console.log(result.exitCode, result.stdout);
  const report = await cloud.sandboxes.readFile(sandbox.id, "/workspace/report.json");
  await writeFile("report.json", report);
} finally {
  await cloud.sandboxes.destroy(sandbox.id);
}
```

## SnapshotsClient

| Method                  | Returns               | Description                                                           |
| ----------------------- | --------------------- | --------------------------------------------------------------------- |
| `list({ sandboxId? })`  | `Promise<Snapshot[]>` | List snapshots, optionally for one sandbox.                           |
| `restore(id, options?)` | `Promise<Sandbox>`    | Create a sandbox from a snapshot; options accept `name` and `region`. |
| `delete(id)`            | `Promise<void>`       | Delete a snapshot.                                                    |

## Usage

```ts theme={null}
const usage = await cloud.usage();
```

`UsageReport.items` contains cumulative usage entries with `org_id`, `meter`,
and `seconds`.

## AssetsClient

| Method                   | Returns                         | Description                                            |
| ------------------------ | ------------------------------- | ------------------------------------------------------ |
| `upload(file, options?)` | `Promise<Asset>`                | Upload a `Blob`; options accept `name` and `filename`. |
| `list()`                 | `Promise<Asset[]>`              | List uploaded assets.                                  |
| `delete(id)`             | `Promise<{ deleted: boolean }>` | Delete an asset.                                       |

```ts theme={null}
import { readFile } from "node:fs/promises";

const contents = await readFile("./MyApp.tar.gz");
const asset = await cloud.assets.upload(
  new Blob([new Uint8Array(contents)]),
  { name: "ios-smoke", filename: "MyApp.tar.gz" },
);

const session = await cloud.ios.create({ installAssets: [asset.id] });
```

## Response types

### SimulatorSession

| Property                     | Type                     | Description                        |
| ---------------------------- | ------------------------ | ---------------------------------- |
| `id`                         | `string`                 | Session identifier.                |
| `platform`                   | `"ios" \| "android"`     | Session platform.                  |
| `status`                     | `string`                 | Current lifecycle state.           |
| `url`                        | `string \| null`         | Viewer URL when available.         |
| `model`                      | `string \| null`         | Allocated or requested model.      |
| `region`                     | `string \| null`         | Allocated region.                  |
| `displayName`                | `string \| null`         | Human-readable name.               |
| `labels`                     | `Record<string, string>` | Session labels.                    |
| `codec`                      | `string`                 | Selected stream codec.             |
| `stream`                     | `SimulatorStream`        | Viewer, host, and codec details.   |
| `createdAt`                  | `string`                 | Creation timestamp.                |
| `releasedAt`                 | `string \| null`         | Release timestamp.                 |
| `expiresAt`                  | `string \| null`         | Hard-expiration timestamp.         |
| `inactivityTimeoutSeconds`   | `number \| null`         | Configured idle timeout.           |
| `inactivityCountdownSeconds` | `number \| null`         | Remaining idle time when reported. |

The response may also include allocation, queue, device, lease, and metering
metadata.

### Asset

| Property      | Type     |
| ------------- | -------- |
| `id`          | `string` |
| `name`        | `string` |
| `filename`    | `string` |
| `contentType` | `string` |
| `byteSize`    | `number` |
| `createdAt`   | `string` |

### Sandbox

| Property    | Type             | Description                                |
| ----------- | ---------------- | ------------------------------------------ |
| `id`        | `string`         | Sandbox identifier.                        |
| `state`     | `SandboxState`   | Current lifecycle state.                   |
| `name`      | `string \| null` | Human-readable name.                       |
| `image`     | `string`         | Base image.                                |
| `region`    | `string \| null` | Placement region.                          |
| `sizeClass` | `string`         | Allocation identifier returned by the API. |
| `milliCpu`  | `number`         | CPU allocation in millicores.              |
| `memMb`     | `number`         | Memory allocation in MiB.                  |
| `orgId`     | `string`         | Owning organization.                       |
| `warmStart` | `boolean`        | Whether the sandbox used a warm start.     |
| `createdAt` | `string`         | Creation timestamp.                        |

The SDK preserves the API's raw snake\_case fields and also adds the camelCase
aliases shown above.

### ExecResult

| Property    | Type     | Description                   |
| ----------- | -------- | ----------------------------- |
| `exitCode`  | `number` | Command exit code.            |
| `exit_code` | `number` | Raw API alias for `exitCode`. |
| `stdout`    | `string` | Captured standard output.     |
| `stderr`    | `string` | Captured standard error.      |

## Errors

Non-successful API responses throw `RunCloudError`:

```ts theme={null}
import { Client, RunCloudError } from "@run-cloud/sdk";

try {
  await new Client().ios.create();
} catch (error) {
  if (error instanceof RunCloudError) {
    console.error(error.status, error.detail);
  }
  throw error;
}
```

| Property | Type     | Description                       |
| -------- | -------- | --------------------------------- |
| `status` | `number` | HTTP response status.             |
| `detail` | `string` | Error detail returned by the API. |
