### Initialize and configure a sandbox image Source: https://docs.opencomputer.dev/reference/python-sdk/image Demonstrates starting from a base image and chaining configuration methods to install packages, set environment variables, and define the working directory. ```python from opencomputer import Image image = ( Image.base() .apt_install(["curl", "jq"]) .pip_install(["requests", "pandas"]) .env({"PROJECT_ROOT": "/workspace"}) .workdir("/workspace") ) ``` -------------------------------- ### Initialize and Configure Sandbox Image Source: https://docs.opencomputer.dev/reference/typescript-sdk/image Demonstrates starting from the base environment and chaining configuration methods to install packages, set environment variables, and define the working directory. ```typescript import { Image } from "@opencomputer/sdk"; const image = Image.base() .aptInstall(['curl', 'jq']) .pipInstall(['requests', 'pandas']) .env({ PROJECT_ROOT: '/workspace' }) .workdir('/workspace'); ``` -------------------------------- ### Expose and Share a Development Server Source: https://docs.opencomputer.dev/cli/preview This sequence of commands demonstrates how to start a development server within a sandbox, expose its port using `oc preview create`, and then list available previews to get the shared URL. ```bash # Start a dev server in the background oc exec sb-abc123 -- bash -c 'cd /app && npm run dev &' # Expose port 3000 oc preview create sb-abc123 --port 3000 # Get the URL oc preview list sb-abc123 ``` -------------------------------- ### Install and Configure oc CLI Source: https://docs.opencomputer.dev/guides/agent-skill Install the `oc` CLI by downloading the binary and making it executable. Configure the CLI with your API key. Ensure the `oc` CLI is installed and configured before using the OpenComputer skill. ```bash curl -fsSL https://github.com/diggerhq/opencomputer/releases/latest/download/oc-$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/') -o /usr/local/bin/oc && chmod +x /usr/local/bin/oc oc config set api-key YOUR_API_KEY ``` -------------------------------- ### Clone and Install Project Dependencies Source: https://docs.opencomputer.dev/guides/build-a-lovable-clone Initializes the project repository and installs all required dependencies. ```bash git clone https://github.com/diggerhq/osslovable.git cd osslovable npm run install:all ``` -------------------------------- ### Install OpenComputer SDK and CLI Source: https://docs.opencomputer.dev/introduction Install the SDK via npm or pip, or download the CLI tool for direct platform interaction. ```bash npm install @opencomputer/sdk ``` ```bash pip install opencomputer-sdk ``` ```bash # See cli/overview for platform-specific install curl -fsSL https://github.com/diggerhq/opencomputer/releases/latest/download/oc-$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/') -o /usr/local/bin/oc && chmod +x /usr/local/bin/oc ``` -------------------------------- ### Create Preview URL Response Example Source: https://docs.opencomputer.dev/api-reference/preview/create Example of a successful response when creating a preview URL. Includes sandbox details, hostname, port, SSL status, and creation timestamp. ```json { "id": "pv-abc123", "sandboxId": "sb-abc123", "hostname": "sb-abc123-p3000.workers.opencomputer.dev", "port": 3000, "sslStatus": "active", "createdAt": "2025-01-15T10:30:00Z" } ``` -------------------------------- ### Install OpenComputer TypeScript SDK Source: https://docs.opencomputer.dev/reference/typescript-sdk/overview Install the SDK using npm, yarn, or pnpm. The SDK is ESM-only. ```bash npm install @opencomputer/sdk ``` ```bash yarn add @opencomputer/sdk ``` ```bash pnpm add @opencomputer/sdk ``` -------------------------------- ### Start the Chat Server Source: https://docs.opencomputer.dev/guides/deploy-openclaw Start the lightweight chat server that provides a web UI for each user's agent and routes messages. Access the UI at http://localhost:3000/. ```bash npx tsx src/chat-server.ts ``` -------------------------------- ### Start Development Server Source: https://docs.opencomputer.dev/guides/build-a-lovable-clone Launches the Express backend and Vite frontend for local development. ```bash npm run dev ``` -------------------------------- ### Install opencomputer-sdk Source: https://docs.opencomputer.dev/reference/python-sdk/overview Install the OpenComputer Python SDK using pip. This is the first step to using the SDK in your Python projects. ```bash pip install opencomputer-sdk ``` -------------------------------- ### Read File Content Example Source: https://docs.opencomputer.dev/api-reference/files/read This example shows the expected plain text response when successfully reading a file. Ensure the correct sandbox ID and file path are provided in the request. ```text Hello, World! ``` -------------------------------- ### Install OpenComputer CLI for Linux (x86_64) Source: https://docs.opencomputer.dev/cli/overview Installs the OpenComputer CLI for Linux on x86_64 architecture. Ensure you have `curl` and `chmod` available. ```bash curl -fsSL https://github.com/diggerhq/opencomputer/releases/latest/download/oc-linux-amd64 -o /usr/local/bin/oc chmod +x /usr/local/bin/oc ``` -------------------------------- ### Install OpenComputer CLI for Linux (ARM64) Source: https://docs.opencomputer.dev/cli/overview Installs the OpenComputer CLI for Linux on ARM64 architecture. Ensure you have `curl` and `chmod` available. ```bash curl -fsSL https://github.com/diggerhq/opencomputer/releases/latest/download/oc-linux-arm64 -o /usr/local/bin/oc chmod +x /usr/local/bin/oc ``` -------------------------------- ### Download URL Response Example Source: https://docs.opencomputer.dev/api-reference/files/generate-download-url Example of a successful 200 OK response containing the signed download URL and expiration timestamp. ```json { "url": "https://app.opencomputer.dev/api/sandboxes/sb-xxx/files/download?path=%2Fapp%2Foutput.zip&expires=1773906434&signature=abc123", "expiresAt": "2025-01-01T01:00:00Z" } ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://docs.opencomputer.dev/guides/deploy-openclaw Clone the OpenClaw template repository and install necessary Node.js dependencies. ```bash git clone https://github.com/diggerhq/oc-openclaw-template.git cd oc-openclaw-template npm install ``` -------------------------------- ### List Exec Sessions Response Example Source: https://docs.opencomputer.dev/api-reference/exec/list-sessions This JSON response shows the structure of data returned when listing execution sessions for a sandbox. It includes details for a single session, indicating its ID, sandbox ID, command, arguments, running status, exit code, start time, and attached clients. ```json [{"sessionID": "es-abc123", "sandboxID": "sb-abc123", "command": "node", "args": ["server.js"], "running": true, "exitCode": null, "startedAt": "2025-01-15T10:30:00Z", "attachedClients": 0}] ``` -------------------------------- ### Quick Start: Create, Execute, Shell, and Kill Sandbox Source: https://docs.opencomputer.dev/cli/overview A basic workflow demonstrating how to create a sandbox, execute a command within it, open an interactive shell, and then clean up by killing the sandbox. ```bash # Create a sandbox oc create # Run a command and wait for the result oc exec sb-abc123 --wait -- echo "Hello from the cloud" # Open an interactive shell oc shell sb-abc123 # Clean up oc sandbox kill sb-abc123 ``` -------------------------------- ### Install OpenComputer Skill Source: https://docs.opencomputer.dev/guides/agent-skill Install the OpenComputer skill using npx. This command is compatible with agents supporting the Agent Skills standard. ```bash npx skills add diggerhq/opencomputer ``` -------------------------------- ### Image Builder Initialization Source: https://docs.opencomputer.dev/reference/python-sdk/image Demonstrates how to start building a sandbox image using the `Image.base()` method and chaining other configuration methods. ```APIDOC ## Image.base() ### Description Start from the default OpenSandbox environment (Ubuntu 22.04, Python, Node.js, build tools). ### Method `Image.base()` ### Endpoint N/A (Class method for initialization) ### Request Example ```python from opencomputer import Image image = ( Image.base() .apt_install(["curl", "jq"]) .pip_install(["requests", "pandas"]) .env({"PROJECT_ROOT": "/workspace"}) .workdir("/workspace") ) ``` ### Response #### Success Response (200) - **Image** (object) - Returns a new Image instance with applied configurations. ``` -------------------------------- ### POST /exec/start Source: https://docs.opencomputer.dev/sandboxes/running-commands Starts a new execution session with a specified command, arguments, environment variables, and working directory. ```APIDOC ## POST /exec/start ### Description Initiates a new process within the sandbox. ### Method POST ### Endpoint /exec/start ### Parameters #### Request Body - **command** (string) - Required - The command to execute - **args** (array) - Optional - Arguments for the command - **env** (object) - Optional - Environment variables - **cwd** (string) - Optional - Current working directory ``` -------------------------------- ### Install OpenComputer CLI for macOS (Intel) Source: https://docs.opencomputer.dev/cli/overview Installs the OpenComputer CLI for macOS on Intel architecture. Ensure you have `curl` and `chmod` available. ```bash curl -fsSL https://github.com/diggerhq/opencomputer/releases/latest/download/oc-darwin-amd64 -o /usr/local/bin/oc chmod +x /usr/local/bin/oc ``` -------------------------------- ### sandbox.exec.start Source: https://docs.opencomputer.dev/reference/typescript-sdk/exec Starts a long-running command with streaming capabilities, allowing for real-time output and interaction. ```APIDOC ## POST /sandbox/exec/start ### Description Start a long-running command with streaming. ### Method POST ### Endpoint /sandbox/exec/start ### Parameters #### Request Body - **command** (string) - Required - Command to execute - **args** (string[]) - Optional - Arguments for the command - **env** (Record) - Optional - Environment variables - **cwd** (string) - Optional - Working directory - **timeout** (number) - Optional - Timeout in seconds - **maxRunAfterDisconnect** (number) - Optional - Seconds to keep running after disconnect - **onStdout** ((data: Uint8Array) => void) - Optional - Stdout callback - **onStderr** ((data: Uint8Array) => void) - Optional - Stderr callback - **onExit** ((exitCode: number) => void) - Optional - Exit callback ### Response #### Success Response (200) - **sessionId** (string) - The ID of the created exec session. - **done** (Promise) - A promise that resolves with the exit code. - **sendStdin** (method) - Method to send input to the process. - **kill** (Promise) - Method to kill the process. - **close** (method) - Method to close the WebSocket connection. ### Request Example ```json { "command": "node server.js", "opts": { "onStdout": "(data) => process.stdout.write(data)" } } ``` ### Response Example ```json { "sessionId": "some-session-id", "done": ">", "sendStdin": "", "kill": ">", "close": "" } ``` ``` -------------------------------- ### Example: Rust Compilation Scaling Source: https://docs.opencomputer.dev/sandboxes/elasticity An example demonstrating how to alias the 'cargo' command to automatically scale up memory before compilation and scale back down afterward, optimizing resource usage for memory-intensive Rust builds. ```APIDOC ## Example: Rust Compilation This example shows how to create a shell alias for `cargo` to manage memory scaling automatically. ```bash alias cargo='_cargo_scaled' _cargo_scaled() { # Scale up to 16GB / 4 vCPU before build curl -sf -X POST http://169.254.169.254/v1/scale \ -H "Content-Type: application/json" -d '{"memoryMB": 16384}' # Run the actual cargo command command cargo "$@" local exit_code=$? # Scale back down to 4GB / 1 vCPU curl -sf -X POST http://169.254.169.254/v1/scale \ -H "Content-Type: application/json" -d '{"memoryMB": 4096}' return $exit_code } ``` Add this to your sandbox's `~/.bashrc` or inject it via `sandbox.exec.run` so every `cargo build`, `cargo test`, etc. automatically gets the extra resources. ``` -------------------------------- ### List and Get Sandboxes (CLI) Source: https://docs.opencomputer.dev/troubleshooting Use the CLI to list all sandboxes or get details about a specific sandbox. Useful for checking sandbox status. ```bash oc ls # list all sandboxes oc sandbox get sb-abc123 # check a specific sandbox ``` -------------------------------- ### Quick Start: Create Secret Store, Add Secret, Launch Sandbox Source: https://docs.opencomputer.dev/sandboxes/secrets Demonstrates the basic workflow of creating a secret store with egress restrictions, adding an encrypted secret, and launching a sandbox. Shows how secrets appear as sealed tokens inside the VM but are correctly substituted for HTTPS requests to allowed hosts. ```typescript import { Sandbox, SecretStore } from '@opencomputer/sdk'; // 1. Create a secret store with egress restrictions const store = await SecretStore.create({ name: 'my-agent-secrets', egressAllowlist: ['api.anthropic.com'], }); // 2. Add an encrypted secret await SecretStore.setSecret(store.id, 'ANTHROPIC_API_KEY', 'sk-ant-...'); // 3. Create a sandbox — secrets are injected as sealed tokens const sandbox = await Sandbox.create({ secretStore: 'my-agent-secrets', timeout: 600, }); // Inside the VM, the env var is sealed — not the real key const result = await sandbox.exec.run('echo $ANTHROPIC_API_KEY'); console.log(result.stdout); // "osb_sealed_7f3a9c..." // But HTTPS requests to allowed hosts get the real value via the proxy const apiResult = await sandbox.exec.run(` curl -s https://api.anthropic.com/v1/messages \ -H "x-api-key: $ANTHROPIC_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "content-type: application/json" \ -d '{"model":"claude-haiku-4-5-20251001","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}' `); console.log(apiResult.stdout); // 200 OK — real key was substituted by the proxy ``` ```python from opencomputer import Sandbox, SecretStore # 1. Create a secret store with egress restrictions store = await SecretStore.create( name='my-agent-secrets', egress_allowlist=['api.anthropic.com'], ) # 2. Add an encrypted secret await SecretStore.set_secret(store['id'], 'ANTHROPIC_API_KEY', 'sk-ant-...') # 3. Create a sandbox — secrets are injected as sealed tokens sandbox = await Sandbox.create( secret_store='my-agent-secrets', timeout=600, ) # Inside the VM, the env var is sealed — not the real key result = await sandbox.exec.run('echo $ANTHROPIC_API_KEY') print(result.stdout) # "osb_sealed_7f3a9c..." # But HTTPS requests to allowed hosts get the real value via the proxy api_result = await sandbox.exec.run( 'curl -s https://api.anthropic.com/v1/messages ' '-H "x-api-key: $ANTHROPIC_API_KEY" ' '-H "anthropic-version: 2023-06-01" ' '-H "content-type: application/json" ' '-d \'{"model":"claude-haiku-4-5-20251001","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}\'' ) print(api_result.stdout) # 200 OK — real key was substituted by the proxy ``` -------------------------------- ### Parallel Exploration Example Source: https://docs.opencomputer.dev/sandboxes/checkpoints Demonstrates creating a checkpoint and using it to run multiple parallel operations. ```APIDOC ## Parallel Exploration Example ### Description This example shows how to create a base checkpoint from a sandbox and then spawn multiple forks from that checkpoint to test different strategies in parallel. ### Code Example ```typescript const sandbox = await Sandbox.create(); await sandbox.exec.run("git clone https://github.com/user/repo /app"); const cp = await sandbox.createCheckpoint("fresh-clone"); const strategies = ["--strategy=ours", "--strategy=theirs", "--strategy=recursive"]; const results = await Promise.all( strategies.map(async (strategy) => { const fork = await Sandbox.createFromCheckpoint(cp.id); const result = await fork.exec.run(`cd /app && git merge origin/main ${strategy}`); await fork.kill(); return { strategy, exitCode: result.exitCode }; }), ); ``` ``` -------------------------------- ### Create a Sandbox Checkpoint Source: https://docs.opencomputer.dev/cli/checkpoint Capture the current filesystem and installed state of a running sandbox. The status progresses from 'processing' to 'ready'. ```bash oc checkpoint create sb-abc123 --name before-migration ``` ```bash # or using the shortcut: oc cp create sb-abc123 --name before-migration ``` -------------------------------- ### List Directory Response Example Source: https://docs.opencomputer.dev/api-reference/files/list-directory Successful response showing directory contents including file names, directory status, size, and path. ```json [ { "name": "app", "isDir": true, "size": 4096, "path": "/app" }, { "name": "README.md", "isDir": false, "size": 1234, "path": "/README.md" } ] ``` -------------------------------- ### exec.start() Source: https://docs.opencomputer.dev/sandboxes/running-commands Start a command as an exec session for long-running processes or streaming output. ```APIDOC ## exec.start() ### Description Start a command as an exec session for long-running processes or streaming output. ### Parameters #### Request Body - **args** (string[]) - Optional - Command arguments. - **env** (object) - Optional - Environment variables. - **cwd** (string) - Optional - Working directory. - **timeout** (number) - Optional - Timeout in seconds. - **maxRunAfterDisconnect** (number) - Optional - Seconds to keep running after disconnect. - **onStdout** (callback) - Optional - Callback for stdout data. - **onStderr** (callback) - Optional - Callback for stderr data. - **onExit** (callback) - Optional - Callback for exit code. ``` -------------------------------- ### POST /api-reference/exec/create-session Source: https://docs.opencomputer.dev/reference/python-sdk/exec Starts a long-running command session in the sandbox. ```APIDOC ## POST /api-reference/exec/create-session ### Description Start a long-running command. Returns the session ID. ### Method POST ### Endpoint /api-reference/exec/create-session ### Parameters #### Request Body - **command** (str) - Required - Command - **args** (list[str]) - Optional - Arguments - **env** (dict[str, str]) - Optional - Environment variables - **cwd** (str) - Optional - Working directory - **timeout** (int) - Optional - Timeout in seconds ### Response #### Success Response (200) - **session_id** (str) - The unique identifier for the started session ``` -------------------------------- ### Install OpenComputer CLI for macOS (Apple Silicon) Source: https://docs.opencomputer.dev/cli/overview Installs the OpenComputer CLI for macOS on Apple Silicon architecture. Ensure you have `curl` and `chmod` available. ```bash curl -fsSL https://github.com/diggerhq/opencomputer/releases/latest/download/oc-darwin-arm64 -o /usr/local/bin/oc chmod +x /usr/local/bin/oc ``` -------------------------------- ### List Patches Response Example Source: https://docs.opencomputer.dev/api-reference/patches/list Example of a successful response when listing patches for a checkpoint. The response is a JSON array of patch objects. ```json [ { "id": "pa-abc123", "checkpointId": "cp-abc123", "script": "apt install -y curl", "description": "Install curl", "strategy": "on_wake", "sequence": 1, "createdAt": "2025-01-15T10:30:00Z" } ] ``` -------------------------------- ### Create and Fork Sandboxes from Checkpoint Source: https://docs.opencomputer.dev/sandboxes/checkpoints Create a sandbox, run setup commands, create a checkpoint, and then fork two independent sandboxes from that checkpoint to run different tests. ```typescript import { Sandbox } from "@opencomputer/sdk"; const sandbox = await Sandbox.create(); await sandbox.exec.run("npm install && npm run build", { cwd: "/app" }); // Checkpoint after setup const cp = await sandbox.createCheckpoint("after-build"); // Fork two independent sandboxes const a = await Sandbox.createFromCheckpoint(cp.id); const b = await Sandbox.createFromCheckpoint(cp.id); await a.exec.run("npm run test:unit", { cwd: "/app" }); await b.exec.run("npm run test:e2e", { cwd: "/app" }); ``` ```python from opencomputer import Sandbox sandbox = await Sandbox.create() await sandbox.exec.run("npm install && npm run build", cwd="/app") cp = await sandbox.create_checkpoint("after-build") a = await Sandbox.create_from_checkpoint(cp["id"]) b = await Sandbox.create_from_checkpoint(cp["id"]) await a.exec.run("npm run test:unit", cwd="/app") await b.exec.run("npm run test:e2e", cwd="/app") ``` -------------------------------- ### Create Explicit Preview URL (Python) Source: https://docs.opencomputer.dev/sandboxes/preview-urls Create a preview URL for a specific port to enable tracking, custom domains, or auth configuration. Requires starting a development server on the specified port within the sandbox. ```python from opencomputer import Sandbox sandbox = await Sandbox.create() await sandbox.exec.run("npx create-next-app@latest /app --yes", timeout=120) await sandbox.exec.start("npm run dev -- --port 3000", cwd="/app") preview = await sandbox.create_preview_url(port=3000) print(preview["hostname"]) ``` -------------------------------- ### Fork from Checkpoint Response Source: https://docs.opencomputer.dev/api-reference/checkpoints/fork Example response returned after successfully creating a new sandbox from a checkpoint. ```json { "sandboxID": "sb-def456", "status": "running", "region": "use2", "workerID": "w-use2-abc123" } ``` -------------------------------- ### Perform Rolling Fleet Update Source: https://docs.opencomputer.dev/guides/deploy-openclaw Execute a rolling update across the entire fleet of agents. Specify the desired version, for example, 'latest'. Ensure Node.js and TypeScript are installed. ```bash npx tsx src/fleet-update.ts --version latest ``` -------------------------------- ### List Sandbox Checkpoints Response Source: https://docs.opencomputer.dev/api-reference/checkpoints/list Example response showing the structure of a sandbox checkpoint list. ```json [ { "id": "cp-abc123", "sandboxID": "sb-abc123", "name": "before-migration", "status": "ready", "sizeBytes": 134217728, "createdAt": "2025-01-15T10:30:00Z" } ] ``` -------------------------------- ### Get Preview Domain Source: https://docs.opencomputer.dev/reference/typescript-sdk/sandbox Constructs the preview URL hostname locally for a given port. ```typescript const domain = sandbox.getPreviewDomain(3000); console.log(`https://${domain}`); ``` -------------------------------- ### Session Result Response Examples Source: https://docs.opencomputer.dev/agents-api/sessions Example responses for session result requests based on the current state of the agent. ```text -- While running: 409 { "error": { "type": "conflict", "message": "Session still running" } } -- When complete: 200 { "data": { "pr_url": "https://..." }, "completed_at": "2026-04-09T..." } -- If no result written: 200 { "data": null, "completed_at": "2026-04-09T..." } ``` -------------------------------- ### Example: Auto-Scaling Script Source: https://docs.opencomputer.dev/sandboxes/elasticity A sample shell script that monitors memory pressure within the sandbox and automatically scales memory up or down based on predefined thresholds and cooldown periods. ```APIDOC ## Example: Auto-Scaling Script A simple shell script that monitors memory pressure and scales automatically. ```bash #!/bin/sh SCALE_API="http://169.254.169.254/v1/scale" MIN_MB=1024 MAX_MB=8192 SCALE_UP_THRESHOLD=80 SCALE_DOWN_THRESHOLD=30 COOLDOWN=30 last_scale=0 while true; do mem_total=$(awk '/MemTotal/{print $2}' /proc/meminfo) mem_avail=$(awk '/MemAvailable/{print $2}' /proc/meminfo) usage_pct=$(( (mem_total - mem_avail) * 100 / mem_total )) total_mb=$((mem_total / 1024)) now=$(date +%s) elapsed=$((now - last_scale)) if [ $usage_pct -gt $SCALE_UP_THRESHOLD ] && [ $elapsed -gt $COOLDOWN ]; then new_mb=$((total_mb * 2)) [ $new_mb -gt $MAX_MB ] && new_mb=$MAX_MB if [ $new_mb -gt $total_mb ]; then echo "usage=$usage_pct% -> scaling UP to ${new_mb}MB" curl -sf -X POST "$SCALE_API" \ -H "Content-Type: application/json" \ -d "{\"memoryMB\":$new_mb}" last_scale=$now fi elif [ $usage_pct -lt $SCALE_DOWN_THRESHOLD ] && [ $total_mb -gt $MIN_MB ] && [ $elapsed -gt $COOLDOWN ]; then new_mb=$((total_mb / 2)) [ $new_mb -lt $MIN_MB ] && new_mb=$MIN_MB if [ $new_mb -lt $total_mb ]; then echo "usage=$usage_pct% -> scaling DOWN to ${new_mb}MB" curl -sf -X POST "$SCALE_API" \ -H "Content-Type: application/json" \ -d "{\"memoryMB\":$new_mb}" last_scale=$now fi fi sleep 5 done ``` ``` -------------------------------- ### Hibernate and Wake Sandbox for Cost Savings Source: https://docs.opencomputer.dev/cli/overview Demonstrates how to hibernate a sandbox to save costs and then wake it up later to resume work, followed by opening an interactive shell. ```bash oc sandbox hibernate sb-abc123 # ... hours later ... oc sandbox wake sb-abc123 oc shell sb-abc123 ``` -------------------------------- ### Create Sandbox and Run Basic Command Source: https://docs.opencomputer.dev/sandboxes/running-commands Initializes a sandbox and executes a simple 'echo' command, logging the standard output. Ensure the sandbox is killed after use to free resources. ```typescript import { Sandbox } from "@opencomputer/sdk"; const sandbox = await Sandbox.create(); const result = await sandbox.exec.run("echo Hello, World!"); console.log(result.stdout); // "Hello, World!\n" await sandbox.kill(); ``` ```python from opencomputer import Sandbox async with await Sandbox.create() as sandbox: result = await sandbox.exec.run("echo Hello, World!") print(result.stdout) # "Hello, World!\n" ``` -------------------------------- ### POST /snapshots Source: https://docs.opencomputer.dev/api-reference/snapshots/create Creates a pre-built sandbox environment from a declarative image manifest. ```APIDOC ## POST /snapshots ### Description Create a pre-built sandbox environment from a declarative image manifest. ### Method POST ### Endpoint /snapshots ### Parameters #### Request Body - **name** (string) - Required - Unique snapshot name - **image** (object) - Required - Declarative image manifest ### Request Example { "name": "data-science", "image": { "steps": [] } } ### Response #### Success Response (201) - **id** (string) - Unique snapshot identifier - **name** (string) - Snapshot name - **status** (string) - Current build status - **contentHash** (string) - SHA256 hash of content - **checkpointId** (string) - Checkpoint identifier - **manifest** (object) - Image manifest - **createdAt** (string) - Creation timestamp - **lastUsedAt** (string) - Last usage timestamp #### Response Example { "id": "snap-abc123", "name": "data-science", "status": "building", "contentHash": "sha256:...", "checkpointId": "", "manifest": { "steps": [] }, "createdAt": "2025-01-15T10:30:00Z", "lastUsedAt": "" } ``` -------------------------------- ### Create Explicit Preview URL (TypeScript) Source: https://docs.opencomputer.dev/sandboxes/preview-urls Create a preview URL for a specific port to enable tracking, custom domains, or auth configuration. Requires starting a development server on the specified port within the sandbox. ```typescript import { Sandbox } from "@opencomputer/sdk"; const sandbox = await Sandbox.create(); await sandbox.exec.run("npx create-next-app@latest /app --yes", { timeout: 120 }); sandbox.exec.start("npm run dev -- --port 3000", { cwd: "/app" }); const preview = await sandbox.createPreviewURL({ port: 3000 }); console.log(preview.hostname); // sb-abc123-p3000.workers.opencomputer.dev ``` -------------------------------- ### Expose Multiple Services from a Sandbox Source: https://docs.opencomputer.dev/cli/preview You can expose multiple services running on different ports within the same sandbox by issuing separate `oc preview create` commands for each port. The `oc preview list` command will then show all active previews with their respective hostnames. ```bash oc preview create sb-abc123 --port 3000 # Frontend oc preview create sb-abc123 --port 8080 # API server oc preview list sb-abc123 # PORT HOSTNAME SSL CREATED # 3000 sb-abc123-p3000.workers.opencomputer.dev active ... # 8080 sb-abc123-p8080.workers.opencomputer.dev active ... ``` -------------------------------- ### Configure Environment Variables Source: https://docs.opencomputer.dev/guides/build-a-lovable-clone Sets up the required API keys and optional domain configuration in a .env file. ```bash ANTHROPIC_API_KEY=sk-ant-... OPENCOMPUTER_API_KEY=your-opencomputer-token DEPLOY_DOMAIN=mycompany.com # optional — defaults to openlovable.cc ``` -------------------------------- ### Start Async Command with Streaming Output Source: https://docs.opencomputer.dev/sandboxes/running-commands Initiates a command as an asynchronous session, enabling real-time handling of stdout and stderr streams via callbacks. Supports configuring environment variables, working directory, and a timeout for the process. ```typescript const session = await sandbox.exec.start("node server.js", { cwd: "/app", env: { PORT: "3000" }, onStdout: (data) => process.stdout.write(data), onStderr: (data) => process.stderr.write(data), onExit: (code) => console.log("Server exited:", code), maxRunAfterDisconnect: 300, // keep running 5min after disconnect }); // Send input session.sendStdin("some input\n"); // Wait for completion (or kill) await session.kill(); ``` -------------------------------- ### Create an Instance Source: https://docs.opencomputer.dev/agents-api/instances Initiates the provisioning of a new sandbox for a specific agent. ```http POST /v1/agents/:agentId/instances ``` ```json { "metadata": { "slack_user": "U123", "team": "engineering" } } ``` -------------------------------- ### Create Preview URL with Custom Domain (Python) Source: https://docs.opencomputer.dev/sandboxes/preview-urls Create a preview URL for a specific port, optionally specifying a custom domain. SSL is provisioned automatically. ```python preview = await sandbox.create_preview_url( port=3000, domain="preview.myapp.com", ) ``` -------------------------------- ### GET /api-reference/preview/list Source: https://docs.opencomputer.dev/reference/typescript-sdk/sandbox List all preview URLs. ```APIDOC ## GET /api-reference/preview/list ### Description List all active preview URLs for the sandbox. ### Method GET ### Endpoint /api-reference/preview/list ### Response #### Success Response (200) - **PreviewURLResult[]** (array) - List of preview URL objects. ``` -------------------------------- ### GET /api-reference/checkpoints/list Source: https://docs.opencomputer.dev/reference/typescript-sdk/sandbox List all checkpoints for the sandbox. ```APIDOC ## GET /api-reference/checkpoints/list ### Description Retrieve a list of all checkpoints associated with the sandbox. ### Method GET ### Endpoint /api-reference/checkpoints/list ### Response #### Success Response (200) - **CheckpointInfo[]** (array) - List of checkpoint objects. ``` -------------------------------- ### GET /api-reference/snapshots/list Source: https://docs.opencomputer.dev/reference/typescript-sdk/snapshots Retrieves a list of all available snapshots. ```APIDOC ## GET /api-reference/snapshots/list ### Description List all snapshots. ### Method GET ### Endpoint /api-reference/snapshots/list ### Response #### Success Response (200) - **SnapshotInfo[]** (array) - A list of all snapshots. ``` -------------------------------- ### Build Declarative Image and Create Sandbox (Python) Source: https://docs.opencomputer.dev/sandboxes/templates Define an image with apt and pip packages, environment variables, and working directory using the SDK. The image is built on the first run and cached for subsequent sandbox creations. ```python from opencomputer import Sandbox, Image # Define an image with packages, env vars, and files image = ( Image.base() .apt_install(["curl", "jq"]) .pip_install(["requests", "pandas"]) .env({"PROJECT_ROOT": "/workspace"}) .workdir("/workspace") ) # Create a sandbox — the image is built on first run, cached after sandbox = await Sandbox.create( image=image, timeout=300, on_build_log=lambda log: print(f"build: {log}"), ) result = await sandbox.exec.run("which curl") print(result.exit_code) # 0 ``` -------------------------------- ### GET /api-reference/snapshots/get Source: https://docs.opencomputer.dev/reference/typescript-sdk/snapshots Retrieves details for a specific snapshot by its name. ```APIDOC ## GET /api-reference/snapshots/get ### Description Get a snapshot by name. ### Method GET ### Endpoint /api-reference/snapshots/get ### Parameters #### Path Parameters - **name** (string) - Required - Snapshot name ### Response #### Success Response (200) - **SnapshotInfo** (object) - The snapshot details. ``` -------------------------------- ### Create a New Sandbox Source: https://docs.opencomputer.dev/cli/sandbox Provisions a new sandbox VM. The sandbox ID is printed on success. Use `--json` to capture it programmatically. ```bash oc create ``` ```bash oc create --timeout 600 --cpu 2 --memory 2048 --env NODE_ENV=production ``` ```bash ID=$(oc create --json | jq -r '.sandboxID') ``` -------------------------------- ### GET /api-reference/sandboxes/list Source: https://docs.opencomputer.dev/reference/cli/sandbox Retrieves a list of all currently running sandboxes. ```APIDOC ## GET /api-reference/sandboxes/list ### Description List all running sandboxes. ### Method GET ### Endpoint /api-reference/sandboxes/list ``` -------------------------------- ### GET /api-reference/patches/list Source: https://docs.opencomputer.dev/reference/cli/patch Lists all patches associated with a specific checkpoint. ```APIDOC ## GET /api-reference/patches/list ### Description Lists all patches associated with a specific checkpoint. Output includes ID, SEQ, DESCRIPTION, STRATEGY, and CREATED columns. ### Method GET ### Endpoint /api-reference/patches/list ``` -------------------------------- ### GET /api-reference/checkpoints/list Source: https://docs.opencomputer.dev/reference/cli/checkpoint List all checkpoints associated with a specific sandbox. ```APIDOC ## GET /api-reference/checkpoints/list ### Description List checkpoints for a sandbox. ### Method GET ### Endpoint /api-reference/checkpoints/list ``` -------------------------------- ### Checkpoint and Fork Sandboxes Source: https://docs.opencomputer.dev/cli/overview Creates a checkpoint named 'ready-state', then spawns two new sandboxes from a checkpoint ('cp-xyz'), and runs different test scripts in each. ```bash oc cp create sb-abc --name ready-state ID1=$(oc cp spawn cp-xyz --json | jq -r '.sandboxID') ID2=$(oc cp spawn cp-xyz --json | jq -r '.sandboxID') oc exec $ID1 --wait -- ./test-a.sh oc exec $ID2 --wait -- ./test-b.sh ``` -------------------------------- ### POST /api-reference/preview/create Source: https://docs.opencomputer.dev/reference/typescript-sdk/sandbox Create a preview URL for a specific port. ```APIDOC ## POST /api-reference/preview/create ### Description Create a preview URL for a container port. ### Method POST ### Endpoint /api-reference/preview/create ### Parameters #### Request Body - **port** (number) - Required - Container port (1–65535) - **domain** (string) - Optional - Custom domain - **authConfig** (object) - Optional - Auth configuration ### Response #### Success Response (200) - **PreviewURLResult** (object) - The created preview URL details. ``` -------------------------------- ### GET /sandboxes Source: https://docs.opencomputer.dev/api-reference/sandboxes/list Retrieves a list of all currently running sandboxes. ```APIDOC ## GET /sandboxes ### Description List all running sandboxes. ### Method GET ### Endpoint /sandboxes ### Response #### Success Response (200) - **sandboxID** (string) - Unique identifier for the sandbox - **status** (string) - Current status of the sandbox - **region** (string) - Deployment region - **workerID** (string) - Identifier for the worker node #### Response Example [ { "sandboxID": "sb-abc123", "status": "running", "region": "use2", "workerID": "w-use2-abc123" } ] ``` -------------------------------- ### GET /preview-urls Source: https://docs.opencomputer.dev/sandboxes/preview-urls Lists all active preview URLs associated with the sandbox. ```APIDOC ## GET /preview-urls ### Description Retrieves a list of all currently active preview URLs for the sandbox. ``` -------------------------------- ### POST /api-reference/sandboxes/create Source: https://docs.opencomputer.dev/reference/cli/sandbox Creates a new sandbox instance with specified resource constraints and environment variables. ```APIDOC ## POST /api-reference/sandboxes/create ### Description Create a new sandbox instance. ### Method POST ### Endpoint /api-reference/sandboxes/create ### Parameters #### Query Parameters - **--timeout** (int) - Optional - Idle timeout in seconds (default: 300) - **--cpu** (int) - Optional - CPU cores (0 = platform default) - **--memory** (int) - Optional - Memory in MB (0 = platform default) - **--env** (string) - Optional - Environment variable KEY=VALUE (repeatable) - **--metadata** (string) - Optional - Metadata KEY=VALUE (repeatable) ``` -------------------------------- ### GET /api-reference/exec/list-sessions Source: https://docs.opencomputer.dev/reference/cli/exec Lists all active execution sessions for a specific sandbox. ```APIDOC ## GET /api-reference/exec/list-sessions ### Description List active exec sessions for a sandbox. Returns session ID, status (running or exited), command, and client count. ### Method GET ### Endpoint /api-reference/exec/list-sessions ``` -------------------------------- ### Use Custom Domains for Preview URLs Source: https://docs.opencomputer.dev/cli/preview To use your own domain for a preview URL, pass the `--domain` flag with your desired domain name. Ensure your DNS records point to OpenComputer's ingress and that the domain is verified in the dashboard. SSL certificates are automatically provisioned. ```bash oc preview create sb-abc123 --port 3000 --domain preview.myapp.com ``` -------------------------------- ### GET /api-reference/exec/list-sessions Source: https://docs.opencomputer.dev/reference/python-sdk/exec Retrieves a list of all currently active exec sessions. ```APIDOC ## GET /api-reference/exec/list-sessions ### Description List all exec sessions. ### Method GET ### Endpoint /api-reference/exec/list-sessions ### Response #### Success Response (200) - **sessions** (list[ExecSessionInfo]) - List of active session objects ``` -------------------------------- ### GET /api-reference/sandboxes/get Source: https://docs.opencomputer.dev/reference/cli/sandbox Retrieves detailed information for a specific sandbox by its ID. ```APIDOC ## GET /api-reference/sandboxes/get ### Description Show detailed information for a sandbox. ### Method GET ### Endpoint /api-reference/sandboxes/get/ ``` -------------------------------- ### GET /snapshots/{name} Source: https://docs.opencomputer.dev/api-reference/snapshots/get Retrieves the details of a specific snapshot by its name. ```APIDOC ## GET /snapshots/{name} ### Description Retrieves the details of a specific snapshot by its name. ### Method GET ### Endpoint /snapshots/{name} ### Parameters #### Path Parameters - **name** (string) - Required - Snapshot name ### Response #### Success Response (200) - **id** (string) - Snapshot ID - **name** (string) - Snapshot name - **status** (string) - Current status of the snapshot - **contentHash** (string) - Content hash of the snapshot - **checkpointId** (string) - Associated checkpoint ID - **manifest** (object) - Snapshot manifest - **createdAt** (string) - Creation timestamp - **lastUsedAt** (string) - Last usage timestamp #### Response Example { "id": "snap-abc123", "name": "data-science", "status": "ready", "contentHash": "sha256:...", "checkpointId": "cp-abc123", "manifest": { "steps": [] }, "createdAt": "2025-01-15T10:30:00Z", "lastUsedAt": "2025-01-16T08:00:00Z" } ``` -------------------------------- ### Create and Manage Sandbox Files Source: https://docs.opencomputer.dev/sandboxes/working-with-files Initialize a sandbox, write a file, read its content, and then terminate the sandbox. Ensure the sandbox is properly closed after use. ```typescript import { Sandbox } from "@opencomputer/sdk"; const sandbox = await Sandbox.create(); await sandbox.files.write("/app/hello.txt", "Hello, World!"); const content = await sandbox.files.read("/app/hello.txt"); console.log(content); // "Hello, World!" await sandbox.kill(); ``` ```python from opencomputer import Sandbox async with await Sandbox.create() as sandbox: await sandbox.files.write("/app/hello.txt", "Hello, World!") content = await sandbox.files.read("/app/hello.txt") print(content) # "Hello, World!" ``` -------------------------------- ### POST /api-reference/preview/create Source: https://docs.opencomputer.dev/reference/cli/preview Exposes a specific container port to the internet to create a preview URL for a sandbox. ```APIDOC ## POST /api-reference/preview/create ### Description Expose sandbox ports to the internet to generate a preview URL. ### Method POST ### Endpoint /api-reference/preview/create ### Parameters #### Query Parameters - **--port** (int) - Required - Container port to expose - **--domain** (string) - Optional - Custom domain ``` -------------------------------- ### GET /v1/agents/:agentId/sessions/:id Source: https://docs.opencomputer.dev/agents-api/sessions Retrieves the details of a specific session. ```APIDOC ## GET /v1/agents/:agentId/sessions/:id ### Description Retrieves the current state and details of a specific session. ### Method GET ### Endpoint /v1/agents/:agentId/sessions/:id ### Parameters #### Path Parameters - **agentId** (string) - Required - The ID of the agent. - **id** (string) - Required - The ID of the session. ``` -------------------------------- ### Create a preview URL for a sandbox Source: https://docs.opencomputer.dev/reference/cli/preview Exposes a specific container port to the internet. Requires the sandbox ID and the target port. ```bash oc preview create sb-abc --port 3000 ``` -------------------------------- ### Get Session Result Source: https://docs.opencomputer.dev/agents-api/sessions Retrieve the output of an agent session after completion. ```http GET /v1/agents/:agentId/sessions/:id/result ``` -------------------------------- ### Hibernate Sandbox Response Source: https://docs.opencomputer.dev/api-reference/sandboxes/hibernate Example response returned after successfully hibernating a sandbox. ```json { "sandboxID": "sb-abc123", "hibernationKey": "checkpoints/sb-abc123/1234567890.tar.zst", "sizeBytes": 134217728, "status": "hibernated" } ``` -------------------------------- ### POST /create-preview-url Source: https://docs.opencomputer.dev/api-reference/preview/create Creates a preview URL to expose a port from the sandbox. ```APIDOC ## POST /create-preview-url ### Description Creates a preview URL to expose a port from the sandbox. ### Method POST ### Endpoint /create-preview-url ### Parameters #### Path Parameters - **id** (string) - Required - Sandbox ID #### Request Body - **port** (integer) - Required - Container port (1–65535) - **domain** (string) - Optional - Custom domain - **authConfig** (object) - Optional - Authentication configuration ### Request Example ```json { "port": 3000, "domain": "example.com", "authConfig": {} } ``` ### Response #### Success Response (201) - **id** (string) - Unique identifier for the preview URL - **sandboxId** (string) - The ID of the sandbox - **hostname** (string) - The hostname of the preview URL - **port** (integer) - The exposed container port - **sslStatus** (string) - The SSL status of the preview URL - **createdAt** (string) - The timestamp when the preview URL was created #### Response Example ```json { "id": "pv-abc123", "sandboxId": "sb-abc123", "hostname": "sb-abc123-p3000.workers.opencomputer.dev", "port": 3000, "sslStatus": "active", "createdAt": "2025-01-15T10:30:00Z" } ``` ``` -------------------------------- ### SSE Response Stream Source: https://docs.opencomputer.dev/agents-api/instances Example of Server-Sent Events returned when sending a message. ```text data: {"type":"text","content":"Cloning the repo now...","conversation_id":"1712345678.123456"} data: {"type":"text","content":"Found 3 issues...","conversation_id":"1712345678.123456"} data: {"type":"done"} ``` -------------------------------- ### GET /exec/list Source: https://docs.opencomputer.dev/sandboxes/running-commands Retrieves a list of all currently running or exited execution sessions. ```APIDOC ## GET /exec/list ### Description Lists all execution sessions, providing status, exit codes, and attached client information. ### Method GET ### Endpoint /exec/list ``` -------------------------------- ### Get Snapshot by Name Source: https://docs.opencomputer.dev/reference/typescript-sdk/snapshots Retrieve a specific snapshot using its unique name. ```typescript snapshots.get("my-snapshot"); ``` -------------------------------- ### Create a New Sandbox Source: https://docs.opencomputer.dev/reference/python-sdk/sandbox Use `Sandbox.create` to initialize a new sandbox. Specify a template and an optional idle timeout in seconds. Falls back to environment variables for API key and URL if not provided. ```python sandbox = await Sandbox.create(template="my-stack", timeout=600) ```