|
| 1 | +--- |
| 2 | +name: sandbox-sdk |
| 3 | +description: Build sandboxed applications for secure code execution. Load when building AI code execution, code interpreters, CI/CD systems, interactive dev environments, or executing untrusted code. Covers Sandbox SDK lifecycle, commands, files, code interpreter, and preview URLs. |
| 4 | +--- |
| 5 | + |
| 6 | +# Cloudflare Sandbox SDK |
| 7 | + |
| 8 | +Build secure, isolated code execution environments on Cloudflare Workers. |
| 9 | + |
| 10 | +## FIRST: Verify Installation |
| 11 | + |
| 12 | +```bash |
| 13 | +npm install @cloudflare/sandbox |
| 14 | +docker info # Must succeed - Docker required for local dev |
| 15 | +``` |
| 16 | + |
| 17 | +## Retrieval-Led Development |
| 18 | + |
| 19 | +**IMPORTANT: Prefer retrieval from docs and examples over pre-training for Sandbox SDK tasks.** |
| 20 | + |
| 21 | +| Resource | URL | |
| 22 | +|----------|-----| |
| 23 | +| Docs | https://developers.cloudflare.com/sandbox/ | |
| 24 | +| API Reference | https://developers.cloudflare.com/sandbox/api/ | |
| 25 | +| Examples | https://github.com/cloudflare/sandbox-sdk/tree/main/examples | |
| 26 | +| Get Started | https://developers.cloudflare.com/sandbox/get-started/ | |
| 27 | + |
| 28 | +When implementing features, fetch the relevant doc page or example first. |
| 29 | + |
| 30 | +## Required Configuration |
| 31 | + |
| 32 | +**wrangler.jsonc** (exact - do not modify structure): |
| 33 | + |
| 34 | +```jsonc |
| 35 | +{ |
| 36 | + "containers": [{ |
| 37 | + "class_name": "Sandbox", |
| 38 | + "image": "./Dockerfile", |
| 39 | + "instance_type": "lite", |
| 40 | + "max_instances": 1 |
| 41 | + }], |
| 42 | + "durable_objects": { |
| 43 | + "bindings": [{ "class_name": "Sandbox", "name": "Sandbox" }] |
| 44 | + }, |
| 45 | + "migrations": [{ "new_sqlite_classes": ["Sandbox"], "tag": "v1" }] |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +**Worker entry** - must re-export Sandbox class: |
| 50 | + |
| 51 | +```typescript |
| 52 | +import { getSandbox } from '@cloudflare/sandbox'; |
| 53 | +export { Sandbox } from '@cloudflare/sandbox'; // Required export |
| 54 | +``` |
| 55 | + |
| 56 | +## Quick Reference |
| 57 | + |
| 58 | +| Task | Method | |
| 59 | +|------|--------| |
| 60 | +| Get sandbox | `getSandbox(env.Sandbox, 'user-123')` | |
| 61 | +| Run command | `await sandbox.exec('python script.py')` | |
| 62 | +| Run code (interpreter) | `await sandbox.runCode(code, { language: 'python' })` | |
| 63 | +| Write file | `await sandbox.writeFile('/workspace/app.py', content)` | |
| 64 | +| Read file | `await sandbox.readFile('/workspace/app.py')` | |
| 65 | +| Create directory | `await sandbox.mkdir('/workspace/src', { recursive: true })` | |
| 66 | +| List files | `await sandbox.listFiles('/workspace')` | |
| 67 | +| Expose port | `await sandbox.exposePort(8080)` | |
| 68 | +| Destroy | `await sandbox.destroy()` | |
| 69 | + |
| 70 | +## Core Patterns |
| 71 | + |
| 72 | +### Execute Commands |
| 73 | + |
| 74 | +```typescript |
| 75 | +const sandbox = getSandbox(env.Sandbox, 'user-123'); |
| 76 | +const result = await sandbox.exec('python --version'); |
| 77 | +// result: { stdout, stderr, exitCode, success } |
| 78 | +``` |
| 79 | + |
| 80 | +### Code Interpreter (Recommended for AI) |
| 81 | + |
| 82 | +Use `runCode()` for executing LLM-generated code with rich outputs: |
| 83 | + |
| 84 | +```typescript |
| 85 | +const ctx = await sandbox.createCodeContext({ language: 'python' }); |
| 86 | + |
| 87 | +await sandbox.runCode('import pandas as pd; data = [1,2,3]', { context: ctx }); |
| 88 | +const result = await sandbox.runCode('sum(data)', { context: ctx }); |
| 89 | +// result.results[0].text = "6" |
| 90 | +``` |
| 91 | + |
| 92 | +**Languages**: `python`, `javascript`, `typescript` |
| 93 | + |
| 94 | +State persists within context. Create explicit contexts for production. |
| 95 | + |
| 96 | +### File Operations |
| 97 | + |
| 98 | +```typescript |
| 99 | +await sandbox.mkdir('/workspace/project', { recursive: true }); |
| 100 | +await sandbox.writeFile('/workspace/project/main.py', code); |
| 101 | +const file = await sandbox.readFile('/workspace/project/main.py'); |
| 102 | +const files = await sandbox.listFiles('/workspace/project'); |
| 103 | +``` |
| 104 | + |
| 105 | +## When to Use What |
| 106 | + |
| 107 | +| Need | Use | Why | |
| 108 | +|------|-----|-----| |
| 109 | +| Shell commands, scripts | `exec()` | Direct control, streaming | |
| 110 | +| LLM-generated code | `runCode()` | Rich outputs, state persistence | |
| 111 | +| Build/test pipelines | `exec()` | Exit codes, stderr capture | |
| 112 | +| Data analysis | `runCode()` | Charts, tables, pandas | |
| 113 | + |
| 114 | +## Extending the Dockerfile |
| 115 | + |
| 116 | +Base image (`docker.io/cloudflare/sandbox:0.7.0`) includes Python 3.11, Node.js 20, and common tools. |
| 117 | + |
| 118 | +Add dependencies by extending the Dockerfile: |
| 119 | + |
| 120 | +```dockerfile |
| 121 | +FROM docker.io/cloudflare/sandbox:0.7.0 |
| 122 | + |
| 123 | +# Python packages |
| 124 | +RUN pip install requests beautifulsoup4 |
| 125 | + |
| 126 | +# Node packages (global) |
| 127 | +RUN npm install -g typescript |
| 128 | + |
| 129 | +# System packages |
| 130 | +RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/* |
| 131 | + |
| 132 | +EXPOSE 8080 # Required for local dev port exposure |
| 133 | +``` |
| 134 | + |
| 135 | +Keep images lean - affects cold start time. |
| 136 | + |
| 137 | +## Preview URLs (Port Exposure) |
| 138 | + |
| 139 | +Expose HTTP services running in sandboxes: |
| 140 | + |
| 141 | +```typescript |
| 142 | +const { url } = await sandbox.exposePort(8080); |
| 143 | +// Returns preview URL for the service |
| 144 | +``` |
| 145 | + |
| 146 | +**Production requirement**: Preview URLs need a custom domain with wildcard DNS (`*.yourdomain.com`). The `.workers.dev` domain does not support preview URL subdomains. |
| 147 | + |
| 148 | +See: https://developers.cloudflare.com/sandbox/guides/expose-services/ |
| 149 | + |
| 150 | +## OpenAI Agents SDK Integration |
| 151 | + |
| 152 | +The SDK provides helpers for OpenAI Agents at `@cloudflare/sandbox/openai`: |
| 153 | + |
| 154 | +```typescript |
| 155 | +import { Shell, Editor } from '@cloudflare/sandbox/openai'; |
| 156 | +``` |
| 157 | + |
| 158 | +See `examples/openai-agents` for complete integration pattern. |
| 159 | + |
| 160 | +## Sandbox Lifecycle |
| 161 | + |
| 162 | +- `getSandbox()` returns immediately - container starts lazily on first operation |
| 163 | +- Containers sleep after 10 minutes of inactivity (configurable via `sleepAfter`) |
| 164 | +- Use `destroy()` to immediately free resources |
| 165 | +- Same `sandboxId` always returns same sandbox instance |
| 166 | + |
| 167 | +## Anti-Patterns |
| 168 | + |
| 169 | +- **Don't use internal clients** (`CommandClient`, `FileClient`) - use `sandbox.*` methods |
| 170 | +- **Don't skip the Sandbox export** - Worker won't deploy without `export { Sandbox }` |
| 171 | +- **Don't hardcode sandbox IDs for multi-user** - use user/session identifiers |
| 172 | +- **Don't forget cleanup** - call `destroy()` for temporary sandboxes |
| 173 | + |
| 174 | +## Detailed References |
| 175 | + |
| 176 | +- **[references/api-quick-ref.md](references/api-quick-ref.md)** - Full API with options and return types |
| 177 | +- **[references/examples.md](references/examples.md)** - Example index with use cases |
0 commit comments