> ## 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

> Use the run.cloud API from Node.js, CI, and agent runtimes.

`@run-cloud/sdk` is the API-key client for iOS simulator sessions, Android
emulator sessions, microVM sandboxes, snapshots, account state, and reusable
app assets. It also packages and submits remote Xcode builds. It requires
Node.js 20 or newer.

See the [latest SDK reference](https://docs.run.cloud/sdk/latest.md) for the complete class, method,
option, and response-type index.

## Install

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

## Authenticate

Create an API key in the [run.cloud dashboard](https://run.cloud/dashboard), then expose it to
the process that runs your application:

```bash theme={null}
export RUN_CLOUD_API_KEY="rc_live_..."
```

The client reads `RUN_CLOUD_API_KEY` automatically. You can also pass the key
directly when your application loads secrets another way:

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

const cloud = new Client({ apiKey: process.env.MY_RUN_CLOUD_KEY });
```

Set `RUN_CLOUD_API_URL` or pass `apiUrl` to use a non-default API host. Do not
put API keys in source code, browser bundles, logs, or committed environment
files.

## Build an Xcode project

```ts theme={null}
import { writeFile } from "node:fs/promises";
import { Client } from "@run-cloud/sdk";

const cloud = new Client();
const submitted = await cloud.xcode.build(process.cwd(), {
  project: "MyApp.xcodeproj",
  scheme: "MyApp",
  sdk: "iphonesimulator",
  configuration: "Debug",
  idempotencyKey: `xcode-${process.env.GITHUB_SHA ?? "local"}`,
});
const completed = await cloud.xcode.wait(submitted.id, {
  onLog: (text) => process.stdout.write(text),
});

if (completed.status !== "succeeded") {
  throw new Error(`${completed.failure?.reason}\n${completed.failure?.action}`);
}
await writeFile("MyApp.tar.gz", await cloud.xcode.downloadArtifact(completed.id));
```

The returned ID remains usable after the submitting process exits. Use
`cloud.xcode.get`, `list`, `events`, `logs`, `cancel`, and `downloadArtifact` to reconnect
to the build. See [Build with Xcode](https://docs.run.cloud/ios/build-with-xcode.md) for signing, source
filters, React Native, XcodeGen, App Store upload, and lifecycle details.

For JavaScript-only Expo or React Native changes, reuse the compatible native
shell and launch the resulting immutable Asset with a stable retry key:

```ts theme={null}
const rebuilt = await cloud.xcode.rebundle(process.cwd(), completed.id, {
  idempotencyKey: `rebundle-${completed.id}-${process.env.GITHUB_SHA ?? "local"}`,
});
const ready = await cloud.xcode.wait(rebuilt.id);
if (ready.status !== "succeeded") throw new Error(ready.failure?.action);

const launch = await cloud.mobile.launch(
  { buildId: ready.id },
  { idempotencyKey: `launch-${ready.id}`, orgId: ready.orgId },
);
console.log(launch.id, launch.sessionId, launch.status);
```

Use `cloud.capabilities.create` when another process needs temporary access to
only the selected Asset, build, or launch idempotency key. Capability secrets
expire in at most one hour and can be revoked sooner.

## Run the complete example

The runnable example checks account access, creates iOS and Android sessions,
opens a URL on each platform, and releases both sessions even when the run is
interrupted or fails:

```bash theme={null}
git clone --depth 1 https://github.com/newly-app/run-cloud-examples.git
cd run-cloud-examples/sdk-ios-android
npm install
npm run demo -- --platform both --open
```

See
[newly-app/run-cloud-examples/sdk-ios-android](https://github.com/newly-app/run-cloud-examples/tree/main/sdk-ios-android)
for platform, codec, duration, and JSON-output options.

## Create and release sessions

Use the platform client when the platform is known. Always release metered
sessions in `finally` so a failed test does not leave them running:

```ts theme={null}
import { writeFile } from "node:fs/promises";
import { Client } from "@run-cloud/sdk";

const cloud = new Client();
const session = await cloud.ios.create({
  displayName: "iOS smoke",
  tags: { suite: "onboarding" },
  inactivityTimeout: "60s",
  hardTimeout: "10m",
});

try {
  const opened = await cloud.ios.openUrl(session.id, "https://run.cloud");
  console.log(opened.platform, opened.device, opened.leaseId, opened.url);
  await new Promise((resolve) => setTimeout(resolve, 3000));
  const screenshot = await cloud.ios.screenshot(session.id);
  await writeFile("run-cloud.png", screenshot);
  console.log(`Captured run-cloud.png (${screenshot.byteLength} bytes)`);
} finally {
  await cloud.ios.delete(session.id);
}
```

`cloud.ios` and `cloud.android` both provide:

| Method | Purpose |
| - | - |
| `create(options)` | Create a metered simulator or emulator session. |
| `list({ all })` | List active sessions, or include released sessions with `all: true`. |
| `get(id)` | Read the latest session state. |
| `openUrl(id, url)` | Open an HTTP(S) URL or app deep link and return a typed `SimulatorOpenUrlResult`. |
| `launchApp(id, bundleId, options)`, `terminateApp(id, bundleId, options)` | Launch or stop an installed app by bundle id or package name. See [Launch and Terminate Apps](https://docs.run.cloud/platform/app-lifecycle.md). |
| `interact(id, interaction, options)` | Send any typed simulator interaction. |
| `tap`, `swipe`, `gesture`, `typeText` | Send pointer, touch, and text input. |
| `pressKey`, `pressButton` | Press a semantic key or device button. |
| `rotate`, `reload`, `scroll` | Change orientation, reload the app, or send scroll input. |
| `toggleSoftwareKeyboard`, `simulateMemoryWarning` | Operate the on-screen keyboard or send a memory warning. |
| `rotateDigitalCrown` | Request Digital Crown input; current mobile sessions report it as unsupported. |
| `setRenderDebug` | Use iOS-only rendering controls. |
| `screenshot(id, options)` | Return the current display as PNG bytes. |
| `streamAudio(id, { signal })` | Stream stereo speaker-output PCM frames until cancelled. |
| `accessibilityTree(id, options)` | Return the current typed accessibility hierarchy. |
| `uploadCameraVideo(id, video, options)` | Loop an MP4 or QuickTime file through the app camera. |
| `uploadMicrophoneAudio(id, audio, options)` | Deliver supported prerecorded audio through the app microphone. |
| `startRecording`, `listRecordings`, `getRecording` | Start and inspect MP4 screen recordings. |
| `stopRecording`, `downloadRecording` | Finalize and download a recording. |
| `logs(id, { tail })` | Read retained entries from the current lease. |
| `followLogs(id, { signal })` | Stream new entries as an async iterable. |
| `delete(id)` | Release the session and stop future metering. |

The iOS client additionally provides:

* `uploadVideo(id, video, options)`, which accepts an MP4 or QuickTime `Blob`
  and imports it into Photos. The uploaded file remains in `cloud.assets` for
  reuse or deletion. This is distinct from `uploadCameraVideo`, which presents
  frames to the app camera.

Camera injection, microphone injection, screenshots, screen recordings,
accessibility trees, and simulator interactions are available on both platform
clients. See
[Read the Accessibility Tree](https://docs.run.cloud/platform/accessibility-tree.md) for its schema and
test patterns.

`SimulatorOpenUrlResult` contains `ok`, `platform`, `sessionId`, `device`,
`leaseId`, and the exact input `url`. Percent encoding is not normalized. See
[Open URLs and Deep Links](https://docs.run.cloud/platform/open-urls.md) for complete encoded HTTPS and
custom-scheme examples, the direct REST request, platform behavior, and errors.

## Record the display

To listen to speaker output or record it as a WAV, see
[Simulator Audio](https://docs.run.cloud/platform/simulator-audio.md). Both platform clients expose
`streamAudio(id, { signal })`; mute in a browser viewer does not affect capture.

Start and stop capture independently of the viewer stream, then download the
ready MP4 through the authenticated API:

```ts theme={null}
const recording = await cloud.ios.startRecording(session.id, {
  idempotencyKey: `ci-${process.env.CI_JOB_ID}`,
});

await cloud.ios.openUrl(session.id, "https://run.cloud");

const ready = await cloud.ios.stopRecording(session.id, recording.id);
if (ready.status !== "ready") throw new Error(`Recording is ${ready.status}`);

const mp4 = await cloud.ios.downloadRecording(session.id, recording.id);
await writeFile("run-cloud.mp4", mp4);
```

Use `listRecordings` and `getRecording` to inspect lifecycle state, failures,
events, retention, and retrieval metadata. The same methods are available on
`cloud.android` and `cloud.simulators`. See
[Record a Simulator](https://docs.run.cloud/platform/simulator-recordings.md) for retry, release,
retention, CLI, and REST details.

## Control the session

Coordinates use the current display with `{ x: 0, y: 0 }` at the top-left and
`{ x: 1, y: 1 }` at the bottom-right. Each call resolves with a correlated,
typed acknowledgement:

```ts theme={null}
const result = await cloud.ios.tap(
  session.id,
  { x: 0.5, y: 0.23 },
  { requestId: "ios.tap.1", timeoutMs: 15_000 },
);

await cloud.ios.swipe(
  session.id,
  { x: 0.5, y: 0.65 },
  { x: 0.5, y: 0.54 },
  { durationMs: 300 },
);
await cloud.ios.typeText(session.id, "Run Cloud");
await cloud.ios.pressKey(session.id, "enter");

console.log(result.requestId, result.status, result.durationMs);
```

Options accept `requestId`, `timeoutMs`, and `signal`. Aborting stops the caller
from waiting but does not release the session. Digital Crown input is unavailable
on current mobile sessions. Render-debug operations are iOS-only. Unsupported
calls fail with a typed API error.

See [Control a Simulator](https://docs.run.cloud/platform/simulator-interactions.md) for every method,
gesture payloads, keys, buttons, result types, and platform behavior.

## Inject camera and microphone media

Both platform clients upload a user-owned media asset and inject it into the
active app. Pass the target bundle/package ID so the acknowledgement identifies
the intended native receiver:

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

const video = new Blob([await readFile("./proof.mp4")], { type: "video/mp4" });
const camera = await cloud.android.uploadCameraVideo(session.id, video, {
  filename: "proof.mp4",
  bundleId: "com.example.CameraRecorder",
});
console.log(`Injecting ${camera.filename} into ${camera.bundleId}`);
```

```ts theme={null}
const audio = new Blob([await readFile("./spoken.wav")], { type: "audio/wav" });
const microphone = await cloud.android.uploadMicrophoneAudio(session.id, audio, {
  filename: "spoken.wav",
  bundleId: "com.example.AudioRecorder",
});
console.log(`Injecting ${microphone.filename} into ${microphone.bundleId}`);
```

Use `cloud.ios` in the same calls for an iOS Simulator. Camera input accepts MP4
and QuickTime. Microphone input accepts AAC, M4A, MP3, MP4-audio, and WAV. Delete
the returned `asset` through `cloud.assets.delete()` when it is no longer needed.
For an iOS Photos import instead, use `cloud.ios.uploadVideo()`.

## Use the generic simulator client

Use `cloud.simulators` when the platform is selected at runtime. Pass the
session platform back to methods that operate on an existing session:

```ts theme={null}
const session = await cloud.simulators.create({
  platform: "android",
  displayName: "Android smoke",
  codec: "auto",
});

try {
  const opened = await cloud.simulators.openUrl(
    session.id,
    "runcloudproof://open/items%2F42?message=hello%20world#proof",
    {
      platform: session.platform,
    },
  );
  console.log(opened.url);
} finally {
  await cloud.simulators.delete(session.id, {
    platform: session.platform,
  });
}
```

`cloud.simulators.list()` returns every platform unless `platform` is supplied. Other generic
simulator lifecycle and interaction methods default to iOS when `platform` is
omitted. `cloud.simulators.screenshot(id, { platform })` and
`cloud.simulators.accessibilityTree(id, { platform })` work on both platforms.

## Run the screenshot examples

The maintained iOS and Android examples build a small native app, install it in
a session, save `screenshots/run-cloud-proof.png`, validate the image, and
release the session:

```bash iOS theme={null}
git clone https://github.com/newly-app/run-cloud-examples.git
cd run-cloud-examples/ios-app-screenshot
npm install
export RUN_CLOUD_API_KEY="rc_live_..."
npm run demo -- --json
```

```bash Android theme={null}
git clone https://github.com/newly-app/run-cloud-examples.git
cd run-cloud-examples/android-app-screenshot
npm install
export RUN_CLOUD_API_KEY="rc_live_..."
npm run demo -- --json
```

Pass `--open` to open the signed viewer during the run or `--app <path>` to use
a prebuilt artifact. Building iOS requires macOS and Xcode. Building Android
requires JDK 17 or newer and Android SDK 35 or newer. The complete source is in
the [iOS example](https://github.com/newly-app/run-cloud-examples/tree/main/ios-app-screenshot)
and [Android example](https://github.com/newly-app/run-cloud-examples/tree/main/android-app-screenshot).

## Check account state

Use `account()` before starting a larger test matrix when you want to surface
access or organization information early:

```ts theme={null}
const account = await cloud.account();
console.log(account.orgs);
```

## Upload and reuse assets

Upload an artifact once, then reference its id from one or more sessions:

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

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

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

`cloud.assets` provides `upload`, `list`, and `delete`. Artifact contents must
match the target platform: iOS needs a simulator-compatible build, while
Android needs an Android-compatible artifact such as an APK.

## Handle API errors

Non-successful responses throw `RunCloudError` with the HTTP status, structured
error fields, and interaction correlation metadata when available:

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

try {
  await new Client().ios.create();
} catch (error) {
  if (isSimulatorCapacityError(error)) {
    console.error("Simulator capacity is temporarily unavailable; retry later.");
  }
  if (error instanceof RunCloudError) {
    console.error({
      status: error.status,
      code: error.code,
      message: error.detail,
      retryable: error.retryable,
      requestId: error.requestId,
      action: error.action,
      suggestedAction: error.suggestedAction,
    });
  }
  throw error;
}
```

`isSimulatorCapacityError(error)` matches only the typed, retry-safe
`simulator_capacity_unavailable` 503 response. Use a bounded retry for that
case; authentication, validation, and other service errors do not match it.
URL-opening failures use stable `invalid_url`, `active_session_not_found`,
lease scope, ended session, platform handler, timeout, and transport codes described in
[Open URLs and Deep Links](https://docs.run.cloud/platform/open-urls.md).
For these failures, `action` is the SDK operation name `"open-url"`, while
`suggestedAction` is the API's human-readable remediation.


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