claude-code-templates 1.24.1 → 1.24.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,442 @@
1
+ # Cloudflare Sandbox Debugging Guide
2
+
3
+ ## 🔍 Available Monitoring Tools
4
+
5
+ ### 1. Launcher with Enhanced Logging
6
+ **File**: `launcher.ts`
7
+ - Detailed logging of each execution step
8
+ - Worker availability checks
9
+ - Code generation monitoring
10
+ - Fallback to direct execution if worker unavailable
11
+ - Colored terminal output for better readability
12
+
13
+ ### 2. Real-time Monitor
14
+ **File**: `monitor.ts`
15
+ - Real-time performance metrics tracking
16
+ - Worker health monitoring
17
+ - Code generation time analysis
18
+ - Sandbox execution monitoring
19
+ - Memory usage tracking
20
+ - Comprehensive error reporting
21
+
22
+ ### 3. Wrangler CLI Tools
23
+ **Built-in Cloudflare debugging tools**:
24
+ - `npx wrangler tail` - Real-time log streaming
25
+ - `npx wrangler containers list` - Container status
26
+ - `npx wrangler deployments list` - Deployment history
27
+ - `npx wrangler dev` - Local development server
28
+
29
+ ## 🚨 Common Troubleshooting
30
+
31
+ ### Problem: "Container not ready"
32
+ **Symptoms**:
33
+ ```
34
+ Error: Container not ready. Please wait 2-3 minutes after deployment.
35
+ ```
36
+
37
+ **Solutions**:
38
+ 1. **Wait for provisioning**:
39
+ ```bash
40
+ # Check container status
41
+ npx wrangler containers list
42
+
43
+ # Expected output after provisioning:
44
+ # ✓ Container ready for sandbox execution
45
+ ```
46
+
47
+ 2. **Verify deployment**:
48
+ ```bash
49
+ npx wrangler deployments list
50
+ # Check deployment status and timestamp
51
+ ```
52
+
53
+ 3. **Check worker logs**:
54
+ ```bash
55
+ npx wrangler tail
56
+ # Look for initialization errors
57
+ ```
58
+
59
+ ### Problem: "Worker not responding"
60
+ **Symptoms**:
61
+ ```
62
+ ❌ Worker health check failed: fetch failed
63
+ ```
64
+
65
+ **Debugging Steps**:
66
+ 1. **Verify worker is deployed**:
67
+ ```bash
68
+ npx wrangler deploy
69
+ # Should return worker URL
70
+ ```
71
+
72
+ 2. **Test worker endpoint**:
73
+ ```bash
74
+ curl https://your-worker.your-subdomain.workers.dev
75
+ # Should return usage instructions
76
+ ```
77
+
78
+ 3. **Check local development**:
79
+ ```bash
80
+ # For local testing
81
+ npm run dev
82
+
83
+ # Test local endpoint
84
+ curl http://localhost:8787
85
+ ```
86
+
87
+ ### Problem: "Anthropic API key not set"
88
+ **Symptoms**:
89
+ ```
90
+ Error: ANTHROPIC_API_KEY is required
91
+ ```
92
+
93
+ **Solutions**:
94
+ 1. **Set as Wrangler secret (Production)**:
95
+ ```bash
96
+ npx wrangler secret put ANTHROPIC_API_KEY
97
+ # Paste your key when prompted
98
+ ```
99
+
100
+ 2. **Set in .dev.vars (Local Development)**:
101
+ ```bash
102
+ # Create .dev.vars file:
103
+ echo "ANTHROPIC_API_KEY=sk-ant-your-key-here" > .dev.vars
104
+ ```
105
+
106
+ 3. **Verify secret is set**:
107
+ ```bash
108
+ npx wrangler secret list
109
+ # Should show ANTHROPIC_API_KEY
110
+ ```
111
+
112
+ ### Problem: "Sandbox execution timeout"
113
+ **Symptoms**:
114
+ ```
115
+ Error: Sandbox execution exceeded 30 second timeout
116
+ ```
117
+
118
+ **Solutions**:
119
+ 1. **Use Durable Objects for longer operations**:
120
+ ```typescript
121
+ // In wrangler.toml, ensure Durable Objects are configured
122
+ [[durable_objects.bindings]]
123
+ name = "Sandbox"
124
+ class_name = "Sandbox"
125
+ ```
126
+
127
+ 2. **Optimize code generation**:
128
+ ```typescript
129
+ // Request more concise code
130
+ const prompt = `Generate SIMPLE Python code...`;
131
+ ```
132
+
133
+ 3. **Break into smaller tasks**:
134
+ ```bash
135
+ # Instead of complex operations, break into steps
136
+ npx claude-code-templates --sandbox cloudflare \
137
+ --prompt "Step 1: Create data structure"
138
+ ```
139
+
140
+ ### Problem: "Docker not running" (Local Development)
141
+ **Symptoms**:
142
+ ```
143
+ Error: Docker daemon is not running
144
+ ```
145
+
146
+ **Solutions**:
147
+ 1. **Start Docker Desktop**:
148
+ - macOS: Open Docker Desktop application
149
+ - Linux: `sudo systemctl start docker`
150
+ - Windows: Start Docker Desktop
151
+
152
+ 2. **Verify Docker is running**:
153
+ ```bash
154
+ docker ps
155
+ # Should list running containers
156
+ ```
157
+
158
+ 3. **Alternative: Deploy directly to Cloudflare**:
159
+ ```bash
160
+ # Skip local testing, deploy directly
161
+ npx wrangler deploy
162
+ ```
163
+
164
+ ## 📊 Using the Monitor for Debugging
165
+
166
+ ### Basic Monitoring Command:
167
+ ```bash
168
+ # Monitor a simple operation
169
+ node monitor.ts "Calculate factorial of 5" your_api_key
170
+
171
+ # Monitor with custom worker URL
172
+ node monitor.ts "Fibonacci 10" your_api_key https://your-worker.workers.dev
173
+ ```
174
+
175
+ ### Monitor Output Example:
176
+ ```
177
+ [14:32:15] ℹ 🚀 Starting enhanced Cloudflare sandbox monitoring
178
+ ============================================================
179
+ 🖥️ SYSTEM INFORMATION
180
+ ============================================================
181
+
182
+ Node.js Version: v20.11.0
183
+ Platform: darwin
184
+ Architecture: arm64
185
+ Memory Usage: 45MB / 128MB
186
+
187
+ ============================================================
188
+
189
+ [14:32:16] ℹ 🔍 Checking Cloudflare Worker health...
190
+ [14:32:16] ✓ Worker is responding
191
+ [14:32:16] ℹ Status: 200 OK
192
+
193
+ [14:32:17] ℹ 🤖 Starting code generation with Claude...
194
+ [14:32:19] ✓ Code generated in 2147ms
195
+ [14:32:19] ℹ Model: claude-sonnet-4-5-20250929
196
+ [14:32:19] ℹ Tokens used: 156 in, 89 out
197
+ [14:32:19] ℹ Code length: 234 characters
198
+
199
+ [14:32:19] ℹ ⚙️ Executing in Cloudflare Sandbox...
200
+ [14:32:21] ✓ Sandbox execution completed in 1856ms
201
+ [14:32:21] ℹ Exit code: 0 (success)
202
+ [14:32:21] ℹ Output length: 3 characters
203
+
204
+ ============================================================
205
+ 📊 PERFORMANCE METRICS
206
+ ============================================================
207
+
208
+ Total Execution Time: 4123ms
209
+ ├─ Code Generation: 2147ms
210
+ └─ Sandbox Execution: 1856ms
211
+ Memory Usage: 48MB
212
+
213
+ Status: Success ✓
214
+ ============================================================
215
+ ```
216
+
217
+ ## 🎯 Debugging Specific Scenarios
218
+
219
+ ### 1. Code Generation Issues
220
+ ```bash
221
+ # Use monitor to see exact Claude API interaction
222
+ node monitor.ts "Complex prompt that might fail"
223
+
224
+ # Look for:
225
+ # - Token usage (may hit limits)
226
+ # - Generated code preview
227
+ # - Model used (should be claude-sonnet-4-5)
228
+ ```
229
+
230
+ ### 2. Sandbox Execution Problems
231
+ ```bash
232
+ # Check worker logs while testing
233
+ npx wrangler tail &
234
+ node launcher.ts "Test prompt"
235
+
236
+ # Look for:
237
+ # - Sandbox creation errors
238
+ # - File write failures
239
+ # - Python execution errors
240
+ ```
241
+
242
+ ### 3. Performance Issues
243
+ ```bash
244
+ # Use monitor to identify bottlenecks
245
+ node monitor.ts "Your prompt"
246
+
247
+ # Compare metrics:
248
+ # - Code Generation Time (Claude API)
249
+ # - Sandbox Execution Time (Cloudflare)
250
+ # - Total Round Trip Time
251
+ ```
252
+
253
+ ### 4. Network/Deployment Issues
254
+ ```bash
255
+ # Check deployments
256
+ npx wrangler deployments list
257
+
258
+ # View recent logs
259
+ npx wrangler tail --format=pretty
260
+
261
+ # Test worker health
262
+ curl -v https://your-worker.workers.dev
263
+ ```
264
+
265
+ ## 🛠 Advanced Configuration
266
+
267
+ ### Enable Debug Mode:
268
+ ```bash
269
+ # In wrangler.toml
270
+ [env.development]
271
+ vars = { DEBUG = "true" }
272
+
273
+ # Or in .dev.vars for local development
274
+ DEBUG=true
275
+ ANTHROPIC_API_KEY=your_key
276
+ ```
277
+
278
+ ### Custom Timeouts:
279
+ ```typescript
280
+ // In src/index.ts
281
+ const result = await sandbox.exec('python /tmp/code.py', {
282
+ timeout: 60000, // 60 seconds
283
+ });
284
+ ```
285
+
286
+ ### Verbose Logging:
287
+ ```bash
288
+ # Set log level
289
+ export WRANGLER_LOG=debug
290
+
291
+ # Run with verbose output
292
+ npx wrangler deploy --verbose
293
+ ```
294
+
295
+ ## 📋 Debugging Checklist
296
+
297
+ ### Before Reporting an Issue:
298
+ - [ ] Cloudflare Workers account active (Paid plan if using Durable Objects)
299
+ - [ ] Anthropic API key valid and has credits
300
+ - [ ] Worker deployed successfully (`npx wrangler deploy`)
301
+ - [ ] Waited 2-3 minutes after first deployment
302
+ - [ ] Containers provisioned (`npx wrangler containers list`)
303
+ - [ ] Secrets configured (`npx wrangler secret list`)
304
+ - [ ] Docker running (for local development)
305
+ - [ ] Used monitor tool for detailed metrics
306
+ - [ ] Checked worker logs (`npx wrangler tail`)
307
+ - [ ] Tested with simple prompt first
308
+
309
+ ### Information to Include in Bug Reports:
310
+ - Full monitor output showing timestamps and metrics
311
+ - Worker URL or local development environment
312
+ - Exact prompt that caused the issue
313
+ - Components installed (if applicable)
314
+ - Worker logs from `npx wrangler tail`
315
+ - Container status from `npx wrangler containers list`
316
+ - Error messages with full stack traces
317
+ - Node.js and Wrangler versions
318
+
319
+ ## 🚀 Performance Optimization Tips
320
+
321
+ ### 1. Minimize Code Generation Time
322
+ ```typescript
323
+ // Be specific to reduce Claude's thinking time
324
+ const prompt = `Generate a single Python function to calculate factorial.
325
+ Use recursion. Include only the function, no tests.`;
326
+ ```
327
+
328
+ ### 2. Use Code Interpreter API
329
+ ```typescript
330
+ // Faster than exec for Python
331
+ import { getCodeInterpreter } from '@cloudflare/sandbox';
332
+ const interpreter = getCodeInterpreter(env.Sandbox, userId);
333
+ const result = await interpreter.notebook.execCell(pythonCode);
334
+ ```
335
+
336
+ ### 3. Implement Caching
337
+ ```typescript
338
+ // Cache generated code for common prompts
339
+ const cacheKey = `code:${hashPrompt(prompt)}`;
340
+ let code = await env.CACHE.get(cacheKey);
341
+ if (!code) {
342
+ code = await generateCode(prompt);
343
+ await env.CACHE.put(cacheKey, code, { expirationTtl: 3600 });
344
+ }
345
+ ```
346
+
347
+ ### 4. Stream Responses
348
+ ```typescript
349
+ // Stream output for better perceived performance
350
+ return new Response(
351
+ new ReadableStream({
352
+ async start(controller) {
353
+ const result = await sandbox.exec(command, {
354
+ onStdout: (data) => controller.enqueue(encoder.encode(data)),
355
+ });
356
+ controller.close();
357
+ },
358
+ })
359
+ );
360
+ ```
361
+
362
+ ## 🔗 Useful Commands Reference
363
+
364
+ ### Deployment & Management
365
+ ```bash
366
+ # Deploy worker
367
+ npx wrangler deploy
368
+
369
+ # Deploy to specific environment
370
+ npx wrangler deploy --env production
371
+
372
+ # Rollback deployment
373
+ npx wrangler rollback
374
+
375
+ # Delete deployment
376
+ npx wrangler delete
377
+ ```
378
+
379
+ ### Secrets Management
380
+ ```bash
381
+ # Add secret
382
+ npx wrangler secret put SECRET_NAME
383
+
384
+ # List secrets
385
+ npx wrangler secret list
386
+
387
+ # Delete secret
388
+ npx wrangler secret delete SECRET_NAME
389
+ ```
390
+
391
+ ### Local Development
392
+ ```bash
393
+ # Start dev server
394
+ npm run dev
395
+
396
+ # Start with specific port
397
+ npx wrangler dev --port 3000
398
+
399
+ # Start with remote Durable Objects
400
+ npx wrangler dev --remote
401
+ ```
402
+
403
+ ### Monitoring & Logs
404
+ ```bash
405
+ # Tail logs in real-time
406
+ npx wrangler tail
407
+
408
+ # Tail with pretty formatting
409
+ npx wrangler tail --format=pretty
410
+
411
+ # Tail specific deployment
412
+ npx wrangler tail --deployment-id <id>
413
+
414
+ # Filter logs
415
+ npx wrangler tail --status error
416
+ ```
417
+
418
+ ### Container Management
419
+ ```bash
420
+ # List containers
421
+ npx wrangler containers list
422
+
423
+ # Get container details
424
+ npx wrangler containers describe <container-id>
425
+ ```
426
+
427
+ ## 💡 Tips & Best Practices
428
+
429
+ 1. **Always test locally first**: Use `npm run dev` before deploying
430
+ 2. **Monitor metrics**: Use the monitor tool to track performance
431
+ 3. **Check logs regularly**: Set up `npx wrangler tail` during testing
432
+ 4. **Use environment-specific configs**: Separate dev/prod in wrangler.toml
433
+ 5. **Implement error handling**: Catch and log all errors properly
434
+ 6. **Set appropriate timeouts**: Balance between user experience and resource usage
435
+ 7. **Use Durable Objects wisely**: Only for stateful operations
436
+ 8. **Cache aggressively**: Reduce API calls with smart caching
437
+ 9. **Stream when possible**: Better UX for long operations
438
+ 10. **Version your deployments**: Tag releases for easy rollback
439
+
440
+ ---
441
+
442
+ **With these tools and techniques, you can effectively debug and optimize your Cloudflare sandbox implementation.**