Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/sandbox/api.md
1# API Reference23## Command Execution45```typescript6// Basic7const result = await sandbox.exec('python3 script.py');8// Returns: { stdout, stderr, exitCode, success, duration }910// With options11await sandbox.exec('python3 test.py', {12cwd: '/workspace/project',13env: { API_KEY: 'secret' },14stream: true,15onOutput: (stream, data) => console.log(data)16});17```1819## File Operations2021```typescript22// Read/Write23const { content } = await sandbox.readFile('/workspace/data.txt');24await sandbox.writeFile('/workspace/file.txt', 'content'); // Auto-creates dirs2526// List/Delete27const files = await sandbox.listFiles('/workspace');28await sandbox.deleteFile('/workspace/temp.txt');29await sandbox.deleteFile('/workspace/dir', { recursive: true });3031// Utils32await sandbox.mkdir('/workspace/dir', { recursive: true });33await sandbox.pathExists('/workspace/file.txt');34```3536## Background Processes3738```typescript39// Start40const process = await sandbox.startProcess('python3 -m http.server 8080', {41processId: 'web-server',42cwd: '/workspace/public',43env: { PORT: '8080' }44});45// Returns: { id, pid, command }4647// Wait for readiness48await process.waitForPort(8080); // Wait for port to listen49await process.waitForLog(/Server running/); // Wait for log pattern50await process.waitForExit(); // Wait for completion5152// Management53const processes = await sandbox.listProcesses();54const info = await sandbox.getProcess('web-server');55await sandbox.stopProcess('web-server');56const logs = await sandbox.getProcessLogs('web-server');57```5859## Port Exposure6061```typescript62// Expose port63const { url } = await sandbox.exposePort(8080, {64name: 'web-app',65hostname: request.hostname66});6768// Management69await sandbox.isPortExposed(8080);70await sandbox.getExposedPorts(request.hostname);71await sandbox.unexposePort(8080);72```7374## Sessions (Isolated Contexts)7576Each session maintains own shell state, env vars, cwd, process namespace.7778```typescript79// Create with context80const session = await sandbox.createSession({81id: 'user-123',82cwd: '/workspace/user123',83env: { USER_ID: '123' }84});8586// Use (full sandbox API)87await session.exec('echo $USER_ID');88await session.writeFile('config.txt', 'data');8990// Manage91await sandbox.getSession('user-123');92await sandbox.deleteSession('user-123');93```9495## Code Interpreter9697```typescript98// Create context with variables99const ctx = await sandbox.createCodeContext({100language: 'python',101variables: {102data: [1, 2, 3, 4, 5],103config: { verbose: true }104}105});106107// Execute code with rich outputs108const result = await sandbox.runCode(`109import matplotlib.pyplot as plt110plt.plot(data, [x**2 for x in data])111plt.savefig('plot.png')112print(f"Processed {len(data)} points")113`, { context: ctx });114// Returns: ExecutionResult { code, logs, results: RichOutput[], error, executionCount }115116// Context persists variables across runs117const result2 = await sandbox.runCode('print(data[0])', { context: ctx }); // Still has 'data'118```119120## WebSocket Connections121122```typescript123// Proxy WebSocket to sandbox service124export default {125async fetch(request: Request, env: Env): Promise<Response> {126const proxyResponse = await proxyToSandbox(request, env);127if (proxyResponse) return proxyResponse;128129if (request.headers.get('Upgrade')?.toLowerCase() === 'websocket') {130const sandbox = getSandbox(env.Sandbox, 'realtime');131return await sandbox.wsConnect(request, 8080);132}133134return new Response('Not a WebSocket request', { status: 400 });135}136};137```138139## Bucket Mounting (S3 Storage)140141```typescript142// Mount R2 bucket (production only, not wrangler dev)143await sandbox.mountBucket(env.DATA_BUCKET, '/data', {144readOnly: false145});146147// Access files in mounted bucket148await sandbox.exec('ls /data');149await sandbox.writeFile('/data/output.txt', 'result');150151// Unmount152await sandbox.unmountBucket('/data');153```154155**Note**: Bucket mounting only works in production. Mounted buckets are sandbox-scoped (visible to all sessions in that sandbox).156157## Lifecycle Management158159```typescript160// Terminate container immediately161await sandbox.destroy();162163// REQUIRED when using keepAlive: true164const sandbox = getSandbox(env.Sandbox, 'temp', { keepAlive: true });165try {166await sandbox.writeFile('/tmp/code.py', code);167const result = await sandbox.exec('python /tmp/code.py');168return result.stdout;169} finally {170await sandbox.destroy(); // Free resources171}172```173174Deletes: files, processes, sessions, network connections, exposed ports.175176## Error Handling177178```typescript179// Command errors180const result = await sandbox.exec('python3 invalid.py');181if (!result.success) {182console.error('Exit code:', result.exitCode);183console.error('Stderr:', result.stderr);184}185186// SDK errors187try {188await sandbox.readFile('/nonexistent');189} catch (error) {190if (error.code === 'FILE_NOT_FOUND') { /* ... */ }191else if (error.code === 'CONTAINER_NOT_READY') { /* retry */ }192else if (error.code === 'TIMEOUT') { /* ... */ }193}194195// Retry pattern (see gotchas.md for full implementation)196```197198199