An open-source, faster Devin alternative
TypeScript
Write Band A foundation pages with full content
Igor Zalutski37400ddc0a30
diff --git a/docs/agents/overview.mdx b/docs/agents/overview.mdxindex d6722193..b954c31b 100644--- a/docs/agents/overview.mdx+++ b/docs/agents/overview.mdx@@ -3,63 +3,129 @@ title: "Agents"description: "Run Claude inside sandboxes"----{/*- TODO: Expand this stub into full content.-- GOAL: Explain what agent sessions are, how they work, and get the reader to a working agent in 60 seconds.-- ABSORBS: Current agents.mdx, sdks/typescript/agent.mdx (overview parts), sdks/python/agent.mdx (overview parts).-*/}--## What is an Agent Session--{/* 2-3 sentences: A Claude Agent SDK instance running inside a sandbox (cloud VM). You send a prompt, it works autonomously — writing files, running commands, iterating — and streams events back. */}--## Quick Example--{/* sandbox.agent.start() with event handling. TS + Python CodeGroup. The simplest working agent. */}+An agent session is a Claude Agent SDK instance running inside a sandbox. You send a prompt, the agent works autonomously — writing files, running commands, iterating on errors — and streams events back to your code.<CodeGroup>```typescript TypeScript-// TODO: Sandbox.create -> agent.start({ prompt, onEvent }) -> session.done -> kill+import { Sandbox } from "@anthropic-ai/opencomputer";++const sandbox = await Sandbox.create();+const session = await sandbox.agent.start({+ prompt: "Create a Next.js app with a landing page",+ onEvent: (event) => console.log(`[${event.type}]`, event),+});++const exitCode = await session.done;+await sandbox.kill();``````python Python-# TODO: Sandbox.create -> agent.start(prompt, on_event) -> session.wait() -> kill+from opencomputer import Sandbox++sandbox = await Sandbox.create()+session = await sandbox.agent.start(+ prompt="Create a Next.js app with a landing page",+ on_event=lambda event: print(f"[{event.type}]", event),+)++exit_code = await session.wait()+await sandbox.kill()```</CodeGroup>## How It Works-{/* Brief (3-4 sentences): SDK spawns Claude inside sandbox VM, Claude gets bash/file tools, works in think->act->observe loop, events stream back via WebSocket. */}+The SDK spawns the Claude Agent SDK inside the sandbox VM as a regular process. Claude gets bash and file tools, then works in a think → act → observe loop. Events stream back to your code over WebSocket as JSON lines.++The agent has full access to the sandbox filesystem, network, and shell — the same environment you'd get with `sandbox.exec` or `oc shell`.++## Starting an Agent-## `sandbox.agent.start(opts)`+`sandbox.agent.start()` creates an agent session and returns immediately. Events arrive via callbacks.-{/* Full param reference with ParamField:- - prompt (required)- - model, systemPrompt, allowedTools, permissionMode, maxTurns, cwd- - mcpServers (Record<string, McpServerConfig>)- - onEvent, onError- - TS-only: resume, onExit, onScrollbackEnd-*/}+### Parameters++| Parameter | Type | Description |+| --- | --- | --- |+| `prompt` | string | Initial prompt for the agent |+| `model` | string | Claude model (default: `claude-sonnet-4-20250514`) |+| `systemPrompt` | string | System prompt |+| `allowedTools` | string[] | Restrict which tools the agent can use |+| `permissionMode` | string | Permission mode for tool use |+| `maxTurns` | number | Maximum conversation turns (default: 50) |+| `cwd` | string | Working directory inside the sandbox |+| `mcpServers` | object | MCP server configuration (see [Tools](/agents/tools)) |+| `onEvent` | callback | Called for each [event](/agents/events) |+| `onError` | callback | Called on error |++**TypeScript only:**++| Parameter | Type | Description |+| --- | --- | --- |+| `resume` | string | Resume a previous session by ID |+| `onExit` | callback | Called when agent process exits |+| `onScrollbackEnd` | callback | Called when scrollback replay completes |++<Note>+ Python uses snake_case: `system_prompt`, `allowed_tools`, `permission_mode`, `max_turns`, `mcp_servers`, `on_event`, `on_error`.+</Note>## AgentSession-{/* Properties and methods table:- - Both SDKs: sessionId, done, sendPrompt, interrupt, configure, kill, close- - Python-specific: collect_events(), wait()- - TS-specific: done returns Promise<number>-*/}+The returned session object lets you interact with the running agent.-## Next+| Method | TypeScript | Python | Description |+| --- | --- | --- | --- |+| Send follow-up | `sendPrompt(text)` | `send_prompt(text)` | Send a follow-up prompt |+| Wait for completion | `await session.done` | `await session.wait()` | Returns exit code |+| Collect all events | — | `await session.collect_events()` | Collect events until exit |+| Interrupt | `session.interrupt()` | `session.interrupt()` | Stop the current turn |+| Reconfigure | `session.configure(opts)` | `session.configure(...)` | Update model, tools, cwd |+| Kill | `await session.kill()` | `await session.kill()` | Terminate the process (SIGKILL) |+| Close | `session.close()` | `await session.close()` | Close WebSocket connection |-{/* Quick links to sub-pages: Events, Tools, Multi-turn */}+| Property | TypeScript | Python |+| --- | --- | --- |+| Session ID | `session.sessionId` | `session.session_id` |-<Tip>- Full reference: [TypeScript SDK](/reference/typescript-sdk#agent) · [Python SDK](/reference/python-sdk#agent) · [HTTP API](/reference/api#agent-sessions).-</Tip>+## Attaching to an Existing Session++Reconnect to a running agent session to resume receiving events:++<CodeGroup>++```typescript TypeScript+const session = await sandbox.agent.attach(sessionId, {+ onEvent: (event) => console.log(event),+});+```++```python Python+session = await sandbox.agent.attach(+ session_id,+ on_event=lambda event: print(event),+)+```++</CodeGroup>++## Listing Sessions++<CodeGroup>++```typescript TypeScript+const sessions = await sandbox.agent.list();+// [{ sessionID, sandboxID, running, startedAt }]+```++```python Python+sessions = await sandbox.agent.list()+# [AgentSessionInfo(session_id, sandbox_id, running, started_at)]+```++</CodeGroup><CardGroup cols={3}><Card title="Events" icon="stream" href="/agents/events">@@ -72,3 +138,7 @@ description: "Run Claude inside sandboxes"Follow-ups, resume, session management</Card></CardGroup>++<Tip>+ Full reference: [TypeScript SDK](/reference/typescript-sdk#agent) · [Python SDK](/reference/python-sdk#agent) · [HTTP API](/reference/api#agent-sessions).+</Tip>diff --git a/docs/how-it-works.mdx b/docs/how-it-works.mdxindex 1246f94a..5251674d 100644--- a/docs/how-it-works.mdx+++ b/docs/how-it-works.mdx@@ -3,40 +3,90 @@ title: "How It Works"description: "Architecture and key technical decisions"----{/*- TODO: Expand this stub into full content.+Your code talks to a **control plane** API, which provisions a Firecracker microVM on a worker node. The response includes a `connectURL` and short-lived JWT for direct worker access. Commands, file operations, and agent sessions run inside that VM — events and I/O stream back over WebSocket.++SDK users only need an API key. The SDK handles worker routing and JWT refresh transparently.++<Steps>+ <Step title="Create">+ Your code calls the control plane (`X-API-Key` auth). A Firecracker microVM boots in ~150ms.+ </Step>+ <Step title="Connect">+ The response includes `connectURL` and a sandbox-scoped JWT `token`. Subsequent operations go directly to the worker (`Bearer` auth) for lower latency.+ </Step>+ <Step title="Operate">+ Run commands, read/write files, start agent sessions. All execution happens inside the VM.+ </Step>+</Steps>- GOAL: Give technically curious users a clear mental model of the system in under 3 minutes.- Cover architecture and the key technical decisions users would have opinions about.+## Firecracker microVMs- TONE: Concise, technical, opinionated. No marketing. A senior engineer should read this- and think "these are reasonable choices, I understand the tradeoffs."-*/}+Each sandbox is a real virtual machine with its own Linux kernel, memory, and disk. Isolation is hardware-level (KVM), not namespace-based like containers.-## Overview+Why not containers? Containers share a kernel. A kernel exploit in one container compromises every other container on the host. Firecracker VMs eliminate that attack surface entirely — the same isolation model that powers AWS Lambda.-{/* One paragraph: your code talks to the control plane, which provisions a Firecracker microVM and returns a worker connectURL/token for data-plane operations. Agents and commands run inside that VM. Events and I/O stream back over WebSocket. */}+## Hibernation-## Firecracker microVMs+`hibernate()` snapshots the VM's memory and disk state, then stops it. No compute costs while hibernated. `wake()` restores the sandbox — the platform attempts a fast snapshot-based resume and falls back to a cold boot from the saved disk state if needed.-{/* Why not containers? Each sandbox is a real VM with its own kernel, memory, and disk. Hardware-level isolation (KVM). Boot in ~150ms. Same technology AWS Lambda uses. */}+The sandbox keeps the same ID across hibernate/wake cycles. A rolling idle timeout (default 300s) auto-hibernates sandboxes that go unused.-## Hibernation+## Checkpoints & Forking-{/* VM state is snapshotted so wake is usually fast. Explain warm-restore behavior and the cold-boot fallback path when exact snapshot restore is unavailable. Tradeoff: snapshot size scales with memory allocation. */}+A checkpoint is a named snapshot of a running sandbox. You can:-## Checkpoints & Forking+- **Restore** — revert the sandbox in-place (all changes since the checkpoint are lost)+- **Fork** — create a new sandbox from the checkpoint++Forking preserves the filesystem and installed packages. The new sandbox starts with a fresh boot from that disk state — don't assume running processes carry over.-{/* Named snapshots. Forking tries warm restore first and falls back to cold boot if needed. Emphasize the user-visible guarantee: preserved filesystem state and a reproducible starting point, not always literal process continuity. */}+```bash+# Checkpoint, then fork two independent sandboxes+oc checkpoint create sb-abc --name ready-state+oc checkpoint spawn cp-xyz # → sandbox A+oc checkpoint spawn cp-xyz # → sandbox B+```++Maximum 10 checkpoints per sandbox.## Templates-{/* Built from Dockerfiles but converted to VM root filesystems (not run as containers). Docker produces a filesystem image, Firecracker boots from it directly. */}+Templates are built from Dockerfiles, but sandboxes are not containers. The Docker build produces a filesystem image that becomes the VM's root disk. The default template includes Ubuntu, Python 3, Node.js, and common CLI tools.++Custom templates skip repeated setup:++```typescript+const sandbox = await Sandbox.create({ template: "my-custom-stack" });+```++See [Templates](/sandboxes/templates) for building your own.## Networking-{/* Each VM gets a TAP device with NAT. Full outbound internet. Inbound access via preview URLs (reverse-proxied through the host). */}+Every sandbox gets full outbound internet access via a TAP device with NAT. No firewall or allowlist to configure.++For inbound access, create a **preview URL** that reverse-proxies public traffic to a port inside the sandbox:++```bash+oc preview create sb-abc --port 3000+```++See [Preview URLs](/sandboxes/preview-urls) for custom domains and auth.## Agent Sessions-{/* Claude Agent SDK runs inside the VM as a regular process. SDK spawns Claude, gives it bash + file tools, manages think->act->observe loop. Events parsed from stdout, streamed to your code over WebSocket. */}+An agent session runs the [Claude Agent SDK](https://docs.anthropic.com/en/docs/agents/claude-code-sdk-overview) inside the VM as a regular process. The SDK gives Claude bash and file tools, then manages the think → act → observe loop. Events stream to your code over WebSocket as JSON lines.++```typescript+const session = await sandbox.agent.start({+ prompt: "Set up a Next.js app with Tailwind CSS",+ onEvent: (event) => console.log(event.type),+});+await session.done;+```++See [Agents](/agents/overview) for the full guide.++<Tip>+ Connection model details: [HTTP API Reference](/reference/api#base-url--authentication).+</Tip>diff --git a/docs/reference/api.mdx b/docs/reference/api.mdxindex c24b09d4..84bf641d 100644--- a/docs/reference/api.mdx+++ b/docs/reference/api.mdx@@ -3,244 +3,629 @@ title: "HTTP API"description: "Complete REST API reference"----{/*- TODO: Expand this stub into full content.+## Base URL & Authentication- GOAL: Complete HTTP API reference. Every endpoint, request/response format, auth headers, status codes.- A developer using curl or a non-SDK language should be able to build a full integration from this page alone.+OpenComputer exposes two API surfaces:- SOURCE: internal/api/router.go (routes), internal/api/sandbox.go, exec_session.go,- agent_session.go, filesystem.go, templates.go (handlers).+| Surface | Base URL | Auth Header | Use |+| --- | --- | --- | --- |+| **Control plane** | `https://app.opencomputer.dev/api` | `X-API-Key: <key>` | Create/list/kill sandboxes, templates, hibernation |+| **Worker direct** | `connectURL` from create/get response | `Authorization: Bearer <jwt>` | Exec, files, agents, PTY, timeout |- KEY NOTES:- - Each endpoint: method, path, request body, response body, status codes, curl example- - Separate control plane routes from worker-direct routes. Hosted/server mode uses both surfaces.- - Derive exact field names from current handler/types source. Do not normalize casing by hand.- - Dual auth: X-API-Key for control plane, JWT Bearer for worker direct access- - WebSocket binary protocol section is essential for non-SDK users- - Token refresh: POST /sandboxes/:id/token/refresh — worker-only, returns new JWT-*/}+The `connectURL` and `token` fields are returned when you create or get a sandbox. Worker-direct routes have **no `/api` prefix** — for example, `POST {connectURL}/sandboxes/:id/exec/run`.-## Base URL & Authentication+SDK users only need the API key. The SDK resolves `connectURL` and manages the JWT automatically.++### Route Availability++Most operational routes are available on **both** surfaces. Exceptions:++| Route | Control Plane | Worker |+| --- | --- | --- |+| `POST /api/sandboxes` (create) | Yes | — |+| `GET /api/sandboxes` (list all) | Yes | — |+| `DELETE /api/sandboxes/:id` (kill) | Yes | — |+| `POST .../hibernate`, `.../wake` | Yes | — |+| Checkpoint routes | Yes | — |+| Preview URL routes | Yes | — |+| Template routes | Yes | — |+| `POST .../token/refresh` | — | Yes |+| `POST .../timeout` | — | Yes |+| Exec, filesystem, agent, PTY routes | Yes | Yes |++### Token Refresh++Worker JWTs are short-lived. To refresh:-{/* Document both surfaces explicitly:- - Control plane base: https://app.opencomputer.dev/api- - Worker direct base: connectURL from sandbox create/get response (no /api prefix)- - Control plane auth: X-API-Key header- - Worker direct auth: Authorization: Bearer <JWT> (or token query param for WS)- - SDK users only need API key — SDK handles JWT transparently- - Add a route-availability matrix: control plane only / worker only / both- - File reads return raw content, not JSON. File writes use raw request body + path query param.- - Token refresh: POST /sandboxes/:id/token/refresh — worker auth only-*/}+```bash+curl -X POST {connectURL}/sandboxes/{id}/token/refresh \+ -H "Authorization: Bearer $TOKEN"+```++Returns a new JWT. The SDKs handle this automatically.++---## Sandbox Lifecycle### `POST /api/sandboxes` — Create-{/* Body matches SandboxConfig: templateID, timeout, envs, metadata, cpuCount, memoryMB.- Hosted/server-mode response is currently minimal: sandboxID, status, connectURL, token, region, workerID.- Do not promise cpuCount/memoryMB/startedAt/endAt on create unless verified for the served surface.- Curl example. */}+Create a new sandbox.++**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `templateID` | string | No | Template name (default: `"base"`) |+| `timeout` | int | No | Idle timeout in seconds (default: `300`) |+| `cpuCount` | int | No | CPU cores, 1–4 (default: `1`) |+| `memoryMB` | int | No | Memory in MB, up to 2048 (default: `512`) |+| `envs` | object | No | Environment variables |+| `metadata` | object | No | Arbitrary key-value pairs |++**Response** `200`:++```json+{+ "sandboxID": "sb-abc123",+ "templateID": "base",+ "status": "running",+ "startedAt": "2025-01-15T10:30:00Z",+ "endAt": "2025-01-15T10:35:00Z",+ "cpuCount": 1,+ "memoryMB": 512,+ "metadata": {},+ "connectURL": "https://worker-xyz.opencomputer.dev",+ "token": "eyJhbG..."+}+```++```bash+curl -X POST https://app.opencomputer.dev/api/sandboxes \+ -H "X-API-Key: $OPENCOMPUTER_API_KEY" \+ -H "Content-Type: application/json" \+ -d '{"templateID": "base", "timeout": 600}'+```### `GET /api/sandboxes` — List-{/* Response: array of sandbox objects. */}+List all running sandboxes.++**Response** `200`: Array of sandbox objects.### `GET /api/sandboxes/:id` — Get-{/* Response: sandbox details. */}+Get sandbox details by ID. Available on both control plane and worker.++**Response** `200`: Sandbox object (same shape as create response).### `DELETE /api/sandboxes/:id` — Kill-{/* 204 on success. */}+Terminate and remove a sandbox.++**Response** `204`: No content.### `POST /api/sandboxes/:id/timeout` — Set Timeout-{/* Body: { timeout }.- Important: in hosted/server mode this must be sent to the worker via connectURL; control plane returns an error telling the client to use the worker directly.-*/}+Update the idle timeout. In hosted mode, this must be sent to the **worker** via `connectURL`.++**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `timeout` | int | Yes | New timeout in seconds (must be > 0) |++**Response** `200`: Empty object.### `POST /api/sandboxes/:id/hibernate` — Hibernate-{/* Snapshot VM state. */}+Snapshot VM state and stop the sandbox. Control plane only.++**Response** `200`:++```json+{+ "sizeBytes": 134217728+}+```### `POST /api/sandboxes/:id/wake` — Wake-{/* Resume from hibernation. */}+Resume a hibernated sandbox. Control plane only.++**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `timeout` | int | No | Idle timeout after wake (default: `300`) |++**Response** `200`: Sandbox object with updated status.++---## Commands (Exec)### `POST /api/sandboxes/:id/exec/run` — Run Command-{/* Body matches ProcessConfig: cmd, optional args, envs, cwd, timeout.- Response: { exitCode, stdout, stderr }.-*/}+Execute a command synchronously and return the result. Available on both surfaces.++**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `cmd` | string | Yes | Command to execute |+| `args` | string[] | No | Command arguments |+| `envs` | object | No | Environment variables |+| `cwd` | string | No | Working directory |+| `timeout` | int | No | Timeout in seconds (default: `60`) |++**Response** `200`:++```json+{+ "exitCode": 0,+ "stdout": "Hello, World!\n",+ "stderr": ""+}+```++```bash+curl -X POST {connectURL}/sandboxes/{id}/exec/run \+ -H "Authorization: Bearer $TOKEN" \+ -H "Content-Type: application/json" \+ -d '{"cmd": "echo", "args": ["Hello, World!"]}'+```### `POST /api/sandboxes/:id/exec` — Create Exec Session-{/* Body matches ExecSessionCreateRequest: cmd, optional args, envs, cwd, timeout, maxRunAfterDisconnect.- Response is ExecSessionInfo with sessionID casing, not sessionId.-*/}+Start a long-running command as a session. Attach via WebSocket to stream I/O.++**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `cmd` | string | Yes | Command to execute |+| `args` | string[] | No | Command arguments |+| `envs` | object | No | Environment variables |+| `cwd` | string | No | Working directory |+| `timeout` | int | No | Timeout in seconds |+| `maxRunAfterDisconnect` | int | No | Seconds to keep running after all clients disconnect |++**Response** `201`:++```json+{+ "sessionID": "es-abc123",+ "sandboxID": "sb-abc123",+ "command": "node",+ "args": ["server.js"],+ "running": true,+ "exitCode": null,+ "startedAt": "2025-01-15T10:30:00Z",+ "attachedClients": 0+}+```### `GET /api/sandboxes/:id/exec` — List Sessions-{/* Response: array of ExecSessionInfo. */}+**Response** `200`: Array of `ExecSessionInfo` objects (same shape as create response).### `GET /api/sandboxes/:id/exec/:sessionID` — WebSocket Attach-{/* Upgrade to WebSocket. Binary protocol. */}+Upgrade to WebSocket. Streams I/O using the [binary protocol](#websocket-binary-protocol).++Pass auth via query parameter: `?token=<jwt>`++On connect, the server replays the scrollback buffer, sends a `0x04` end marker, then streams live output.### `POST /api/sandboxes/:id/exec/:sessionID/kill` — Kill Session-{/* Body: { signal? }. */}+**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `signal` | int | No | Signal number (default: `9` / SIGKILL) |++**Response** `200`: Empty object.++---## Agent Sessions-### `POST /api/sandboxes/:id/agent` — Create Agent Session+Agent sessions run the Claude Agent SDK inside the sandbox. Events stream over the exec session WebSocket transport — there is no separate agent WebSocket endpoint.++### `POST /api/sandboxes/:id/agent` — Create++**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `prompt` | string | No | Initial prompt |+| `model` | string | No | Claude model name |+| `systemPrompt` | string | No | System prompt |+| `allowedTools` | string[] | No | Restrict available tools |+| `permissionMode` | string | No | Permission mode |+| `maxTurns` | int | No | Maximum turns |+| `cwd` | string | No | Working directory |+| `mcpServers` | object | No | MCP server configuration |+| `resume` | string | No | Session ID to resume |++**Response** `201`:++```json+{+ "sessionID": "as-abc123",+ "sandboxID": "sb-abc123",+ "running": true,+ "startedAt": "2025-01-15T10:30:00Z",+ "claudeSessionID": ""+}+```-{/* Body matches AgentSessionCreateRequest: prompt, model, systemPrompt, allowedTools, permissionMode, maxTurns, cwd, mcpServers, resume.- Note: there is no separate agent WebSocket endpoint; attach uses the exec session WebSocket transport.-*/}+```bash+curl -X POST {connectURL}/sandboxes/{id}/agent \+ -H "Authorization: Bearer $TOKEN" \+ -H "Content-Type: application/json" \+ -d '{"prompt": "Create a hello world app", "model": "claude-sonnet-4-20250514"}'+```-### `GET /api/sandboxes/:id/agent` — List Agent Sessions+### `GET /api/sandboxes/:id/agent` — List-{/* Response: array of session objects. */}+**Response** `200`: Array of `AgentSessionInfo` objects.### `POST /api/sandboxes/:id/agent/:sid/prompt` — Send Follow-up-{/* Body: { text }. */}+**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `text` | string | Yes | Follow-up prompt text |++**Response** `200`: Empty object.### `POST /api/sandboxes/:id/agent/:sid/interrupt` — Interrupt-{/* Stop current turn. */}+Stop the agent's current turn.++**Response** `200`: Empty object.### `POST /api/sandboxes/:id/agent/:sid/kill` — Kill-{/* Terminate agent session. */}+Terminate the agent session.++**Response** `200`: Empty object.++---## Filesystem### `GET /api/sandboxes/:id/files?path=...` — Read File-{/* Returns file content as plain text. */}+Returns file content as **plain text** (not JSON). The `path` query parameter is required.-### `PUT /api/sandboxes/:id/files` — Write File+```bash+curl {connectURL}/sandboxes/{id}/files?path=/app/index.js \+ -H "Authorization: Bearer $TOKEN"+```-{/* Raw request body is written as file contents. `path` is a required query parameter. */}+**Response** `200`: Raw file content with `Content-Type: text/plain`.++### `PUT /api/sandboxes/:id/files?path=...` — Write File++The request body is written as raw file content (not JSON). The `path` query parameter specifies the destination.++```bash+curl -X PUT {connectURL}/sandboxes/{id}/files?path=/app/hello.txt \+ -H "Authorization: Bearer $TOKEN" \+ -H "Content-Type: text/plain" \+ -d "Hello, World!"+```++**Response** `200`: Empty object.### `GET /api/sandboxes/:id/files/list?path=...` — List Directory-{/* Response: array of EntryInfo. */}+**Query parameter:** `path` (default: `/`)++**Response** `200`:++```json+[+ { "name": "app", "isDir": true, "size": 4096, "path": "/app" },+ { "name": "README.md", "isDir": false, "size": 1234, "path": "/README.md" }+]+```-### `POST /api/sandboxes/:id/files/mkdir` — Create Directory+Each entry has: `name` (string), `isDir` (boolean), `size` (int64), `path` (string).-{/* `path` is a required query parameter. */}+### `POST /api/sandboxes/:id/files/mkdir?path=...` — Create Directory++The `path` query parameter specifies the directory to create.++**Response** `200`: Empty object.### `DELETE /api/sandboxes/:id/files?path=...` — Remove-{/* Delete file or directory. */}+Delete a file or directory. The `path` query parameter is required.++**Response** `200`: Empty object.++---## Checkpoints+Maximum 10 checkpoints per sandbox.+### `POST /api/sandboxes/:id/checkpoints` — Create-{/* Body: { name }. Response: CheckpointInfo. */}+**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `name` | string | Yes | Checkpoint name (unique per sandbox) |++**Response** `201`:++```json+{+ "id": "cp-abc123",+ "sandboxID": "sb-abc123",+ "name": "before-migration",+ "status": "processing",+ "sizeBytes": 0,+ "createdAt": "2025-01-15T10:30:00Z"+}+```++Status transitions: `processing` → `ready` or `failed`.### `GET /api/sandboxes/:id/checkpoints` — List-{/* Response: array of CheckpointInfo. */}+**Response** `200`: Array of `CheckpointInfo` objects.### `POST /api/sandboxes/:id/checkpoints/:checkpointId/restore` — Restore-{/* Revert sandbox in-place. */}+Revert the sandbox in-place to a checkpoint. All changes since the checkpoint are lost.++**Response** `200`: Empty object.### `POST /api/sandboxes/from-checkpoint/:checkpointId` — Fork-{/* Create new sandbox from checkpoint. Response: sandbox object. */}+Create a new sandbox from a checkpoint.++**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `timeout` | int | No | Idle timeout for the new sandbox (default: `300`) |++**Response** `200`: Sandbox object (same shape as create).++```bash+curl -X POST https://app.opencomputer.dev/api/sandboxes/from-checkpoint/cp-abc123 \+ -H "X-API-Key: $OPENCOMPUTER_API_KEY" \+ -H "Content-Type: application/json" \+ -d '{"timeout": 600}'+```### `DELETE /api/sandboxes/:id/checkpoints/:checkpointId` — Delete-{/* 204 on success. */}+**Response** `204`: No content.++---## Checkpoint Patches+Patches are scripts that run when a sandbox is spawned from a checkpoint. They apply in sequence order.+### `POST /api/sandboxes/checkpoints/:checkpointId/patches` — Create-{/* Body: { script, description? }. */}+**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `script` | string | Yes | Bash script to execute on spawn |+| `description` | string | No | Human-readable description |++**Response** `201`:++```json+{+ "patch": {+ "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"+ }+}+```### `GET /api/sandboxes/checkpoints/:checkpointId/patches` — List-{/* Response: array of PatchInfo. */}+**Response** `200`: Array of `PatchInfo` objects.### `DELETE /api/sandboxes/checkpoints/:checkpointId/patches/:patchId` — Delete-{/* 204 on success. */}+**Response** `204`: No content.++---## Preview URLs### `POST /api/sandboxes/:id/preview` — Create-{/* Body: { port, domain?, authConfig? }.- Response is the full preview object: id, sandboxId, orgId, hostname, optional customHostname, port, sslStatus, authConfig, createdAt, and optional cfHostnameId.-*/}+**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `port` | int | Yes | Container port (1–65535) |+| `domain` | string | No | Custom domain |+| `authConfig` | object | No | Authentication configuration |++**Response** `201`:++```json+{+ "id": "pv-abc123",+ "sandboxId": "sb-abc123",+ "hostname": "sb-abc123-p3000.preview.opencomputer.dev",+ "port": 3000,+ "sslStatus": "active",+ "createdAt": "2025-01-15T10:30:00Z"+}+```### `GET /api/sandboxes/:id/preview` — List-{/* Response: array of preview URL objects. */}+**Response** `200`: Array of preview URL objects.### `DELETE /api/sandboxes/:id/preview/:port` — Delete-{/* 204 on success. */}+**Response** `204`: No content.++---## Templates+Templates are built from Dockerfiles. The Docker build produces a filesystem image that Firecracker boots from directly.+### `POST /api/templates` — Build-{/* Body: { name, dockerfile, tag? }.- Response shape comes from the current template store record. Verify field names from the handler/store before writing the final page.-*/}+**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `name` | string | Yes | Template name |+| `dockerfile` | string | Yes | Dockerfile content |+| `tag` | string | No | Image tag (default: `"latest"`) |++**Response** `201`:++```json+{+ "id": "tpl-abc123",+ "name": "my-template",+ "tag": "latest",+ "status": "ready",+ "createdAt": "2025-01-15T10:30:00Z"+}+```++Dockerfile templates return `status: "ready"` immediately. Sandbox-snapshot templates transition `processing` → `ready`.### `GET /api/templates` — List-{/* Response: array of TemplateInfo. */}+**Response** `200`: Array of template objects.### `GET /api/templates/:name` — Get-{/* Response: TemplateInfo. */}+**Response** `200`: Template object.### `DELETE /api/templates/:name` — Delete-{/* 204 on success. */}+**Response** `204`: No content.++---## PTY+Terminal sessions for interactive shell access.+### `POST /api/sandboxes/:id/pty` — Create-{/* Body: { cols?, rows?, shell? }. Response uses sessionID casing. */}+**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `cols` | int | No | Terminal columns (default: `80`) |+| `rows` | int | No | Terminal rows (default: `24`) |+| `shell` | string | No | Shell path (default: `/bin/bash`) |++**Response** `201`:++```json+{+ "sessionID": "ps-abc123",+ "sandboxID": "sb-abc123"+}+```### `GET /api/sandboxes/:id/pty/:sessionID` — WebSocket-{/* Upgrade to WebSocket. Binary protocol same as exec. */}+Upgrade to WebSocket. Raw binary I/O — data from the PTY is sent as-is, data received is written to PTY stdin.++Pass auth via query parameter: `?token=<jwt>`### `POST /api/sandboxes/:id/pty/:sessionID/resize` — Resize-{/* Body: { cols, rows }. */}+**Request body:**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `cols` | int | Yes | New column count |+| `rows` | int | Yes | New row count |++**Response** `200`: Empty object.++<Note>+ PTY resize is HTTP-only — not exposed in the TypeScript or Python SDKs. The SDKs handle resize automatically for interactive sessions.+</Note>### `DELETE /api/sandboxes/:id/pty/:sessionID` — Kill-{/* Terminate PTY session. */}+Terminate a PTY session.++**Response** `200`: Empty object.++---## WebSocket Binary Protocol-{/* Exec and PTY sessions use binary WebSocket frames.- Input: prefix 0x00 + stdin data.- Output: 0x01 (stdout), 0x02 (stderr), 0x03 (exit code, 4-byte BE int32), 0x04 (scrollback end marker).- On connect: server replays scrollback buffer, sends 0x04, then live-streams.-*/}+Exec and PTY WebSocket sessions use binary frames with a 1-byte stream prefix:++| Byte | Direction | Meaning |+| --- | --- | --- |+| `0x00` | Client → Server | stdin data |+| `0x01` | Server → Client | stdout data |+| `0x02` | Server → Client | stderr data |+| `0x03` | Server → Client | Exit code (4-byte big-endian int32) |+| `0x04` | Server → Client | Scrollback end marker |++**Connection flow:**++1. Client opens WebSocket with `?token=<jwt>`+2. Server replays scrollback buffer (historical output)+3. Server sends `0x04` to mark end of scrollback+4. Live output streams as `0x01`/`0x02` frames+5. When the process exits, server sends `0x03` with the exit code+6. Server closes the connection++**Sending input:** Prefix your data with `0x00` and send as a binary frame.++**PTY sessions** use the same binary framing but without stream prefixes — raw bidirectional terminal data.++---## Error Format-{/* All errors: {"error": "message"} envelope.- Common codes: 400, 401, 403, 404, 409, 500.-*/}+All errors use a consistent envelope:++```json+{+ "error": "descriptive error message"+}+```++| Status Code | Meaning |+| --- | --- |+| `400` | Invalid request (missing fields, bad values) |+| `401` | Missing or invalid authentication |+| `403` | Insufficient permissions |+| `404` | Resource not found |+| `409` | Conflict (duplicate resource, e.g. checkpoint name) |+| `429` | Quota exceeded |+| `500` | Internal server error |+| `503` | Feature unavailable in current deployment mode |diff --git a/docs/reference/cli.mdx b/docs/reference/cli.mdxindex 73d51afa..7269d3b6 100644--- a/docs/reference/cli.mdx+++ b/docs/reference/cli.mdx@@ -3,116 +3,251 @@ title: "CLI Reference"description: "Every command, subcommand, and flag"----{/*- TODO: Expand this stub into full content.+## Global Flags- GOAL: Exhaustive CLI reference. Every command, every subcommand, every flag.- The lookup page for exact syntax when the CLI guide pages aren't enough.+These flags apply to all commands.- SOURCE: cmd/oc/internal/commands/ — all command files.+| Flag | Type | Env Variable | Description |+| --- | --- | --- | --- |+| `--api-key` | string | `OPENCOMPUTER_API_KEY` | API key for authentication |+| `--api-url` | string | `OPENCOMPUTER_API_URL` | Control plane URL |+| `--json` | boolean | — | Output as JSON |- KEY NOTES:- - Each command: full syntax, flags table (name, type, default, description), output example- - Aliases: oc create = oc sandbox create, oc ls = oc sandbox list, oc cp = oc checkpoint- - This page is lookup-oriented — no tutorials, no "why"-*/}+----## Global Flags+## `oc sandbox`-| Flag | Environment Variable | Description |-| --- | --- | --- |-| `--api-key` | `OPENCOMPUTER_API_KEY` | API key for authentication |-| `--api-url` | `OPENCOMPUTER_API_URL` | Control plane URL |-| `--json` | — | Output as JSON instead of tables |+Manage sandbox lifecycle.-## `oc sandbox`+### `oc sandbox create`++Create a new sandbox. **Alias:** `oc create`++| Flag | Type | Default | Description |+| --- | --- | --- | --- |+| `--timeout` | int | `300` | Idle timeout in seconds |+| `--cpu` | int | `0` | CPU cores (0 = platform default) |+| `--memory` | int | `0` | Memory in MB (0 = platform default) |+| `--env` | string | — | Environment variable `KEY=VALUE` (repeatable) |+| `--metadata` | string | — | Metadata `KEY=VALUE` (repeatable) |-{/* Aliases: oc create = oc sandbox create, oc ls = oc sandbox list */}+```bash+oc create --timeout 600 --cpu 2 --memory 1024 --env NODE_ENV=production+```-### `oc sandbox create` / `oc create`+### `oc sandbox list`-{/* Flags: --timeout, --cpu, --memory, --env, --metadata. Output: sandbox ID. */}+List all running sandboxes. **Alias:** `oc ls`-### `oc sandbox list` / `oc ls`+Output columns: `ID`, `TEMPLATE`, `STATUS`, `CPU`, `MEM`, `AGE`-{/* Output: table with ID, TEMPLATE, STATUS, CPU, MEM, AGE. */}+```bash+oc ls+oc ls --json+```### `oc sandbox get <id>`-{/* Output: detailed sandbox info. */}+Show detailed information for a sandbox.++Output: ID, Template, Status, CPU, Memory, Started, Ends.### `oc sandbox kill <id>`+Terminate and remove a sandbox.+### `oc sandbox hibernate <id>`+Snapshot VM state and stop the sandbox. Displays snapshot size on success.+### `oc sandbox wake <id>`-{/* Flags: --timeout */}+Resume a hibernated sandbox.++| Flag | Type | Default | Description |+| --- | --- | --- | --- |+| `--timeout` | int | `300` | Idle timeout in seconds after wake |### `oc sandbox set-timeout <id> <seconds>`+Update the idle timeout for a running sandbox.++```bash+oc sandbox set-timeout sb-abc123 600+```++---+## `oc exec`-### `oc exec <id> -- <command...>`+Execute commands inside a sandbox.++### `oc exec <id> [flags] -- <command...>`++By default, creates an **exec session** and prints the session ID with attach instructions. Use `--wait` to run synchronously — output streams to your terminal and the CLI exits with the process exit code.++| Flag | Type | Default | Description |+| --- | --- | --- | --- |+| `--wait` | boolean | `false` | Wait for completion, stream output, mirror exit code |+| `--cwd` | string | — | Working directory |+| `--timeout` | int | `0` | Timeout in seconds (0 = none) |+| `--env` | string | — | Environment variable `KEY=VALUE` (repeatable) |-{/* Flags: --cwd, --timeout, --env, --wait.- Important: plain `oc exec` creates a session. `--wait` uses synchronous exec/run behavior with exit-code passthrough.-*/}+```bash+# Synchronous — streams output, exits with process exit code+oc exec sb-abc --wait -- npm run build++# Asynchronous — creates session, prints session ID+oc exec sb-abc -- node server.js+# → Session es-xyz created. Attach with: oc exec attach sb-abc es-xyz+```### `oc exec list <id>`+List active exec sessions for a sandbox.++Output: session ID, status (`running` or `exited (code)`), command, client count.+### `oc exec attach <id> <session-id>`-{/* Command exists, but the CLI implementation is currently a stub that prints guidance instead of attaching. */}+<Warning>+ Not yet implemented. The command exists but prints guidance to use the SDK or a WebSocket client (`websocat`).+</Warning>### `oc exec kill <id> <session-id>`+Kill an exec session.++| Flag | Type | Default | Description |+| --- | --- | --- | --- |+| `--signal` | int | `9` | Signal number (default: SIGKILL) |++---+## `oc shell`### `oc shell <id>`-{/* Flags: --shell (default /bin/bash). WebSocket PTY session. */}+Open an interactive terminal (PTY) session via WebSocket.++| Flag | Type | Default | Description |+| --- | --- | --- | --- |+| `--shell` | string | `/bin/bash` | Shell to use |++Terminal size is auto-detected and resize events are forwarded. Press `Ctrl+D` or type `exit` to disconnect. The PTY session is cleaned up automatically on exit.++```bash+oc shell sb-abc123+oc shell sb-abc123 --shell /bin/zsh+```++---## `oc checkpoint`-{/* Alias: oc cp */}+Manage sandbox checkpoints. **Alias:** `oc cp`++### `oc checkpoint create <sandbox-id>`-### `oc checkpoint create <sandbox-id> --name <name>`+Create a named checkpoint of a running sandbox.++| Flag | Type | Default | Description |+| --- | --- | --- | --- |+| `--name` | string | — | Checkpoint name (**required**) |++```bash+oc cp create sb-abc --name before-migration+```### `oc checkpoint list <sandbox-id>`+List checkpoints for a sandbox.++Output columns: `ID`, `NAME`, `STATUS`, `SIZE`, `CREATED`+### `oc checkpoint restore <sandbox-id> <checkpoint-id>`+Revert a sandbox in-place to a checkpoint. All changes since the checkpoint are lost.+### `oc checkpoint spawn <checkpoint-id>`-{/* Flags: --timeout */}+Create a new sandbox from a checkpoint (fork).++| Flag | Type | Default | Description |+| --- | --- | --- | --- |+| `--timeout` | int | `300` | Idle timeout for the new sandbox |++```bash+ID=$(oc cp spawn cp-xyz --json | jq -r '.sandboxID')+oc exec "$ID" --wait -- echo "forked sandbox ready"+```### `oc checkpoint delete <sandbox-id> <checkpoint-id>`+Delete a checkpoint.++---+## `oc patch`+Manage checkpoint patches — scripts that run when a sandbox is spawned from a checkpoint.+### `oc patch create <checkpoint-id>`-{/* Flags: --script (file or - for stdin), --description */}+| Flag | Type | Default | Description |+| --- | --- | --- | --- |+| `--script` | string | — | Path to script file, or `-` for stdin (**required**) |+| `--description` | string | — | Patch description |++```bash+oc patch create cp-xyz --script=./setup.sh --description="Install deps"+echo "apt install -y curl" | oc patch create cp-xyz --script=-+```### `oc patch list <checkpoint-id>`+Output columns: `ID`, `SEQ`, `DESCRIPTION`, `STRATEGY`, `CREATED`+### `oc patch delete <checkpoint-id> <patch-id>`+---+## `oc preview`+Manage preview URLs for exposing sandbox ports to the internet.+### `oc preview create <sandbox-id>`-{/* Flags: --port (required), --domain */}+| Flag | Type | Default | Description |+| --- | --- | --- | --- |+| `--port` | int | — | Container port to expose (**required**) |+| `--domain` | string | — | Custom domain |++```bash+oc preview create sb-abc --port 3000+```### `oc preview list <sandbox-id>`+Output columns: `PORT`, `HOSTNAME`, `SSL`, `CREATED`+### `oc preview delete <sandbox-id> <port>`+---+## `oc config`+Manage CLI configuration. Settings are persisted to a local config file.+### `oc config set <key> <value>`-{/* Keys: api-key, api-url */}+Supported keys: `api-key`, `api-url`.++```bash+oc config set api-key sk-1234...+oc config set api-url https://app.opencomputer.dev+```### `oc config show`++Display current configuration. The API key is masked (first 4 and last 4 characters shown).diff --git a/docs/sandboxes/overview.mdx b/docs/sandboxes/overview.mdxindex cf9d284c..e25acf8c 100644--- a/docs/sandboxes/overview.mdx+++ b/docs/sandboxes/overview.mdx@@ -3,99 +3,217 @@ title: "Sandboxes"description: "The compute primitive — full Linux VMs in the cloud"----{/*- TODO: Expand this stub into full content.+A sandbox is a full Linux virtual machine in the cloud. Each one has its own filesystem, network stack, and process space — completely isolated from other sandboxes via hardware-level virtualization. Think of it as a disposable laptop that starts in milliseconds and sleeps when idle.- GOAL: The definitive page for understanding and working with the sandbox primitive.- Concept + lifecycle + full SDK API for sandbox management.+<CodeGroup>- ABSORBS: sdks/typescript/sandbox.mdx, sdks/python/sandbox.mdx.+```typescript TypeScript+import { Sandbox } from "@anthropic-ai/opencomputer";- KEY NOTES:- - Python context manager: async with await Sandbox.create() as sandbox: (auto-kills on exit)- - TS-only: cpuCount, memoryMB on create. Python must use HTTP API for custom resources.- - Lifecycle states: running, hibernated, stopped, error- - Rolling timeout resets on every operation, default 300s- - Distinguish sandbox guarantees from default-template contents and deployment-specific resource defaults-*/}+const sandbox = await Sandbox.create();+const result = await sandbox.exec.run("echo Hello from $(uname -a)");+console.log(result.stdout);+await sandbox.kill();+```-## What is a Sandbox+```python Python+from opencomputer import Sandbox-{/* A full Linux virtual machine in the cloud. Isolated environment: own filesystem, network, processes. Think of it as a laptop that sleeps when idle and wakes instantly. */}+async with await Sandbox.create() as sandbox:+ result = await sandbox.exec.run("echo Hello from $(uname -a)")+ print(result.stdout)+# sandbox is killed automatically on exit+```-## Quick Example+</CodeGroup>-{/* Create -> run command -> kill. TS + Python CodeGroup. */}+## Creating a Sandbox<CodeGroup>```typescript TypeScript-// TODO: Sandbox.create -> exec.run('echo hello') -> kill+const sandbox = await Sandbox.create({+ template: "my-custom-template",+ timeout: 600,+ cpuCount: 2,+ memoryMB: 1024,+ envs: { NODE_ENV: "production" },+ metadata: { project: "my-app" },+});``````python Python-# TODO: Sandbox.create -> exec.run('echo hello') -> kill+sandbox = await Sandbox.create(+ template="my-custom-template",+ timeout=600,+ envs={"NODE_ENV": "production"},+ metadata={"project": "my-app"},+)```-</CodeGroup>+```bash curl+curl -X POST https://app.opencomputer.dev/api/sandboxes \+ -H "X-API-Key: $OPENCOMPUTER_API_KEY" \+ -H "Content-Type: application/json" \+ -d '{+ "templateID": "my-custom-template",+ "timeout": 600,+ "cpuCount": 2,+ "memoryMB": 1024,+ "envs": {"NODE_ENV": "production"},+ "metadata": {"project": "my-app"}+ }'+```-## Specs+</CodeGroup>-{/* Table:- - Keep this focused on sandbox/runtime guarantees: isolated VM, filesystem, network, lifecycle, configurable resources- - Do not hard-code hosted defaults for CPU/memory unless verified against the current hosted deployment- - Move package lists (Python, Node, common CLI tools) to the default-template section/page, not the sandbox primitive-*/}+### Parameters-## Creating a Sandbox+| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `template` | string | `"base"` | Template for the VM root filesystem |+| `timeout` | number | `300` | Idle timeout in seconds (resets on every operation) |+| `envs` | object | — | Environment variables set inside the VM |+| `metadata` | object | — | Arbitrary key-value pairs stored with the sandbox |+| `cpuCount` | number | — | CPU cores (max 4). TypeScript and HTTP API only |+| `memoryMB` | number | — | Memory in MB (max 2048). TypeScript and HTTP API only |+| `apiKey` | string | — | Defaults to `OPENCOMPUTER_API_KEY` env var |+| `apiUrl` | string | — | Defaults to `OPENCOMPUTER_API_URL` env var |-{/* Sandbox.create(opts) with ParamField reference:- - Both SDKs: template, timeout, apiKey/api_key, apiUrl/api_url, envs, metadata- - TS-only: cpuCount, memoryMB- - Note for Python: use HTTP API for custom resources-*/}+<Note>+ `cpuCount` and `memoryMB` are not available in the Python SDK. Use the [HTTP API](/reference/api#sandbox-lifecycle) directly for custom resources from Python.+</Note>## Connecting to an Existing Sandbox-{/* Sandbox.connect(sandboxId) — TS + Python CodeGroup */}+<CodeGroup>++```typescript TypeScript+const sandbox = await Sandbox.connect("sb-abc123");+```++```python Python+sandbox = await Sandbox.connect("sb-abc123")+```++</CodeGroup>## Lifecycle-{/* Status states: running, hibernated, stopped, error.- Text-based lifecycle: running <-> hibernated -> stopped; running -> error- Rolling timeout: resets on every operation, default 300s.- What happens on timeout: auto-hibernate if possible, else stop.-*/}+Sandboxes have four states:++| Status | Description |+| --- | --- |+| `running` | Active, accepting operations |+| `hibernated` | State saved, no compute cost |+| `stopped` | Terminated |+| `error` | Failed |++A rolling idle timeout (default 300s) resets on every operation — exec, file access, agent activity. When the timeout expires, the sandbox auto-hibernates if possible, otherwise stops.## Hibernation & Wake-{/* Like closing a laptop lid: sandbox identity stays the same and the platform attempts a fast snapshot-based resume.- - sandbox.hibernate(), sandbox.wake() — TS SDK- - Usually resumes quickly, no cost while hibernated- - Auto-triggered on idle timeout- - Difference from checkpoints: hibernation = transparent resume; checkpoints = named snapshots you fork from- - Note: Python SDK doesn't have hibernate/wake. HTTP API: POST /api/sandboxes/:id/hibernate, wake. CLI: oc sandbox hibernate, wake.-*/}+Hibernation snapshots the VM state and stops it — no cost while hibernated. Wake restores the sandbox, typically fast, with a cold-boot fallback if snapshot restore is unavailable.++<CodeGroup>++```typescript TypeScript+await sandbox.hibernate();+// ... later ...+await sandbox.wake({ timeout: 600 });+```++```http HTTP+POST /api/sandboxes/sb-abc123/hibernate++POST /api/sandboxes/sb-abc123/wake+Content-Type: application/json++{"timeout": 600}+```++</CodeGroup><Note>- `hibernate()` and `wake()` are available in the TypeScript SDK and CLI. Python SDK support is planned — use the HTTP API directly for now.+ `hibernate()` and `wake()` are available in the TypeScript SDK and [CLI](/cli/sandbox). Python SDK support is planned — use the [HTTP API](/reference/api#sandbox-lifecycle) directly.</Note>-## Other Methods+## Methods-{/* kill(), isRunning()/is_running(), setTimeout()/set_timeout()- Note: document the SDK normally; reserve the worker-direct hosted API nuance for reference/api.-*/}+| Method | TypeScript | Python | Description |+| --- | --- | --- | --- |+| Kill | `await sandbox.kill()` | `await sandbox.kill()` | Terminate the sandbox |+| Check status | `await sandbox.isRunning()` | `await sandbox.is_running()` | Returns boolean |+| Set timeout | `await sandbox.setTimeout(600)` | `await sandbox.set_timeout(600)` | Update idle timeout (seconds) |+| Hibernate | `await sandbox.hibernate()` | — | Snapshot and stop |+| Wake | `await sandbox.wake()` | — | Resume from hibernation |## Properties-{/* sandboxId, agent, exec, files, pty- Python-specific: async with await Sandbox.create() as sandbox: (context manager, auto-kills on exit)-*/}+| Property | TypeScript | Python | Description |+| --- | --- | --- | --- |+| Sandbox ID | `sandbox.sandboxId` | `sandbox.sandbox_id` | Unique identifier |+| Status | `sandbox.status` | `sandbox.status` | Current lifecycle state |+| Agent | `sandbox.agent` | `sandbox.agent` | [Agent sessions](/agents/overview) |+| Exec | `sandbox.exec` | `sandbox.exec` | [Command execution](/sandboxes/running-commands) |+| Files | `sandbox.files` | `sandbox.files` | [Filesystem](/sandboxes/working-with-files) |+| PTY | `sandbox.pty` | `sandbox.pty` | [Interactive terminals](/sandboxes/interactive-terminals) |++<Warning>+ `sandbox.commands` is a deprecated alias for `sandbox.exec`. Use `sandbox.exec` in all new code.+</Warning>++### Python Context Manager++The Python SDK supports `async with` for automatic cleanup:++```python+async with await Sandbox.create() as sandbox:+ result = await sandbox.exec.run("echo hello")+ print(result.stdout)+# sandbox.kill() called automatically on exit+```++## Forking from Checkpoints++Create a sandbox from a saved checkpoint — useful for parallel testing from a known-good state:++<CodeGroup>++```typescript TypeScript+const forked = await Sandbox.createFromCheckpoint("cp-abc123", { timeout: 600 });+```++```python Python+forked = await Sandbox.create_from_checkpoint("cp-abc123", timeout=600)+```++</CodeGroup>++See [Checkpoints](/sandboxes/checkpoints) for the full workflow.## Related-{/* Links to: Running Commands, Files, Terminals, Checkpoints, Templates, Agents overview (agents run inside sandboxes) */}+<CardGroup cols={2}>+ <Card title="Running Commands" href="/sandboxes/running-commands">+ Execute shell commands+ </Card>+ <Card title="Working with Files" href="/sandboxes/working-with-files">+ Read, write, and manage files+ </Card>+ <Card title="Interactive Terminals" href="/sandboxes/interactive-terminals">+ PTY sessions for interactive work+ </Card>+ <Card title="Checkpoints" href="/sandboxes/checkpoints">+ Snapshot, fork, and restore+ </Card>+ <Card title="Templates" href="/sandboxes/templates">+ Custom VM images+ </Card>+ <Card title="Preview URLs" href="/sandboxes/preview-urls">+ Expose ports to the internet+ </Card>+</CardGroup><Tip>CLI: [`oc sandbox`](/cli/sandbox) for lifecycle management. Full reference: [TypeScript SDK](/reference/typescript-sdk#sandbox) · [Python SDK](/reference/python-sdk#sandbox) · [HTTP API](/reference/api#sandbox-lifecycle).