### Start with Base Image and Install Packages Source: https://github.com/diggerhq/opencomputer/blob/main/docs/reference/python-sdk/image.mdx Begin with the default OpenSandbox environment and install system and Python packages. Set environment variables and the working directory for the image build. ```python from opencomputer import Image image = ( Image.base() .apt_install(["curl", "jq"]) .pip_install(["requests", "pandas"]) .env({"PROJECT_ROOT": "/workspace"}) .workdir("/workspace") ) ``` -------------------------------- ### Example: Mount Directory with bindfs Source: https://github.com/diggerhq/opencomputer/blob/main/docs/sandboxes/mounts.mdx Mirror a local directory to another path using bindfs. This example first installs bindfs and then configures the mount, allowing reads and writes to pass through to the source directory. ```typescript await sandbox.exec.run("apt-get update && apt-get install -y bindfs"); await sandbox.mounts.add({ path: "/mnt/mirror", driver: "command", command: ["bindfs", "-f", "-o", "allow_other", "/home/sandbox/data", "{mountpoint}"], readOnly: false, }); // reads/writes under /mnt/mirror now pass through to /home/sandbox/data ``` -------------------------------- ### UI Development Workflow Source: https://github.com/diggerhq/opencomputer/blob/main/deploy/ec2/README.md Sets up the UI development environment by installing dependencies and starting the development server. This should be run in a separate terminal. ```bash cd web && npm install && npm run dev # http://localhost:3000 ``` -------------------------------- ### Create and Run Sandbox (Python) Source: https://github.com/diggerhq/opencomputer/blob/main/docs/quickstart.mdx Create a new sandbox, run a command within it, and then kill the sandbox. Ensure the SDK is installed. This example uses asyncio for asynchronous operations. ```python import asyncio from opencomputer import Sandbox async def main(): sandbox = await Sandbox.create() # Run a command inside the sandbox result = await sandbox.commands.run("echo 'Hello World from OpenSandbox!'") print(result.stdout) await sandbox.kill() asyncio.run(main()) ``` -------------------------------- ### Install @opencomputer/sdk Source: https://github.com/diggerhq/opencomputer/blob/main/docs/reference/typescript-sdk/overview.mdx Install the SDK using npm, yarn, or pnpm. ```bash npm install @opencomputer/sdk ``` ```bash yarn add @opencomputer/sdk ``` ```bash pnpm add @opencomputer/sdk ``` -------------------------------- ### Install OpenComputer SDK Source: https://github.com/diggerhq/opencomputer/blob/main/README.md Install the OpenComputer SDK using npm for Node.js or pip for Python. ```bash npm install @opencomputer/sdk ``` ```bash pip install opencomputer-sdk ``` -------------------------------- ### Install VNC Stack Source: https://github.com/diggerhq/opencomputer/blob/main/docs/guides/browser-automation.mdx Installs the necessary VNC components (xvfb, x11vnc, novnc, websockify) using apt-get. This command should be run within the sandbox environment. ```typescript await sandbox.commands.run( "sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq xvfb x11vnc novnc websockify", ); ``` -------------------------------- ### Install Apt Packages Source: https://github.com/diggerhq/opencomputer/blob/main/docs/sdks/python/templates.mdx Installs system packages using apt-get. Provide a list of package names. ```python image = Image.base().apt_install(["curl", "git", "jq"]) ``` -------------------------------- ### Install and Configure oc CLI Source: https://github.com/diggerhq/opencomputer/blob/main/docs/guides/agent-skill.mdx Install the `oc` CLI using a script and configure it with an API key. This is a prerequisite for using the OpenComputer skill. ```bash curl -fsSL https://raw.githubusercontent.com/digger/opencomputer/main/scripts/install.sh | bash oc config set api-key YOUR_API_KEY ``` -------------------------------- ### Python: Setup Burst Sandbox with Restart Hook Source: https://github.com/diggerhq/opencomputer/blob/main/docs/sandboxes/burst-sandboxes.mdx Sets up a burst sandbox, installs a restart-notice hook, and writes a worker script. The worker script handles resuming from a previous state after a restart. Use this for agent or batch systems requiring resilience to restarts. ```python from opencomputer import Sandbox sandbox = await Sandbox.create(burst=True, timeout=0) await sandbox.exec.run("mkdir -p /home/sandbox/.opencomputer /home/sandbox/app") await sandbox.files.write( "/home/sandbox/.opencomputer/on-restart-notice", "#!/bin/sh set -eu echo \"restart notice: ${1:-25}s\" >> /home/sandbox/app/events.log touch /home/sandbox/app/restarting sync ", ) await sandbox.exec.run("chmod +x /home/sandbox/.opencomputer/on-restart-notice") await sandbox.files.write( "/home/sandbox/app/worker.sh", "#!/bin/sh set -eu cd /home/sandbox/app if [ -f restarting ]; then echo \"resumed after restart\" >> events.log rm -f restarting else echo \"started\" >> events.log fi i=$(cat counter 2>/dev/null || echo 0) while true; do i=$((i + 1)) echo \"$i\" > counter sync sleep 5 done ", ) await sandbox.exec.run("chmod +x /home/sandbox/app/worker.sh") await sandbox.exec.background( "/home/sandbox/app/worker.sh", max_run_after_disconnect=0, ) ``` -------------------------------- ### Create Sandbox Request Example Source: https://github.com/diggerhq/opencomputer/blob/main/docs/api-reference/sandboxes/create.mdx This example demonstrates a basic request to create a sandbox with a specified template ID and resource allocation. It includes environment variables and metadata for further customization. ```json { "templateID": "base", "cpuCount": 1, "memoryMB": 1024, "envs": { "MY_VAR": "my_value" }, "metadata": { "user": "test" } } ``` -------------------------------- ### Install OpenComputer CLI Source: https://github.com/diggerhq/opencomputer/blob/main/docs/introduction.mdx Install the OpenComputer command-line interface (CLI) using a curl script. This installs to ~/.local/bin without requiring sudo. ```bash # Installs to ~/.local/bin (no sudo). See cli/overview for manual install. curl -fsSL https://raw.githubusercontent.com/diggerhq/opencomputer/main/scripts/install.sh | bash ``` -------------------------------- ### Install OpenComputer SDK with npm Source: https://github.com/diggerhq/opencomputer/blob/main/docs/introduction.mdx Install the OpenComputer SDK using npm for Node.js environments. ```bash npm install @opencomputer/sdk ``` -------------------------------- ### Install OpenComputer SDK with pip Source: https://github.com/diggerhq/opencomputer/blob/main/docs/introduction.mdx Install the OpenComputer SDK using pip for Python environments. ```bash pip install opencomputer-sdk ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/diggerhq/opencomputer/blob/main/docs/guides/build-a-lovable-clone.mdx Clone the lovable repository and install all project dependencies using npm. ```bash git clone https://github.com/diggerhq/osslovable.git cd osslovable npm run install:all ``` -------------------------------- ### Start Development Server Source: https://github.com/diggerhq/opencomputer/blob/main/docs/guides/build-a-lovable-clone.mdx Start the development server for both the Express backend and Vite frontend. Access the application via http://localhost:5173. ```bash npm run dev ``` -------------------------------- ### POST /api/agent/start Source: https://github.com/diggerhq/opencomputer/blob/main/docs/reference/python-sdk/agent.mdx Starts a new agent session with the specified configuration. ```APIDOC ## POST /api/agent/start ### Description Starts an agent session. ### Method POST ### Endpoint /api/agent/start ### Parameters #### Request Body - **prompt** (str) - Required - Initial prompt for the agent. - **model** (str) - Required - The Claude model to use. - **system_prompt** (str) - Optional - System prompt for the agent. - **allowed_tools** (list[str]) - Optional - Restricts the tools the agent can use. - **permission_mode** (str) - Optional - The permission mode for the agent. - **max_turns** (int) - Optional - Maximum number of turns for the session. Defaults to 50. - **cwd** (str) - Optional - The current working directory for the agent. - **mcp_servers** (dict[str, Any]) - Optional - MCP server configuration. - **on_event** (Callable[[AgentEvent], None]) - Optional - Callback for agent events. - **on_error** (Callable[[str], None]) - Optional - Callback for agent errors. ### Request Example ```json { "prompt": "Build a todo app", "on_event": "lambda e: print(e.type)" } ``` ### Response #### Success Response (200) - **AgentSession** - An object representing the active agent session. #### Response Example ```json { "session_id": "sess_abc123", "sandbox_id": "sbx_xyz789" } ``` ``` -------------------------------- ### Connect Slack App Source: https://github.com/diggerhq/opencomputer/blob/main/docs/background-agents/quickstart.mdx Installs the OpenComputer Slack app. This is a preview feature. ```bash oc connect slack # install the OpenComputer Slack app (Preview — see below) ``` -------------------------------- ### Install OpenComputer CLI on Linux (x86_64) Source: https://github.com/diggerhq/opencomputer/blob/main/docs/cli/overview.mdx Use this command to download and install the OpenComputer CLI for Linux on x86_64 architecture. ```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 `oc` CLI Source: https://github.com/diggerhq/opencomputer/blob/main/skills/opencomputer/SKILL.md Installs the `oc` CLI using a one-liner script from the official GitHub repository. This command should be run if `which oc` returns no output. ```bash curl -fsSL https://raw.githubusercontent.com/diggerhq/opencomputer/main/scripts/install.sh | bash ``` -------------------------------- ### Start a New Session Source: https://github.com/diggerhq/opencomputer/blob/main/docs/background-agents/sessions.mdx Initiates a new session with a given name and description. This is the primary way to start a new task or workflow. ```bash oc session start fixer "migrate the date helpers to Temporal" ``` -------------------------------- ### Install OpenComputer CLI on Linux (ARM64) Source: https://github.com/diggerhq/opencomputer/blob/main/skills/opencomputer/README.md Manually install the OpenComputer CLI for Linux on ARM64 architecture. Ensure the binary is executable. ```bash # Linux (ARM64) curl -fsSL https://github.com/diggerhq/opencomputer/releases/latest/download/oc-linux-arm64 -o /usr/local/bin/oc chmod +x /usr/local/bin/oc ``` -------------------------------- ### image.aptInstall(packages) Source: https://github.com/diggerhq/opencomputer/blob/main/docs/reference/typescript-sdk/image.mdx Installs system packages using apt-get during the image build process. ```APIDOC ## image.aptInstall(packages) ### Parameters #### Request Body - **packages** (string[]) - Required - System packages to install via apt-get ### Returns `Image` ``` -------------------------------- ### Quick Start: Create and Use a Sandbox Source: https://github.com/diggerhq/opencomputer/blob/main/sdks/typescript/README.md Demonstrates creating a sandbox, executing commands, reading/writing files, and cleaning up the sandbox. ```typescript import { Sandbox } from "@opencomputer/sdk"; const sandbox = await Sandbox.create({ template: "base" }); // Execute commands const result = await sandbox.commands.run("echo hello"); console.log(result.stdout); // "hello\n" // Read and write files await sandbox.files.write("/tmp/test.txt", "Hello, world!"); const content = await sandbox.files.read("/tmp/test.txt"); // Clean up await sandbox.kill(); ``` -------------------------------- ### Install System Packages with aptInstall Source: https://github.com/diggerhq/opencomputer/blob/main/docs/reference/typescript-sdk/image.mdx Add system packages to be installed via apt-get during the image build process. Ensure the package names are valid for apt. ```typescript Image.base().aptInstall(['curl', 'jq']) ``` -------------------------------- ### Checkpoint Workflow: Setup Once, Fork Many Source: https://github.com/diggerhq/opencomputer/blob/main/skills/opencomputer/SKILL.md Illustrates setting up a base environment, checkpointing it, and then spawning multiple copies from the checkpoint. ```bash # Create base environment ID=$(oc create --json | jq -r '.sandboxID') oc exec $ID --wait -- apt update oc exec $ID --wait -- apt install -y python3 pip oc exec $ID --wait -- pip install flask # Checkpoint it CP=$(oc checkpoint create $ID --name "python-flask" --json | jq -r '.id') # Wait for checkpoint to be ready oc checkpoint list $ID # Spawn copies from the checkpoint FORK1=$(oc checkpoint spawn $CP --json | jq -r '.sandboxID') FORK2=$(oc checkpoint spawn $CP --json | jq -r '.sandboxID') ``` -------------------------------- ### Quick Start with OpenComputer SDK Source: https://github.com/diggerhq/opencomputer/blob/main/sdks/python/README.md Demonstrates creating a sandbox, running commands, and managing files using the OpenComputer Python SDK. Ensure you have an event loop running for asyncio operations. ```python import asyncio from opencomputer import Sandbox async def main(): sandbox = await Sandbox.create(template="base") # Execute commands result = await sandbox.commands.run("echo hello") print(result.stdout) # "hello\n" # Read and write files await sandbox.files.write("/tmp/test.txt", "Hello, world!") content = await sandbox.files.read("/tmp/test.txt") # Clean up await sandbox.kill() await sandbox.close() asyncio.run(main()) ``` -------------------------------- ### Example Turn Events Source: https://github.com/diggerhq/opencomputer/blob/main/docs/agent-sessions/events.mdx Illustrates the sequence of events that occur during a single agent turn, from start to completion. ```text turn.started tool.call npm test exec.completed exit 1 agent.message "3 tests fail" (level: user) turn.completed needs_input ``` -------------------------------- ### Instantiate Sandbox from Snapshot and Cleanup Source: https://github.com/diggerhq/opencomputer/blob/main/docs/sdks/typescript/templates.mdx This example shows how to instantly boot a sandbox from a pre-built snapshot. It then runs a command within the sandbox and proceeds to clean up the snapshot. This is useful for environments that are used frequently. ```typescript // Instant — no build, just boot from snapshot const mlSandbox = await Sandbox.create({ snapshot: 'ml-env' }); await mlSandbox.commands.run('python3 -c "import pandas; print(pandas.__version__)"'); await mlSandbox.kill(); // Cleanup await snapshots.delete('ml-env'); ``` -------------------------------- ### Get Sandbox Usage with cURL Source: https://github.com/diggerhq/opencomputer/blob/main/docs/sandboxes/usage.mdx Retrieve sandbox usage data using cURL by making a GET request to the API endpoint. You can specify a time range using `from` and `to` parameters. The output can be piped to `jq` for easy parsing, for example, to view the totals. ```bash curl -s "$OPENCOMPUTER_API_URL/api/sandboxes/sb-abc/usage?from=2026-05-27T00:00:00Z&to=2026-05-27T01:00:00Z" \ -H "X-API-Key: $OPENCOMPUTER_API_KEY" | jq '.totals' ``` -------------------------------- ### Get Usage Response (groupBy=sandbox) Source: https://github.com/diggerhq/opencomputer/blob/main/docs/api-reference/usage/get-usage.mdx Example response when grouping usage by sandbox. Includes total usage and a list of individual sandbox details. ```json { "from": "2026-03-23T00:00:00Z", "to": "2026-04-22T00:00:00Z", "groupBy": "sandbox", "total": { "memoryGbSeconds": 20000, "diskOverageGbSeconds": 360 }, "items": [ { "sandboxId": "sb-abc", "alias": "my-agent", "status": "running", "tags": { "env": "prod", "team": "payments" }, "tagsLastUpdatedAt": "2026-04-19T14:02:00Z", "memoryGbSeconds": 8000, "diskOverageGbSeconds": 120 } ], "nextCursor": null } ``` -------------------------------- ### GitHub Issue Labeled Trigger Source: https://github.com/diggerhq/opencomputer/blob/main/docs/agent-sessions/triggers.mdx Configure a GitHub trigger to start a session when an issue is labeled with 'agent'. This is an example of a TOML configuration for an agent trigger. ```toml [[triggers]] type = "github" on = "issue.labeled:agent" ``` -------------------------------- ### Create and Use a Sandbox Source: https://github.com/diggerhq/opencomputer/blob/main/skills/opencomputer/SKILL.md Demonstrates the basic workflow for creating a sandbox, executing commands within it, and then cleaning it up. ```bash ID=$(oc create --json | jq -r '.sandboxID') oc exec $ID --wait -- apt update oc exec $ID --wait -- apt install -y nodejs oc exec $ID -- node -e "console.log('hello')" oc sandbox kill $ID ``` -------------------------------- ### Create a Workspace Source: https://github.com/diggerhq/opencomputer/blob/main/docs/background-agents/quickstart.mdx Prepares a repository for an agent by cloning, running setup, and snapshotting. This is optional and in preview. ```bash oc workspace create web \ --repo github.com/acme/web \ --setup "pnpm i && pnpm build" ``` -------------------------------- ### Create Sandbox with On-Demand Image Source: https://github.com/diggerhq/opencomputer/blob/main/docs/how-it-works.mdx Create a sandbox using an on-demand image that is built and cached based on its content hash. This example installs curl and pandas. ```typescript // On-demand image (built + cached by content hash) const image = Image.base().aptInstall(['curl']).pipInstall(['pandas']); const sandbox = await Sandbox.create({ image }); ``` -------------------------------- ### Get Sandbox Tags Response Example Source: https://github.com/diggerhq/opencomputer/blob/main/docs/api-reference/sandboxes/get-tags.mdx This JSON object shows a successful response when retrieving tags for a sandbox. It includes the tags and the last updated timestamp. ```json { "tags": { "env": "prod", "team": "payments" }, "tagsLastUpdatedAt": "2026-04-19T14:02:00Z" } ``` -------------------------------- ### Get Delivery Response Example Source: https://github.com/diggerhq/opencomputer/blob/main/docs/api-reference/webhooks/delivery-get.mdx This JSON object represents a successful response when fetching a delivered webhook message. It contains details about the message event, payload, and timestamp. ```json { "id": "msg_2aB…", "eventType": "sandbox.stopped", "eventId": "sb-3f9a…:sandbox.stopped", "payload": { "type": "sandbox.stopped", "sandboxId": "sb-3f9a…", "eventId": "sb-3f9a…:sandbox.stopped", "event": { "id": "sb-3f9a…:sandbox.stopped", "ts": "2026-06-24T12:00:00Z", "orgId": "org_…", "sandboxId": "sb-3f9a…", "type": "sandbox.stopped", "data": { "reason": "user_requested" } } }, "timestamp": "2026-06-24T12:00:00Z" } ``` -------------------------------- ### Set Environment Variables Source: https://github.com/diggerhq/opencomputer/blob/main/docs/agent-sessions/quickstart.mdx Before running the quickstart, set your OpenComputer API key and Anthropic API key as environment variables. ```bash OPENCOMPUTER_API_KEY=osb_... ANTHROPIC_API_KEY=sk-ant-... ``` -------------------------------- ### Run Custom Shell Commands with runCommands Source: https://github.com/diggerhq/opencomputer/blob/main/docs/reference/typescript-sdk/image.mdx Execute arbitrary shell commands during the image build. This is useful for custom setup or build steps not covered by apt or pip installs. ```typescript Image.base().runCommands('echo "Hello"', 'mkdir mydir') ``` -------------------------------- ### Create a new sandbox Source: https://github.com/diggerhq/opencomputer/blob/main/docs/reference/cli/sandbox.mdx Use `oc create` to provision a new sandbox. You can specify timeout, CPU, memory, environment variables, and preview authentication settings. The `--preview-auth` flag generates a token, while `--preview-auth-token` allows you to provide your own. ```bash oc create --timeout 600 --cpu 2 --memory 1024 --env NODE_ENV=production ``` ```bash oc create --preview-auth # server-generated token ``` ```bash oc create --preview-auth-token "$GATEWAY_TOKEN" # bring your own ``` -------------------------------- ### Create a Workspace Source: https://github.com/diggerhq/opencomputer/blob/main/docs/agent-sessions/workspaces.mdx Creates a new workspace named 'web' for the 'acme/web' repository. It includes setup commands to install dependencies and build the project, and specifies a pool size of 1 for pre-booted machines. ```bash oc workspace create web \ --repo github.com/acme/web \ --setup "pnpm i && pnpm build" \ --pool 1 ``` -------------------------------- ### Create Sandbox with Pre-built Snapshot Source: https://github.com/diggerhq/opencomputer/blob/main/docs/how-it-works.mdx Create a sandbox instantly by booting from a pre-built snapshot. This is faster than building an image on demand. ```typescript // Pre-built snapshot (instant boot) const sandbox = await Sandbox.create({ snapshot: 'my-custom-stack' }); ``` -------------------------------- ### GCP Packer Template Example Source: https://github.com/diggerhq/opencomputer/blob/main/docs/multi-cloud.md A Packer HCL template for building a GCE image for worker nodes in GCP. It follows similar provisioning steps as the AWS template, including QEMU installation and binary copying. ```hcl # deploy/packer/worker-ami-gcp.pkr.hcl # Same provisioning as AWS template (install QEMU, copy binaries, install systemd unit) # Builds a GCE image instead of an AMI. ``` -------------------------------- ### Expose and Share a Dev Server Source: https://github.com/diggerhq/opencomputer/blob/main/docs/cli/preview.mdx This snippet shows the workflow for starting a development server within a sandbox, exposing its port, and then listing the available preview URLs. ```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 ``` -------------------------------- ### Get Sandbox Usage Source: https://github.com/diggerhq/opencomputer/blob/main/docs/sandboxes/usage.mdx Retrieves usage data for a specific sandbox within a given time window. The SDK provides a convenient way to fetch this data, while the cURL example shows the direct API interaction. ```APIDOC ## GET /api/sandboxes/{sandboxId}/usage ### Description Retrieves usage metrics for a specific sandbox, including memory utilization over time. This endpoint is crucial for monitoring resource consumption. ### Method GET ### Endpoint /api/sandboxes/{sandboxId}/usage ### Parameters #### Query Parameters - **from** (string) - Optional - The start of the time window (ISO 8601 format). Defaults to 1 hour ago. - **to** (string) - Optional - The end of the time window (ISO 8601 format). Defaults to now. ### Request Example ```bash curl -s "https://app.opencomputer.dev/api/sandboxes/sb-abc/usage?from=2026-05-27T00:00:00Z&to=2026-05-27T01:00:00Z" \ -H "X-API-Key: $OPENCOMPUTER_API_KEY" ``` ### Response #### Success Response (200) - **totals** (object) - Contains aggregated usage statistics. - **memoryUsedGbSeconds** (number) - Total memory used in GB-seconds. - **memoryAllocatedGbSeconds** (number) - Total memory allocated in GB-seconds. - **points** (array) - An array of usage data points. - **ts** (string) - Timestamp of the data point. - **usedMemoryMbAvg** (number) - Average memory used in MB for the bucket. - **allocatedMemoryMb** (number) - Memory allocated in MB for the bucket. #### Response Example ```json { "totals": { "memoryUsedGbSeconds": 123.45, "memoryAllocatedGbSeconds": 246.90 }, "points": [ { "ts": "2026-05-27T00:00:00Z", "usedMemoryMbAvg": 512, "allocatedMemoryMb": 1024 } ] } ``` ``` -------------------------------- ### Sandbox Creation and Usage Source: https://github.com/diggerhq/opencomputer/blob/main/sdks/typescript/README.md Demonstrates how to create a sandbox, execute commands, read/write files, and clean up the sandbox. ```APIDOC ## Sandbox ### Description Provides functionality to create, interact with, and manage sandboxes. ### Methods #### create Creates a new sandbox instance. - **Parameters** - `options` (object) - Required - Options for creating the sandbox. - `template` (string) - Required - The template to use for the sandbox. #### commands.run Executes a command within the sandbox. - **Parameters** - `command` (string) - Required - The command to run. - **Returns** - `object` - The result of the command execution. - `stdout` (string) - The standard output of the command. #### files.write Writes content to a file within the sandbox. - **Parameters** - `path` (string) - Required - The path to the file. - `content` (string) - Required - The content to write to the file. #### files.read Reads the content of a file from the sandbox. - **Parameters** - `path` (string) - Required - The path to the file. - **Returns** - `string` - The content of the file. #### kill Terminates the sandbox. ### Example ```typescript import { Sandbox } from "@opencomputer/sdk"; const sandbox = await Sandbox.create({ template: "base" }); // Execute commands const result = await sandbox.commands.run("echo hello"); console.log(result.stdout); // "hello\n" // Read and write files await sandbox.files.write("/tmp/test.txt", "Hello, world!"); const content = await sandbox.files.read("/tmp/test.txt"); // Clean up await sandbox.kill(); ``` ``` -------------------------------- ### Start a Claude Agent Session with TypeScript SDK Source: https://github.com/diggerhq/opencomputer/blob/main/README.md Initiates a Claude agent session within a sandbox, configuring environment variables and handling real-time events. Also shows how to get a live preview URL. ```typescript import { Sandbox } from '@opencomputer/sdk'; const sandbox = await Sandbox.create({ template: 'default', apiKey: 'YOUR_API_KEY', envs: { ANTHROPIC_API_KEY: 'YOUR_ANTHROPIC_KEY' }, }); // Start a Claude agent session inside the sandbox const session = await sandbox.agent.start({ prompt: 'Create a todo app with React', systemPrompt: 'You are a senior fullstack developer...', maxTurns: 30, cwd: '/workspace', onEvent: (event) => { switch (event.type) { case 'assistant': console.log('Agent:', event.message?.content); break; case 'turn_complete': console.log('Done!'); break; case 'error': console.error(event.message); break; } }, }); // Get a live preview URL const preview = await sandbox.createPreviewURL({ port: 80 }); console.log('Preview:', preview); ``` -------------------------------- ### POST /api/sandboxes/{id}/preview/rotate Source: https://github.com/diggerhq/opencomputer/blob/main/docs/api-reference/preview/rotate-auth.mdx Mints a new bearer token for the sandbox's preview-URL auth gate. The old token stops working immediately. If the sandbox was originally created without previewAuth, this call installs a token and starts enforcing the gate. ```APIDOC ## POST /api/sandboxes/{id}/preview/rotate ### Description Mints a new bearer token for the sandbox's preview-URL auth gate. The old token stops working immediately — there is no zero-downtime dual-token mode, so roll the new token out to your caller before discarding the old one. If the sandbox was originally created without previewAuth, this call installs a token and starts enforcing the gate from that point on. ### Method POST ### Endpoint /api/sandboxes/{id}/preview/rotate ### Parameters #### Path Parameters - **id** (string) - Required - Sandbox ID ### Response #### Success Response (200) - **previewAuthToken** (string) - The newly minted bearer token. This is returned only once. - **scheme** (string) - The authentication scheme, typically "bearer". #### Response Example ```json { "previewAuthToken": "qx2sSi5IYXWBvnnRqwK9Ky_cIAI-x0Vx1bPCt0XMxsI", "scheme": "bearer" } ``` ### Errors - **404** - Sandbox not found, or owned by a different org - **410** - Sandbox is `stopped` or `error` - **503** - Database not configured (combined-mode CP without PG) ``` -------------------------------- ### Get Calendar API Response Example Source: https://github.com/diggerhq/opencomputer/blob/main/docs/api-reference/capacity/get-calendar.mdx This JSON response shows a snapshot of memory capacity in GB for a given time window, broken down into 15-minute intervals. It includes details on reservation limits, currently reserved capacity, and available reservable capacity for each interval. ```json { "from": "2026-04-29T02:00:00Z", "to": "2026-04-29T04:00:00Z", "resource": "memory_gb", "intervals": [ { "startsAt": "2026-04-29T02:00:00Z", "endsAt": "2026-04-29T02:15:00Z", "reservationLimitGb": 300, "reservedGb": 80, "reservableGb": 220 } ] } ``` -------------------------------- ### Create Sandbox with Preview Authentication Enabled Source: https://github.com/diggerhq/opencomputer/blob/main/docs/cli/preview.mdx Create a new sandbox and enable bearer-token authentication for its preview URLs. The initial token is displayed only once. ```bash oc sandbox create --preview-auth # Created sandbox sb-abc123 (status: running) # Preview auth token (shown once): qx2sSi5IYXWBvnnRqwK9Ky_cIAI-x0Vx1bPCt0XMxsI ``` -------------------------------- ### Create a Preview URL Source: https://github.com/diggerhq/opencomputer/blob/main/skills/opencomputer/SKILL.md Expose a sandbox port via a public URL. You can specify the port and an optional custom domain. ```bash # Create a preview URL oc preview create --port 3000 oc preview create --port 8080 --domain myapp.example.com ``` -------------------------------- ### TypeScript: Setup Burst Sandbox with Restart Hook Source: https://github.com/diggerhq/opencomputer/blob/main/docs/sandboxes/burst-sandboxes.mdx Sets up a burst sandbox, installs a restart-notice hook, and writes a worker script. The worker script handles resuming from a previous state after a restart. Use this for agent or batch systems requiring resilience to restarts. ```typescript import { Sandbox } from "@opencomputer/sdk"; const sandbox = await Sandbox.create({ burst: true, timeout: 0, }); await sandbox.exec.run("mkdir -p /home/sandbox/.opencomputer /home/sandbox/app"); await sandbox.files.write( "/home/sandbox/.opencomputer/on-restart-notice", `#!/bin/sh set -eu echo "restart notice: ${1:-25}s" >> /home/sandbox/app/events.log touch /home/sandbox/app/restarting sync `, ); await sandbox.exec.run("chmod +x /home/sandbox/.opencomputer/on-restart-notice"); await sandbox.files.write( "/home/sandbox/app/worker.sh", `#!/bin/sh set -eu cd /home/sandbox/app if [ -f restarting ]; then echo "resumed after restart" >> events.log rm -f restarting else echo "started" >> events.log fi i=$(cat counter 2>/dev/null || echo 0) while true; do i=$((i + 1)) echo "$i" > counter sync sleep 5 done `, ); await sandbox.exec.run("chmod +x /home/sandbox/app/worker.sh"); await sandbox.exec.background("/home/sandbox/app/worker.sh", { maxRunAfterDisconnect: 0, }); ``` -------------------------------- ### Get Webhook Response Example Source: https://github.com/diggerhq/opencomputer/blob/main/docs/api-reference/webhooks/get.mdx This JSON object represents a successful response when fetching a webhook destination. It includes details like the webhook's ID, name, URL, associated event types, sandbox ID (if applicable), enabled status, and creation/update timestamps. The `hasSecret` field indicates if a secret is configured for this webhook. ```json { "id": "whk_3f9a2c", "name": "prod", "url": "https://app.example.com/oc-webhook", "eventTypes": ["sandbox.stopped"], "sandboxId": null, "enabled": true, "hasSecret": true, "createdAt": "2026-06-24T12:00:00Z", "updatedAt": "2026-06-24T12:00:00Z" } ``` -------------------------------- ### Create EC2 QEMU Development Host Source: https://github.com/diggerhq/opencomputer/blob/main/deploy/ec2/README.md Launches a QEMU development host on EC2. This process can take approximately 5-10 minutes and will output the public IP address of the instance. ```bash source ~/.opensandbox-dev.env cd ./deploy/ec2/deploy-qemu-dev.sh create # ~5–10 min, prints the public IP ``` -------------------------------- ### Cell ID Examples Source: https://github.com/diggerhq/opencomputer/blob/main/SELFHOSTING.md Examples of cell IDs demonstrating the specified format. These examples show how to construct valid identifiers for different cloud environments. ```text azure-us-east-2-a azure-us-west-2-b aws-us-east-1-a ``` -------------------------------- ### Build and Run Sandbox with On-Demand Image Source: https://github.com/diggerhq/opencomputer/blob/main/docs/sdks/python/templates.mdx Demonstrates creating a sandbox with a custom image built on-demand. This includes installing packages, adding files, setting environment variables, and running commands within the sandbox. Use this pattern for development environments where image customization is frequent. ```python import asyncio from opencomputer import Sandbox, Image, Snapshots async def main(): # ── Pattern 1: On-demand image ── dev_image = ( Image.base() .apt_install(["curl", "jq"]) .pip_install(["requests"]) .add_file("/workspace/config.json", '{"debug": true}') .env({"APP_ENV": "development"}) .workdir("/workspace") ) sandbox = await Sandbox.create( image=dev_image, on_build_log=lambda log: print(f"build: {log}"), ) await sandbox.commands.run("curl --version") await sandbox.kill() # ── Pattern 2: Pre-built snapshot ── snapshots = Snapshots() prod_image = ( Image.base() .apt_install(["python3-pip", "git"]) .pip_install(["pandas", "numpy", "scikit-learn"]) .run_commands("mkdir -p /workspace/data") .env({"APP_ENV": "production"}) .workdir("/workspace") ) await snapshots.create( name="ml-env", image=prod_image, on_build_logs=lambda log: print(f"build: {log}"), ) # Instant — no build, just boot from snapshot ml_sandbox = await Sandbox.create(snapshot="ml-env") await ml_sandbox.commands.run( 'python3 -c "import pandas; print(pandas.__version__)"' ) await ml_sandbox.kill() # Cleanup await snapshots.delete("ml-env") asyncio.run(main()) ``` -------------------------------- ### Create and Run Sandbox (TypeScript) Source: https://github.com/diggerhq/opencomputer/blob/main/docs/quickstart.mdx Create a new sandbox, run a command within it, and then kill the sandbox. Ensure the SDK is installed. ```typescript import { Sandbox } from "@opencomputer/sdk"; const sandbox = await Sandbox.create(); // Run a command inside the sandbox const result = await sandbox.commands.run("echo 'Hello World from OpenSandbox!'"); console.log(result.stdout); await sandbox.kill(); ``` -------------------------------- ### GitHub App Installations Source: https://github.com/diggerhq/opencomputer/blob/main/docs/agent-sessions/api-reference.mdx List GitHub App installations visible to OpenComputer. ```APIDOC ## GET /github/installations ### Description List all GitHub App installations that are visible to OpenComputer within your organization. This list may be empty if your organization only uses the default OpenComputer App and has not explicitly granted it access to specific repositories. ### Method GET ### Endpoint /github/installations ### Response #### Success Response (200 OK) - An array of GitHub App installation objects. Each object represents an installation and may contain details about the installation ID, repository access, etc. The structure of these objects is not detailed in the source text but is expected to be consistent with GitHub's installation representation. ``` -------------------------------- ### Create a Base Image with Customizations Source: https://github.com/diggerhq/opencomputer/blob/main/docs/reference/typescript-sdk/image.mdx Start from the default OpenSandbox environment and add system packages, Python packages, environment variables, and set the working directory. This is useful for setting up a consistent build environment. ```typescript import { Image } from "@opencomputer/sdk"; const image = Image.base() .aptInstall(['curl', 'jq']) .pipInstall(['requests', 'pandas']) .env({ PROJECT_ROOT: '/workspace' }) .workdir('/workspace'); ``` -------------------------------- ### Response Example Source: https://github.com/diggerhq/opencomputer/blob/main/docs/api-reference/checkpoints/create.mdx This is an example of a successful response when creating a checkpoint. The status will initially be 'processing'. ```json { "id": "cp-abc123", "sandboxID": "sb-abc123", "name": "before-migration", "status": "processing", "sizeBytes": 0, "createdAt": "2025-01-15T10:30:00Z" } ``` -------------------------------- ### Create a session Source: https://github.com/diggerhq/opencomputer/blob/main/docs/sessions-api/sessions.mdx Creates a cloud sandbox, starts an AI agent with your prompt, and returns a session with a live preview URL. The agent begins working immediately — stream events to follow its progress. ```APIDOC ## Create a session ### Description Creates a cloud sandbox, starts an AI agent with your prompt, and returns a session with a live preview URL. The agent begins working immediately — stream events to follow its progress. ### Method POST ### Endpoint /v1/sessions ### Parameters #### Request Body - **prompt** (string) - Required - What the agent should build or do - **user_id** (string) - Required - Your user's ID (for session ownership) - **user_email** (string) - Optional - User email (stored for reference) - **user_name** (string) - Optional - User name (stored for reference) - **agent_config** (object) - Optional - Agent configuration - **agent_config.system_prompt** (string) - System prompt for the AI agent - **agent_config.skills** (object) - Map of `path → content` — files synced into the sandbox at `/workspace/agent/` - **agent_config.allowed_tools** (string[]) - Tools the agent can use. Default: `["bash", "read", "write", "edit", "glob", "grep"]` - **agent_config.cwd** (string) - Agent working directory. Default: `/workspace/app` ### Request Example ```bash curl -X POST https://api.opencomputer.dev/v1/sessions \ -H "Content-Type: application/json" \ -H "X-API-Key: osb_your_api_key" \ -d { "prompt": "Build a todo app with Next.js and Tailwind", "user_id": "user_123", "agent_config": { "system_prompt": "You are a web app builder. Work in /workspace/app.", "skills": { ".claude/skills/build-app/SKILL.md": "# Build App\n\nScaffold, install, edit, verify." } } } ``` ### Response #### Success Response (201) - **id** (string) - Unique identifier for the session - **status** (string) - Current status of the session (e.g., "running", "ended") - **sandboxId** (string) - Identifier for the sandbox environment - **previewUrl** (string) - URL for live preview of the session - **project** (object) - Details about the project being built - **project.title** (string) - **project.framework** (string) - **project.artifacts** (array) - **messages** (array) - Array of messages in the session - **messages[].id** (string) - **messages[].role** (string) - **messages[].content** (string) - **messages[].createdAt** (string) - **events** (array) - Array of events that occurred during the session - **events[].id** (string) - **events[].type** (string) - **events[].level** (string) - **events[].message** (string) - **events[].createdAt** (string) - **userId** (string) - The ID of the user who created the session - **createdAt** (string) - Timestamp when the session was created - **updatedAt** (string) - Timestamp when the session was last updated #### Response Example ```json { "id": "session_abc123", "status": "running", "sandboxId": "sb-31317626", "previewUrl": "https://sb-31317626-p3000.workers.opencomputer.dev", "project": { "title": "Build a todo app", "framework": "nextjs", "artifacts": [] }, "messages": [ { "id": "msg_xxx", "role": "user", "content": "Build a todo app with Next.js and Tailwind", "createdAt": "2026-03-18T17:00:00.000Z" } ], "events": [ { "id": "evt_xxx", "type": "session_started", "level": "info", "message": "Bootstrapping sandbox...", "createdAt": "2026-03-18T17:00:00.000Z" } ], "userId": "user_123", "createdAt": "2026-03-18T17:00:00.000Z", "updatedAt": "2026-03-18T17:00:02.000Z" } ``` ``` -------------------------------- ### List GitHub App Installations Source: https://github.com/diggerhq/opencomputer/blob/main/docs/agent-sessions/api-reference.mdx Retrieve a list of all GitHub App installations that are visible to OpenComputer. ```typescript oc.github.installations.list() ``` -------------------------------- ### sandbox.agent.start Source: https://github.com/diggerhq/opencomputer/blob/main/docs/reference/typescript-sdk.mdx Starts a new agent session with the specified options. This method allows for initial prompts, model selection, tool restrictions, and event callbacks. ```APIDOC ## sandbox.agent.start(opts?) ### Description Start an agent session. ### Method `start` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **prompt** (string) - Optional - Initial prompt - **model** (string) - Optional - Claude model - **systemPrompt** (string) - Optional - System prompt - **allowedTools** (string[]) - Optional - Restrict tools - **permissionMode** (string) - Optional - Permission mode - **maxTurns** (number) - Optional - Max turns (default: 50) - **cwd** (string) - Optional - Working directory - **mcpServers** (Record) - Optional - MCP servers - **resume** (string) - Optional - Resume session ID - **onEvent** ((event: AgentEvent) => void) - Optional - Event callback - **onError** ((data: string) => void) - Optional - Stderr callback - **onExit** ((exitCode: number) => void) - Optional - Exit callback - **onScrollbackEnd** (() => void) - Optional - Scrollback done callback ### Request Example ```typescript const session = await sandbox.agent.start({ prompt: "Build a todo app", onEvent: (e) => console.log(e.type), }); ``` ### Response #### Success Response - **AgentSession** - Represents an active agent session. ``` -------------------------------- ### Create and Run Command in Sandbox (Python) Source: https://github.com/diggerhq/opencomputer/blob/main/docs/introduction.mdx Create a new sandbox, run a command within it, print the output, and then terminate the sandbox. Requires the opencomputer-sdk package and asyncio. ```python import asyncio from opencomputer import Sandbox async def main(): sandbox = await Sandbox.create() result = await sandbox.commands.run("echo 'Hello World from OpenSandbox!'") print(result.stdout) await sandbox.kill() asyncio.run(main()) ``` -------------------------------- ### Create Sandbox with Burst Mode and Webhooks Source: https://github.com/diggerhq/opencomputer/blob/main/docs/api-reference/sandboxes/create.mdx This example shows how to create a sandbox with burst mode enabled for preserved disk state across restarts. It also includes webhook registration for lifecycle event notifications. ```json { "templateID": "base", "burst": true, "webhooks": [ { "url": "https://app.example.com/oc-webhook", "secret": "whsec_Hk9…", "eventTypes": ["sandbox.created", "sandbox.ready"] } ] } ``` -------------------------------- ### Start Headed Browser Services Source: https://github.com/diggerhq/opencomputer/blob/main/docs/guides/browser-automation.mdx Starts the Xvfb, x11vnc, and websockify services as long-lived exec sessions. These services enable the headed browser functionality and VNC access. Ensure Xvfb is started before x11vnc, and x11vnc before websockify. ```typescript const xvfb = await sandbox.exec.start("Xvfb", { args: [":99", "-screen", "0", "1280x800x24", "-ac"], }); await new Promise((r) => setTimeout(r, 1500)); const x11vnc = await sandbox.exec.start("x11vnc", { args: ["-display", ":99", "-forever", "-shared", "-nopw", "-rfbport", "5900", "-quiet"], }); const websockify = await sandbox.exec.start("websockify", { args: ["--web=/usr/share/novnc/", "6080", "localhost:5900"], }); ``` -------------------------------- ### Create a Sandbox Source: https://github.com/diggerhq/opencomputer/blob/main/docs/cli/overview.mdx Quickly create a new OpenComputer sandbox. This is the first step in many workflows. ```bash oc create ``` -------------------------------- ### Install OpenComputer TypeScript SDK Source: https://github.com/diggerhq/opencomputer/blob/main/sdks/typescript/README.md Install the SDK using npm. This package supersedes the older `@opencomputer/agents-sdk`. ```bash npm install @opencomputer/sdk ``` -------------------------------- ### Install Pip Packages Source: https://github.com/diggerhq/opencomputer/blob/main/docs/sdks/python/templates.mdx Installs Python packages using pip. Provide a list of package names. ```python image = Image.base().pip_install(["requests", "pandas", "numpy"]) ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/diggerhq/opencomputer/blob/main/docs/guides/build-a-lovable-clone.mdx Create a .env file at the project root to store API keys and deployment domain. Set DEPLOY_DOMAIN to your custom domain if configured, otherwise it defaults to openlovable.cc. ```bash ANTHROPIC_API_KEY=sk-ant-... OPENCOMPUTER_API_KEY=your-opencomputer-token DEPLOY_DOMAIN=mycompany.com # optional — defaults to openlovable.cc ``` -------------------------------- ### Create Sandbox with Preview Authentication Source: https://github.com/diggerhq/opencomputer/blob/main/docs/api-reference/sandboxes/create.mdx This example demonstrates how to enable bearer token authentication for the sandbox's preview URLs. It includes an auto-generated token for secure access. ```json { "templateID": "base", "previewAuth": { "scheme": "bearer", "token": "auto" } } ``` -------------------------------- ### Check if `oc` CLI is installed Source: https://github.com/diggerhq/opencomputer/blob/main/skills/opencomputer/SKILL.md Verifies if the `oc` command-line interface is installed on the system by checking its presence in the PATH. ```bash which oc ``` -------------------------------- ### image.apt_install(packages) Source: https://github.com/diggerhq/opencomputer/blob/main/docs/reference/python-sdk/image.mdx Installs system packages using apt-get. This method is part of the Image builder and returns a new Image instance with the specified packages added. ```APIDOC ## image.apt_install(packages) ### Description Installs system packages via apt-get. ### Parameters #### Request Body - **packages** (list[str]) - Required - System packages to install via apt-get ### Returns `Image` ``` -------------------------------- ### image.pip_install(packages) - Install Python Packages Source: https://github.com/diggerhq/opencomputer/blob/main/docs/sdks/python/templates.mdx Installs specified Python packages using `pip` during the image build process. ```APIDOC ## image.pip_install(packages) ### Description Install Python packages via `pip`. ### Method N/A (Method chaining) ### Endpoint N/A ### Parameters #### Request Body - **packages** (list[str]) - Required - List of pip package names to install. ### Request Example ```python image = Image.base().pip_install(["requests", "pandas", "numpy"]) ``` ### Response N/A ``` -------------------------------- ### Create a Workspace Source: https://github.com/diggerhq/opencomputer/blob/main/docs/background-agents/workspaces.mdx Use this command to create a new workspace, specifying the repository, setup commands, optional warm-up commands, and the number of pre-booted machines. ```bash oc workspace create web \ --repo github.com/acme/web \ --setup "pnpm i && pnpm build" \ --warm "pnpm test --filter smoke" \ --pool 1 ```