项目文件夹

文件
wehub-resource-sync bb5c75ce05
Component Security Validation / Security Audit (push) Has been cancelled
Deploy to Cloudflare Pages / deploy (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:38:58 +08:00

1 行
11 KiB
JSON

{"content": "# Cloudflare Claude Code Sandbox\n\nExecute Claude Code in an isolated Cloudflare Workers sandbox environment with AI-powered code execution.\n\n## Description\n\nThis component sets up Cloudflare Sandbox SDK integration to run Claude Code in a secure, isolated cloud environment. Built on Cloudflare's container-based sandboxes with Durable Objects for persistent execution.\n\n## Features\n\n- **Isolated Execution**: Run Claude Code in secure Cloudflare Workers sandboxes\n- **AI Code Executor**: Turn natural language into executable Python/Node.js code\n- **Real-time Streaming**: Stream execution output as it happens\n- **Persistent Storage**: Use Durable Objects for stateful sandbox sessions\n- **Global Distribution**: Leverage Cloudflare's edge network for low latency\n- **Component Installation**: Automatically install agents and commands in sandbox\n\n## Requirements\n\n- Cloudflare Account (Workers Paid plan for Durable Objects)\n- Anthropic API Key\n- Node.js 16.17.0+\n- Docker (for local development)\n- Wrangler CLI\n\n## Architecture\n\n```\n┌─────────────────────────────────────────────────────┐\n│ User Request (Natural Language) │\n└──────────────────┬──────────────────────────────────┘\n │\n ▼\n┌─────────────────────────────────────────────────────┐\n│ Cloudflare Worker (API Endpoint) │\n│ • POST /execute │\n│ • Receives question/prompt │\n└──────────────────┬──────────────────────────────────┘\n │\n ▼\n┌─────────────────────────────────────────────────────┐\n│ Claude AI (via Anthropic SDK) │\n│ • Generates Python/TypeScript code │\n│ • Returns executable implementation │\n└──────────────────┬──────────────────────────────────┘\n │\n ▼\n┌─────────────────────────────────────────────────────┐\n│ Cloudflare Sandbox (Durable Object) │\n│ • Isolated container execution │\n│ • Python/Node.js runtime │\n│ • File system access │\n│ • Real-time streaming output │\n└──────────────────┬──────────────────────────────────┘\n │\n ▼\n┌─────────────────────────────────────────────────────┐\n│ Results │\n│ • Generated code │\n│ • Execution output │\n│ • Error messages (if any) │\n└─────────────────────────────────────────────────────┘\n```\n\n## Usage\n\n```bash\n# Execute a prompt in Cloudflare sandbox\nnpx claude-code-templates@latest --sandbox cloudflare --prompt \"Calculate the 10th Fibonacci number\"\n\n# Pass API keys directly\nnpx claude-code-templates@latest --sandbox cloudflare \\\n --anthropic-api-key your_anthropic_key \\\n --prompt \"Create a web scraper\"\n\n# Install components and execute\nnpx claude-code-templates@latest --sandbox cloudflare \\\n --agent frontend-developer \\\n --command setup-react \\\n --anthropic-api-key your_anthropic_key \\\n --prompt \"Create a modern todo app\"\n\n# Deploy your own Cloudflare Worker sandbox\ncd .claude/sandbox/cloudflare\nnpm install\nnpx wrangler secret put ANTHROPIC_API_KEY\nnpx wrangler deploy\n```\n\n## Environment Setup\n\nThe component creates:\n- `.claude/sandbox/cloudflare/src/index.ts` - Worker with sandbox logic\n- `.claude/sandbox/cloudflare/wrangler.toml` - Cloudflare configuration\n- `.claude/sandbox/cloudflare/package.json` - Node.js dependencies\n- `.claude/sandbox/cloudflare/launcher.ts` - TypeScript launcher script\n- `.claude/sandbox/cloudflare/monitor.ts` - Real-time monitoring tool\n\n## API Key Configuration\n\n### Option 1: CLI Parameters (Recommended)\n```bash\nnpx claude-code-templates@latest --sandbox cloudflare \\\n --anthropic-api-key your_anthropic_api_key \\\n --prompt \"Your prompt here\"\n```\n\n### Option 2: Wrangler Secrets\n```bash\ncd .claude/sandbox/cloudflare\nnpx wrangler secret put ANTHROPIC_API_KEY\n# Paste your API key when prompted\n```\n\n### Option 3: Environment Variables\n```bash\nexport ANTHROPIC_API_KEY=your_anthropic_api_key_here\n\n# Or create .dev.vars file:\nANTHROPIC_API_KEY=your_anthropic_api_key_here\n```\n\n**Note**: Wrangler secrets are required for production deployment. CLI parameters work for local execution only.\n\n## How it Works\n\n1. User sends natural language request (e.g., \"What's the factorial of 5?\")\n2. Cloudflare Worker receives request via POST /execute\n3. Claude generates executable Python/TypeScript code via Anthropic API\n4. Code is written to sandbox file system\n5. Sandbox executes code in isolated container\n6. Results stream back in real-time\n7. Worker returns both code and execution output\n\n## Deployment\n\n### Local Development\n```bash\ncd .claude/sandbox/cloudflare\nnpm install\nnpm run dev\n\n# Test locally\ncurl -X POST http://localhost:8787/execute \\\n -H \"Content-Type: application/json\" \\\n -d '{\"question\": \"What is 2^10?\"}'\n```\n\n### Production Deployment\n```bash\n# Set API key secret\nnpx wrangler secret put ANTHROPIC_API_KEY\n\n# Deploy to Cloudflare Workers\nnpx wrangler deploy\n\n# Wait 2-3 minutes for container provisioning\nnpx wrangler containers list\n\n# Test deployment\ncurl -X POST https://your-worker.your-subdomain.workers.dev/execute \\\n -H \"Content-Type: application/json\" \\\n -d '{\"question\": \"Calculate factorial of 5\"}'\n```\n\n## Security Benefits\n\n- **Container Isolation**: Each execution runs in isolated Cloudflare container\n- **No Local Access**: Sandboxes have no access to your local system\n- **Resource Limits**: Automatic CPU time and memory constraints\n- **Temporary Execution**: Containers destroyed after execution\n- **Edge Security**: Cloudflare's security infrastructure built-in\n\n## Advanced Features\n\n### Code Interpreter API\n```typescript\n// Use built-in code interpreter instead of exec\nimport { getCodeInterpreter } from '@cloudflare/sandbox';\n\nconst interpreter = getCodeInterpreter(env.Sandbox, 'user-id');\nconst result = await interpreter.notebook.execCell('print(2**10)');\n```\n\n### Streaming Output\n```typescript\n// Stream execution results in real-time\nreturn new Response(\n new ReadableStream({\n async start(controller) {\n const result = await sandbox.exec('python script.py', {\n onStdout: (data) => controller.enqueue(data),\n onStderr: (data) => controller.enqueue(data)\n });\n controller.close();\n }\n })\n);\n```\n\n### Persistent Sessions\n```typescript\n// Maintain sandbox state across requests\nconst sandbox = getSandbox(env.Sandbox, userId);\nawait sandbox.writeFile('/data/state.json', JSON.stringify(state));\n// Later...\nconst state = await sandbox.readFile('/data/state.json');\n```\n\n## Examples\n\n```bash\n# Mathematical computation\nnpx claude-code-templates@latest --sandbox cloudflare \\\n --prompt \"Calculate the 100th Fibonacci number\"\n\n# Data analysis\nnpx claude-code-templates@latest --sandbox cloudflare \\\n --prompt \"What is the mean of [10, 20, 30, 40, 50]?\"\n\n# String manipulation\nnpx claude-code-templates@latest --sandbox cloudflare \\\n --prompt \"Reverse the string 'Hello World'\"\n\n# Web development\nnpx claude-code-templates@latest --sandbox cloudflare \\\n --agent frontend-developer \\\n --prompt \"Create a responsive navigation bar\"\n```\n\n## Comparison with E2B\n\n| Feature | Cloudflare Sandbox | E2B Sandbox |\n|---------|-------------------|-------------|\n| **Provider** | Cloudflare Workers | E2B.dev |\n| **Infrastructure** | Cloudflare Edge Network | Cloud VMs |\n| **Pricing** | $5/month (Workers Paid) | Usage-based |\n| **Cold Start** | ~100ms | ~2-3 seconds |\n| **Max Duration** | 30 seconds (Workers) | Up to hours |\n| **Languages** | Python, Node.js | Full Linux environment |\n| **Global** | Yes (edge network) | Single region |\n| **Best For** | Fast, lightweight tasks | Long-running operations |\n\n## Troubleshooting\n\n### Container Not Ready\n```bash\n# After first deployment, wait 2-3 minutes\nnpx wrangler containers list\n\n# Check container status\nnpx wrangler tail\n```\n\n### API Key Issues\n```bash\n# Verify secret is set\nnpx wrangler secret list\n\n# Update secret\nnpx wrangler secret put ANTHROPIC_API_KEY\n```\n\n### Local Development Issues\n```bash\n# Ensure Docker is running\ndocker ps\n\n# Clear wrangler cache\nrm -rf .wrangler\n\n# Reinstall dependencies\nrm -rf node_modules package-lock.json\nnpm install\n```\n\n## Performance Tips\n\n1. **Use Code Interpreter API** for better Python performance\n2. **Implement caching** for frequently used code patterns\n3. **Stream output** for long-running operations\n4. **Use Durable Objects** for session persistence\n5. **Deploy to multiple regions** (automatic with Workers)\n\n## Template Information\n\n- **Provider**: Cloudflare Workers + Sandbox SDK\n- **Runtime**: V8 isolates with container sandboxes\n- **Languages**: Python 3.x, Node.js\n- **Timeout**: 30 seconds (Workers), configurable for Durable Objects\n- **Memory**: 128MB default\n- **Storage**: Ephemeral (use Durable Objects for persistence)\n\n## Resources\n\n- [Cloudflare Sandbox SDK Docs](https://developers.cloudflare.com/sandbox/)\n- [Workers Documentation](https://developers.cloudflare.com/workers/)\n- [Durable Objects Guide](https://developers.cloudflare.com/durable-objects/)\n- [Wrangler CLI Reference](https://developers.cloudflare.com/workers/wrangler/)\n- [Anthropic API Documentation](https://docs.anthropic.com/)\n\n## Next Steps\n\nAfter installation:\n1. Set up Cloudflare account and get API credentials\n2. Install Wrangler CLI: `npm install -g wrangler`\n3. Configure secrets: `npx wrangler secret put ANTHROPIC_API_KEY`\n4. Deploy your worker: `npx wrangler deploy`\n5. Test with example requests\n6. Customize sandbox configuration for your use case\n\n## License\n\nUses Cloudflare Sandbox SDK (open source) and requires Cloudflare Workers Paid plan ($5/month) for Durable Objects support.\n"}