Remotehost Docs

TypeScript SDK

Create and operate RemoteHost sandboxes from TypeScript

The official @remotehost/sdk package is the server-side TypeScript interface to RemoteHost. It is generated from the same OpenAPI contract as the REST API, with a resource-oriented layer for commands, files, previews, metrics, sandbox lifecycle operations, and the workspaces, environments and environment templates they run in.

Install

npm install @remotehost/sdk

Requires Node.js 20 or newer. Bun, Deno, edge runtimes, and custom fetch implementations are supported when they provide the standard Fetch and Web API globals.

This page documents @remotehost/sdk 1.0.0, the first version npm serves: the client, sandbox create, retrieve and list, commands, files, previews, metrics, the sandbox lifecycle (sleep, wake, waitUntilReady, resize and destroy), vmm on create, and the remotehost.workspaces, remotehost.environments and remotehost.environmentTemplates clients. Check what you have with npm ls @remotehost/sdk.

Authenticate

Create a key and store it in your server environment. Never expose the key to browser code. Create it in the console under API keys, or with the CLI:

remote keys create --name production-backend --template platform
export REMOTEHOST_API_KEY=rh_sk_...

--template platform grants what a product backend needs to create and run sandboxes. It needs CLI 1.0.0 or newer (remote --version; upgrade with remote update). See remote keys for the other templates and scopes.

An org with no plan or trial can't create sandboxes, so start your trial first (Getting Started).

import RemoteHost from "@remotehost/sdk";

const remotehost = new RemoteHost({
  orgId: "org_123",
});

The client reads REMOTEHOST_API_KEY by default. Pass apiKey explicitly when secrets are provided by your runtime rather than environment variables.

Create a sandbox

const sandbox = await remotehost.sandboxes.create({
  projectId: "project_123",
  agent: "codex",
  profile: "agent-standard",
});

Creation waits until the sandbox is running and the agent inside it answers a request, so the next operation can run immediately. Use waitForReady: false when you want the provisioning response without polling.

const sandbox = await remotehost.sandboxes.create({
  projectId: "project_123",
  agent: "codex",
  waitForReady: false,
});

await sandbox.waitUntilReady({ timeoutMs: 5 * 60_000 });

Pass vmm to choose the VMM the sandbox runs on, qemu or firecracker. Left out, it runs on its custom template's, else its environment template's, else your org's default. On RemoteHost's hosted service the default is qemu, and VMM choice is on. A deployment where VMM choice is off refuses vmm with 400.

const sandbox = await remotehost.sandboxes.create({
  projectId: "project_123",
  agent: "codex",
  vmm: "qemu",
});

console.log(sandbox.data.vmm);

A sandbox's vmm is a plain string, so a VMM added later reads as it is. Its provider stays firecracker whatever the VMM.

Retrieve an existing sandbox when only its id is available:

const sandbox = await remotehost.sandboxes.retrieve("sandbox_123");

Run commands

const result = await sandbox.commands.run("pnpm test", {
  timeoutSeconds: 300,
});

if (result.exitCode !== 0) {
  console.error(result.stderr);
}

Commands are non-interactive and run to completion. stdout and stderr are individually bounded at 64 KiB; truncated tells you when either limit was reached. Use the CLI or terminal WebSocket for interactive PTY sessions.

Work with files

const directory = await sandbox.files.list("/code/src");
const source = await sandbox.files.readText("/code/src/index.ts");

await sandbox.files.write("/code/src/config.json", JSON.stringify({ enabled: true }));
await sandbox.files.write("/code/assets/logo.png", imageBytes);

Relative paths resolve beneath /code. Binary files are transferred as base64 internally and returned as Uint8Array by readBytes. Individual reads and writes are limited to 2 MiB.

Create previews

Team previews require a signed-in RemoteHost member. Public previews are revocable URLs for the users of your own product.

const preview = await sandbox.previews.create({
  port: 3000,
  audience: "public",
  expiresInSeconds: 3600,
  endUserId: "usr_8f21",
});

console.log(preview.url);

const links = await sandbox.previews.list();
await sandbox.previews.revoke(links[0].id);

Lifecycle and resources

await sandbox.sleep();
await sandbox.wake();
await sandbox.waitUntilReady();

const metrics = await sandbox.metrics.get();
const recommendation = await sandbox.metrics.sample();

await sandbox.resize({ vcpu: 8, memoryGb: 16, diskGb: 80 });
await sandbox.destroy();

sleep preserves a persistent sandbox's disk while releasing its machine, and returns while its snapshot is still saving. A wake before the save finishes waits for it, asking again once a second for up to snapshotWaitMs (3 minutes by default; 0 does not wait). resize takes the whole shape, vcpu, memoryGb and diskGb, even when only one of them changes. destroy permanently removes the sandbox. The older stop and resume spellings remain available but are deprecated.

Workspaces, environments and templates

An org's work is split into workspaces. Each one is internal, where your team builds, or external, the infrastructure your product runs on for your customers. The kind is set when the workspace is created and never changes. A project lives in one workspace and has its kind.

A project has environments: compute, storage and network running together. An environment is a durable disk with its checkpoints and its own git branch, remotehost/<name>, and it runs as sandboxes, one at a time under a lease. Each environment boots from one of the project's environment templates: machine size, setup script, services, ports, environment variables and egress.

The SDK has a client for each: remotehost.workspaces, remotehost.environments and remotehost.environmentTemplates. Not all of it is open yet. Said plainly:

  • Workspaces are not generally available. The workspace API is off until it is enabled for a deployment, and every remotehost.workspaces call fails with a 404 until then. Once it is on, an API key pinned to a workspace can retrieve that one workspace; any other workspace answers the same 404 as one that does not exist. Listing workspaces and every write are refused to API keys with 403, and a key with no workspace pin cannot call it at all.
  • A key pinned to a workspace reaches only that workspace's projects. A project in any other workspace, and everything in it (its environments, environment templates, sandboxes and agent sessions, and a terminal into one of its sandboxes), answers 404, the same as one that does not exist. Lists leave them out. Reading another workspace's usage limit or end users answers 404 too. What is answered for the whole org, such as the subscription and the org's usage, is refused with 403 and the code workspace_pinned.
  • API keys reach environments only where the deployment enables it. Key access to environments is off until it is enabled for a deployment. Until then every remotehost.environments call made with an API key fails with 403, as it always has. A signed-in user is unaffected either way.
  • Once it is on, an API key reaches only its owner's environments. The owner is the person who minted the key, or the service account it acts as. The key lists only those environments, and an environment it creates belongs to that owner. Anyone else's environment answers 404, the same as one that does not exist. Each call needs the scope its route checks: sandbox.read to list and retrieve, sandbox.create to create, update, attach or fork, and sandbox.stop to detach. A missing scope fails with 403. The platform key template holds all of them. A sandbox's own Claims key never reaches environments.
  • Another owner's environment's runs are hidden from a key. The sandboxes and agent sessions that are another owner's environment's runs are left out of sandboxes.list and the session lists, and answer 404 by id, whether or not key access to environments is on.
  • Deleting an environment needs a key minted for it. With key access on, environments.delete needs the sandbox.environment.delete scope, named in the key's own scopes. No key template includes it, and a key with no scopes does not hold it either. Without it the call fails with 403. Mint the key with the platform scopes plus sandbox.environment.delete. The person or service account behind the key must also be able to delete environments in the project (owners, admins and project admins can).
  • Fork is off unless it is enabled for the deployment; while off it fails with 404.
  • Deleting an environment template is not open to API keys. List, create, retrieve and update are.

Workspaces

const workspaces = await remotehost.workspaces.list();

const workspace = await remotehost.workspaces.create({
  name: "Customer infrastructure",
  kind: "external",
});

await remotehost.workspaces.update(workspace.id, { name: "Tenant infrastructure" });
await remotehost.workspaces.delete(workspace.id);

slug is optional on create and is derived from the name when left out. update changes the name or slug, never the kind. An org's default workspaces (is_default), where a project lands when it names none, cannot be deleted, and neither can a workspace that still holds projects. A project reports its workspace as workspace_id and its kind as workspace_kind.

Environment templates

const { environmentTemplate } = await remotehost.environmentTemplates.create({
  projectId: "project_123",
  name: "web",
  machineSize: "default",
  setupScript: "pnpm install",
  services: [{ name: "dev", command: "pnpm dev", port: 3000 }],
  ports: [3000],
  egressPolicy: "trusted",
});

const templates = await remotehost.environmentTemplates.list({ projectId: "project_123" });

The setup script runs from /code on every fresh or cold boot, after the checkout and before the agent, for at most 30 minutes, so it must be safe to run twice on the same disk. Services are long-running foreground commands started after it; they are still rolling out, so not every host starts them yet. ports lists each port with a team preview; nothing is made public. egressPolicy is none, trusted (the default: package registries, git providers and model APIs, plus egressAllowlist), full, or custom (egressAllowlist only).

A change to the network rules is pushed to the running sandboxes held to them, and the result says what happened:

const { egressPropagation } = await remotehost.environmentTemplates.update(environmentTemplate.id, {
  projectId: "project_123",
  egressPolicy: "custom",
  egressAllowlist: ["registry.npmjs.org", "*.example.com"],
});

for (const sandbox of egressPropagation?.failed ?? []) {
  console.warn(sandbox.name, sandbox.error, sandbox.stopped ? "stopped" : "still on old rules");
}

applied lists the sandboxes now enforcing the new rules, failed the ones the push could not reach (each stopped instead where possible), and notRunning the ones already gone. Deleting a template is refused with 409 while an environment names it; sandboxes still booting from it keep it until the last of them is deleted (keptForSandboxes).

Environments

const environment = await remotehost.environments.create({
  projectId: "project_123",
  name: "feature-x",
  environmentTemplateId: environmentTemplate.id,
});

const { sandbox, attached } = await remotehost.environments.attach(environment.id, {
  projectId: "project_123",
  agent: "codex",
});

await sandbox.waitUntilReady();
await sandbox.commands.run("pnpm test");

await remotehost.environments.detach(environment.id, { projectId: "project_123" });

A new environment starts asleep with no sandbox. Its name fixes its git branch, and a later rename does not move it. Leave out environmentTemplateId, or pass null, to follow the project's default template; naming another one is refused with 403 environment_enforced when the project enforces its default. On the environment the API returns, the template is in the environmentId field.

An environment's VMM is fixed when it is made: vmm on create, else its environment template's, else the VMM its environment template's custom template is built for, else your org's default. The environment template's VMM is only a default, which vmm on create overrides; a vmm other than its custom template's is refused with 409 vmm_mismatch. Every sandbox attach gives it runs on that VMM, and a fork runs on its checkpoint's. Environment templates take vmm too, a VMM or null; one whose custom template is built for another VMM is refused with 409 vmm_mismatch.

attach returns the same Sandbox object as sandboxes.create. attached says how it got one: created, resumed (a sleeping sandbox woken), existing (already running), or takeover. detach saves the sandbox and stops it, resolves once the stop is under way, and releases the lease when the snapshot commits. Calling it again is harmless.

The lease keeps one sandbox per environment. While another sandbox is starting or stopping, attach fails with 409 workspace_leased; retry shortly. When the host running it has stopped answering, it fails with 409 lease_expired, and takeover: true moves the environment to a new sandbox restored from its last saved snapshot. recovery on the result says what was restored and what was lost.

const { environment: copy, forkedFrom } = await remotehost.environments.fork(environment.id, {
  projectId: "project_123",
  name: "feature-x-retry",
});

await remotehost.environments.delete(environment.id, { projectId: "project_123" });

fork makes a new environment in the same project that starts as a copy of this one at a durable checkpoint, its head unless you pass checkpointId, uncommitted work included. Only the environment's owner can fork it. delete destroys the environment's sandboxes and loses uncommitted work; a sandbox that cannot be destroyed yet is listed in executionsPendingCleanup and destroyed once it can be.

Errors, retries, and cancellation

import { RemoteHostAPIError } from "@remotehost/sdk";

try {
  await sandbox.commands.run("pnpm test");
} catch (error) {
  if (error instanceof RemoteHostAPIError) {
    console.error(error.status, error.code, error.requestId, error.message);
  }
  throw error;
}

code is set when the API has a machine-readable reason: rate_limited and limit_reached for plan limits; plan_required (402) when the org has no plan or trial yet, or for a profile the plan does not include; snapshot_in_progress for a wake whose snapshot is still saving after snapshotWaitMs; and host_unavailable (503) when the sandbox's host is restarting, draining or unreachable.

The SDK retries transient GET and HEAD failures twice with exponential backoff and honors Retry-After. Mutating requests are replayed in one case only: a 503 host_unavailable with retryable: true, which the API sends only when it changed nothing, so a create or wake is safe to send again. Those are retried with Retry-After for up to hostUnavailableRetryMs (60 seconds by default; 0 turns it off). A host_unavailable with retryable: false means the request may have been partly carried out: check the sandbox's status before trying again. Configure retries globally with maxRetries and hostUnavailableRetryMs, or cancel an individual operation with signal or timeoutMs.

const remotehost = new RemoteHost({
  orgId: "org_123",
  maxRetries: 3,
  hostUnavailableRetryMs: 2 * 60_000,
  timeoutMs: 10 * 60_000,
});

await sandbox.files.read("large.log", { timeoutMs: 30_000 });

See the API Reference for the underlying REST operations and the Platform Guide for multi-tenant product architecture.

On this page