An open-source, faster Devin alternative
TypeScript
Write Band B entity pages and SDK reference with full content
Igor Zalutskia245382305f2
diff --git a/docs/agents/events.mdx b/docs/agents/events.mdxindex 08006bb3..aebc162d 100644--- a/docs/agents/events.mdx+++ b/docs/agents/events.mdx@@ -3,82 +3,148 @@ title: "Events"description: "Understanding the agent event stream"----{/*- TODO: Expand this stub into full content.+Agent sessions emit events via the `onEvent` callback. Each event has a `type` field. The wrapper forwards Claude Agent SDK messages as-is — tolerate unknown event types and preserve unknown fields for forward compatibility.++```typescript+const session = await sandbox.agent.start({+ prompt: "Build a REST API",+ onEvent: (event) => {+ switch (event.type) {+ case "assistant":+ process.stdout.write(String(event.message ?? ""));+ break;+ case "result":+ console.log("Done:", event);+ break;+ default:+ // Log unknown events rather than ignoring them+ console.log(`[${event.type}]`, event);+ }+ },+});+```- GOAL: Explain the common agent events and how to handle them safely.- The wrapper mostly forwards Claude Agent SDK messages through as-is, so this page should document- the common events and patterns without pretending the event taxonomy is narrower or more stable than it is.-*/}--## Overview+## Event Lifecycle-{/* Brief intro: agent sessions emit typed events via onEvent callback. Each event has a `type` field. */}+A typical successful session emits events in this order:-## Event Lifecycle+```+ready → configured → assistant / system / tool_use_summary → result → turn_complete+```-{/* Show a typical successful flow, but note this is illustrative rather than exhaustive:- ready -> configured -> assistant/system/tool_use_summary/... -> result -> turn_complete-*/}+This is illustrative — the exact sequence depends on what the agent does. Multiple `assistant`, `system`, and `tool_use_summary` events may interleave as the agent works.## Event Reference-{/* Cover the common event families. Each subsection should explain what it means, when it fires,- the fields people usually care about, and a code example.- Add a note near the top: preserve unknown fields and tolerate unknown event types.-*/}-### `ready`-{/* Agent process started, waiting for configuration. */}+The agent process started and is waiting for configuration. Emitted once at session start.### `configured`-{/* Agent configured and working on the prompt. */}+Configuration applied, agent is working on the prompt.### `assistant`-{/* Claude's text output. Do not hard-code a single payload shape; current wrapper comments show `message`,- and upstream Claude SDK event fields may evolve. Document the common fields and show how to inspect raw events.-*/}+Claude's text output. This is the agent "thinking out loud" or explaining what it's doing. The `message` field contains the text, but the exact payload shape comes from the upstream Claude SDK and may evolve.-### `tool_use_summary`+### `system`-{/* Tool summary event from the wrapper/SDK stream. Document common fields only; do not overfit the exact shape. */}+System-level messages from the SDK. Common subtypes include initialization, task progress, and status updates.-### `system`+### `tool_use_summary`-{/* System-level messages from the SDK stream. Call out common subtypes like init, task_started, and task_progress. */}+Summary of a tool the agent just used — typically includes tool name and a brief description of what it did.### `tool_progress`-{/* Long-running tool progress updates. Call out common fields like tool_name and elapsed_time_seconds. */}+Progress updates from long-running tools. Common fields include `tool_name` and `elapsed_time_seconds`.### `result`-{/* Final result event. Document common fields like subtype plus result or structured_output, but note the payload varies by run/output mode. */}+Final result of the agent's work. The `subtype` field indicates the kind of result. Payload varies by run mode — may include structured output, a summary, or error details.### `turn_complete`-{/* Turn finished. Fields: claude_session_id (used for resume). Emitted after result. */}+The agent finished its current turn. Includes `claude_session_id` which you can use to [resume the conversation](/agents/multi-turn#resuming-across-sessions) in a new session.++```typescript+onEvent: (event) => {+ if (event.type === "turn_complete") {+ savedSessionId = event.claude_session_id;+ }+}+```### `interrupted`-{/* Agent was interrupted via session.interrupt(). */}+The agent was stopped via `session.interrupt()`.### `error`-{/* Agent emitted an explicit error event. Message field is common, but preserve unknown fields. */}+The agent emitted an error. The `message` field describes what went wrong.## Filtering Events-{/* Practical patterns:- - Log only assistant messages- - Capture the final result- - Build progress indicators from system/task/tool_progress events- - Preserve unknown events for forward compatibility-*/}+Common patterns:++<CodeGroup>++```typescript TypeScript+// Capture only assistant output+const session = await sandbox.agent.start({+ prompt: "Explain this codebase",+ onEvent: (event) => {+ if (event.type === "assistant") {+ process.stdout.write(String(event.message ?? ""));+ }+ },+});+```++```python Python+# Collect all events and filter afterward+session = await sandbox.agent.start(prompt="Explain this codebase")+events = await session.collect_events()++assistant_messages = [e for e in events if e.type == "assistant"]+result = next((e for e in events if e.type == "result"), None)+```++</CodeGroup>## Error Handling-{/* error events vs onError (stderr) vs rejected promises. When each fires, how to respond. */}+There are three error surfaces:++| Surface | When | Example |+| --- | --- | --- |+| `error` event | Agent reports an error during execution | Invalid tool use, model error |+| `onError` callback | Raw stderr output from the agent process | Crash logs, unhandled exceptions |+| Promise rejection | WebSocket or API failure | Network error, auth expired |++Handle all three for robust agent monitoring:++```typescript+const session = await sandbox.agent.start({+ prompt: "...",+ onEvent: (event) => {+ if (event.type === "error") {+ console.error("Agent error:", event.message);+ }+ },+ onError: (data) => {+ console.error("Process stderr:", data);+ },+});++try {+ await session.done;+} catch (err) {+ console.error("Connection error:", err);+}+```++<Tip>+ Back to [Agents overview](/agents/overview). Full reference: [TypeScript SDK](/reference/typescript-sdk#agent) · [Python SDK](/reference/python-sdk#agent).+</Tip>diff --git a/docs/agents/multi-turn.mdx b/docs/agents/multi-turn.mdxindex d026aa5b..a87612d0 100644--- a/docs/agents/multi-turn.mdx+++ b/docs/agents/multi-turn.mdx@@ -3,61 +3,175 @@ title: "Multi-turn"description: "Follow-ups, resume, and session management"----{/*- TODO: Expand this stub into full content.+Agent conversations can extend beyond a single prompt. Send follow-up prompts within the same session, resume a conversation in a new session, or reconnect to a running agent.- GOAL: Everything about conversations that go beyond a single prompt —- follow-ups, resuming across sessions, and managing running sessions.+## Follow-up Prompts- KEY NOTES:- - resume is TS-only in the SDK surface. If showing an HTTP workaround, document the real flow:- create agent session with resume, then attach via exec-session WebSocket.- - Distinguish attach (reconnect to running session) vs resume (new session continuing old conversation, TS only).- - Agent sessions are SDK-only — no CLI command yet.-*/}+Use `sendPrompt()` to continue a conversation within the same running session:-## Follow-up Prompts+<CodeGroup>++```typescript TypeScript+const session = await sandbox.agent.start({+ prompt: "Create a REST API with Express",+ onEvent: (event) => console.log(`[${event.type}]`, event),+});++await session.done;++// Send a follow-up in the same session+session.sendPrompt("Now add input validation to all endpoints");+await session.done;+```-{/* session.sendPrompt(text) to continue within same session.- Example: start a task, wait for completion, send follow-up. TS + Python CodeGroup. */}+```python Python+session = await sandbox.agent.start(+ prompt="Create a REST API with Express",+ on_event=lambda event: print(f"[{event.type}]", event),+)++await session.wait()++# Send a follow-up in the same session+session.send_prompt("Now add input validation to all endpoints")+await session.wait()+```++</CodeGroup>## Resuming Across Sessions-{/* TS only. resume parameter in agent.start().- - Capture claude_session_id from turn_complete event- - Pass as resume in new agent.start() call- - Example: save session ID, create sandbox from checkpoint, resume conversation- - Note: Python SDK does not support resume. If including HTTP, use the real agent-create + exec-attach flow.-*/}+Resume continues a previous conversation in a **new** agent session. This is useful when the original session has ended or you want to fork the conversation.++Capture the `claude_session_id` from the `turn_complete` event, then pass it as `resume` when starting a new session:++```typescript+let claudeSessionId: string;++const session1 = await sandbox.agent.start({+ prompt: "Set up a Next.js project with Tailwind",+ onEvent: (event) => {+ if (event.type === "turn_complete") {+ claudeSessionId = event.claude_session_id;+ }+ },+});+await session1.done;++// Later — possibly in a different sandbox forked from the same checkpoint+const session2 = await sandbox.agent.start({+ prompt: "Now add a dark mode toggle",+ resume: claudeSessionId,+ onEvent: (event) => console.log(event),+});+await session2.done;+```<Note>- Resume is currently available in the TypeScript SDK only. Python SDK support is planned.+ `resume` is available in the TypeScript SDK only. Python SDK support is planned — use the [HTTP API](/reference/api#agent-sessions) directly to pass the `resume` field.</Note>+### Attach vs Resume++| | Attach | Resume |+| --- | --- | --- |+| Session state | Still running | Ended or running |+| What happens | Reconnect to event stream | New session, continues conversation |+| SDK support | TypeScript, Python | TypeScript only |+## Interrupting-{/* session.interrupt() to stop the current turn. Both SDKs. */}+Stop the agent's current turn:++<CodeGroup>++```typescript TypeScript+session.interrupt();+// The session emits an "interrupted" event+```++```python Python+session.interrupt()+```++</CodeGroup>++The agent stops working but the session stays alive — you can send a new prompt to continue.## Reconfiguring Mid-Session-{/* session.configure() to change model, tools, etc. while session is running. */}+Change model, tools, or working directory while the session is running:-## Managing Sessions+<CodeGroup>++```typescript TypeScript+session.configure({+ model: "claude-sonnet-4-20250514",+ maxTurns: 20,+ allowedTools: ["Read", "Bash"],+});+```-{/* List, attach, and manage running agent sessions. */}+```python Python+session.configure(+ model="claude-sonnet-4-20250514",+ max_turns=20,+ allowed_tools=["Read", "Bash"],+)+```++</CodeGroup>++The new configuration takes effect on the next turn.++## Managing Sessions### Listing Sessions-{/* sandbox.agent.list() — both SDKs. */}+<CodeGroup>++```typescript TypeScript+const sessions = await sandbox.agent.list();+for (const s of sessions) {+ console.log(s.sessionID, s.running ? "running" : "stopped");+}+```++```python Python+sessions = await sandbox.agent.list()+for s in sessions:+ print(s.session_id, "running" if s.running else "stopped")+```++</CodeGroup>### Attaching to a Running Session-{/* sandbox.agent.attach(sessionId) — reconnect to running session. Both SDKs.- When to use attach vs resume:- - attach = same session still running, reconnect to event stream- - resume = new session continuing old conversation (TS only)-*/}+Reconnect to an agent session that's already running — useful after a network disconnect or when monitoring from a different client:++<CodeGroup>++```typescript TypeScript+const session = await sandbox.agent.attach(sessionId, {+ onEvent: (event) => console.log(event),+ onError: (data) => console.error(data),+});+```++```python Python+session = await sandbox.agent.attach(+ session_id,+ on_event=lambda event: print(event),+ on_error=lambda data: print("error:", data),+)+```++</CodeGroup><Note>Agent sessions are SDK-only — there is no CLI command for agents yet.</Note>++<Tip>+ Back to [Agents overview](/agents/overview). See also: [Events](/agents/events) · [Tools](/agents/tools).+</Tip>diff --git a/docs/agents/tools.mdx b/docs/agents/tools.mdxindex 40c0cfcd..913613e7 100644--- a/docs/agents/tools.mdx+++ b/docs/agents/tools.mdx@@ -3,40 +3,157 @@ title: "Tools"description: "Configure what tools an agent can use"----{/*- TODO: Expand this stub into full content.-- GOAL: Explain how to configure what tools an agent can use, including MCP servers.- MCP servers are the main event on this page — most configuration value is here.-*/}+By default, the agent has access to bash, file read/write, and Python — the same tools available in [Claude Code](https://docs.anthropic.com/en/docs/agents/claude-code-sdk-overview). You can restrict these and add custom tools via MCP servers.## Default Tools-{/* What the agent can do out of the box: bash, file read/write, Python. Brief explanation of allowedTools param to restrict. */}+The agent runs with all Claude Code tools enabled. To restrict which tools the agent can use, pass `allowedTools`:-## MCP Servers+<CodeGroup>++```typescript TypeScript+const session = await sandbox.agent.start({+ prompt: "Analyze the CSV files in /data",+ allowedTools: ["Read", "Bash"],+});+```-{/* Main event on this page. What MCP is (one sentence), then how to configure:- - mcpServers param structure: Record<string, { command, args?, env? }>- - MCP servers run inside the sandbox, agent discovers tools via protocol-*/}+```python Python+session = await sandbox.agent.start(+ prompt="Analyze the CSV files in /data",+ allowed_tools=["Read", "Bash"],+)+```-### Example: SQLite Database Tool+</CodeGroup>++## MCP Servers-{/* TS + Python CodeGroup showing mcpServers config with sqlite MCP server */}+[Model Context Protocol](https://modelcontextprotocol.io/) servers give the agent access to custom tools. MCP servers run inside the sandbox — the agent discovers available tools via the protocol.++Pass MCP server configuration when starting the agent:++<CodeGroup>++```typescript TypeScript+const session = await sandbox.agent.start({+ prompt: "Query the users table and summarize the results",+ mcpServers: {+ sqlite: {+ command: "npx",+ args: ["-y", "@modelcontextprotocol/server-sqlite", "/data/app.db"],+ },+ },+});+```++```python Python+session = await sandbox.agent.start(+ prompt="Query the users table and summarize the results",+ mcp_servers={+ "sqlite": {+ "command": "npx",+ "args": ["-y", "@modelcontextprotocol/server-sqlite", "/data/app.db"],+ },+ },+)+```++</CodeGroup>++### McpServerConfig++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| `command` | string | Yes | Command to start the MCP server |+| `args` | string[] | No | Command arguments |+| `env` | object | No | Environment variables for the server process |### Example: Custom API Tool-{/* TS + Python CodeGroup showing custom MCP server */}+```typescript+const session = await sandbox.agent.start({+ prompt: "Fetch the latest deployment status",+ mcpServers: {+ deploy: {+ command: "node",+ args: ["/tools/deploy-server.js"],+ env: { DEPLOY_API_KEY: process.env.DEPLOY_API_KEY },+ },+ },+});+```## System Prompt-{/* systemPrompt param — how to steer agent behavior with custom instructions. Example. */}+Steer agent behavior with a custom system prompt:++<CodeGroup>++```typescript TypeScript+const session = await sandbox.agent.start({+ prompt: "Review the codebase for security issues",+ systemPrompt: "You are a security auditor. Focus on OWASP Top 10 vulnerabilities. Output findings as a markdown checklist.",+});+```++```python Python+session = await sandbox.agent.start(+ prompt="Review the codebase for security issues",+ system_prompt="You are a security auditor. Focus on OWASP Top 10 vulnerabilities. Output findings as a markdown checklist.",+)+```++</CodeGroup>## Permission Mode-{/* permissionMode param — what it controls, available values. */}+Controls how the agent handles tool permissions:++<CodeGroup>++```typescript TypeScript+const session = await sandbox.agent.start({+ prompt: "Set up the project",+ permissionMode: "bypassPermissions", // default — agent runs freely+});+```++```python Python+session = await sandbox.agent.start(+ prompt="Set up the project",+ permission_mode="bypassPermissions",+)+```++</CodeGroup>++The default is `bypassPermissions` — the agent can use any available tool without confirmation. This is safe because the agent runs inside an isolated sandbox VM.## Max Turns-{/* maxTurns param — limiting agent iterations. When to use it. */}+Limit how many think → act → observe iterations the agent can perform:++<CodeGroup>++```typescript TypeScript+const session = await sandbox.agent.start({+ prompt: "Fix the failing test",+ maxTurns: 10, // default: 50+});+```++```python Python+session = await sandbox.agent.start(+ prompt="Fix the failing test",+ max_turns=10,+)+```++</CodeGroup>++Lower `maxTurns` to prevent runaway agents on simple tasks. The default is 50.++<Tip>+ Back to [Agents overview](/agents/overview). See also: [Events](/agents/events) · [Multi-turn](/agents/multi-turn).+</Tip>diff --git a/docs/reference/python-sdk.mdx b/docs/reference/python-sdk.mdxindex 2c04f25c..69b290b7 100644--- a/docs/reference/python-sdk.mdx+++ b/docs/reference/python-sdk.mdx@@ -3,22 +3,6 @@ title: "Python SDK"description: "Complete Python SDK reference"----{/*- TODO: Expand this stub into full content.-- GOAL: Exhaustive Python SDK reference. Every class, every method, every type.- Accurate to actual Python SDK — note gaps vs TypeScript honestly.-- SOURCE: sdks/python/opencomputer/ — all source files.-- KEY NOTES:- - Each method: full async signature, params with types and defaults, return type, one-line example- - Not available: hibernate/wake, cpuCount/memoryMB, exec streaming, exec.attach, agent resume- - Python-unique: collect_events(), wait(), recv(), context manager- - Include ExecSessionInfo.attachedClients- - Template class is singular (not Templates), but verify the public construction story before documenting usage examples-*/}-## Installation```bash@@ -29,49 +13,134 @@ pip install opencomputer-sdkfrom opencomputer import Sandbox, Template```+---+## Sandbox### Class Methods-#### `await Sandbox.create(template?, timeout?, api_key?, api_url?, envs?, metadata?): Sandbox`+#### `await Sandbox.create(...): Sandbox`++Create a new sandbox.-{/* No cpuCount/memoryMB — use HTTP API for custom resources */}+| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `template` | str | `"base"` | Template name |+| `timeout` | int | `300` | Idle timeout in seconds |+| `api_key` | str | env var | API key |+| `api_url` | str | env var | API URL |+| `envs` | dict[str, str] | None | Environment variables |+| `metadata` | dict[str, str] | None | Arbitrary metadata |-#### `await Sandbox.connect(sandbox_id, api_key?, api_url?): Sandbox`+```python+sandbox = await Sandbox.create(template="my-stack", timeout=600)+```++<Note>+ `cpuCount` and `memoryMB` are not available in the Python SDK. Use the [HTTP API](/reference/api#sandbox-lifecycle) for custom resources.+</Note>++#### `await Sandbox.connect(sandbox_id, ...): Sandbox`++| Parameter | Type | Description |+| --- | --- | --- |+| `sandbox_id` | str | Sandbox ID (**required**) |+| `api_key` | str | API key (optional) |+| `api_url` | str | API URL (optional) |++```python+sandbox = await Sandbox.connect("sb-abc123")+```#### `await Sandbox.create_from_checkpoint(checkpoint_id, ...): Sandbox`-#### `await Sandbox.create_checkpoint_patch(checkpoint_id, script, description?, ...): dict`+| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `checkpoint_id` | str | — | Checkpoint ID (**required**) |+| `timeout` | int | `300` | Idle timeout |+| `api_key` | str | env var | API key |+| `api_url` | str | env var | API URL |++```python+forked = await Sandbox.create_from_checkpoint("cp-abc123")+```++#### `await Sandbox.create_checkpoint_patch(checkpoint_id, script, ...): dict`++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `checkpoint_id` | str | Yes | Target checkpoint |+| `script` | str | Yes | Bash script |+| `description` | str | No | Description |++```python+result = await Sandbox.create_checkpoint_patch("cp-abc", script="apt install -y curl")+```#### `await Sandbox.list_checkpoint_patches(checkpoint_id, ...): list[dict]`+```python+patches = await Sandbox.list_checkpoint_patches("cp-abc")+```+#### `await Sandbox.delete_checkpoint_patch(checkpoint_id, patch_id, ...): None`+```python+await Sandbox.delete_checkpoint_patch("cp-abc", "pa-xyz")+```+### Context Manager+Auto-kills the sandbox on exit:+```pythonasync with await Sandbox.create() as sandbox:- # sandbox auto-kills on exit- pass+ result = await sandbox.exec.run("echo hello")+ print(result.stdout)+# sandbox.kill() called automatically```### Instance Methods#### `await sandbox.kill(): None`+Terminate the sandbox.+#### `await sandbox.is_running(): bool`+Check if the sandbox is running.+#### `await sandbox.set_timeout(timeout): None`+Update idle timeout.++| Parameter | Type | Description |+| --- | --- | --- |+| `timeout` | int | New timeout in seconds |+#### `await sandbox.create_checkpoint(name): dict`+Create a named checkpoint. Returns checkpoint info as a dictionary.+#### `await sandbox.list_checkpoints(): list[dict]`+List all checkpoints for the sandbox.+#### `await sandbox.restore_checkpoint(checkpoint_id): None`+Revert in-place to a checkpoint.+#### `await sandbox.delete_checkpoint(checkpoint_id): None`-#### `await sandbox.create_preview_url(port, domain?): dict`+Delete a checkpoint.++#### `await sandbox.create_preview_url(port, domain?, auth_config?): dict`++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `port` | int | Yes | Container port (1–65535) |+| `domain` | str | No | Custom domain |+| `auth_config` | dict | No | Auth configuration |#### `await sandbox.list_preview_urls(): list[dict]`@@ -79,96 +148,321 @@ async with await Sandbox.create() as sandbox:#### `await sandbox.close(): None`+Close HTTP clients. Called automatically by the context manager.+### Not Available in Python-{/* hibernate(), wake(), cpuCount/memoryMB on create — use HTTP API directly */}+These features are TypeScript-only. Use the [HTTP API](/reference/api) directly:++- `hibernate()` / `wake()`+- `cpuCount` / `memoryMB` on create### Properties-{/* sandbox_id, agent, exec, files, pty */}+| Property | Type | Description |+| --- | --- | --- |+| `sandbox_id` | str | Sandbox ID |+| `status` | str | Current status |+| `agent` | Agent | [Agent sessions](#agent) |+| `exec` | Exec | [Command execution](#exec) |+| `files` | Filesystem | [File operations](#filesystem) |+| `pty` | Pty | [Terminal sessions](#pty) |+| `commands` | Exec | **Deprecated** — alias for `exec` |++---## Agent-### `await sandbox.agent.start(prompt, model?, system_prompt?, allowed_tools?, permission_mode?, max_turns?, cwd?, mcp_servers?, on_event?, on_error?): AgentSession`+Accessed via `sandbox.agent`.++### `await sandbox.agent.start(...): AgentSession`++Start an agent session.++| Parameter | Type | Description |+| --- | --- | --- |+| `prompt` | str | Initial prompt |+| `model` | str | Claude model |+| `system_prompt` | str | System prompt |+| `allowed_tools` | list[str] | Restrict tools |+| `permission_mode` | str | Permission mode |+| `max_turns` | int | Max turns (default: 50) |+| `cwd` | str | Working directory |+| `mcp_servers` | dict[str, Any] | MCP server configuration |+| `on_event` | Callable[[AgentEvent], None] | Event callback |+| `on_error` | Callable[[str], None] | Stderr callback |++```python+session = await sandbox.agent.start(+ prompt="Build a todo app",+ on_event=lambda e: print(e.type),+)+```++<Note>+ `resume`, `on_exit`, and `on_scrollback_end` are not available in the Python SDK.+</Note>-{/* No resume param. No on_exit, on_scrollback_end. */}+### `await sandbox.agent.attach(session_id, ...): AgentSession`-### `await sandbox.agent.attach(session_id, on_event?, on_error?): AgentSession`+Reconnect to a running agent session. Accepts `on_event` and `on_error`.### `await sandbox.agent.list(): list[AgentSessionInfo]`+List all agent sessions.+### AgentSession-{/* session_id, collect_events(), wait(), send_prompt(), interrupt(), configure(), kill(), close() */}+| Member | Type | Description |+| --- | --- | --- |+| `session_id` | str | Session ID |+| `sandbox_id` | str | Sandbox ID |+| `send_prompt(text)` | method | Send follow-up prompt |+| `interrupt()` | method | Interrupt current turn |+| `configure(...)` | method | Update model, tools, cwd |+| `await kill(signal=9)` | method | Kill agent process |+| `await close()` | method | Close WebSocket |-#### `session.collect_events(): list[AgentEvent]`+#### `await session.collect_events(): list[AgentEvent]`-{/* Python-unique: returns all events since last call */}+Collect all events until the agent process exits. Python-unique alternative to callbacks.++```python+session = await sandbox.agent.start(prompt="Fix the tests")+events = await session.collect_events()+for event in events:+ if event.type == "result":+ print(event.data)+```#### `await session.wait(): int`-{/* Python-unique: waits for session to complete, returns exit code */}+Wait for the agent to finish. Returns the exit code.++```python+exit_code = await session.wait()+```### AgentEvent-{/* Dataclass: type, data. Dict-like access: event['type'], event.get(...).- Do not hard-code a single event payload shape; assistant/result/system payloads vary.-*/}+Dataclass with dict-like access:++```python+@dataclass+class AgentEvent:+ type: str+ data: dict[str, Any]++# Usage:+event["message"] # dict-like access+event.get("message") # safe access with default+event.type # attribute access+```++### AgentSessionInfo++```python+@dataclass+class AgentSessionInfo:+ session_id: str+ sandbox_id: str+ running: bool+ started_at: str+```++---## Exec-### `await sandbox.exec.run(command, timeout?, env?, cwd?): ProcessResult`+Accessed via `sandbox.exec`.-{/* ProcessResult: exit_code, stdout, stderr */}+### `await sandbox.exec.run(command, ...): ProcessResult`-### `await sandbox.exec.start(command, args?, env?, cwd?, timeout?): str`+Run a command synchronously via `sh -c`.++| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `command` | str | — | Shell command (**required**) |+| `timeout` | int | `60` | Timeout in seconds |+| `env` | dict[str, str] | None | Environment variables |+| `cwd` | str | None | Working directory |++```python+result = await sandbox.exec.run("npm test", cwd="/app")+```-{/* Returns session ID (string), NOT an ExecSession object. No streaming callbacks. */}+### `await sandbox.exec.start(command, ...): str`++Start a long-running command. Returns the **session ID** (not a session object).++| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `command` | str | — | Command (**required**) |+| `args` | list[str] | None | Arguments |+| `env` | dict[str, str] | None | Environment variables |+| `cwd` | str | None | Working directory |+| `timeout` | int | None | Timeout in seconds |++```python+session_id = await sandbox.exec.start("node server.js", cwd="/app")+```++<Note>+ Python `exec.start()` returns a session ID string. There are no streaming callbacks, `ExecSession` object, or `maxRunAfterDisconnect`. For streaming, use the [WebSocket binary protocol](/reference/api#websocket-binary-protocol).+</Note>### `await sandbox.exec.list(): list[ExecSessionInfo]`-### `await sandbox.exec.kill(session_id, signal?): None`+List all exec sessions.++### `await sandbox.exec.kill(session_id, signal=9): None`++Kill an exec session.### Not Available in Python-{/* attach(), streaming callbacks (onStdout, onStderr, onExit), maxRunAfterDisconnect, ExecSession object */}+- `exec.attach()` — reconnect to running session+- Streaming callbacks (`on_stdout`, `on_stderr`, `on_exit`)+- `ExecSession` object with `send_stdin()` and `done`+- `max_run_after_disconnect`++### ProcessResult++```python+@dataclass+class ProcessResult:+ exit_code: int+ stdout: str+ stderr: str+```++### ExecSessionInfo++```python+@dataclass+class ExecSessionInfo:+ session_id: str+ sandbox_id: str+ command: str+ args: list[str]+ running: bool+ exit_code: int | None+ started_at: str+ attached_clients: int+```++---## Filesystem+Accessed via `sandbox.files`.+### `await sandbox.files.read(path): str`+Read a file as a UTF-8 string.+### `await sandbox.files.read_bytes(path): bytes`+Read a file as raw bytes.+### `await sandbox.files.write(path, content): None`-### `await sandbox.files.list(path?): list[EntryInfo]`+Write content to a file. Accepts `str` or `bytes`.++### `await sandbox.files.list(path="/"): list[EntryInfo]`++List directory contents.### `await sandbox.files.make_dir(path): None`+Create a directory.+### `await sandbox.files.remove(path): None`+Delete a file or directory.+### `await sandbox.files.exists(path): bool`+Check if a path exists. Client-side wrapper — attempts a read and returns `False` on error.+### EntryInfo-{/* name, is_dir, path, size */}+```python+@dataclass+class EntryInfo:+ name: str+ is_dir: bool+ path: str+ size: int = 0+```++---## Pty-### `await sandbox.pty.create(cols?, rows?, on_output?): PtySession`+Accessed via `sandbox.pty`.-### PtySession+### `await sandbox.pty.create(cols=80, rows=24, on_output=None): PtySession`-{/* session_id, send(data), recv() (Python-unique: returns bytes), close() */}+Create an interactive terminal session.-## Template+| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `cols` | int | `80` | Terminal columns |+| `rows` | int | `24` | Terminal rows |+| `on_output` | Callable[[bytes], None] | None | Output callback |++### PtySession++| Member | Type | Description |+| --- | --- | --- |+| `session_id` | str | Session ID |+| `sandbox_id` | str | Sandbox ID |+| `send(data)` | method | Send input (str or bytes) |+| `await recv()` | method | Receive output bytes (Python-unique) |+| `await close()` | method | Close the PTY |<Note>- `Template` is a standalone type (singular, not `Templates`), but the current SDK does not expose an obvious public constructor/helper in the same way the other surfaces do. Before publishing examples here, either document the real public entry point or improve the SDK ergonomics and then document that.+ `recv()` is Python-unique — a pull-based alternative to the `on_output` callback. Returns raw `bytes`.</Note>-### Template API+---++## Template++`Template` is a standalone class (singular, not `Templates`).++<Warning>+ The Python SDK's `Template` class does not expose a public constructor. Template management is available via the instance methods below (accessed internally), but for direct template operations from Python, use the [HTTP API](/reference/api#templates) instead.+</Warning>++### Instance Methods++If you have a `Template` instance (e.g., obtained internally by the SDK):++#### `await template.build(name, dockerfile): TemplateInfo`++Build a template from a Dockerfile string.++#### `await template.list(): list[TemplateInfo]`-{/* Do not publish fictional classmethods like Template.build(...) unless they actually exist.- Document the real callable surface or explicitly route readers to the HTTP API until the Python SDK ergonomics are fixed.-*/}+List all templates.++#### `await template.get(name): TemplateInfo`++Get a template by name.++#### `await template.delete(name): None`++Delete a template.++### TemplateInfo++```python+@dataclass+class TemplateInfo:+ template_id: str+ name: str+ tag: str+ status: str # "ready" | "building" | "error"+```diff --git a/docs/reference/typescript-sdk.mdx b/docs/reference/typescript-sdk.mdxindex f31d5ca0..3099b9cc 100644--- a/docs/reference/typescript-sdk.mdx+++ b/docs/reference/typescript-sdk.mdx@@ -3,20 +3,6 @@ title: "TypeScript SDK"description: "Complete TypeScript SDK reference"----{/*- TODO: Expand this stub into full content.-- GOAL: Exhaustive TypeScript SDK reference. Every class, every method, every type, every parameter.- The page a developer lands on when they need the exact signature.-- SOURCE: sdks/typescript/src/ — all source files.-- KEY NOTES:- - Each method: full signature, params with types and defaults, return type, one-line example- - Include ExecSessionInfo.attachedClients- - Templates is standalone class (not Sandbox property)-*/}-## Installation```bash@@ -27,151 +13,513 @@ npm install @opencomputer/sdkimport { Sandbox, Templates } from "@opencomputer/sdk";```-## Sandbox+----{/* Static methods: create(opts?), connect(sandboxId, opts?), createFromCheckpoint(checkpointId, opts?),- createCheckpointPatch(checkpointId, opts), listCheckpointPatches(checkpointId, opts?), deleteCheckpointPatch(checkpointId, patchId, opts?) */}+## Sandbox### Static Methods#### `Sandbox.create(opts?): Promise<Sandbox>`-{/* SandboxOpts: template, timeout, apiKey, apiUrl, envs, metadata, cpuCount, memoryMB */}+Create a new sandbox.++| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `template` | string | `"base"` | Template name |+| `timeout` | number | `300` | Idle timeout in seconds |+| `apiKey` | string | env var | API key |+| `apiUrl` | string | env var | API URL |+| `envs` | Record\<string, string\> | — | Environment variables |+| `metadata` | Record\<string, string\> | — | Arbitrary metadata |+| `cpuCount` | number | — | CPU cores (max 4) |+| `memoryMB` | number | — | Memory in MB (max 2048) |++```typescript+const sandbox = await Sandbox.create({ template: "my-stack", timeout: 600 });+```#### `Sandbox.connect(sandboxId, opts?): Promise<Sandbox>`+Connect to an existing sandbox.++| Parameter | Type | Description |+| --- | --- | --- |+| `sandboxId` | string | Sandbox ID |+| `apiKey` | string | API key (optional) |+| `apiUrl` | string | API URL (optional) |++```typescript+const sandbox = await Sandbox.connect("sb-abc123");+```+#### `Sandbox.createFromCheckpoint(checkpointId, opts?): Promise<Sandbox>`+Create a new sandbox from a checkpoint.++| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `checkpointId` | string | — | Checkpoint ID (**required**) |+| `timeout` | number | `300` | Idle timeout |+| `apiKey` | string | env var | API key |+| `apiUrl` | string | env var | API URL |++```typescript+const forked = await Sandbox.createFromCheckpoint("cp-abc123");+```+#### `Sandbox.createCheckpointPatch(checkpointId, opts): Promise<PatchResult>`+Create a patch for a checkpoint.++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `checkpointId` | string | Yes | Target checkpoint |+| `script` | string | Yes | Bash script |+| `description` | string | No | Description |+| `apiKey` | string | No | API key |+| `apiUrl` | string | No | API URL |++```typescript+const result = await Sandbox.createCheckpointPatch("cp-abc", { script: "apt install -y curl" });+```+#### `Sandbox.listCheckpointPatches(checkpointId, opts?): Promise<PatchInfo[]>`+```typescript+const patches = await Sandbox.listCheckpointPatches("cp-abc");+```+#### `Sandbox.deleteCheckpointPatch(checkpointId, patchId, opts?): Promise<void>`+```typescript+await Sandbox.deleteCheckpointPatch("cp-abc", "pa-xyz");+```+### Instance Methods#### `sandbox.kill(): Promise<void>`+Terminate the sandbox.+#### `sandbox.isRunning(): Promise<boolean>`+Check if the sandbox is running.+#### `sandbox.hibernate(): Promise<void>`+Snapshot VM state and stop. No compute cost while hibernated.+#### `sandbox.wake(opts?): Promise<void>`+Resume a hibernated sandbox.++| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `timeout` | number | `300` | Idle timeout after wake |+#### `sandbox.setTimeout(timeout): Promise<void>`+Update the idle timeout.++| Parameter | Type | Description |+| --- | --- | --- |+| `timeout` | number | New timeout in seconds |+#### `sandbox.createCheckpoint(name): Promise<CheckpointInfo>`+Create a named checkpoint.+#### `sandbox.listCheckpoints(): Promise<CheckpointInfo[]>`+List all checkpoints for the sandbox.+#### `sandbox.restoreCheckpoint(checkpointId): Promise<void>`+Revert in-place to a checkpoint.+#### `sandbox.deleteCheckpoint(checkpointId): Promise<void>`+Delete a checkpoint.+#### `sandbox.createPreviewURL(opts): Promise<PreviewURLResult>`+| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `port` | number | Yes | Container port (1–65535) |+| `domain` | string | No | Custom domain |+| `authConfig` | Record\<string, unknown\> | No | Auth configuration |+#### `sandbox.listPreviewURLs(): Promise<PreviewURLResult[]>`#### `sandbox.deletePreviewURL(port): Promise<void>`### Properties-{/* sandboxId: string, agent: Agent, exec: Exec, files: Filesystem, pty: Pty */}+| Property | Type | Description |+| --- | --- | --- |+| `sandboxId` | string | Sandbox ID (readonly) |+| `status` | string | Current status (readonly) |+| `agent` | Agent | [Agent sessions](#agent) |+| `exec` | Exec | [Command execution](#exec) |+| `files` | Filesystem | [File operations](#filesystem) |+| `pty` | Pty | [Terminal sessions](#pty) |+| `commands` | Exec | **Deprecated** — alias for `exec` |### Types-{/* SandboxOpts, CheckpointInfo, PatchInfo, PatchResult, PreviewURLResult */}+#### SandboxOpts++```typescript+interface SandboxOpts {+ template?: string;+ timeout?: number;+ apiKey?: string;+ apiUrl?: string;+ envs?: Record<string, string>;+ metadata?: Record<string, string>;+ cpuCount?: number;+ memoryMB?: number;+}+```++#### CheckpointInfo++```typescript+interface CheckpointInfo {+ id: string;+ sandboxId: string;+ orgId: string;+ name: string;+ sandboxConfig: object;+ status: string; // "processing" | "ready" | "failed"+ sizeBytes: number;+ createdAt: string;+}+```++#### PatchInfo++```typescript+interface PatchInfo {+ id: string;+ checkpointId: string;+ sequence: number;+ script: string;+ description: string;+ strategy: string; // "on_wake"+ createdAt: string;+}+```++#### PatchResult++```typescript+interface PatchResult {+ patch: PatchInfo;+}+```++#### PreviewURLResult++```typescript+interface PreviewURLResult {+ id: string;+ sandboxId: string;+ orgId: string;+ hostname: string;+ customHostname?: string;+ port: number;+ cfHostnameId?: string;+ sslStatus: string;+ authConfig?: object;+ createdAt: string;+}+```++---## Agent+Accessed via `sandbox.agent`.+### `sandbox.agent.start(opts?): Promise<AgentSession>`-{/* AgentStartOpts extends AgentConfig: prompt, model, systemPrompt, allowedTools, permissionMode, maxTurns, cwd, mcpServers, onEvent, onError, resume, onExit, onScrollbackEnd */}+Start an agent session.++| Parameter | Type | Description |+| --- | --- | --- |+| `prompt` | string | Initial prompt |+| `model` | string | Claude model |+| `systemPrompt` | string | System prompt |+| `allowedTools` | string[] | Restrict tools |+| `permissionMode` | string | Permission mode |+| `maxTurns` | number | Max turns (default: 50) |+| `cwd` | string | Working directory |+| `mcpServers` | Record\<string, McpServerConfig\> | MCP servers |+| `resume` | string | Resume session ID |+| `onEvent` | (event: AgentEvent) => void | Event callback |+| `onError` | (data: string) => void | Stderr callback |+| `onExit` | (exitCode: number) => void | Exit callback |+| `onScrollbackEnd` | () => void | Scrollback done callback |++```typescript+const session = await sandbox.agent.start({+ prompt: "Build a todo app",+ onEvent: (e) => console.log(e.type),+});+```### `sandbox.agent.attach(sessionId, opts?): Promise<AgentSession>`+Reconnect to a running agent session. Accepts `onEvent`, `onError`, `onExit`, `onScrollbackEnd`.+### `sandbox.agent.list(): Promise<AgentSessionInfo[]>`+List all agent sessions.+### AgentSession-{/* sessionId, done: Promise<number>, sendPrompt(), interrupt(), configure(), kill(), close() */}+| Member | Type | Description |+| --- | --- | --- |+| `sessionId` | string | Session ID |+| `done` | Promise\<number\> | Resolves with exit code |+| `sendPrompt(text)` | method | Send follow-up prompt |+| `interrupt()` | method | Interrupt current turn |+| `configure(config)` | method | Update agent configuration |+| `kill(signal?)` | Promise\<void\> | Kill agent process |+| `close()` | method | Close WebSocket |### Types-{/* AgentStartOpts, AgentConfig, AgentEvent, McpServerConfig */}+#### AgentEvent++```typescript+interface AgentEvent {+ type: string;+ [key: string]: unknown;+}+```++#### McpServerConfig++```typescript+interface McpServerConfig {+ command: string;+ args?: string[];+ env?: Record<string, string>;+}+```++---## Exec+Accessed via `sandbox.exec`.+### `sandbox.exec.run(command, opts?): Promise<ProcessResult>`-{/* RunOpts: timeout, env, cwd */}+Run a command synchronously.++| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `command` | string | — | Shell command (**required**) |+| `timeout` | number | `60` | Timeout in seconds |+| `env` | Record\<string, string\> | — | Environment variables |+| `cwd` | string | — | Working directory |++```typescript+const result = await sandbox.exec.run("npm test", { cwd: "/app" });+```### `sandbox.exec.start(command, opts?): Promise<ExecSession>`-{/* ExecStartOpts: args, env, cwd, timeout, maxRunAfterDisconnect, onStdout, onStderr, onExit */}+Start a long-running command with streaming.++| Parameter | Type | Description |+| --- | --- | --- |+| `command` | string | Command (**required**) |+| `args` | string[] | Arguments |+| `env` | Record\<string, string\> | Environment variables |+| `cwd` | string | Working directory |+| `timeout` | number | Timeout in seconds |+| `maxRunAfterDisconnect` | number | Seconds to keep running after disconnect |+| `onStdout` | (data: Uint8Array) => void | Stdout callback |+| `onStderr` | (data: Uint8Array) => void | Stderr callback |+| `onExit` | (exitCode: number) => void | Exit callback |++```typescript+const session = await sandbox.exec.start("node server.js", {+ onStdout: (data) => process.stdout.write(data),+});+```### `sandbox.exec.attach(sessionId, opts?): Promise<ExecSession>`-{/* ExecAttachOpts: onStdout, onStderr, onExit, onScrollbackEnd */}+Reconnect to a running exec session.++| Parameter | Type | Description |+| --- | --- | --- |+| `sessionId` | string | Session ID (**required**) |+| `onStdout` | (data: Uint8Array) => void | Stdout callback |+| `onStderr` | (data: Uint8Array) => void | Stderr callback |+| `onExit` | (exitCode: number) => void | Exit callback |+| `onScrollbackEnd` | () => void | Scrollback replay done |### `sandbox.exec.list(): Promise<ExecSessionInfo[]>`+List all exec sessions.+### `sandbox.exec.kill(sessionId, signal?): Promise<void>`+Kill an exec session. Default signal: `9` (SIGKILL).+### ExecSession-{/* sessionId, done: Promise<number>, sendStdin(), kill(), close() */}+| Member | Type | Description |+| --- | --- | --- |+| `sessionId` | string | Session ID |+| `done` | Promise\<number\> | Resolves with exit code |+| `sendStdin(data)` | method | Send input (string or Uint8Array) |+| `kill(signal?)` | Promise\<void\> | Kill process |+| `close()` | method | Close WebSocket |### Types-{/* RunOpts, ExecStartOpts, ExecAttachOpts, ProcessResult, ExecSessionInfo */}+#### ProcessResult++```typescript+interface ProcessResult {+ exitCode: number;+ stdout: string;+ stderr: string;+}+```++#### ExecSessionInfo++```typescript+interface ExecSessionInfo {+ sessionID: string;+ sandboxID: string;+ command: string;+ args: string[];+ running: boolean;+ exitCode?: number;+ startedAt: string;+ attachedClients: number;+}+```++---## Filesystem+Accessed via `sandbox.files`.+### `sandbox.files.read(path): Promise<string>`+Read a file as a UTF-8 string.+### `sandbox.files.readBytes(path): Promise<Uint8Array>`+Read a file as raw bytes.+### `sandbox.files.write(path, content): Promise<void>`+Write content to a file. Accepts `string` or `Uint8Array`.+### `sandbox.files.list(path?): Promise<EntryInfo[]>`+List directory contents. Default path: `"/"`.+### `sandbox.files.makeDir(path): Promise<void>`+Create a directory (recursive).+### `sandbox.files.remove(path): Promise<void>`+Delete a file or directory.+### `sandbox.files.exists(path): Promise<boolean>`+Check if a path exists. Client-side wrapper — attempts a read and returns `false` on error.+### Types-{/* EntryInfo: name, isDir, size, modTime */}+#### EntryInfo++```typescript+interface EntryInfo {+ name: string;+ isDir: boolean;+ path: string;+ size: number;+}+```++---## Pty+Accessed via `sandbox.pty`.+### `sandbox.pty.create(opts?): Promise<PtySession>`-{/* PtyOpts: cols, rows, onOutput */}+Create an interactive terminal session.++| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `cols` | number | `80` | Terminal columns |+| `rows` | number | `24` | Terminal rows |+| `onOutput` | (data: Uint8Array) => void | — | Output callback |### PtySession-{/* sessionId, send(data), close() */}+| Member | Type | Description |+| --- | --- | --- |+| `sessionId` | string | Session ID |+| `send(data)` | method | Send input (string or Uint8Array) |+| `close()` | method | Close the PTY |++---## Templates-<Note>- `Templates` is not a Sandbox property. Document the real public construction pattern: `const templates = new Templates(apiUrl, apiKey)`.-</Note>+Standalone class — not a property on Sandbox.### `new Templates(apiUrl, apiKey)`+```typescript+import { Templates } from "@opencomputer/sdk";++const templates = new Templates("https://app.opencomputer.dev", apiKey);+```+### `templates.build(name, dockerfile): Promise<TemplateInfo>`+Build a template from a Dockerfile string.+### `templates.list(): Promise<TemplateInfo[]>`+List all templates.+### `templates.get(name): Promise<TemplateInfo>`+Get a template by name.+### `templates.delete(name): Promise<void>`+Delete a template.+### Types-{/* TemplateInfo: templateID, name, tag, status */}+#### TemplateInfo++```typescript+interface TemplateInfo {+ templateID: string;+ name: string;+ tag: string;+ status: string; // "ready" | "building" | "error"+}+```diff --git a/docs/sandboxes/checkpoints.mdx b/docs/sandboxes/checkpoints.mdxindex bbde8509..c9f05b91 100644--- a/docs/sandboxes/checkpoints.mdx+++ b/docs/sandboxes/checkpoints.mdx@@ -3,83 +3,175 @@ title: "Checkpoints"description: "Snapshot and fork sandbox state"----{/*- TODO: Expand this stub into full content.+A checkpoint is a named snapshot of a running sandbox. Fork new sandboxes from it to start from a known-good environment — like git branches for VMs.- GOAL: Complete guide to checkpoints — named VM snapshots you can fork from.- Entity page: concept + API + examples.+<CodeGroup>- ABSORBS: sdks/typescript/checkpoints.mdx, sdks/python/checkpoints.mdx.+```typescript TypeScript+import { Sandbox } from "@opencomputer/sdk";- KEY NOTES:- - CheckpointInfo fields differ per surface: TS has sandboxConfig + orgId, HTTP has sizeBytes, Python returns raw dict- - Status: processing → ready (or failed)- - Key difference from hibernation: hibernation resumes SAME sandbox, checkpoints create NEW sandboxes- - Avoid "exactly where it left off" wording. Warm restore exists, but fork/restore can fall back to cold boot.-*/}+const sandbox = await Sandbox.create();+await sandbox.exec.run("npm install && npm run build", { cwd: "/app" });-## What is a Checkpoint+// Checkpoint after setup+const cp = await sandbox.createCheckpoint("after-build");-{/* Named snapshot of a running sandbox's state. Fork new sandboxes from it to start from the same saved environment. Like git commits for VMs. Be precise about guarantees: preserved filesystem state and a reproducible starting point, with warm restore when available. */}+// Fork two independent sandboxes+const a = await Sandbox.createFromCheckpoint(cp.id);+const b = await Sandbox.createFromCheckpoint(cp.id);-## Quick Example+await a.exec.run("npm run test:unit", { cwd: "/app" });+await b.exec.run("npm run test:e2e", { cwd: "/app" });+```-{/* Create checkpoint -> fork new sandbox -> verify state preserved. TS + Python CodeGroup. */}+```python Python+from opencomputer import Sandbox-<CodeGroup>+sandbox = await Sandbox.create()+await sandbox.exec.run("npm install && npm run build", cwd="/app")-```typescript TypeScript-// TODO: sandbox.createCheckpoint('before-deploy') -> Sandbox.createFromCheckpoint(id) -> verify-```+cp = await sandbox.create_checkpoint("after-build")-```python Python-# TODO: sandbox.create_checkpoint('before-deploy') -> Sandbox.create_from_checkpoint(id) -> verify+a = await Sandbox.create_from_checkpoint(cp["id"])+b = await Sandbox.create_from_checkpoint(cp["id"])++await a.exec.run("npm run test:unit", cwd="/app")+await b.exec.run("npm run test:e2e", cwd="/app")```</CodeGroup>## Checkpoints vs Hibernation-{/* Key difference:- - Hibernation pauses and resumes the SAME sandbox- - Checkpoints create NEW sandboxes from saved state- - A sandbox can have many checkpoints; hibernation is a single pause/resume-*/}+| | Checkpoint | Hibernation |+| --- | --- | --- |+| Purpose | Fork new sandboxes from saved state | Pause and resume the **same** sandbox |+| Original sandbox | Keeps running | Stopped |+| Can fork | Yes — unlimited new sandboxes | No |+| Count | Up to 10 per sandbox | One hibernation state |+| Use case | Parallel testing, branching experiments | Cost savings, idle timeout |++## What Gets Preserved++Checkpoints capture the filesystem and installed state. Forked sandboxes start with a fresh boot from that disk state — the platform attempts warm restore when possible, but may fall back to a cold boot. Don't assume running processes carry over.## API Reference### Create Checkpoint-{/* sandbox.createCheckpoint(name) / create_checkpoint(name). ParamField. */}+<CodeGroup>++```typescript TypeScript+const checkpoint = await sandbox.createCheckpoint("before-migration");+// checkpoint.id, checkpoint.status ("processing" → "ready")+```++```python Python+checkpoint = await sandbox.create_checkpoint("before-migration")+# checkpoint["id"], checkpoint["status"]+```++</CodeGroup>++Checkpoint name must be unique within the sandbox. Status transitions from `processing` to `ready` (or `failed`).### List Checkpoints-{/* sandbox.listCheckpoints() / list_checkpoints(). Returns CheckpointInfo[]. */}+<CodeGroup>++```typescript TypeScript+const checkpoints = await sandbox.listCheckpoints();+```++```python Python+checkpoints = await sandbox.list_checkpoints()+```++</CodeGroup>### Fork from Checkpoint-{/* Sandbox.createFromCheckpoint(checkpointId) / create_from_checkpoint(). Creates new sandbox. */}+Creates a new sandbox from a checkpoint:++<CodeGroup>++```typescript TypeScript+const forked = await Sandbox.createFromCheckpoint(checkpointId, {+ timeout: 600,+});+```++```python Python+forked = await Sandbox.create_from_checkpoint(checkpoint_id, timeout=600)+```++</CodeGroup>### Restore Checkpoint-{/* sandbox.restoreCheckpoint(checkpointId) / restore_checkpoint(). Reverts sandbox in-place. */}+Revert a sandbox in-place. All changes since the checkpoint are lost:++<CodeGroup>++```typescript TypeScript+await sandbox.restoreCheckpoint(checkpointId);+```++```python Python+await sandbox.restore_checkpoint(checkpoint_id)+```++</CodeGroup>### Delete Checkpoint-{/* sandbox.deleteCheckpoint(checkpointId) / delete_checkpoint(). */}+<CodeGroup>-## CheckpointInfo+```typescript TypeScript+await sandbox.deleteCheckpoint(checkpointId);+```-{/* Fields:- - TS: id, sandboxId, orgId, name, sandboxConfig, status, sizeBytes, createdAt- - Python: returns raw dict from API- - HTTP: id, sandboxId, orgId, name, status, sizeBytes, createdAt- Status: processing -> ready (or failed)-*/}+```python Python+await sandbox.delete_checkpoint(checkpoint_id)+```-## Examples+</CodeGroup>-{/* Checkpoint before risky operation. Fork for parallel exploration (try 5 approaches from same state). */}+## CheckpointInfo++| Field | TypeScript | Python | Description |+| --- | --- | --- | --- |+| ID | `id` | `id` | Checkpoint UUID |+| Sandbox ID | `sandboxId` | `sandboxID` | Source sandbox |+| Name | `name` | `name` | Human-readable name |+| Status | `status` | `status` | `processing`, `ready`, or `failed` |+| Size | `sizeBytes` | `sizeBytes` | Snapshot size in bytes |+| Created | `createdAt` | `createdAt` | Timestamp |++<Note>+ The TypeScript SDK returns typed `CheckpointInfo` objects. Python returns raw dictionaries with the HTTP API field names.+</Note>++## Example: Parallel Exploration++Try multiple approaches from the same starting point:++```typescript+const sandbox = await Sandbox.create();+await sandbox.exec.run("git clone https://github.com/user/repo /app");+const cp = await sandbox.createCheckpoint("fresh-clone");++// Try three different migration strategies in parallel+const strategies = ["--strategy=ours", "--strategy=theirs", "--strategy=recursive"];+const results = await Promise.all(+ strategies.map(async (strategy) => {+ const fork = await Sandbox.createFromCheckpoint(cp.id);+ const result = await fork.exec.run(`cd /app && git merge origin/main ${strategy}`);+ await fork.kill();+ return { strategy, exitCode: result.exitCode };+ }),+);+```<Tip>CLI equivalent: [`oc checkpoint`](/cli/checkpoint). Full reference: [TypeScript SDK](/reference/typescript-sdk#sandbox) · [Python SDK](/reference/python-sdk#sandbox) · [HTTP API](/reference/api#checkpoints).diff --git a/docs/sandboxes/interactive-terminals.mdx b/docs/sandboxes/interactive-terminals.mdxindex 67666b58..e523970e 100644--- a/docs/sandboxes/interactive-terminals.mdx+++ b/docs/sandboxes/interactive-terminals.mdx@@ -3,64 +3,97 @@ title: "Interactive Terminals"description: "Full PTY sessions inside sandboxes"----{/*- TODO: Expand this stub into full content.+A PTY session is a full interactive terminal inside the sandbox — like SSH but over WebSocket. Supports colors, cursor movement, and full-screen applications (vim, htop).- GOAL: Full guide to interactive terminal sessions inside sandboxes.- Promoted from SDK-only pages — most users discover PTY through oc shell.+<CodeGroup>++```typescript TypeScript+import { Sandbox } from "@opencomputer/sdk";++const sandbox = await Sandbox.create();+const pty = await sandbox.pty.create({+ onOutput: (data) => process.stdout.write(data),+});- ABSORBS: sdks/typescript/pty.mdx, sdks/python/pty.mdx.+pty.send("ls -la /app\n");+// ... wait for output ...+pty.close();+await sandbox.kill();+```- KEY NOTES:- - recv() is Python-only (pull-based alternative to onOutput callback)- - resize() not available in SDKs. HTTP API has POST /sandboxes/:id/pty/:sessionID/resize but no SDK wrapper.- - CLI: oc shell <sandbox-id> supports --shell flag (default /bin/bash)-*/}+```python Python+from opencomputer import Sandbox-## What is a PTY Session+sandbox = await Sandbox.create()+pty = await sandbox.pty.create(+ on_output=lambda data: print(data.decode(), end=""),+)-{/* A full interactive terminal inside the sandbox. Supports colors, full-screen apps (vim, top). Like SSH but over WebSocket. */}+pty.send("ls -la /app\n")+output = await pty.recv() # pull-based alternative+pty.close()+await sandbox.kill()+```-## Quick Example+</CodeGroup>-{/* Create PTY, send command, read output. TS + Python CodeGroup. */}+## Creating a PTY<CodeGroup>```typescript TypeScript-// TODO: sandbox.pty.create({ onOutput }) -> session.send('ls\n') -> close+const pty = await sandbox.pty.create({+ cols: 120,+ rows: 40,+ onOutput: (data) => process.stdout.write(data),+});``````python Python-# TODO: sandbox.pty.create(on_output=...) -> session.send('ls\n') -> recv() -> close+pty = await sandbox.pty.create(+ cols=120,+ rows=40,+ on_output=lambda data: print(data.decode(), end=""),+)```</CodeGroup>-## Creating a PTY--{/* sandbox.pty.create(opts) */}--### PtyOpts+### Parameters-{/* ParamField: cols (default 80), rows (default 24), onOutput callback */}+| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `cols` | number | `80` | Terminal columns |+| `rows` | number | `24` | Terminal rows |+| `onOutput` | callback | — | Called with output data (TS: `Uint8Array`, Python: `bytes`) |## PtySession-{/* Methods table:- - send(data) — both SDKs- - close() — both SDKs- - recv() — Python-only (returns bytes; pull-based alternative to onOutput callback)- - Note: resize() not available in SDKs. HTTP API has POST /sandboxes/:id/pty/:sessionID/resize but no SDK wrapper.-*/}+| Member | TypeScript | Python | Description |+| --- | --- | --- | --- |+| Session ID | `pty.sessionId` | `pty.session_id` | Unique session ID |+| Send input | `pty.send(data)` | `pty.send(data)` | Send keystrokes or commands |+| Receive output | via `onOutput` callback | `await pty.recv()` | Get terminal output |+| Close | `pty.close()` | `await pty.close()` | Close the PTY session |-## Examples+<Note>+ `recv()` is Python-only — a pull-based alternative to the `on_output` callback. Returns raw bytes.+</Note>-{/* Run interactive commands, pipe stdin. */}+### Resize++PTY resize is available via the [HTTP API](/reference/api#pty) only (`POST /api/sandboxes/:id/pty/:sessionID/resize`). The SDKs do not expose a resize method — the CLI handles resize automatically for interactive sessions.## CLI-{/* oc shell <sandbox-id> — opens interactive terminal. Supports --shell flag (default /bin/bash). */}+The fastest way to get an interactive shell:++```bash+oc shell sb-abc123+oc shell sb-abc123 --shell /bin/zsh+```++Terminal size is auto-detected and resize events are forwarded. See [`oc shell`](/cli/shell) for details.<Tip>CLI equivalent: [`oc shell`](/cli/shell). Full reference: [TypeScript SDK](/reference/typescript-sdk#pty) · [Python SDK](/reference/python-sdk#pty) · [HTTP API](/reference/api#pty).diff --git a/docs/sandboxes/patches.mdx b/docs/sandboxes/patches.mdxindex 142f64f7..f885d263 100644--- a/docs/sandboxes/patches.mdx+++ b/docs/sandboxes/patches.mdx@@ -3,69 +3,141 @@ title: "Patches"description: "Scripts that run when forking from a checkpoint"----{/*- TODO: Expand this stub into full content.+A patch is a shell script attached to a checkpoint. Every time a sandbox is forked from that checkpoint, patches run automatically — inject configuration, update dependencies, or customize state without modifying the checkpoint itself.- GOAL: Complete guide to patches — shell scripts attached to checkpoints.- Entity page: concept + API + examples.+<CodeGroup>++```typescript TypeScript+import { Sandbox } from "@opencomputer/sdk";- ABSORBS: sdks/typescript/patches.mdx, sdks/python/patches.mdx.+// Attach a patch to an existing checkpoint+const result = await Sandbox.createCheckpointPatch(checkpointId, {+ script: 'echo "export API_KEY=$1" >> /root/.bashrc',+ description: "Inject API key at fork time",+});+console.log(result.patch.id, result.patch.sequence);++// Fork — patch runs automatically+const sandbox = await Sandbox.createFromCheckpoint(checkpointId);+```- KEY NOTES:- - Patches run in creation order, strategy is always on_wake- - Patch methods are static on Sandbox class, not instance methods- - Document failure handling: what happens if a patch script fails-*/}+```python Python+from opencomputer import Sandbox++result = await Sandbox.create_checkpoint_patch(+ checkpoint_id,+ script='echo "export API_KEY=$1" >> /root/.bashrc',+ description="Inject API key at fork time",+)++sandbox = await Sandbox.create_from_checkpoint(checkpoint_id)+```-## What is a Patch+</CodeGroup>-{/* A shell script attached to a checkpoint that runs every time a sandbox is forked from that checkpoint. Inject config, update deps, or customize state at fork time without modifying the checkpoint. */}+## API Reference-## Quick Example+### Create Patch-{/* Create patch on checkpoint. TS + Python CodeGroup. */}+Patch methods are **static** on the Sandbox class — they operate on checkpoints, not sandbox instances.<CodeGroup>```typescript TypeScript-// TODO: Sandbox.createCheckpointPatch(checkpointId, { script: '...', description: '...' })+const result = await Sandbox.createCheckpointPatch(checkpointId, {+ script: "apt-get update && apt-get install -y redis-server",+ description: "Install Redis",+});+// result.patch.id, result.patch.sequence``````python Python-# TODO: Sandbox.create_checkpoint_patch(checkpoint_id, script='...', description='...')+result = await Sandbox.create_checkpoint_patch(+ checkpoint_id,+ script="apt-get update && apt-get install -y redis-server",+ description="Install Redis",+)```</CodeGroup>-## API Reference+| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `checkpointId` | string | Yes | Target checkpoint |+| `script` | string | Yes | Bash script to execute on fork |+| `description` | string | No | Human-readable description |-### Create Patch+### List Patches-{/* Sandbox.createCheckpointPatch(checkpointId, { script, description }). ParamField. */}+<CodeGroup>-### List Patches+```typescript TypeScript+const patches = await Sandbox.listCheckpointPatches(checkpointId);+for (const p of patches) {+ console.log(p.sequence, p.description);+}+```-{/* Sandbox.listCheckpointPatches(checkpointId). Returns PatchInfo[]. */}+```python Python+patches = await Sandbox.list_checkpoint_patches(checkpoint_id)+```++</CodeGroup>### Delete Patch-{/* Sandbox.deleteCheckpointPatch(checkpointId, patchId). */}+<CodeGroup>++```typescript TypeScript+await Sandbox.deleteCheckpointPatch(checkpointId, patchId);+```++```python Python+await Sandbox.delete_checkpoint_patch(checkpoint_id, patch_id)+```++</CodeGroup>## When Patches Run-{/* Applied on wake/boot from checkpoint. Strategy is always `on_wake`. */}+Patches execute when a sandbox is **forked** from the checkpoint (via `Sandbox.createFromCheckpoint()` or `oc checkpoint spawn`). The strategy is always `on_wake`.## Execution Order-{/* Patches run in creation order. */}+Patches run in creation order (by `sequence` number). If you create three patches, they execute as patch 1 → patch 2 → patch 3 every time a sandbox is forked.-## Failure Handling+## PatchInfo-{/* What happens if a patch script fails. */}+| Field | Type | Description |+| --- | --- | --- |+| `id` | string | Patch UUID |+| `checkpointId` | string | Parent checkpoint |+| `script` | string | Bash script content |+| `description` | string | Human-readable description |+| `strategy` | string | Always `"on_wake"` |+| `sequence` | number | Execution order |+| `createdAt` | string | Timestamp |-## Example+## Example: Environment-Specific Forks-{/* Inject API keys at fork time. Update packages without rebuilding checkpoint. */}+Use patches to create different environments from one checkpoint:++```typescript+// Base checkpoint has the app installed+const cpId = "cp-abc123";++// Patch for staging+await Sandbox.createCheckpointPatch(cpId, {+ script: `+ echo 'DATABASE_URL=postgres://staging-db/app' >> /app/.env+ echo 'LOG_LEVEL=debug' >> /app/.env+ `,+ description: "Staging environment config",+});++// Every fork now gets staging config+const staging = await Sandbox.createFromCheckpoint(cpId);+```<Tip>CLI equivalent: [`oc patch`](/cli/patch). Full reference: [TypeScript SDK](/reference/typescript-sdk#sandbox) · [Python SDK](/reference/python-sdk#sandbox) · [HTTP API](/reference/api#checkpoint-patches).diff --git a/docs/sandboxes/preview-urls.mdx b/docs/sandboxes/preview-urls.mdxindex 63a97165..a94adbdb 100644--- a/docs/sandboxes/preview-urls.mdx+++ b/docs/sandboxes/preview-urls.mdx@@ -3,67 +3,115 @@ title: "Preview URLs"description: "Expose sandbox ports to the internet"----{/*- TODO: Expand this stub into full content.+A preview URL is a public HTTPS endpoint that routes traffic to a port inside your sandbox. Start a web server, create a preview URL, and share the link.- GOAL: Complete guide to preview URLs — exposing sandbox ports to the internet.- Entity page: concept + API + examples.+<CodeGroup>- KEY NOTES:- - Custom domain setup is org-level configuration (dashboard, not SDK)- - SSL automatic via Cloudflare- - Preview URLs persist across hibernation/wake cycles-*/}+```typescript TypeScript+import { Sandbox } from "@opencomputer/sdk";-## What is a Preview URL+const sandbox = await Sandbox.create();+await sandbox.exec.run("npx create-next-app@latest /app --yes", { timeout: 120 });+sandbox.exec.start("npm run dev -- --port 3000", { cwd: "/app" });-{/* A public HTTPS URL that exposes a port inside your sandbox to the internet. Start a web server on port 3000, create a preview URL, and anyone can access it. */}+const preview = await sandbox.createPreviewURL({ port: 3000 });+console.log(preview.hostname); // sb-abc123-p3000.preview.opencomputer.dev+```-## Quick Example+```python Python+from opencomputer import Sandbox-{/* Create preview URL. TS + Python CodeGroup. */}+sandbox = await Sandbox.create()+await sandbox.exec.run("npx create-next-app@latest /app --yes", timeout=120)+await sandbox.exec.start("npm run dev -- --port 3000", cwd="/app")++preview = await sandbox.create_preview_url(port=3000)+print(preview["hostname"])+```++</CodeGroup>++## API Reference++### Create Preview URL<CodeGroup>```typescript TypeScript-// TODO: sandbox.createPreviewURL({ port: 3000 }) -> url+const preview = await sandbox.createPreviewURL({+ port: 3000,+ domain: "preview.myapp.com", // optional custom domain+});``````python Python-# TODO: sandbox.create_preview_url(port=3000) -> url+preview = await sandbox.create_preview_url(+ port=3000,+ domain="preview.myapp.com",+)```</CodeGroup>-## API Reference+| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `port` | number | Yes | Container port to expose (1–65535) |+| `domain` | string | No | Custom domain |+| `authConfig` | object | No | Authentication configuration |-### Create Preview URL+### List Preview URLs-{/* sandbox.createPreviewURL({ port, domain?, authConfig? }). ParamField. */}+<CodeGroup>-### List Preview URLs+```typescript TypeScript+const previews = await sandbox.listPreviewURLs();+for (const p of previews) {+ console.log(`Port ${p.port}: https://${p.hostname}`);+}+```-{/* sandbox.listPreviewURLs(). */}+```python Python+previews = await sandbox.list_preview_urls()+for p in previews:+ print(f"Port {p['port']}: https://{p['hostname']}")+```++</CodeGroup>### Delete Preview URL-{/* sandbox.deletePreviewURL(port). */}+<CodeGroup>++```typescript TypeScript+await sandbox.deletePreviewURL(3000);+```++```python Python+await sandbox.delete_preview_url(3000)+```++</CodeGroup>## Custom Domains-{/* Requires Cloudflare integration on deployment.- - Pass domain param when creating- - SSL automatic via Cloudflare- - Custom domain setup is org-level config (dashboard, not SDK)-*/}+Pass a `domain` when creating a preview URL. SSL is provisioned automatically via Cloudflare. Custom domain verification is configured at the organization level through the dashboard — not through the SDK.## Persistence-{/* Preview URLs persist across hibernation/wake cycles. */}+Preview URLs persist across hibernation and wake cycles. If you hibernate a sandbox and wake it later, the preview URLs are still active.-## Examples+## Multiple Ports-{/* Share a dev server. Multiple ports. Custom domain. */}+Expose multiple services from the same sandbox:++```typescript+// Frontend+await sandbox.createPreviewURL({ port: 3000 });+// API server+await sandbox.createPreviewURL({ port: 8080 });+// Database admin+await sandbox.createPreviewURL({ port: 5432 });+```<Tip>CLI equivalent: [`oc preview`](/cli/preview). Full reference: [TypeScript SDK](/reference/typescript-sdk#sandbox) · [Python SDK](/reference/python-sdk#sandbox) · [HTTP API](/reference/api#preview-urls).diff --git a/docs/sandboxes/running-commands.mdx b/docs/sandboxes/running-commands.mdxindex 1dd473be..1e23499d 100644--- a/docs/sandboxes/running-commands.mdx+++ b/docs/sandboxes/running-commands.mdx@@ -3,87 +3,209 @@ title: "Running Commands"description: "Execute shell commands inside a sandbox"----{/*- TODO: Expand this stub into full content.+Two modes: `exec.run()` waits for the result, `exec.start()` creates a session for long-running or streaming commands.- GOAL: Comprehensive guide to executing shell commands inside sandboxes.- Two modes: run() (wait for result) and start() (streaming/async).+<CodeGroup>++```typescript TypeScript+import { Sandbox } from "@opencomputer/sdk";++const sandbox = await Sandbox.create();+const result = await sandbox.exec.run("echo Hello, World!");+console.log(result.stdout); // "Hello, World!\n"+await sandbox.kill();+```- ABSORBS: sdks/typescript/commands.mdx, sdks/python/commands.mdx, running-commands.mdx (root).+```python Python+from opencomputer import Sandbox- KEY NOTES:- - Use sandbox.exec.* consistently (NOT sandbox.commands — deprecated alias)- - Be honest about Python SDK gaps in streaming — don't pretend parity exists- - TS exec.start() returns ExecSession with callbacks; Python returns str (session ID only)- - TS-only: attach(), streaming callbacks (onStdout, onStderr, onExit), maxRunAfterDisconnect-*/}+async with await Sandbox.create() as sandbox:+ result = await sandbox.exec.run("echo Hello, World!")+ print(result.stdout) # "Hello, World!\n"+```-## Quick Commands: `sandbox.exec.run()`+</CodeGroup>-{/* Run a shell command and wait for the result. TS + Python CodeGroup. */}+## Quick Commands: `exec.run()`++Run a shell command and wait for the result. The command runs via `sh -c`, so pipes, redirects, and shell expansion work.<CodeGroup>```typescript TypeScript-// TODO: sandbox.exec.run('echo "hello"') -> result.stdout+// Working directory and environment variables+const result = await sandbox.exec.run("npm run build", {+ cwd: "/app",+ env: { NODE_ENV: "production" },+ timeout: 120,+});++if (result.exitCode !== 0) {+ console.error("Build failed:", result.stderr);+}``````python Python-# TODO: sandbox.exec.run('echo "hello"') -> result.stdout+result = await sandbox.exec.run(+ "npm run build",+ cwd="/app",+ env={"NODE_ENV": "production"},+ timeout=120,+)++if result.exit_code != 0:+ print("Build failed:", result.stderr)```</CodeGroup>### Parameters-{/* ParamField: command (required), timeout (default 60), env, cwd */}+| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `command` | string | — | Shell command to run (**required**) |+| `timeout` | number | `60` | Timeout in seconds |+| `env` | object | — | Environment variables |+| `cwd` | string | — | Working directory |### ProcessResult-{/* Table: exitCode/exit_code, stdout, stderr */}+| Field | TypeScript | Python | Type |+| --- | --- | --- | --- |+| Exit code | `exitCode` | `exit_code` | number |+| Standard output | `stdout` | `stdout` | string |+| Standard error | `stderr` | `stderr` | string |-### Examples+## Async Commands: `exec.start()`-{/* Working directory, env vars, timeout, chaining commands. TS + Python CodeGroup. */}+Start a command as an exec session for long-running processes or streaming output. The TypeScript and Python SDKs differ significantly here.-## Async Commands: `sandbox.exec.start()`+### TypeScript — Full Streaming-{/* Start long-running command, stream output.- - TS: full streaming — returns ExecSession with onStdout, onStderr, onExit callbacks, sendStdin(), kill(), close(). Supports maxRunAfterDisconnect.- - Python: returns str (session ID only). No streaming callbacks, no ExecSession. Use exec.list() and exec.kill().-*/}+Returns an `ExecSession` with callbacks for stdout, stderr, and exit:-### TypeScript — Full Streaming+```typescript+const session = await sandbox.exec.start("node server.js", {+ cwd: "/app",+ env: { PORT: "3000" },+ onStdout: (data) => process.stdout.write(data),+ onStderr: (data) => process.stderr.write(data),+ onExit: (code) => console.log("Server exited:", code),+ maxRunAfterDisconnect: 300, // keep running 5min after disconnect+});++// Send input+session.sendStdin("some input\n");-{/* TS example with onStdout, onStderr, onExit, sendStdin, kill */}+// Wait for completion (or kill)+await session.kill();+```++#### ExecStartOpts++| Parameter | Type | Description |+| --- | --- | --- |+| `args` | string[] | Command arguments |+| `env` | object | Environment variables |+| `cwd` | string | Working directory |+| `timeout` | number | Timeout in seconds |+| `maxRunAfterDisconnect` | number | Seconds to keep running after disconnect |+| `onStdout` | callback | `(data: Uint8Array) => void` |+| `onStderr` | callback | `(data: Uint8Array) => void` |+| `onExit` | callback | `(exitCode: number) => void` |++#### ExecSession++| Member | Type | Description |+| --- | --- | --- |+| `sessionId` | string | Session ID |+| `done` | `Promise<number>` | Resolves with exit code |+| `sendStdin(data)` | method | Send input to the process |+| `kill(signal?)` | method | Kill the process (default: SIGKILL) |+| `close()` | method | Close the WebSocket connection |### Python — Session ID-{/* Python example: start() returns session_id, then list/kill */}+Python's `exec.start()` returns a session ID string. There are no streaming callbacks or ExecSession object.-### ExecSession (TypeScript)+```python+session_id = await sandbox.exec.start(+ "node server.js",+ args=None,+ env={"PORT": "3000"},+ cwd="/app",+)-{/* Table: sessionId, done, sendStdin, kill, close */}+# Check session status+sessions = await sandbox.exec.list()+for s in sessions:+ print(s.session_id, "running" if s.running else f"exited ({s.exit_code})")-## Managing Sessions+# Kill when done+await sandbox.exec.kill(session_id)+```++<Note>+ Python does not support `exec.attach()`, streaming callbacks, `maxRunAfterDisconnect`, or the `ExecSession` object. For streaming in Python, use the [WebSocket binary protocol](/reference/api#websocket-binary-protocol) directly.+</Note>-{/* exec.list() — both SDKs. exec.attach() — TS only. exec.kill() — both SDKs. */}+## Managing Sessions### List Sessions-{/* TS + Python CodeGroup */}+<CodeGroup>++```typescript TypeScript+const sessions = await sandbox.exec.list();+for (const s of sessions) {+ console.log(s.sessionID, s.running ? "running" : `exited (${s.exitCode})`);+ console.log(` command: ${s.command}, clients: ${s.attachedClients}`);+}+```++```python Python+sessions = await sandbox.exec.list()+for s in sessions:+ status = "running" if s.running else f"exited ({s.exit_code})"+ print(s.session_id, status, f"clients: {s.attached_clients}")+```++</CodeGroup>### Attach to Running Session (TypeScript only)-{/* Reconnect to running session by ID. TS example with onStdout, onScrollbackEnd. */}+Reconnect to a running exec session to resume streaming output:++```typescript+const session = await sandbox.exec.attach(sessionId, {+ onStdout: (data) => process.stdout.write(data),+ onStderr: (data) => process.stderr.write(data),+ onExit: (code) => console.log("Exited:", code),+ onScrollbackEnd: () => console.log("--- live output ---"),+});+```++On attach, the server replays the scrollback buffer (historical output), sends a scrollback-end marker, then streams live output.### Kill a Session-{/* TS + Python CodeGroup */}+<CodeGroup>++```typescript TypeScript+await sandbox.exec.kill(sessionId);+await sandbox.exec.kill(sessionId, 15); // SIGTERM+```-## Examples+```python Python+await sandbox.exec.kill(session_id)+await sandbox.exec.kill(session_id, signal=15) # SIGTERM+```++</CodeGroup>-{/* Dev server (TS streaming), long-running process, reconnect pattern (TS only) */}+<Warning>+ `sandbox.commands` is a deprecated alias for `sandbox.exec`. Use `sandbox.exec` in all new code.+</Warning><Tip>CLI equivalent: [`oc exec`](/cli/exec). Full reference: [TypeScript SDK](/reference/typescript-sdk#exec) · [Python SDK](/reference/python-sdk#exec) · [HTTP API](/reference/api#commands-exec).diff --git a/docs/sandboxes/templates.mdx b/docs/sandboxes/templates.mdxindex 99a88d8a..29297f91 100644--- a/docs/sandboxes/templates.mdx+++ b/docs/sandboxes/templates.mdx@@ -3,89 +3,165 @@ title: "Templates"description: "Pre-built base images for sandboxes"----{/*- TODO: Expand this stub into full content.+A template is a pre-built filesystem image that sandboxes start from. Build custom templates from Dockerfiles to skip repeated setup — install your dependencies once, then create sandboxes instantly from that template.- GOAL: Complete guide to templates — pre-built base images for sandboxes.- Entity page: concept + API + examples.+<CodeGroup>++```typescript TypeScript+import { Sandbox, Templates } from "@opencomputer/sdk";++const templates = new Templates(apiUrl, apiKey);+await templates.build("my-stack", `+FROM ubuntu:22.04+RUN apt-get update && apt-get install -y nodejs npm+RUN npm install -g pnpm+WORKDIR /app+`);++// Create a sandbox with the custom template+const sandbox = await Sandbox.create({ template: "my-stack" });+await sandbox.exec.run("pnpm --version"); // already installed+```++```bash curl+# Build template+curl -X POST https://app.opencomputer.dev/api/templates \+ -H "X-API-Key: $OPENCOMPUTER_API_KEY" \+ -H "Content-Type: application/json" \+ -d '{+ "name": "my-stack",+ "dockerfile": "FROM ubuntu:22.04\nRUN apt-get update && apt-get install -y nodejs npm\nRUN npm install -g pnpm\nWORKDIR /app"+ }'++# Create sandbox from template+curl -X POST https://app.opencomputer.dev/api/sandboxes \+ -H "X-API-Key: $OPENCOMPUTER_API_KEY" \+ -H "Content-Type: application/json" \+ -d '{"templateID": "my-stack"}'+```++</CodeGroup>++<Note>+ `Templates` is a standalone class, not a property on Sandbox. TypeScript exports `Templates` (plural), Python exports `Template` (singular).+</Note>++<Note>+ The Python `Template` class does not have a public constructor. Use the HTTP API for template management from Python, or use `Sandbox.create(template="my-stack")` after building the template via HTTP.+</Note>- ABSORBS: sdks/typescript/templates.mdx, sdks/python/templates.mdx.+## Default Template- KEY NOTES:- - Templates is not a Sandbox property- - TS: Templates (plural), Python: Template (singular)- - Do not invent static helper APIs. Document the actual exported construction/usage pattern for each SDK.- - Python template ergonomics are currently awkward; if no public construction helper exists, either improve the SDK first or make this section HTTP-first.- - Template status depends on template type. Dockerfile builds currently return ready immediately; sandbox-snapshot templates use processing -> ready.- - Be explicit about `default` vs legacy `base` naming where relevant- - Default template: derive pre-installed list from Dockerfile.default-*/}+Sandboxes use the default template when no template is specified. It includes:-## What is a Template+- **Ubuntu 22.04**+- **Python 3** with pip, venv, setuptools+- **Node.js 20 LTS** with npm+- **Build tools:** build-essential, cmake, pkg-config+- **CLI tools:** git, git-lfs, curl, wget, jq, rsync, htop, tree+- **Editors:** nano, vim-tiny+- **Database:** sqlite3+- **Networking:** openssh-client, iproute2, net-tools, dnsutils+- **Claude Agent SDK** and claude-code (pre-installed for agent sessions)-{/* Pre-built base image that sandboxes start from. The `default` template includes Ubuntu, Python, Node.js. Build custom templates from Dockerfiles to skip setup time. */}+## API Reference-## Quick Example+### Build Template-{/* Build template -> create sandbox from it.- Use real SDK construction only. If Python still lacks a public ergonomic entry point, use HTTP for the primary example and call the SDK gap out explicitly.-*/}+Templates are built from Dockerfiles. The Docker build produces a filesystem image that Firecracker boots as the VM's root disk.<CodeGroup>```typescript TypeScript-// TODO: use the real exported Templates construction pattern, then build/list/get/delete from that instance+const templates = new Templates(apiUrl, apiKey);+const info = await templates.build("node20-pnpm", `+FROM ubuntu:22.04+RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash -+RUN apt-get install -y nodejs && npm install -g pnpm+`);+console.log(info.status); // "ready"```-```python Python-# TODO: only add a Python SDK example if there is a public construction path worth documenting; otherwise use HTTP and note the SDK ergonomics gap+```bash curl+curl -X POST https://app.opencomputer.dev/api/templates \+ -H "X-API-Key: $OPENCOMPUTER_API_KEY" \+ -H "Content-Type: application/json" \+ -d '{"name": "node20-pnpm", "dockerfile": "FROM ubuntu:22.04\n..."}'```</CodeGroup>-## Default Template+Dockerfile templates return `status: "ready"` immediately. Sandbox-snapshot templates transition `processing` → `ready`.-{/* What's pre-installed: Ubuntu, Python 3, Node.js, common CLI tools. Derived from Dockerfile.default. */}+### List Templates-## API Reference+<CodeGroup>-<Note>- Templates is a standalone class, not a property on Sandbox. TypeScript exports `Templates` (plural), Python exports `Template` (singular).-</Note>+```typescript TypeScript+const all = await templates.list();+```-### Build Template+```bash curl+curl https://app.opencomputer.dev/api/templates \+ -H "X-API-Key: $OPENCOMPUTER_API_KEY"+```-{/* Document the real SDK invocation pattern and the HTTP API.- Do not publish fictional static helpers if the SDK requires an instance.-*/}+</CodeGroup>-### List Templates+### Get Template-{/* Document the real SDK callable surface for listing templates plus the HTTP API.- Avoid implying Python classmethods if the SDK does not expose them.-*/}+<CodeGroup>-### Get Template+```typescript TypeScript+const info = await templates.get("my-stack");+```-{/* Document the real SDK callable surface for fetching a template plus the HTTP API. */}+```bash curl+curl https://app.opencomputer.dev/api/templates/my-stack \+ -H "X-API-Key: $OPENCOMPUTER_API_KEY"+```++</CodeGroup>### Delete Template-{/* Document the real SDK callable surface for deleting a template plus the HTTP API. */}+<CodeGroup>++```typescript TypeScript+await templates.delete("my-stack");+```++```bash curl+curl -X DELETE https://app.opencomputer.dev/api/templates/my-stack \+ -H "X-API-Key: $OPENCOMPUTER_API_KEY"+```++</CodeGroup>### Using with Sandbox.create-{/* Sandbox.create({ template: 'my-template' }) */}+Pass the template name when creating a sandbox:-## TemplateInfo+<CodeGroup>++```typescript TypeScript+const sandbox = await Sandbox.create({ template: "my-stack" });+```-{/* Fields: verify against the current handler/SDK mapping before writing the final page.- Status is not one universal enum across all template creation flows.-*/}+```python Python+sandbox = await Sandbox.create(template="my-stack")+```-## Example+</CodeGroup>++## TemplateInfo-{/* Template with specific language/framework pre-installed (e.g., Node 20 + pnpm). */}+| Field | TypeScript | Python | Description |+| --- | --- | --- | --- |+| Template ID | `templateID` | `template_id` | Unique identifier |+| Name | `name` | `name` | Template name |+| Tag | `tag` | `tag` | Image tag (default: `"latest"`) |+| Status | `status` | `status` | `ready`, `building`, or `error` |<Tip>Full reference: [TypeScript SDK](/reference/typescript-sdk#templates) · [Python SDK](/reference/python-sdk#template) · [HTTP API](/reference/api#templates).diff --git a/docs/sandboxes/working-with-files.mdx b/docs/sandboxes/working-with-files.mdxindex df155dd5..7ae8b655 100644--- a/docs/sandboxes/working-with-files.mdx+++ b/docs/sandboxes/working-with-files.mdx@@ -3,59 +3,183 @@ title: "Working with Files"description: "Read, write, and manage files inside a sandbox"----{/*- TODO: Expand this stub into full content.+<CodeGroup>- GOAL: Complete guide to reading, writing, and managing files inside sandboxes.+```typescript TypeScript+import { Sandbox } from "@opencomputer/sdk";- ABSORBS: sdks/typescript/filesystem.mdx, sdks/python/filesystem.mdx, working-with-files.mdx (root).+const sandbox = await Sandbox.create();- KEY NOTES:- - Current structure is already good — merge TS/Python into CodeGroups and ensure consistency.- - exists() is a client-side SDK wrapper built on a normal file read request, not a separate HTTP endpoint.-*/}+await sandbox.files.write("/app/hello.txt", "Hello, World!");+const content = await sandbox.files.read("/app/hello.txt");+console.log(content); // "Hello, World!"++await sandbox.kill();+```++```python Python+from opencomputer import Sandbox++async with await Sandbox.create() as sandbox:+ await sandbox.files.write("/app/hello.txt", "Hello, World!")+ content = await sandbox.files.read("/app/hello.txt")+ print(content) # "Hello, World!"+```++</CodeGroup>## Reading Files-{/* sandbox.files.read(path) — returns string content. TS + Python CodeGroup. */}+<CodeGroup>-### Read as Bytes+```typescript TypeScript+// Read as string+const text = await sandbox.files.read("/app/config.json");-{/* sandbox.files.readBytes(path) / read_bytes(path) — returns binary. TS + Python CodeGroup. */}+// Read as bytes+const bytes = await sandbox.files.readBytes("/app/image.png");+```++```python Python+# Read as string+text = await sandbox.files.read("/app/config.json")++# Read as bytes+data = await sandbox.files.read_bytes("/app/image.png")+```++</CodeGroup>## Writing Files-{/* sandbox.files.write(path, content) — text and binary. TS + Python CodeGroup. */}+Content can be a string or binary data:++<CodeGroup>++```typescript TypeScript+// Write text+await sandbox.files.write("/app/config.json", JSON.stringify({ port: 3000 }));++// Write binary+const imageData = new Uint8Array([...]);+await sandbox.files.write("/app/logo.png", imageData);+```++```python Python+# Write text+await sandbox.files.write("/app/config.json", '{"port": 3000}')++# Write binary+await sandbox.files.write("/app/logo.png", image_bytes)+```++</CodeGroup>## Listing Directories-{/* sandbox.files.list(path) — returns EntryInfo[]. TS + Python CodeGroup. */}+<CodeGroup>++```typescript TypeScript+const entries = await sandbox.files.list("/app");+for (const entry of entries) {+ console.log(entry.isDir ? "📁" : "📄", entry.name, entry.size);+}+```++```python Python+entries = await sandbox.files.list("/app")+for entry in entries:+ kind = "dir" if entry.is_dir else "file"+ print(f"{kind}: {entry.name} ({entry.size} bytes)")+```++</CodeGroup>### EntryInfo-{/* Table: name, isDir/is_dir, path, size.- Do not document modTime/mod_time on EntryInfo unless the SDK starts returning it.-*/}+| Field | TypeScript | Python | Type |+| --- | --- | --- | --- |+| Name | `name` | `name` | string |+| Is directory | `isDir` | `is_dir` | boolean |+| Full path | `path` | `path` | string |+| Size in bytes | `size` | `size` | number |## Managing Files-{/* make_dir, remove, exists. TS + Python CodeGroup for each. */}-### Create Directory-{/* sandbox.files.makeDir(path) / make_dir(path) */}+<CodeGroup>++```typescript TypeScript+await sandbox.files.makeDir("/app/data");+```++```python Python+await sandbox.files.make_dir("/app/data")+```++</CodeGroup>### Remove-{/* sandbox.files.remove(path) */}+Deletes a file or directory:++<CodeGroup>++```typescript TypeScript+await sandbox.files.remove("/app/temp");+```++```python Python+await sandbox.files.remove("/app/temp")+```++</CodeGroup>### Check Existence-{/* sandbox.files.exists(path) — client-side convenience wrapper, not a dedicated HTTP endpoint. Both SDKs. */}+<CodeGroup>++```typescript TypeScript+if (await sandbox.files.exists("/app/config.json")) {+ const config = await sandbox.files.read("/app/config.json");+}+```++```python Python+if await sandbox.files.exists("/app/config.json"):+ config = await sandbox.files.read("/app/config.json")+```++</CodeGroup>++<Note>+ `exists()` is a client-side convenience — it attempts a file read and returns `false` on error. There is no dedicated HTTP endpoint for existence checks.+</Note>## Examples-{/* Upload & run a script. Copy files between paths. */}+### Upload and Run a Script++<CodeGroup>++```typescript TypeScript+await sandbox.files.write("/tmp/setup.sh", `#!/bin/bash+apt-get update && apt-get install -y redis-server+redis-server --daemonize yes+`);+await sandbox.exec.run("chmod +x /tmp/setup.sh && /tmp/setup.sh");+```++```python Python+await sandbox.files.write("/tmp/setup.sh", """#!/bin/bash+apt-get update && apt-get install -y redis-server+redis-server --daemonize yes+""")+await sandbox.exec.run("chmod +x /tmp/setup.sh && /tmp/setup.sh")+```++</CodeGroup><Tip>Full reference: [TypeScript SDK](/reference/typescript-sdk#filesystem) · [Python SDK](/reference/python-sdk#filesystem) · [HTTP API](/reference/api#filesystem).