Đang tải…
Đang tải…
npx claude-code-templates@latest --sandbox cloudflare/SANDBOX_DEBUGGINGFile: launcher.ts
File: monitor.ts
Built-in Cloudflare debugging tools:
npx wrangler tail - Real-time log streamingnpx wrangler containers list - Container statusnpx wrangler deployments list - Deployment historynpx wrangler dev - Local development serverSymptoms:
Error: Container not ready. Please wait 2-3 minutes after deployment.
Solutions:
Wait for provisioning:
# Check container status
npx wrangler containers list
# Expected output after provisioning:
# ✓ Container ready for sandbox execution
Verify deployment:
npx wrangler deployments list
# Check deployment status and timestamp
Check worker logs:
npx wrangler tail
# Look for initialization errors
Symptoms:
❌ Worker health check failed: fetch failed
Debugging Steps:
Verify worker is deployed:
npx wrangler deploy
# Should return worker URL
Test worker endpoint:
curl https://your-worker.your-subdomain.workers.dev
# Should return usage instructions
Check local development:
# For local testing
npm run dev
# Test local endpoint
curl http://localhost:8787
Symptoms:
Error: ANTHROPIC_API_KEY is required
Solutions:
Set as Wrangler secret (Production):
npx wrangler secret put ANTHROPIC_API_KEY
# Paste your key when prompted
Set in .dev.vars (Local Development):
# Create .dev.vars file:
echo "ANTHROPIC_API_KEY=sk-ant-your-key-here" > .dev.vars
Verify secret is set:
npx wrangler secret list
# Should show ANTHROPIC_API_KEY
Symptoms:
Error: Sandbox execution exceeded 30 second timeout
Solutions:
Use Durable Objects for longer operations:
// In wrangler.toml, ensure Durable Objects are configured
[[durable_objects.bindings]]
name = "Sandbox"
class_name = "Sandbox"
Optimize code generation:
// Request more concise code
const prompt = `Generate SIMPLE Python code...`;
Break into smaller tasks:
# Instead of complex operations, break into steps
npx claude-code-templates --sandbox cloudflare \
--prompt "Step 1: Create data structure"
Symptoms:
Error: Docker daemon is not running
Solutions:
Start Docker Desktop:
sudo systemctl start dockerVerify Docker is running:
docker ps
# Should list running containers
Alternative: Deploy directly to Cloudflare:
# Skip local testing, deploy directly
npx wrangler deploy
# Monitor a simple operation
node monitor.ts "Calculate factorial of 5" your_api_key
# Monitor with custom worker URL
node monitor.ts "Fibonacci 10" your_api_key https://your-worker.workers.dev
[14:32:15] ℹ 🚀 Starting enhanced Cloudflare sandbox monitoring
============================================================
🖥️ SYSTEM INFORMATION
============================================================
Node.js Version: v20.11.0
Platform: darwin
Architecture: arm64
Memory Usage: 45MB / 128MB
============================================================
[14:32:16] ℹ 🔍 Checking Cloudflare Worker health...
[14:32:16] ✓ Worker is responding
[14:32:16] ℹ Status: 200 OK
[14:32:17] ℹ 🤖 Starting code generation with Claude...
[14:32:19] ✓ Code generated in 2147ms
[14:32:19] ℹ Model: claude-sonnet-4-5-20250929
[14:32:19] ℹ Tokens used: 156 in, 89 out
[14:32:19] ℹ Code length: 234 characters
[14:32:19] ℹ ⚙️ Executing in Cloudflare Sandbox...
[14:32:21] ✓ Sandbox execution completed in 1856ms
[14:32:21] ℹ Exit code: 0 (success)
[14:32:21] ℹ Output length: 3 characters
============================================================
📊 PERFORMANCE METRICS
============================================================
Total Execution Time: 4123ms
├─ Code Generation: 2147ms
└─ Sandbox Execution: 1856ms
Memory Usage: 48MB
Status: Success ✓
============================================================
# Use monitor to see exact Claude API interaction
node monitor.ts "Complex prompt that might fail"
# Look for:
# - Token usage (may hit limits)
# - Generated code preview
# - Model used (should be claude-sonnet-4-5)
# Check worker logs while testing
npx wrangler tail &
node launcher.ts "Test prompt"
# Look for:
# - Sandbox creation errors
# - File write failures
# - Python execution errors
# Use monitor to identify bottlenecks
node monitor.ts "Your prompt"
# Compare metrics:
# - Code Generation Time (Claude API)
# - Sandbox Execution Time (Cloudflare)
# - Total Round Trip Time
# Check deployments
npx wrangler deployments list
# View recent logs
npx wrangler tail --format=pretty
# Test worker health
curl -v https://your-worker.workers.dev
# In wrangler.toml
[env.development]
vars = { DEBUG = "true" }
# Or in .dev.vars for local development
DEBUG=true
ANTHROPIC_API_KEY=your_key
// In src/index.ts
const result = await sandbox.exec('python /tmp/code.py', {
timeout: 60000, // 60 seconds
});
# Set log level
export WRANGLER_LOG=debug
# Run with verbose output
npx wrangler deploy --verbose
npx wrangler deploy)npx wrangler containers list)npx wrangler secret list)npx wrangler tail)npx wrangler tailnpx wrangler containers list// Be specific to reduce Claude's thinking time
const prompt = `Generate a single Python function to calculate factorial.
Use recursion. Include only the function, no tests.`;
// Faster than exec for Python
import { getCodeInterpreter } from '@cloudflare/sandbox';
const interpreter = getCodeInterpreter(env.Sandbox, userId);
const result = await interpreter.notebook.execCell(pythonCode);
// Cache generated code for common prompts
const cacheKey = `code:${hashPrompt(prompt)}`;
let code = await env.CACHE.get(cacheKey);
if (!code) {
code = await generateCode(prompt);
await env.CACHE.put(cacheKey, code, { expirationTtl: 3600 });
}
// Stream output for better perceived performance
return new Response(
new ReadableStream({
async start(controller) {
const result = await sandbox.exec(command, {
onStdout: (data) => controller.enqueue(encoder.encode(data)),
});
controller.close();
},
})
);
# Deploy worker
npx wrangler deploy
# Deploy to specific environment
npx wrangler deploy --env production
# Rollback deployment
npx wrangler rollback
# Delete deployment
npx wrangler delete
# Add secret
npx wrangler secret put SECRET_NAME
# List secrets
npx wrangler secret list
# Delete secret
npx wrangler secret delete SECRET_NAME
# Start dev server
npm run dev
# Start with specific port
npx wrangler dev --port 3000
# Start with remote Durable Objects
npx wrangler dev --remote
# Tail logs in real-time
npx wrangler tail
# Tail with pretty formatting
npx wrangler tail --format=pretty
# Tail specific deployment
npx wrangler tail --deployment-id <id>
# Filter logs
npx wrangler tail --status error
# List containers
npx wrangler containers list
# Get container details
npx wrangler containers describe <container-id>
npm run dev before deployingnpx wrangler tail during testingWith these tools and techniques, you can effectively debug and optimize your Cloudflare sandbox implementation.