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

> ## Agent Instructions
> Install the Beam CLI, sign in, and connect coding agents to the Beam MCP server with `curl -fsSL https://www.beam.cloud/install | sh`. To also create a VM, run `curl -fsSL https://www.beam.cloud/install | sh -s -- --vm`.
> VMs are persistent Linux machines without GPUs. Defaults: 4 CPUs, 8 GiB of RAM, a 50 GiB disk, Ubuntu 24.04, and a browser desktop. A running VM accrues usage until you stop, pause, or remove it, or until an idle timeout puts it to sleep.
> Stopping a VM keeps its disk and discards RAM and processes. Pausing keeps both, and resuming restores them. To pause after 5 idle minutes and wake on access, run `beam vm update NAME --ttl 300 --idle-action pause --auto-resume`.
> Core VM commands: `beam vm new NAME`, `beam vm ssh NAME`, `beam vm sync NAME ./dir`, `beam vm exec NAME -- CMD`, `beam vm expose NAME PORT --protected`, `beam vm fork NAME NEW_NAME`, `beam vm pause NAME`, `beam vm stop NAME`, `beam vm rm NAME`.
> For GPUs, use a sandbox or a deployed endpoint. Sandboxes are disposable environments that boot in seconds and fork from snapshots.
> Current rates are at https://www.beam.cloud/pricing.

# JavaScript and TypeScript SDK

Use `@beamcloud/beam-js` to create and manage Beam resources from JavaScript or TypeScript. The package includes TypeScript declarations and supports Node.js ES modules and CommonJS.

This reference covers public workflows in `@beamcloud/beam-js`. The package includes TypeScript declarations for the complete API. Python and TypeScript SDK capabilities and defaults differ.

# Installation

Install the package with `npm`:

```bash theme={null}
npm install @beamcloud/beam-js
```

...or using `yarn`:

```bash theme={null}
yarn add @beamcloud/beam-js
```

# Configuration

Locate your Beam Token (API Key) and Workspace ID in the [dashboard](https://platform.beam.cloud/settings/api-keys) and set them as environment variables.

```bash theme={null}
export BEAM_TOKEN=YOUR_BEAM_TOKEN
export BEAM_WORKSPACE_ID=YOUR_WORKSPACE_ID
```

## `beamOpts`

Global configuration object for the Beam client.

```typescript theme={null}
import { beamOpts } from "@beamcloud/beam-js";

beamOpts.token = process.env.BEAM_TOKEN!;
beamOpts.workspaceId = process.env.BEAM_WORKSPACE_ID!;
beamOpts.gatewayUrl = "https://app.beam.cloud"; // Optional, defaults to https://app.beam.cloud
```

**Required Configuration:**

* `token`: Your Beam authentication token
* `workspaceId`: Your Beam workspace ID

**Optional Configuration:**

* `gatewayUrl`: The Beam gateway URL (defaults to `https://app.beam.cloud`)
* `timeout`: Default HTTP client timeout in milliseconds (30000)

Configure these values before the first request; the underlying HTTP client is cached. Keep tokens on the server, not in browser bundles.

## VM quickstart

Persistent VMs are available in version 1.1.0 and later. One `VM` object exposes lifecycle, commands, files, snapshots, templates, Docker, desktop controls, and private access.

```javascript theme={null}
import { beamOpts, VM } from "@beamcloud/beam-js";

beamOpts.token = process.env.BEAM_TOKEN || "";
const vm = await VM.create({
  name: "agent-workspace",
  cpu: 2,
  memory: "4Gi",
  protectedPorts: [7681],
  idleTimeout: 300,
  autoResume: true,
});

const command = await vm.exec(["node", "--version"]);
await command.wait();
console.log(await command.stdout.read());

const snapshot = await vm.snapshots.create("ready");
const branch = await snapshot.fork({ name: "experiment" });
await branch.remove();
await vm.stop();
await vm.close();
```

Save this as `vm.mjs` and run `node vm.mjs`. Configure `BEAM_TOKEN` before running it. `VM.get(nameOrId)` reads state without starting compute; `VM.connect(nameOrId)` starts or resumes the VM and waits for command execution to be ready. VM operations can resolve the token's workspace when `beamOpts.workspaceId` is omitted.

See the [VM SDK guide](https://docs.beam.cloud/v2/vm/sdk.md) for configuration and complete examples.

## Sandbox quickstart

Run a simple Node.js server in a sandbox. This example uses the `Image` class to create a custom container image and the `Sandbox` class to create a sandbox instance.

```typescript theme={null}
import { beamOpts, Image, Sandbox } from "@beamcloud/beam-js";

beamOpts.token = process.env.BEAM_TOKEN!;
beamOpts.workspaceId = process.env.BEAM_WORKSPACE_ID!;

async function main() {
  const image = new Image({
    baseImage: "node:20",
    commands: [
      "apt update",
      "apt install -y nodejs npm",
      "git clone https://github.com/beam-cloud/quickstart-node.git /app",
    ],
  });

  const sandbox = new Sandbox({
    name: "quickstart",
    image: image,
    cpu: 2,
    memory: 1024,
    keepWarmSeconds: 300,
  });

  const instance = await sandbox.create();

  const process4 = await instance.exec([
    "sh",
    "-c",
    "cd /app && node server.js",
  ]);

  const url = await instance.exposePort(3000);
  console.log(`Server is running at ${url}`);
}

main();
```

# Virtual machines

`VM.create(config)` and `new VM(config).create()` return the same `VM` class as `VM.get()`, `VM.connect()`, and the entries returned by `VM.list()`. Config uses camelCase; CPU is cores, memory is MiB or a quantity such as `"4Gi"`, idle timeouts are seconds, and operation deadlines use `timeoutMs`.

| Capability | API |
| - | - |
| Create and resolve | `VM.create(config)`, `VM.get(nameOrId)`, `VM.connect(nameOrId)`, `VM.list(options)` |
| State and configuration | `vm.info`, `vm.status`, `vm.spec`, `vm.refresh()`, `vm.update(options)` |
| Lifecycle | `vm.start()`, `vm.resume()`, `vm.pause()`, `vm.stop()`, `vm.remove()` |
| Processes and files | `vm.exec(argv, options)`, `vm.execShell(text)`, `vm.getProcess(pid)`, `vm.listProcesses()`, `vm.fs` |
| Snapshots | `vm.snapshots.create/list/get/delete/fork`, workspace-wide `VM.snapshots` |
| Private templates | `vm.templates.create/list/get/delete/fork`, workspace-wide `VM.templates` |
| Fork the current root | `vm.fork(name)` |
| Docker | `vm.docker.exec/run/compose/version` |
| Desktop | `vm.desktop.screenshot/resize/click/press/write/record/stopRecording` |
| URLs and access | `vm.exposePort()`, `vm.getUrl()`, `vm.accessUrl()`, `vm.getAccessToken()`, `vm.rotateAccessToken()` |
| Private TCP and SSH | `vm.tunnel()`, `vm.portForward()`, `vm.ssh()`, `vm.scp()`, `vm.sync()` |
| Prompts, logs and metrics | `vm.prompt()`, `vm.logs()`, `vm.metrics()`, `vm.keepAlive(callback)` |

Stop/start preserves the root filesystem. Pause/resume also preserves RAM and processes. Snapshots and templates capture the root and restore into an independent VM; they do not provide in-place rollback. `close()` releases local connections and watchers while leaving the VM's lifecycle state intact.

The [VM guide](https://docs.beam.cloud/v2/vm/sdk.md) documents every method, creation options, idempotent retries, snapshot boundaries, and process reattachment.

# Environment

## `Image`

Defines a custom container image that your code will run in.

An Image object encapsulates the configuration of a custom container image that will be used as the runtime environment for executing tasks.

```typescript theme={null}
import {
  Image,
  PythonVersion,
  GpuType,
  GpuTypeAlias,
} from "@beamcloud/beam-js";

const image = new Image({
  baseImage: "docker.io/nvidia/cuda:12.3.1-runtime-ubuntu20.04",
  pythonVersion: PythonVersion.Python311, // Type-safe enum approach
  commands: ["apt-get update -y", "apt-get install ffmpeg -y"],
  pythonPackages: ["transformers", "torch"],
  gpu: GpuType.A10G, // Type-safe enum approach
});

await image.build();

// Alternative using string literals for convenience
const imageWithStringLiterals = new Image({
  baseImage: "docker.io/nvidia/cuda:12.3.1-runtime-ubuntu20.04",
  pythonVersion: "python3.11", // String literal for Python version
  commands: ["apt-get update -y", "apt-get install ffmpeg -y"],
  pythonPackages: ["transformers", "torch"],
  gpu: "A10G", // String literal for GPU
});

await imageWithStringLiterals.build();
```

**Constructor Parameters:**

**pythonVersion** `PythonVersionAlias` (default: PythonVersion.Python3)

The Python version to be used in the image. Can be a PythonVersion enum (e.g.,
PythonVersion.Python311) or string literal (e.g., "python3.11"). Defaults to
Python 3.

**pythonPackages** `string[] | string` (default: \[])

A list of Python packages to install in the container image. Alternatively, a
string containing a path to a requirements.txt can be provided.

**commands** `string[]` (default: \[])

A list of shell commands to run when building your container image. These
commands can be used for setting up the environment, installing dependencies,
etc.

**baseImage** `string`

A custom base image to replace the default ubuntu20.04 image used in your
container. This can be a public or private image from Docker Hub, Amazon ECR,
Google Cloud Artifact Registry, or NVIDIA GPU Cloud Registry.

**baseImageCreds** `ImageCredentials` (default: \{})

Credentials for accessing private registries. Can be a dictionary of key/value
pairs or an array of environment variable names.

**envVars** `string[]` (default: \[])

Environment variables to add to the image. These will be available when
building the image and when the container is running.

**secrets** `string[]` (default: \[])

A list of secrets that are injected into the container as environment
variables.

**gpu** `GpuTypeAlias`

Builds the image on a GPU node. Can be a GpuType enum (e.g., GpuType.H100) or
string literal (e.g., "H100").

### `Image.fromDockerfile()`

Create an Image from a local Dockerfile.

```typescript theme={null}
import { Image } from "@beamcloud/beam-js";

const image = await Image.fromDockerfile("./Dockerfile", "./context");
```

**dockerfilePath** `string` *required*

Path to the Dockerfile.

**contextDir** `string` (default: undefined)

Directory to sync as build context. Defaults to the Dockerfile directory.

### Other image constructors and build helpers

`Image.fromRegistry(imageUri, credentials?)` uses a registry image; `Image.fromId(imageId)` reuses a Beam image. `addLocalPath(pattern)` includes local build files, `buildWithGpu(gpu)` requests a GPU for the build, and `exists()` checks the image cache. These methods complement `fromDockerfile`, `withEnvs`, and `withSecrets`.

### `Image.addPythonPackages()`

Add pip packages to install during the build. Accepts a list or a path to requirements.txt.

```typescript theme={null}
// Using an array of package names
image.addPythonPackages(["transformers==4.44.0", "torch==2.4.0"]);

// Using a requirements.txt file
image.addPythonPackages("./requirements.txt");
```

**packages** `string[] | string` *required*

Package names or a `requirements.txt` path.

### `Image.withEnvs()`

Add environment variables available during build and at runtime.

```typescript theme={null}
image.withEnvs({ HF_HOME: "/models", HF_HUB_ENABLE_HF_TRANSFER: "1" });
```

**envVars** `string[] | Record\<string, string\> | string` *required*

Environment variables as key/value pairs, array of "KEY=VALUE" strings, or
single string.

### `Image.withSecrets()`

Expose platform secrets to the build environment.

```typescript theme={null}
image.withSecrets(["HF_TOKEN"]);
```

**secrets** `string[]` *required*

Secret names created via the platform.

### `Image.micromamba()`

Switch package management to micromamba and target a micromamba Python.

```typescript theme={null}
image.micromamba();
```

### `Image.addMicromambaPackages()`

Install micromamba packages and optional channels.

```typescript theme={null}
image.addMicromambaPackages(["pandas", "numpy"], ["conda-forge"]);
```

**packages** `string[] | string` *required*

Package names or a `requirements.txt` path.

**channels** `string[]` (default: \[])

Micromamba channels.

### `Image.build()`

Build the image and return the result.

```typescript theme={null}
const result = await image.build();
console.log("Build successful:", result.success);
```

# Deployments

## `Deployments`

You can use this to manage and interact with deployed Beam applications.

```typescript theme={null}
import { Deployments, EStubType } from "@beamcloud/beam-js";

// List all deployments
const deployments = await Deployments.list();

// Get a deployment by ID
const deployment = await Deployments.get({ id: "deployment-id" });

// Get a deployment by name and stub type
const namedDeployment = await Deployments.get({
  name: "my-app",
  stubType: EStubType.EndpointDeployment,
});

// Call the deployment
const response = await deployment.call({ message: "Hello World" });

// Connect to realtime deployment
const ws = await deployment.realtime("/", (event) => {
  console.log("Received:", event.data);
});
```

### `Deployments.list()`

List all deployments in your workspace.

```typescript theme={null}
const deployments = await Deployments.list({
  stubType: EStubType.EndpointDeployment,
  active: true,
  limit: 10,
});
```

### `Deployments.get()`

Retrieve a deployment by ID, name, or URL.

```typescript theme={null}
// By ID
const deployment = await Deployments.get({ id: "deployment-id" });

// By name and stub type
const namedDeployment = await Deployments.get({
  name: "my-app",
  stubType: EStubType.EndpointDeployment,
});
```

**id** `string`

The deployment ID to retrieve.

**name** `string`

The deployment name (must be used with stubType).

**stubType** `string`

The stub type (must be used with name).

**url** `string`

The deployment URL.

## `Deployment`

A deployment instance with methods for interaction.

### `Deployment.call()`

Call the deployment with data.

```typescript theme={null}
const response = await deployment.call(
  { message: "Hello World" },
  "/endpoint-path", // optional path
  "POST", // optional HTTP method
);
```

**data** `any` *required*

The data to send to the deployment.

**path** `string`

Optional path to append to the deployment URL.

**method** `'GET' | 'POST'` (default: 'POST')

HTTP method to use for the request.

### `Deployment.realtime()`

Connect to a realtime deployment via WebSocket.

```typescript theme={null}
const ws = await deployment.realtime("/", (event) => {
  console.log("Message received:", event.data);
});

// Send a message
ws.send(JSON.stringify({ message: "Hello" }));
```

**path** `string`

Optional path to append to the WebSocket URL.

**onmessage** `(event: MessageEvent) =\> void`

Optional message handler function.

### `Deployment.httpUrl()` / `Deployment.websocketUrl()`

Get the HTTP or WebSocket URL for the deployment.

```typescript theme={null}
const httpUrl = deployment.httpUrl("/api/predict");
const wsUrl = deployment.websocketUrl("/realtime");
```

# Sandbox

A sandboxed container for running Python code or arbitrary processes.

You can use this to create isolated environments where you can execute code,
manage files, and run processes.

```typescript theme={null}
import { Sandbox, Image, GpuType } from "@beamcloud/beam-js";

const sandbox = new Sandbox({
  name: "my-sandbox",
  cpu: 2,
  memory: "1Gi",
  gpu: GpuType.T4, // Using enum
  image: new Image({
    pythonPackages: ["numpy", "pandas"],
  }),
  keepWarmSeconds: 300,
});

// Alternative with string literal
const sandboxWithStringGpu = new Sandbox({
  name: "my-sandbox-2",
  cpu: 2,
  memory: "1Gi",
  gpu: "T4", // Using string literal
  image: new Image({
    pythonPackages: ["numpy", "pandas"],
  }),
  keepWarmSeconds: 300,
});

// Create a new sandbox instance
const instance = await sandbox.create();

// Or connect to an existing one
const existingInstance = await Sandbox.connect("sandbox-id");
```

You can also configure sandbox networking at creation time to pre-expose ports
or restrict outbound traffic.

```typescript theme={null}
const networkedSandbox = new Sandbox({
  name: "networked-sandbox",
  image: new Image({
    baseImage: "node:20",
  }),
  ports: [3000, 8080],
  allowList: ["api.openai.com"],
});

const networkedInstance = await networkedSandbox.create();
const urls = await networkedInstance.listUrls();
console.log("Known URLs:", urls);
```

**ports** `number[]` (default: \[])

Ports to expose immediately when the sandbox is created. These ports will be
available via public URLs as soon as the sandbox starts.

**blockNetwork** `boolean` (default: false)

Blocks outbound access except approved hosts of bound brokered secrets.
Inbound exposed ports remain reachable. Cannot be combined with an explicit `allowList`.

**allowList** `string[]` (default: undefined)

Up to 64 hostnames, `*.wildcards`, bare IPs or CIDRs, including IPv4 and IPv6.
Hostnames govern TLS SNI on 443/HTTP Host on 80; other TCP needs IP/CIDR rules. Proxied private destinations remain blocked even with explicit IP/CIDR rules. Cannot be combined with `blockNetwork=true`. See [network rules](https://docs.beam.cloud/v2/sandbox/networking.md#allow-lists).

**secrets** `SecretVar[]` (default: \[])

Runtime workspace secrets such as `[{ name: "API_KEY" }]`. Approved credential hosts are required;
the guest receives placeholders. See [brokered secrets](https://docs.beam.cloud/v2/environment/secrets.md#brokered-secrets-for-vms-and-sandboxes).

### `Sandbox.create()`

Create a new sandbox instance. The TypeScript default lifetime is 60 seconds; set `keepWarmSeconds` explicitly for longer sessions. The constructor's optional second argument, `syncLocalDir`, defaults to `false`.

You may pass an entrypoint array or `{ entrypoint, waitForReady }`. Normal creation waits for readiness; `waitForReady: false` returns before the sandbox is ready for process and filesystem calls.

```typescript theme={null}
const instance = await sandbox.create(["python", "app.py"]); // optional entrypoint
console.log(`Sandbox created with ID: ${instance.sandboxId}`);
```

### `Sandbox.connect()`

Connect to an existing sandbox instance by ID.

```typescript theme={null}
const instance = await Sandbox.connect("sandbox-123");
```

**id** `string` *required*

The container ID of the existing sandbox instance.

### `Sandbox.createFromSnapshot()`

Restore a sandbox from a memory checkpoint returned by `SandboxInstance.snapshot()`. For a filesystem image ID, use `Image.fromId()` instead.

```typescript theme={null}
const instance = await Sandbox.createFromSnapshot("snapshot-123");
```

**snapshotId** `string` *required*

The ID of the snapshot to create the sandbox from.

### `Sandbox.terminate()`

Terminate a sandbox by ID without connecting first:

```typescript theme={null}
await Sandbox.terminate("sandbox-id");
```

## SandboxInstance

A sandbox instance that provides access to the sandbox internals.

### `SandboxInstance.runCode()`

Run Python code in the sandbox.

```typescript theme={null}
const result = await instance.runCode(`
import numpy as np
print("NumPy version:", np.__version__)
result = np.array([1, 2, 3, 4, 5])
print("Array:", result)
`);

if ("result" in result) {
  console.log("Output:", result.result);
}
```

**code** `string` *required*

The Python code to execute.

**blocking** `boolean` (default: true)

Whether to wait for the process to complete.

### `SandboxInstance.exec()`

Run an arbitrary command in the sandbox. An array preserves literal arguments; a string is shell text. Use `execShell()` explicitly when you need pipes, redirection, or shell expansion. Do not concatenate untrusted input into shell strings.

```typescript theme={null}
// Using an array of command and arguments
const process = await instance.exec(["ls", "-la", "/workspace"]);
const exitCode = await process.wait();

// Using a single string command
const process2 = await instance.exec("ls -la /workspace");

// With execution options
const process3 = await instance.exec(["node", "server.js"], {
  cwd: "/app",
  env: { NODE_ENV: "production" },
});

// Get the process ID
const pid = process.pid;

// Read output
const stdout = await process.stdout.read();
const stderr = await process.stderr.read();
```

**command** `string | string[]` *required*

The command to execute. Can be a single string or an array of strings (command
and arguments).

**opts** `ExecOptions`

Optional execution options.

**opts.cwd** `string`

The working directory for the command.

**opts.env** `Record\<string, string\>`

Environment variables to set for the command.

### Shell commands and process discovery

```typescript theme={null}
const job = await instance.execShell("printf 'hello\n' | wc -c");
await job.wait();
for await (const chunk of job.stdout) console.log(chunk);

const processes = await instance.listProcesses();
for (const process of processes) console.log(process.pid, process.command);
const sameProcess = instance.getProcess(job.pid);
```

`exec` and `execShell` return a process handle. `opts.wait: true` asks the execution request to wait; the return type is still a process. `runCode(code, false)` also returns a process, while blocking `runCode` returns a result object. Narrow its union type before using result-only properties.

Output streams are consumed as you read them. `.poll()` and `.status()` return an exit-code/status tuple; `.wait()` waits for exit. `.kill()` stops a process, while `instance.terminate()` stops the entire sandbox.

### `SandboxInstance.exposePort()`

Dynamically expose a port to the internet. The URL is public: add application authentication before exposing sensitive functionality, and bind the server to `0.0.0.0` or `::`.

```typescript theme={null}
const url = await instance.exposePort(8000);
console.log(`Web service available at: ${url}`);
```

**port** `number` *required*

The port number to expose within the sandbox.

Use `listUrls()` to inspect every currently exposed URL, including ports
exposed at creation time with `ports`.

### `SandboxInstance.listUrls()`

List the currently exposed preview/public URLs for the sandbox. Returns
`Promise<Record<number, string>>`, keyed by port number.

```typescript theme={null}
const urls = await instance.listUrls();

for (const [port, url] of Object.entries(urls)) {
  console.log(`Port ${port} available at: ${url}`);
}
```

### `SandboxInstance.updateNetworkPermissions()`

Dynamically update outbound network permissions for the sandbox. This method
returns `Promise<void>`.

Because the method signature is positional, pass `false` as the first argument
when updating to an allow list without fully blocking outbound traffic.

```typescript theme={null}
// Block outbound traffic except bound credential hosts
await instance.updateNetworkPermissions(true);

// Allow only specific destinations
await instance.updateNetworkPermissions(false, ["api.openai.com", "8.8.8.8/32"]);

// Remove all outbound restrictions
await instance.updateNetworkPermissions(false, []);
```

**blockNetwork** `boolean` (default: false)

Blocks outbound access except approved hosts of bound brokered secrets.
Cannot be combined with an explicit `allowList`.

**allowList** `string[]`

Up to 64 hostnames, wildcard domains, IPs or CIDRs. Passing `[]` removes outbound
restrictions. Cannot be used together with `blockNetwork=true`.

Credential hosts must fit within an explicit allowlist's hostname rules; IP/CIDR entries alone do not cover them. Updates close existing connections without restarting;
exposed ports remain reachable regardless of outbound restrictions.

### `SandboxInstance.snapshot()`

Create a memory snapshot of the current sandbox. This method captures the memory state of the sandbox as an immutable artifact. You can later restore this snapshot into a new sandbox instance using `createFromSnapshot()`.

```typescript theme={null}
const snapshotId = await instance.snapshot();
console.log(`Created memory snapshot: ${snapshotId}`);

// Restore from memory snapshot
const restoredInstance = await Sandbox.createFromSnapshot(snapshotId);
```

### `SandboxInstance.createImageFromFilesystem()`

Create an image from the sandbox filesystem. This method returns an image ID that can be used to create new sandboxes with the same filesystem state. You can use the `Image.fromId()` method to create a new image instance.

```typescript theme={null}
const imageId = await instance.createImageFromFilesystem();
console.log(`Created image from filesystem: ${imageId}`);

// Use the snapshot as a base image for new sandboxes
const image = Image.fromId(imageId);
const newSandbox = new Sandbox({
  name: "from-filesystem",
  image: image,
  // ... other config
});
```

### `SandboxInstance.updateTtl()`

Reset the remaining sandbox lifetime. Commands do not automatically turn a finite TTL into an unlimited lifetime.

```typescript theme={null}
// Keep alive for 1 hour
await instance.updateTtl(3600);

// Make it never timeout
await instance.updateTtl(-1);
```

**ttl** `number` *required*

The number of seconds to keep the sandbox alive. Use -1 for sandboxes that
never timeout.

### `SandboxInstance.sandboxId`

Get the ID of the sandbox.

```typescript theme={null}
const sandboxId = instance.sandboxId;
```

### `SandboxInstance.terminate()`

Terminate the container associated with this sandbox instance.

```typescript theme={null}
const success = await instance.terminate();
```

## SandboxProcess

Represents a running process within a sandbox.

### `SandboxProcess.wait()`

Wait for the process to complete.

```typescript theme={null}
const process = await instance.exec(["sleep", "5"]);
const exitCode = await process.wait();
console.log("Process exited with code:", exitCode);
```

### `SandboxProcess.kill()`

Kill the process.

```typescript theme={null}
const process = await instance.exec(["sleep", "100"]);
await process.kill();
```

### `SandboxProcess.status()`

Get the status of the process.

```typescript theme={null}
const [exitCode, status] = await process.status();
if (exitCode >= 0) {
  console.log("Process finished with exit code:", exitCode);
}
```

### `SandboxProcess.stdout` / `SandboxProcess.stderr`

Get handles to the process output streams.

```typescript theme={null}
const process = await instance.exec(["echo", "Hello World"]);
const output = await process.stdout.read();
console.log("Output:", output);
```

## SandboxFileSystem

File system interface for managing files within a sandbox.

### `SandboxFileSystem.uploadFile()`

Upload a local file to the sandbox.

```typescript theme={null}
await instance.fs.uploadFile(
  "./local-file.txt",
  "/workspace/uploaded-file.txt",
);
```

**localPath** `string` *required*

The path to the local file to upload.

**sandboxPath** `string` *required*

The destination path within the sandbox.

### `SandboxFileSystem.downloadFile()`

Download a file from the sandbox to a local path.

```typescript theme={null}
await instance.fs.downloadFile(
  "/workspace/output.txt",
  "./downloaded-output.txt",
);
```

**sandboxPath** `string` *required*

The path to the file within the sandbox.

**localPath** `string` *required*

The destination path on the local filesystem.

### `SandboxFileSystem.listFiles()`

List the files in a directory in the sandbox.

```typescript theme={null}
const files = await instance.fs.listFiles("/workspace");
for (const file of files) {
  console.log(`${file.name} (${file.isDir ? "directory" : "file"})`);
}
```

**sandboxPath** `string` *required*

The path to the directory within the sandbox.

### `SandboxFileSystem.deleteFile()`

Delete a file in the sandbox.

```typescript theme={null}
await instance.fs.deleteFile("/tmp/temp-file.txt");
```

**sandboxPath** `string` *required*

The path to the file within the sandbox.

### `SandboxFileSystem.statFile()`

Get metadata of a file in the sandbox.

```typescript theme={null}
const fileInfo = await instance.fs.statFile("/path/to/file.txt");
console.log(`File size: ${fileInfo.size} bytes`);
console.log(`Is directory: ${fileInfo.isDir}`);
```

**sandboxPath** `string` *required*

The path to the file within the sandbox.

### Read, write, search, and directories

```typescript theme={null}
await instance.fs.createDirectory("/workspace/example");
await instance.fs.writeText("/workspace/example/hello.txt", "hello");
const text = await instance.fs.readText("/workspace/example/hello.txt");
await instance.fs.writeBytes(
  "/workspace/example/data.bin",
  Buffer.from([1, 2, 3]),
);
const bytes = await instance.fs.readBytes("/workspace/example/data.bin");
const matches = await instance.fs.findInFiles("/workspace/example", "hello");
await instance.fs.replaceInFiles("/workspace/example", "hello", "goodbye");
await instance.fs.deleteFile("/workspace/example/hello.txt");
await instance.fs.deleteFile("/workspace/example/data.bin");
await instance.fs.deleteDirectory("/workspace/example");
```

Short aliases include `upload`, `download` (returns a Buffer), `stat`, `list`, `mkdir`, `removeDir`, `removeFile`, `find`, and `replace`. `remove(path)` deletes a file; pass `{ dir: true }` for a directory. `findInFiles` searches file contents with a pattern, not filenames. `replaceInFiles` performs literal replacement.

The TypeScript SDK does not expose all Python helpers, such as the Python Docker manager or `fs.wait_for`. Use the documented APIs for the installed package.

# Pod

A **Pod** is an object that allows you to run arbitrary services in a fast, scalable, and secure remote container on Beam.

You can think of a Pod as a lightweight compute environment that you fully control—complete with a custom container, ports you can expose, environment variables, volumes, secrets, and GPUs.

```typescript theme={null}
import { Pod, Image } from "@beamcloud/beam-js";

// Create a Pod that runs a simple HTTP server
const pod = new Pod({
  name: "web-server",
  cpu: 2,
  memory: "512Mi",
  image: new Image({
    baseImage: "python:3.9-slim",
    pythonPackages: ["requests"],
  }),
  ports: [8000],
});

// Create the pod container
const result = await pod.create(["python", "-m", "http.server", "8000"]);

console.log("Container ID:", result.containerId);
console.log("URL:", result.url);
```

### `Pod.create()`

Create a new container that runs until it completes or is explicitly killed.

```typescript theme={null}
const result = await pod.create(["python", "app.py"]);
console.log("Pod created successfully:", result.url);
```

**entrypoint** `string[]`

The command to run in the container.

# Storage

## `Volume`

Creates a Volume instance.

Use an absolute `mountPath` for the location inside your container.

```typescript theme={null}
import { Volume } from "@beamcloud/beam-js";

const volume = new Volume("model-weights", "/weights");
await volume.getOrCreate();

// Use with Pod or Sandbox
const pod = new Pod({
  name: "my-pod",
  volumes: [volume],
  // ... other config
});
```

**name** `string` *required*

The name of the volume, a descriptive identifier for the data volume.

**mountPath** `string` *required*

The path where the volume is mounted within the container environment.

### `Volume.getOrCreate()`

Get or create the volume in the platform.

```typescript theme={null}
const success = await volume.getOrCreate();
console.log("Volume ready:", volume.ready);
```

## `CloudBucket`

Mount an existing S3-compatible bucket. Credential fields refer to Beam secret names.

```typescript theme={null}
import { CloudBucket, Sandbox } from "@beamcloud/beam-js";

const bucket = new CloudBucket("my-bucket", "/data", {
  accessKey: "AWS_ACCESS_KEY_ID",
  secretKey: "AWS_SECRET_ACCESS_KEY",
  readOnly: true,
});
const sandbox = new Sandbox({ name: "bucket-reader", volumes: [bucket] });
```

Optional configuration includes `endpoint`, `region`, and `forcePathStyle` for compatible storage providers. See [external storage](https://docs.beam.cloud/v2/data/external-storage.md).

# Utils

## `TaskPolicy`

Task policy for managing the lifecycle of individual tasks.

```typescript theme={null}
import { TaskPolicy } from "@beamcloud/beam-js";

const policy = new TaskPolicy({
  maxRetries: 3,
  timeout: 300,
  ttl: 3600,
});
```

**maxRetries** `number` (default: 0)

The maximum number of times a task will be retried if the container crashes.

**timeout** `number` (default: 0)

The maximum number of seconds a task can run before it times out. Set it to -1
to disable the timeout.

**ttl** `number` (default: 0)

The expiration time for a task in seconds. Must be greater than 0 and less
than 24 hours (86400 seconds).

# Types

The TypeScript SDK includes comprehensive type definitions for all resources:

* `GpuType`: Enum of available GPU types (T4, A10G, A100, H100, etc.)
* `GpuTypeAlias`: Union type allowing both enum values and string literals for GPU specification
* `PythonVersion`: Enum of supported Python versions
* `PythonVersionAlias`: Union type allowing both enum values and string literals for Python version specification
* `TaskStatus`: Enum of task statuses (PENDING, RUNNING, COMPLETE, etc.)
* `DeploymentData`: Interface for deployment data
* `TaskData`: Interface for task data
* `ExecOptions`: Options for sandbox command execution (cwd, env)
* `PodInstanceData`: Interface for pod instance data
* And many more...

```typescript theme={null}
import {
  Image,
  GpuType,
  GpuTypeAlias,
  PythonVersion,
  TaskStatus,
  DeploymentData,
} from "@beamcloud/beam-js";

// Use types for better TypeScript support
const gpu: GpuType = GpuType.A10G; // Enum approach
const gpuAlias: GpuTypeAlias = "A10G"; // String literal approach
const anotherGpu: GpuTypeAlias = GpuType.H100; // Both work with GpuTypeAlias

const python: PythonVersion = PythonVersion.Python311; // Enum approach
type PythonVersionOption = NonNullable<
  ConstructorParameters<typeof Image>[0]["pythonVersion"]
>;
const pythonAlias: PythonVersionOption = "python3.11"; // String literal approach
const anotherPython: PythonVersionOption = PythonVersion.Python310; // Both are accepted

// Both approaches work seamlessly for any alias type
function createResource(gpu: GpuTypeAlias, python: PythonVersionOption) {
  console.log(`Using GPU: ${gpu}, Python: ${python}`);
}

createResource(GpuType.H100, PythonVersion.Python311); // Works with enums
createResource("H100", "python3.11"); // Works with strings
createResource("A10G", PythonVersion.Python310); // Works with mixed approaches
```

## `ExecOptions`

Options for configuring command execution in a sandbox.

```typescript theme={null}
import { ExecOptions } from "@beamcloud/beam-js";

const opts: ExecOptions = {
  cwd: "/app",
  env: { NODE_ENV: "production", DEBUG: "true" },
};

const process = await instance.exec(["node", "server.js"], opts);
```

**cwd** `string`

The working directory for the command.

**env** `Record\<string, string\>`

Environment variables to set for the command.

**wait** `boolean` (default: false)

Wait in the execution request. The returned value is still a process handle.


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