Skip to content

Commit a7ef37e

Browse files
committed
Update included skills
1 parent 85b5eba commit a7ef37e

File tree

4 files changed

+352
-0
lines changed

4 files changed

+352
-0
lines changed

skills/durable-objects/SKILL.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,19 @@ description: Create and review Cloudflare Durable Objects. Use when building sta
77

88
Build stateful, coordinated applications on Cloudflare's edge using Durable Objects.
99

10+
## Retrieval-First Development
11+
12+
**Prefer retrieval from official docs over pre-training for Durable Objects tasks.**
13+
14+
| Resource | URL |
15+
|----------|-----|
16+
| Docs | https://developers.cloudflare.com/durable-objects/ |
17+
| API Reference | https://developers.cloudflare.com/durable-objects/api/ |
18+
| Best Practices | https://developers.cloudflare.com/durable-objects/best-practices/ |
19+
| Examples | https://developers.cloudflare.com/durable-objects/examples/ |
20+
21+
Fetch the relevant doc page when implementing features.
22+
1023
## When to Use
1124

1225
- Creating new Durable Object classes for stateful coordination

skills/sandbox-sdk/SKILL.md

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
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
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
# Sandbox SDK API Reference
2+
3+
Detailed API for `@cloudflare/sandbox`. For full docs: https://developers.cloudflare.com/sandbox/api/
4+
5+
## Lifecycle
6+
7+
```typescript
8+
getSandbox(binding: DurableObjectNamespace<Sandbox>, sandboxId: string, options?: SandboxOptions): Sandbox
9+
10+
interface SandboxOptions {
11+
sleepAfter?: string; // Duration before auto-sleep (default: "10m")
12+
keepAlive?: boolean; // Prevent auto-sleep (default: false)
13+
normalizeId?: boolean; // Lowercase IDs for preview URLs (default: false)
14+
}
15+
16+
await sandbox.destroy(): Promise<void> // Immediately terminate and delete all state
17+
```
18+
19+
## Commands
20+
21+
```typescript
22+
await sandbox.exec(command: string, options?: ExecOptions): Promise<ExecResult>
23+
24+
interface ExecOptions {
25+
cwd?: string; // Working directory
26+
env?: Record<string, string>; // Environment variables
27+
timeout?: number; // Timeout in ms (default: 60000)
28+
stdin?: string; // Input to command
29+
}
30+
31+
interface ExecResult {
32+
stdout: string;
33+
stderr: string;
34+
exitCode: number;
35+
success: boolean; // exitCode === 0
36+
}
37+
```
38+
39+
## Code Interpreter
40+
41+
```typescript
42+
await sandbox.createCodeContext(options?: CreateContextOptions): Promise<CodeContext>
43+
44+
interface CreateContextOptions {
45+
language?: 'python' | 'javascript' | 'typescript'; // default: 'python'
46+
cwd?: string; // Working directory (default: '/workspace')
47+
envVars?: Record<string, string>;
48+
timeout?: number; // Request timeout in ms (default: 30000)
49+
}
50+
51+
await sandbox.runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>
52+
53+
interface RunCodeOptions {
54+
context?: CodeContext; // Reuse context for state persistence
55+
language?: 'python' | 'javascript' | 'typescript';
56+
timeout?: number; // Execution timeout in ms (default: 60000)
57+
}
58+
59+
interface ExecutionResult {
60+
code: string;
61+
logs: { stdout: string[]; stderr: string[] };
62+
results: RichOutput[]; // text, html, png, json, etc.
63+
error?: { name: string; value: string; traceback: string[] };
64+
executionCount: number;
65+
}
66+
```
67+
68+
## Files
69+
70+
```typescript
71+
await sandbox.writeFile(path: string, content: string | Uint8Array): Promise<void>
72+
await sandbox.readFile(path: string): Promise<{ content: string }>
73+
await sandbox.mkdir(path: string, options?: { recursive?: boolean }): Promise<void>
74+
await sandbox.listFiles(path: string): Promise<FileMetadata[]>
75+
await sandbox.deleteFile(path: string): Promise<void>
76+
77+
interface FileMetadata {
78+
name: string;
79+
path: string;
80+
isDirectory: boolean;
81+
size: number;
82+
modifiedAt: string;
83+
}
84+
```
85+
86+
## Ports
87+
88+
```typescript
89+
await sandbox.exposePort(port: number): Promise<{ url: string; token: string }>
90+
await sandbox.unexposePort(port: number): Promise<void>
91+
await sandbox.listPorts(): Promise<PortInfo[]>
92+
```
93+
94+
## Error Handling
95+
96+
Errors include context about the operation:
97+
98+
```typescript
99+
try {
100+
await sandbox.exec('invalid-command');
101+
} catch (error) {
102+
// error.message includes command and sandbox context
103+
}
104+
```
105+
106+
For `runCode()`, check `result.error` instead of catching:
107+
108+
```typescript
109+
const result = await sandbox.runCode('1/0', { language: 'python' });
110+
if (result.error) {
111+
console.error(result.error.name); // "ZeroDivisionError"
112+
}
113+
```
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Sandbox SDK Examples
2+
3+
All examples: https://github.com/cloudflare/sandbox-sdk/tree/main/examples
4+
5+
## Example Index
6+
7+
| Example | Use Case | Key File |
8+
|---------|----------|----------|
9+
| `minimal` | Basic setup, exec, file ops | `src/index.ts` |
10+
| `code-interpreter` | AI code execution with Workers AI | `src/index.ts` |
11+
| `openai-agents` | OpenAI Agents SDK integration | `src/index.ts` |
12+
| `opencode` | OpenCode agent integration | `src/index.ts` |
13+
| `claude-code` | Claude Code agent integration | `src/index.ts` |
14+
| `typescript-validator` | TypeScript compilation/validation | `src/index.ts` |
15+
| `authentication` | Auth patterns for sandboxes | `src/index.ts` |
16+
17+
## When to Use Which Example
18+
19+
| Building | Start With |
20+
|----------|------------|
21+
| AI code execution | `code-interpreter` |
22+
| Agent with shell + file editing | `openai-agents` |
23+
| Basic command execution | `minimal` |
24+
| Code validation service | `typescript-validator` |
25+
| Multi-user sandboxes | `authentication` |
26+
27+
## Common Patterns from Examples
28+
29+
**Sandbox per user/session** (from `openai-agents`):
30+
```typescript
31+
const sandbox = getSandbox(env.Sandbox, `session-${sessionId}`);
32+
```
33+
34+
**Code context reuse** (from `code-interpreter`):
35+
```typescript
36+
const pythonCtx = await sandbox.createCodeContext({ language: 'python' });
37+
const result = await sandbox.runCode(code, { context: pythonCtx });
38+
```
39+
40+
**Resource cleanup** (from `code-interpreter`):
41+
```typescript
42+
try {
43+
// ... use sandbox
44+
} finally {
45+
await sandbox.destroy();
46+
}
47+
```
48+
49+
Fetch the full example source when implementing similar patterns.

0 commit comments

Comments
 (0)