sandbox-sdk

作者: Cloudflare

构建沙盒化应用程序以实现安全代码执行。在构建AI代码执行、代码解释器、CI/CD系统、交互式开发环境或执行不受信任的代码时加载。涵盖Sandbox SDK生命周期、命令、文件、代码解释器和预览URL。

npx skills add https://github.com/cloudflare/skills --skill sandbox-sdk

Cloudflare Sandbox SDK

Build secure, isolated code execution environments on Cloudflare Workers.

FIRST: Verify Installation

npm install @cloudflare/sandbox
docker info  # Must succeed - Docker required for local dev

Retrieval Sources

Your knowledge of the Sandbox SDK may be outdated. Prefer retrieval over pre-training for any Sandbox SDK task.

ResourceURL
Docshttps://developers.cloudflare.com/sandbox/
API Referencehttps://developers.cloudflare.com/sandbox/api/
Exampleshttps://github.com/cloudflare/sandbox-sdk/tree/main/examples
Get Startedhttps://developers.cloudflare.com/sandbox/get-started/

When implementing features, fetch the relevant doc page or example first.

Required Configuration

wrangler.jsonc (exact - do not modify structure):

{
  "containers": [{
    "class_name": "Sandbox",
    "image": "./Dockerfile",
    "instance_type": "lite",
    "max_instances": 1
  }],
  "durable_objects": {
    "bindings": [{ "class_name": "Sandbox", "name": "Sandbox" }]
  },
  "migrations": [{ "new_sqlite_classes": ["Sandbox"], "tag": "v1" }]
}

Worker entry - must re-export Sandbox class:

import { getSandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';  // Required export

Quick Reference

TaskMethod
Get sandboxgetSandbox(env.Sandbox, 'user-123')
Run commandawait sandbox.exec('python script.py')
Run code (interpreter)await sandbox.runCode(code, { language: 'python' })
Write fileawait sandbox.writeFile('/workspace/app.py', content)
Read fileawait sandbox.readFile('/workspace/app.py')
Create directoryawait sandbox.mkdir('/workspace/src', { recursive: true })
List filesawait sandbox.listFiles('/workspace')
Expose portawait sandbox.exposePort(8080)
Destroyawait sandbox.destroy()

Core Patterns

Execute Commands

const sandbox = getSandbox(env.Sandbox, 'user-123');
const result = await sandbox.exec('python --version');
// result: { stdout, stderr, exitCode, success }

Code Interpreter (Recommended for AI)

Use runCode() for executing LLM-generated code with rich outputs:

const ctx = await sandbox.createCodeContext({ language: 'python' });

await sandbox.runCode('import pandas as pd; data = [1,2,3]', { context: ctx });
const result = await sandbox.runCode('sum(data)', { context: ctx });
// result.results[0].text = "6"

Languages: python, javascript, typescript

State persists within context. Create explicit contexts for production.

File Operations

await sandbox.mkdir('/workspace/project', { recursive: true });
await sandbox.writeFile('/workspace/project/main.py', code);
const file = await sandbox.readFile('/workspace/project/main.py');
const files = await sandbox.listFiles('/workspace/project');

When to Use What

NeedUseWhy
Shell commands, scriptsexec()Direct control, streaming
LLM-generated coderunCode()Rich outputs, state persistence
Build/test pipelinesexec()Exit codes, stderr capture
Data analysisrunCode()Charts, tables, pandas

Extending the Dockerfile

Base image (docker.io/cloudflare/sandbox:0.7.0) includes Python 3.11, Node.js 20, and common tools.

Add dependencies by extending the Dockerfile:

FROM docker.io/cloudflare/sandbox:0.7.0

# Python packages
RUN pip install requests beautifulsoup4

# Node packages (global)
RUN npm install -g typescript

# System packages
RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*

EXPOSE 8080  # Required for local dev port exposure

Keep images lean - affects cold start time.

Preview URLs (Port Exposure)

Expose HTTP services running in sandboxes:

const { url } = await sandbox.exposePort(8080);
// Returns preview URL for the service

Production requirement: Preview URLs need a custom domain with wildcard DNS (*.yourdomain.com). The .workers.dev domain does not support preview URL subdomains.

See: https://developers.cloudflare.com/sandbox/guides/expose-services/

OpenAI Agents SDK Integration

The SDK provides helpers for OpenAI Agents at @cloudflare/sandbox/openai:

import { Shell, Editor } from '@cloudflare/sandbox/openai';

See examples/openai-agents for complete integration pattern.

Sandbox Lifecycle

  • getSandbox() returns immediately - container starts lazily on first operation
  • Containers sleep after 10 minutes of inactivity (configurable via sleepAfter)
  • Use destroy() to immediately free resources
  • Same sandboxId always returns same sandbox instance

Anti-Patterns

  • Don't use internal clients (CommandClient, FileClient) - use sandbox.* methods
  • Don't skip the Sandbox export - Worker won't deploy without export { Sandbox }
  • Don't hardcode sandbox IDs for multi-user - use user/session identifiers
  • Don't forget cleanup - call destroy() for temporary sandboxes

Detailed References

来自 Cloudflare 的更多技能

agents-sdk
Cloudflare
在Cloudflare Workers上使用Agents SDK构建AI代理。创建有状态代理、持久化工作流、实时WebSocket应用、定时任务、MCP服务器或聊天应用时加载。涵盖Agent类、状态管理、可调用RPC、Workflows集成及React钩子。
official
building-ai-agent-on-cloudflare
Cloudflare
基于Cloudflare构建AI智能体,使用Agents SDK实现状态管理、实时WebSocket、定时任务、工具集成及聊天功能。生成可直接部署到Workers的生产级智能体代码。 适用场景:用户需要“构建智能体”、“AI智能体”、“聊天智能体”、“有状态智能体”,提及“Agents SDK”,需要“实时AI”、“WebSocket AI”,或询问智能体“状态管理”、“定时任务”、“工具调用”。
developmentofficial
building-mcp-server-on-cloudflare
Cloudflare
在 Cloudflare Workers 上构建远程 MCP(模型上下文协议)服务器,支持工具、OAuth 认证和生产部署。生成服务器代码、配置认证提供者并部署到 Workers。 使用场景:用户想要“构建 MCP 服务器”、“创建 MCP 工具”、“远程 MCP”、“部署 MCP”、添加“MCP 的 OAuth”,或提及 Cloudflare 上的模型上下文协议。也会在“MCP 认证”或“MCP 部署”时触发。
developmentofficial
cloudflare
Cloudflare
全面的Cloudflare平台技能,涵盖Workers、Pages、存储(KV、D1、R2)、AI(Workers AI、Vectorize、Agents SDK)、网络(Tunnel、Spectrum)、安全(WAF、DDoS)以及基础设施即代码(Terraform、Pulumi)。适用于任何Cloudflare开发任务。
official
durable-objects
Cloudflare
创建和审查Cloudflare Durable Objects。用于构建有状态协调(聊天室、多玩家游戏、预订系统)、实现RPC方法、SQLite存储、警报、WebSocket,或审查DO代码以遵循最佳实践。涵盖Workers集成、wrangler配置以及使用Vitest进行测试。
official
web-perf
Cloudflare
使用Chrome DevTools MCP分析网页性能。测量核心网页指标(FCP、LCP、TBT、CLS、速度指数),识别渲染阻塞资源、网络依赖链、布局偏移、缓存问题及可访问性差距。当被要求审计、分析、调试或优化页面加载性能、Lighthouse评分或网站速度时使用。
official
workers-best-practices
Cloudflare
审查并根据生产最佳实践对Cloudflare Workers代码进行审核。在编写新的Workers、审查Worker代码、配置wrangler.jsonc或检查常见的Workers反模式(流式处理、浮动Promise、全局状态、机密、绑定、可观测性)时加载。倾向于从Cloudflare文档中检索信息,而非依赖预训练知识。
official
wrangler
Cloudflare
Cloudflare Workers CLI,用于部署、开发和管理 Workers、KV、R2、D1、Vectorize、Hyperdrive、Workers AI、Containers、Queues、Workflows、Pipelines 及 Secrets Store。在运行 wrangler 命令前加载,以确保正确的语法和最佳实践。
official