Files
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
..

{"content": "# Cloudflare Claude Code Sandbox\n\nExecute Claude Code in isolated Cloudflare Workers sandboxes with AI-powered code generation.\n\n## Quick Start\n\n### 1. Install Dependencies\n```bash\nnpm install\n```\n\n### 2. Configure API Key\n```bash\n# For local development, create .dev.vars:\necho \"ANTHROPIC_API_KEY=your-api-key-here\" > .dev.vars\n\n# For production, use wrangler secrets:\nnpx wrangler secret put ANTHROPIC_API_KEY\n```\n\n### 3. Local Development\n```bash\n# Start development server (requires Docker)\nnpm run dev\n\n# In another terminal, test the endpoint:\ncurl -X POST http://localhost:8787/execute \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"question\": \"What is the 10th Fibonacci number?\"}'\n```\n\n### 4. Deploy to Cloudflare\n```bash\n# Deploy worker\nnpx wrangler deploy\n\n# Wait 2-3 minutes for container provisioning\nnpx wrangler containers list\n\n# Test production endpoint\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## Architecture\n\nThis sandbox combines three powerful technologies:\n\n1. **Claude AI** (Anthropic) - Generates executable code from natural language\n2. **Cloudflare Workers** - Runs at the edge for global low-latency access\n3. **Sandbox SDK** - Provides isolated container execution\n\n```\nUser Question → Cloudflare Worker → Claude AI → Generated Code → Sandbox → Results\n```\n\n## API Reference\n\n### POST /execute\n\nExecute a natural language question as code.\n\n**Request:**\n```json\n{\n  \"question\": \"What is the 100th Fibonacci number?\",\n  \"maxTokens\": 2048,          // Optional: Max tokens for code generation\n  \"timeout\": 30000,            // Optional: Execution timeout in ms\n  \"language\": \"python\"         // Optional: \"python\" or \"javascript\"\n}\n```\n\n**Response:**\n```json\n{\n  \"success\": true,\n  \"question\": \"What is the 100th Fibonacci number?\",\n  \"code\": \"def fibonacci(n):\\n    if n <= 1:\\n        return n\\n    return fibonacci(n-1) + fibonacci(n-2)\\n\\nprint(fibonacci(100))\",\n  \"output\": \"354224848179261915075\\n\",\n  \"error\": \"\",\n  \"sandboxId\": \"user-1234567890-abc123\",\n  \"executionTime\": 2147\n}\n```\n\n### GET /health\n\nCheck worker health status.\n\n**Response:**\n```json\n{\n  \"status\": \"healthy\",\n  \"timestamp\": \"2025-10-19T12:00:00.000Z\",\n  \"worker\": \"cloudflare-claude-sandbox\"\n}\n```\n\n## Command Line Tools\n\n### Launcher\nExecute prompts directly from command line:\n\n```bash\n# Basic usage\nnode launcher.ts \"Calculate factorial of 5\"\n\n# With custom worker URL\nnode launcher.ts \"Fibonacci 10\" \"\" your_api_key https://your-worker.workers.dev\n\n# With components\nnode launcher.ts \"Create a React app\" \"--agent frontend-developer\" your_api_key\n```\n\n### Monitor\nMonitor execution with detailed metrics:\n\n```bash\n# Monitor execution\nnode monitor.ts \"Calculate factorial of 5\" your_api_key\n\n# Monitor production worker\nnode monitor.ts \"Sum array\" your_api_key https://your-worker.workers.dev\n```\n\n## Examples\n\n### Mathematical Calculations\n```bash\ncurl -X POST http://localhost:8787/execute \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"question\": \"What is the factorial of 20?\"}'\n```\n\n### String Manipulation\n```bash\ncurl -X POST http://localhost:8787/execute \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"question\": \"Reverse the string Hello World\"}'\n```\n\n### Data Analysis\n```bash\ncurl -X POST http://localhost:8787/execute \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"question\": \"Calculate the mean of [10, 20, 30, 40, 50]\"}'\n```\n\n### JavaScript Execution\n```bash\ncurl -X POST http://localhost:8787/execute \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"question\": \"Sort an array of numbers\",\n    \"language\": \"javascript\"\n  }'\n```\n\n## Configuration\n\n### Environment Variables\n\n**Local Development (.dev.vars):**\n```bash\nANTHROPIC_API_KEY=sk-ant-your-key-here\n```\n\n**Production (Wrangler Secrets):**\n```bash\nnpx wrangler secret put ANTHROPIC_API_KEY\n```\n\n### Wrangler Configuration\n\nEdit `wrangler.toml` to customize:\n\n```toml\n# Worker name (must be unique)\nname = \"my-custom-sandbox\"\n\n# Resource limits\n[limits]\ncpu_ms = 100  # CPU time per request\n\n# Environment-specific configuration\n[env.production]\nvars = { ENVIRONMENT = \"production\" }\n```\n\n## Troubleshooting\n\n### Container Not Ready\nAfter first deployment, wait 2-3 minutes:\n```bash\nnpx wrangler containers list\n```\n\n### Docker Issues (Local Development)\nEnsure Docker is running:\n```bash\ndocker ps\n```\n\n### API Key Not Set\nFor local development:\n```bash\necho \"ANTHROPIC_API_KEY=your-key\" > .dev.vars\n```\n\nFor production:\n```bash\nnpx wrangler secret put ANTHROPIC_API_KEY\n```\n\n### View Logs\n```bash\n# Real-time logs\nnpx wrangler tail\n\n# Pretty formatted\nnpx wrangler tail --format=pretty\n```\n\n## Performance Tips\n\n1. **Use specific prompts**: More specific questions generate faster code\n2. **Implement caching**: Cache generated code for common questions\n3. **Stream output**: Use streaming for long-running operations\n4. **Set appropriate timeouts**: Balance between UX and resource usage\n5. **Monitor metrics**: Use the monitor tool to identify bottlenecks\n\n## Security\n\n- Sandboxes are isolated containers with no network access\n- Code execution is limited by timeout (default 30s)\n- CPU and memory limits are enforced by Cloudflare\n- API keys are stored as encrypted Wrangler secrets\n- CORS is enabled for browser access (configure as needed)\n\n## Cost Estimation\n\n**Cloudflare Workers:**\n- Free tier: 100,000 requests/day (limited Durable Objects)\n- Paid plan ($5/month): 10M requests/month + unlimited Durable Objects\n\n**Anthropic API:**\n- Claude Sonnet 4.5: ~$3 per million input tokens\n- Average request: ~200 tokens = $0.0006 per request\n\n**Example costs for 10,000 requests/month:**\n- Cloudflare: $5/month (paid plan)\n- Anthropic: ~$6/month (avg 200 tokens/request)\n- **Total: ~$11/month**\n\n## Development\n\n### Project Structure\n```\ncloudflare-claude-sandbox/\n├── src/\n│   └── index.ts           # Worker source code\n├── launcher.ts            # CLI launcher tool\n├── monitor.ts             # Monitoring tool\n├── wrangler.toml          # Cloudflare configuration\n├── package.json           # Dependencies\n├── tsconfig.json          # TypeScript config\n└── README.md              # This file\n```\n\n### Scripts\n- `npm run dev` - Start local development server\n- `npm run deploy` - Deploy to Cloudflare\n- `npm run tail` - View real-time logs\n- `npm run launch` - Run launcher tool\n- `npm run monitor` - Run monitoring tool\n- `npm run type-check` - Check TypeScript types\n- `npm test` - Run tests\n\n## Resources\n\n- [Cloudflare Sandbox SDK](https://developers.cloudflare.com/sandbox/)\n- [Cloudflare Workers Documentation](https://developers.cloudflare.com/workers/)\n- [Anthropic API Documentation](https://docs.anthropic.com/)\n- [Wrangler CLI Reference](https://developers.cloudflare.com/workers/wrangler/)\n\n## License\n\nMIT License - See LICENSE file for details\n\n## Support\n\nFor issues and questions:\n1. Check the [debugging guide](./SANDBOX_DEBUGGING.md)\n2. Run the monitor tool for detailed metrics\n3. Check Cloudflare worker logs: `npx wrangler tail`\n4. Open an issue on GitHub\n\n---\n\nBuilt with ❤️ using Cloudflare Workers, Claude AI, and the Sandbox SDK\n"}