computesdk 1.0.2 → 1.1.1

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.
package/README.md CHANGED
@@ -1,135 +1,246 @@
1
- # ComputeSDK
1
+ <div align="center">
2
+ <img src="https://www.computesdk.com/_astro/hv_main_logo_light.CpYMD9-V.svg" alt="ComputeSDK" width="300" />
3
+ </div>
2
4
 
3
- A unified abstraction layer for executing code in secure, isolated sandboxed environments across multiple cloud providers.
5
+ <div align="center">
6
+ <strong>A free and open-source toolkit for running other people's code in your applications.</strong>
7
+ </div>
4
8
 
5
- Similar to how Vercel's AI SDK abstracts different LLM providers, ComputeSDK abstracts different compute sandbox providers into a single, consistent TypeScript interface.
9
+ <div align="center">
6
10
 
7
- ## Features
11
+ [![npm version](https://badge.fury.io/js/computesdk.svg)](https://badge.fury.io/js/computesdk)
12
+ [![TypeScript](https://img.shields.io/badge/TypeScript-100%25-blue.svg)](https://www.typescriptlang.org/)
13
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
14
+ [![Documentation](https://img.shields.io/badge/docs-computesdk.com-blue)](https://computesdk.com)
15
+
16
+ </div>
8
17
 
9
- - **Unified API** - Single interface for multiple sandbox providers
10
- - **Auto-detection** - Automatically detects and uses available providers
11
- - **Provider-agnostic** - Switch between providers without code changes
12
- - **Type-safe** - Full TypeScript support with comprehensive type definitions
13
- - **Extensible** - Easy to add new providers
14
- - **Production-ready** - Built for real-world applications
18
+ ---
15
19
 
16
- ## Supported Providers
20
+ ## What is ComputeSDK?
17
21
 
18
- - **E2B** - Python-focused code execution with templates
19
- - **Vercel** - Node.js and Python execution on Vercel infrastructure
20
- - **Cloudflare** - Edge computing with Cloudflare Workers and Durable Objects
21
- - **Fly.io** - Fast boot containers (community contribution target)
22
+ ComputeSDK is a free and open-source toolkit for running other people's code in your applications. Think of it as the "AI SDK for compute" - providing a consistent TypeScript interface whether you're using E2B, Vercel, or Daytona.
22
23
 
23
- ## Installation
24
+ **Why ComputeSDK?**
25
+ - 🔄 **Provider-agnostic** - Switch between E2B, Vercel, Daytona and more (coming soon) without code changes
26
+ - 🛡️ **Security-first** - Isolated sandboxes protect your infrastructure
27
+ - ⚡ **Developer experience** - Simple, TypeScript-native API
28
+ - 🌍 **Production-ready** - Used by teams building the next generation of developer tools
29
+
30
+ **Perfect for building:**
31
+ - **Code execution platforms** - Run user-submitted code safely
32
+ - **Educational tools** - Interactive coding environments
33
+ - **Data analysis applications** - Process code with full filesystem access
34
+ - **AI-powered development tools** - Let AI agents write and execute code
35
+ - **Testing & CI/CD systems** - Isolated test environments
36
+
37
+ ## Features
38
+
39
+ - 🚀 **Multi-provider support** - E2B, Vercel, Daytona
40
+ - 📁 **Filesystem operations** - Read, write, create directories across providers
41
+ - 🖥️ **Terminal support** - Interactive PTY terminals (E2B)
42
+ - ⚡ **Command execution** - Run shell commands directly
43
+ - 🛡️ **Type-safe** - Full TypeScript support with comprehensive error handling
44
+ - 📦 **Modular** - Install only the providers you need
45
+ - 🔧 **Extensible** - Easy to add custom providers
46
+ - 🌐 **Web Framework Integration** - Built-in request handlers for Next.js, Nuxt, SvelteKit, etc.
47
+ - 🎨 **Frontend Integration** - Client-side hooks and utilities via @computesdk/ui
48
+
49
+ ## Get Started in 30 Seconds
24
50
 
25
51
  ```bash
52
+ # Install the core SDK
26
53
  npm install computesdk
54
+
55
+ # Add your preferred provider
56
+ npm install @computesdk/e2b # For data science and Python
57
+ npm install @computesdk/vercel # For web-scale Node.js/Python
58
+ npm install @computesdk/daytona # For development workspaces
59
+
60
+ # Frontend integration (optional)
61
+ npm install @computesdk/ui # React hooks and utilities
27
62
  ```
28
63
 
29
- ### Install Provider Packages
64
+ Set your environment variables and you're ready to go:
30
65
 
31
66
  ```bash
32
- # Install the providers you need
33
- npm install @computesdk/e2b # E2B provider
34
- npm install @computesdk/vercel # Vercel provider
35
- npm install @computesdk/cloudflare # Cloudflare provider
67
+ export E2B_API_KEY=your_api_key
68
+ # or VERCEL_TOKEN=your_token
69
+ # or DAYTONA_API_KEY=your_key
36
70
  ```
37
71
 
38
72
  ## Quick Start
39
73
 
40
- ### Auto-detection (Recommended)
41
-
42
74
  ```typescript
43
- import { ComputeSDK } from 'computesdk';
75
+ import { compute } from 'computesdk';
76
+ import { e2b } from '@computesdk/e2b';
44
77
 
45
- // Automatically detects and uses available providers
46
- const sdk = new ComputeSDK();
47
- const sandbox = await sdk.createSandbox();
78
+ // Set default provider
79
+ compute.setConfig({
80
+ provider: e2b({ apiKey: process.env.E2B_API_KEY })
81
+ });
48
82
 
49
- const result = await sandbox.execute('print("Hello from ComputeSDK!")');
50
- console.log(result.stdout); // "Hello from ComputeSDK!"
83
+ // Create a sandbox
84
+ const sandbox = await compute.sandbox.create({});
51
85
 
52
- await sandbox.kill();
86
+ // Execute code
87
+ const result = await sandbox.runCode('print("Hello World!")');
88
+ console.log(result.stdout); // "Hello World!"
89
+
90
+ // Clean up
91
+ await compute.sandbox.destroy(sandbox.sandboxId);
53
92
  ```
54
93
 
55
- ### Provider-specific Usage
94
+ ## Provider Setup
95
+
96
+ ### E2B - Full Development Environment
97
+
98
+ E2B provides full filesystem and terminal support:
99
+
100
+ ```bash
101
+ export E2B_API_KEY=e2b_your_api_key_here
102
+ ```
56
103
 
57
104
  ```typescript
58
- import { executeSandbox } from 'computesdk';
105
+ import { compute } from 'computesdk';
59
106
  import { e2b } from '@computesdk/e2b';
60
107
 
61
- // Execute with specific provider
62
- const result = await executeSandbox({
63
- sandbox: e2b(),
64
- code: 'print("Hello from E2B!")',
65
- runtime: 'python'
108
+ compute.setConfig({
109
+ provider: e2b({ apiKey: process.env.E2B_API_KEY })
66
110
  });
67
111
 
68
- console.log(result.stdout);
112
+ const sandbox = await compute.sandbox.create({});
113
+
114
+ // Execute Python with data science libraries
115
+ const result = await sandbox.runCode(`
116
+ import pandas as pd
117
+ import numpy as np
118
+
119
+ data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
120
+ df = pd.DataFrame(data)
121
+ print(df)
122
+ print(f"Sum: {df.sum().sum()}")
123
+ `);
124
+
125
+ // Interactive terminal support
126
+ const terminal = await sandbox.terminal.create({
127
+ command: 'bash',
128
+ cols: 80,
129
+ rows: 24
130
+ });
69
131
  ```
70
132
 
71
- ### Multiple Providers
133
+ ### Vercel - Scalable Serverless Execution
134
+
135
+ Vercel provides reliable execution with filesystem support:
136
+
137
+ ```bash
138
+ # Method 1: OIDC Token (Recommended)
139
+ vercel env pull # Downloads VERCEL_OIDC_TOKEN
140
+
141
+ # Method 2: Traditional
142
+ export VERCEL_TOKEN=your_vercel_token_here
143
+ export VERCEL_TEAM_ID=your_team_id_here
144
+ export VERCEL_PROJECT_ID=your_project_id_here
145
+ ```
72
146
 
73
147
  ```typescript
74
- import { executeSandbox } from 'computesdk';
75
- import { e2b } from '@computesdk/e2b';
148
+ import { compute } from 'computesdk';
76
149
  import { vercel } from '@computesdk/vercel';
77
- import { cloudflare } from '@computesdk/cloudflare';
78
-
79
- // Try different providers for different use cases
80
- const providers = [
81
- { name: 'E2B', provider: e2b() },
82
- { name: 'Vercel', provider: vercel() },
83
- { name: 'Cloudflare', provider: cloudflare({ env }) }
84
- ];
85
-
86
- for (const { name, provider } of providers) {
87
- try {
88
- const result = await executeSandbox({
89
- sandbox: provider,
90
- code: 'print("Hello from ' + name + '!")'
91
- });
92
- console.log(`${name}:`, result.stdout);
93
- } catch (error) {
94
- console.error(`${name} failed:`, error.message);
95
- }
96
- }
150
+
151
+ compute.setConfig({
152
+ provider: vercel({ runtime: 'node' })
153
+ });
154
+
155
+ const sandbox = await compute.sandbox.create({});
156
+
157
+ // Execute Node.js or Python
158
+ const result = await sandbox.runCode(`
159
+ console.log('Node.js version:', process.version);
160
+ console.log('Hello from Vercel!');
161
+ `);
162
+
163
+ // Up to 45 minutes execution time
164
+ // Global infrastructure deployment
97
165
  ```
98
166
 
99
- ## API Reference
167
+ ### Daytona - Development Workspaces
100
168
 
101
- ### `ComputeSDK`
169
+ Daytona provides development workspace environments:
102
170
 
103
- Main SDK class for auto-detection and management.
171
+ ```bash
172
+ export DAYTONA_API_KEY=your_daytona_api_key_here
173
+ ```
104
174
 
105
175
  ```typescript
106
- const sdk = new ComputeSDK(options?: ComputeSDKOptions);
107
- ```
176
+ import { compute } from 'computesdk';
177
+ import { daytona } from '@computesdk/daytona';
108
178
 
109
- #### Methods
179
+ compute.setConfig({
180
+ provider: daytona({ apiKey: process.env.DAYTONA_API_KEY })
181
+ });
110
182
 
111
- - `createSandbox(config?: SandboxConfig)` - Creates a sandbox using auto-detection
112
- - `getAvailableProviders()` - Returns list of available providers
113
- - `registerProvider(name: string, provider: ComputeSpecification)` - Registers a custom provider
183
+ const sandbox = await compute.sandbox.create({});
114
184
 
115
- ### `executeSandbox(config: ExecutionConfig)`
185
+ // Execute in development workspace
186
+ const result = await sandbox.runCode(`
187
+ print('Hello from Daytona!')
188
+ import sys
189
+ print(f'Python version: {sys.version}')
190
+ `);
191
+ ```
116
192
 
117
- Utility function for one-off code execution.
193
+ ## Core API
194
+
195
+ ### Configuration
118
196
 
119
197
  ```typescript
120
- interface ExecutionConfig {
121
- sandbox: ComputeSpecification;
122
- code: string;
123
- runtime?: 'python' | 'node';
124
- timeout?: number;
125
- }
198
+ import { compute } from 'computesdk';
199
+
200
+ // Set default provider
201
+ compute.setConfig({ provider: myProvider });
202
+
203
+ // Get current config
204
+ const config = compute.getConfig();
205
+
206
+ // Clear config
207
+ compute.clearConfig();
126
208
  ```
127
209
 
128
- ### `ExecutionResult`
210
+ ### Sandbox Management
211
+
212
+ ```typescript
213
+ // Create sandbox with explicit provider
214
+ const sandbox = await compute.sandbox.create({
215
+ provider: e2b({ apiKey: 'your-key' }),
216
+ options: { runtime: 'python', timeout: 300000 }
217
+ });
218
+
219
+ // Create sandbox with default provider
220
+ const sandbox = await compute.sandbox.create({
221
+ options: { runtime: 'python' }
222
+ });
223
+
224
+ // Get existing sandbox
225
+ const sandbox = await compute.sandbox.getById('sandbox-id');
129
226
 
130
- Result object returned by all execution methods.
227
+ // List all sandboxes
228
+ const sandboxes = await compute.sandbox.list();
229
+
230
+ // Destroy sandbox
231
+ await compute.sandbox.destroy('sandbox-id');
232
+ ```
233
+
234
+ ### Code Execution
131
235
 
132
236
  ```typescript
237
+ // Run code
238
+ const result = await sandbox.runCode('print("Hello")', 'python');
239
+
240
+ // Run shell command
241
+ const result = await sandbox.runCommand('ls', ['-la']);
242
+
243
+ // Result structure
133
244
  interface ExecutionResult {
134
245
  stdout: string;
135
246
  stderr: string;
@@ -140,219 +251,383 @@ interface ExecutionResult {
140
251
  }
141
252
  ```
142
253
 
143
- ### `SandboxInfo`
144
-
145
- Information about a sandbox instance.
254
+ ### Filesystem Operations
146
255
 
147
256
  ```typescript
148
- interface SandboxInfo {
149
- id: string;
150
- provider: string;
151
- runtime: string;
152
- status: 'running' | 'stopped';
153
- createdAt: Date;
154
- timeout: number;
155
- metadata?: Record<string, any>;
156
- }
257
+ // Write file
258
+ await sandbox.filesystem.writeFile('/tmp/hello.py', 'print("Hello")');
259
+
260
+ // Read file
261
+ const content = await sandbox.filesystem.readFile('/tmp/hello.py');
262
+
263
+ // Create directory
264
+ await sandbox.filesystem.mkdir('/tmp/mydir');
265
+
266
+ // List directory
267
+ const files = await sandbox.filesystem.readdir('/tmp');
268
+
269
+ // Check if exists
270
+ const exists = await sandbox.filesystem.exists('/tmp/hello.py');
271
+
272
+ // Remove file/directory
273
+ await sandbox.filesystem.remove('/tmp/hello.py');
157
274
  ```
158
275
 
159
- ## Configuration
276
+ ### Terminal Operations
277
+
278
+ ```typescript
279
+ // Create terminal (E2B only)
280
+ const terminal = await sandbox.terminal.create({
281
+ command: 'bash',
282
+ cols: 80,
283
+ rows: 24
284
+ });
160
285
 
161
- ### Environment Variables
286
+ // Write to terminal
287
+ await terminal.write('ls -la\n');
162
288
 
163
- Each provider requires specific environment variables:
289
+ // Resize terminal
290
+ await terminal.resize(120, 30);
164
291
 
165
- ```bash
166
- # E2B
167
- E2B_API_KEY=your_e2b_api_key
292
+ // Kill terminal
293
+ await terminal.kill();
168
294
 
169
- # Vercel
170
- VERCEL_TOKEN=your_vercel_token
171
- VERCEL_TEAM_ID=your_team_id
172
- VERCEL_PROJECT_ID=your_project_id
295
+ // List terminals
296
+ const terminals = await sandbox.terminal.list();
173
297
 
174
- # Cloudflare (Workers environment only)
175
- # Requires Durable Object bindings in wrangler.toml
298
+ // Get terminal by ID
299
+ const terminal = await sandbox.terminal.getById('terminal-id');
176
300
  ```
177
301
 
178
- ### Provider Configuration
302
+ ## Web Framework Integration
303
+
304
+ ComputeSDK provides built-in request handlers for web frameworks:
179
305
 
180
306
  ```typescript
181
- import { ComputeSDK } from 'computesdk';
307
+ import { handleComputeRequest } from 'computesdk';
182
308
  import { e2b } from '@computesdk/e2b';
183
- import { vercel } from '@computesdk/vercel';
184
309
 
185
- const sdk = new ComputeSDK({
186
- preferredProviders: ['e2b', 'vercel'], // Order of preference
187
- timeout: 300000, // Global timeout (5 minutes)
188
- retryAttempts: 3 // Retry failed executions
189
- });
310
+ // Next.js API route
311
+ export async function POST(request: Request) {
312
+ return handleComputeRequest({
313
+ request,
314
+ provider: e2b({ apiKey: process.env.E2B_API_KEY })
315
+ });
316
+ }
190
317
 
191
- // Or configure providers individually
192
- const customSandbox = e2b({
193
- timeout: 600000, // 10 minutes
194
- template: 'python-data-science'
318
+ // Client usage
319
+ const response = await fetch('/api/compute', {
320
+ method: 'POST',
321
+ headers: { 'Content-Type': 'application/json' },
322
+ body: JSON.stringify({
323
+ action: 'compute.sandbox.runCode',
324
+ code: 'print("Hello from web!")',
325
+ runtime: 'python'
326
+ })
195
327
  });
328
+
329
+ const result = await response.json();
330
+ console.log(result.result.stdout);
331
+ ```
332
+
333
+ ### Supported Actions
334
+
335
+ - `compute.sandbox.create` - Create new sandbox
336
+ - `compute.sandbox.destroy` - Destroy sandbox
337
+ - `compute.sandbox.getInfo` - Get sandbox information
338
+ - `compute.sandbox.list` - List all sandboxes
339
+ - `compute.sandbox.runCode` - Execute code
340
+ - `compute.sandbox.runCommand` - Run shell command
341
+ - `compute.sandbox.filesystem.readFile` - Read file
342
+ - `compute.sandbox.filesystem.writeFile` - Write file
343
+ - `compute.sandbox.filesystem.mkdir` - Create directory
344
+ - `compute.sandbox.filesystem.readdir` - List directory
345
+ - `compute.sandbox.filesystem.exists` - Check if path exists
346
+ - `compute.sandbox.filesystem.remove` - Remove file/directory
347
+ - `compute.sandbox.terminal.create` - Create terminal
348
+ - `compute.sandbox.terminal.list` - List terminals
349
+ - `compute.sandbox.terminal.getById` - Get terminal by ID
350
+ - `compute.sandbox.terminal.destroy` - Destroy terminal
351
+ - `compute.sandbox.terminal.write` - Write to terminal
352
+ - `compute.sandbox.terminal.resize` - Resize terminal
353
+ - `compute.sandbox.terminal.kill` - Kill terminal
354
+
355
+ ## Frontend Integration
356
+
357
+ Use `@computesdk/ui` for React hooks and utilities:
358
+
359
+ ```typescript
360
+ import { useCompute } from '@computesdk/ui';
361
+
362
+ function CodeExecutor() {
363
+ const compute = useCompute({
364
+ apiEndpoint: '/api/compute',
365
+ defaultRuntime: 'python'
366
+ });
367
+
368
+ const executeCode = async () => {
369
+ const sandbox = await compute.sandbox.create();
370
+ const result = await sandbox.runCode('print("Hello World!")');
371
+ console.log(result.result?.stdout);
372
+ await sandbox.destroy();
373
+ };
374
+
375
+ return (
376
+ <button onClick={executeCode}>
377
+ Execute Code
378
+ </button>
379
+ );
380
+ }
381
+ ```
382
+
383
+ ## Error Handling
384
+
385
+ ```typescript
386
+ try {
387
+ const sandbox = await compute.sandbox.create({});
388
+ const result = await sandbox.runCode('invalid code');
389
+ } catch (error) {
390
+ console.error('Execution failed:', error.message);
391
+ }
196
392
  ```
197
393
 
198
394
  ## Examples
199
395
 
200
- ### Data Processing
396
+ ### Data Science with E2B
201
397
 
202
398
  ```typescript
203
- import { executeSandbox } from 'computesdk';
399
+ import { compute } from 'computesdk';
204
400
  import { e2b } from '@computesdk/e2b';
205
401
 
206
- const result = await executeSandbox({
207
- sandbox: e2b(),
208
- code: `
402
+ compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY }) });
403
+
404
+ const sandbox = await compute.sandbox.create({});
405
+
406
+ // Create project structure
407
+ await sandbox.filesystem.mkdir('/analysis');
408
+ await sandbox.filesystem.mkdir('/analysis/data');
409
+ await sandbox.filesystem.mkdir('/analysis/output');
410
+
411
+ // Write input data
412
+ const csvData = `name,age,city
413
+ Alice,25,New York
414
+ Bob,30,San Francisco
415
+ Charlie,35,Chicago`;
416
+
417
+ await sandbox.filesystem.writeFile('/analysis/data/people.csv', csvData);
418
+
419
+ // Process data with Python
420
+ const result = await sandbox.runCode(`
209
421
  import pandas as pd
210
- import numpy as np
422
+ import matplotlib.pyplot as plt
423
+
424
+ # Read data
425
+ df = pd.read_csv('/analysis/data/people.csv')
426
+ print("Data loaded:")
427
+ print(df)
428
+
429
+ # Calculate statistics
430
+ avg_age = df['age'].mean()
431
+ print(f"\\nAverage age: {avg_age}")
432
+
433
+ # Create visualization
434
+ plt.figure(figsize=(8, 6))
435
+ plt.bar(df['name'], df['age'])
436
+ plt.title('Age by Person')
437
+ plt.xlabel('Name')
438
+ plt.ylabel('Age')
439
+ plt.savefig('/analysis/output/age_chart.png')
440
+ print("\\nChart saved to /analysis/output/age_chart.png")
441
+
442
+ # Save results
443
+ results = {
444
+ 'total_people': len(df),
445
+ 'average_age': avg_age,
446
+ 'cities': df['city'].unique().tolist()
447
+ }
211
448
 
212
- # Create sample data
213
- data = pd.DataFrame({
214
- 'sales': [100, 150, 200, 120, 180],
215
- 'profit': [20, 30, 45, 25, 40]
216
- })
217
-
218
- # Calculate metrics
219
- total_sales = data['sales'].sum()
220
- avg_profit = data['profit'].mean()
221
- profit_margin = (data['profit'].sum() / total_sales) * 100
222
-
223
- print(f"Total Sales: ${total_sales}")
224
- print(f"Average Profit: ${avg_profit:.2f}")
225
- print(f"Profit Margin: {profit_margin:.1f}%")
226
- `
227
- });
449
+ import json
450
+ with open('/analysis/output/results.json', 'w') as f:
451
+ json.dump(results, f, indent=2)
452
+
453
+ print("Results saved!")
454
+ `);
228
455
 
229
456
  console.log(result.stdout);
457
+
458
+ // Read the results
459
+ const results = await sandbox.filesystem.readFile('/analysis/output/results.json');
460
+ console.log('Analysis results:', JSON.parse(results));
461
+
462
+ await compute.sandbox.destroy(sandbox.sandboxId);
230
463
  ```
231
464
 
232
- ### Web API Simulation
465
+ ### Cross-Provider Data Processing
233
466
 
234
467
  ```typescript
235
- import { executeSandbox } from 'computesdk';
468
+ import { compute } from 'computesdk';
236
469
  import { vercel } from '@computesdk/vercel';
470
+ import { daytona } from '@computesdk/daytona';
471
+
472
+ async function processData(provider: any) {
473
+ compute.setConfig({ provider });
474
+
475
+ const sandbox = await compute.sandbox.create({});
476
+
477
+ // Create workspace
478
+ await sandbox.filesystem.mkdir('/workspace');
479
+
480
+ // Write input data
481
+ await sandbox.filesystem.writeFile('/workspace/input.json',
482
+ JSON.stringify({ numbers: [1, 2, 3, 4, 5] })
483
+ );
484
+
485
+ // Process with code execution
486
+ const result = await sandbox.runCode(`
487
+ import json
237
488
 
238
- const result = await executeSandbox({
239
- sandbox: vercel({ runtime: 'node' }),
240
- code: `
241
- const express = require('express');
242
- const app = express();
489
+ # Read input
490
+ with open('/workspace/input.json', 'r') as f:
491
+ data = json.load(f)
243
492
 
244
- // Simulate API routes
245
- const routes = {
246
- '/api/users': { users: ['Alice', 'Bob', 'Charlie'] },
247
- '/api/stats': { active: 150, total: 1000 }
248
- };
493
+ # Process
494
+ numbers = data['numbers']
495
+ result = {
496
+ 'sum': sum(numbers),
497
+ 'average': sum(numbers) / len(numbers),
498
+ 'count': len(numbers)
499
+ }
249
500
 
250
- // Process request
251
- const path = '/api/users';
252
- const response = routes[path] || { error: 'Not found' };
501
+ # Write output
502
+ with open('/workspace/output.json', 'w') as f:
503
+ json.dump(result, f, indent=2)
504
+
505
+ print("Processing complete!")
506
+ `);
507
+
508
+ // Read results
509
+ const output = await sandbox.filesystem.readFile('/workspace/output.json');
510
+ await compute.sandbox.destroy(sandbox.sandboxId);
511
+
512
+ return JSON.parse(output);
513
+ }
253
514
 
254
- console.log('API Response:', JSON.stringify(response, null, 2));
255
- `
256
- });
515
+ // Use with different providers
516
+ const vercelResult = await processData(vercel({ runtime: 'python' }));
517
+ console.log('Vercel result:', vercelResult);
257
518
 
258
- console.log(result.stdout);
519
+ const daytonaResult = await processData(daytona({ runtime: 'python' }));
520
+ console.log('Daytona result:', daytonaResult);
259
521
  ```
260
522
 
261
- ### Edge Computing
523
+ ## Provider Packages
262
524
 
263
- ```typescript
264
- import { executeSandbox } from 'computesdk';
265
- import { cloudflare } from '@computesdk/cloudflare';
266
-
267
- // Within a Cloudflare Worker
268
- export default {
269
- async fetch(request: Request, env: Env): Promise<Response> {
270
- const result = await executeSandbox({
271
- sandbox: cloudflare({ env }),
272
- code: `
273
- import json
274
- from datetime import datetime
525
+ ComputeSDK uses separate provider packages:
275
526
 
276
- # Process request data
277
- data = {
278
- "timestamp": datetime.now().isoformat(),
279
- "region": "auto",
280
- "processed": True
281
- }
527
+ ```bash
528
+ npm install @computesdk/e2b # E2B provider
529
+ npm install @computesdk/vercel # Vercel provider
530
+ npm install @computesdk/daytona # Daytona provider
531
+ ```
532
+
533
+ Each provider implements the same interface but may support different capabilities (filesystem, terminal, etc.).
282
534
 
283
- print(json.dumps(data))
284
- `
285
- });
535
+ ## Custom Providers
286
536
 
287
- return new Response(result.stdout, {
288
- headers: { 'Content-Type': 'application/json' }
289
- });
537
+ Create custom providers using the factory:
538
+
539
+ ```typescript
540
+ import { createProvider } from 'computesdk';
541
+
542
+ const myProvider = createProvider({
543
+ name: 'my-provider',
544
+ methods: {
545
+ sandbox: {
546
+ create: async (config, options) => {
547
+ // Implementation
548
+ },
549
+ getById: async (config, id) => {
550
+ // Implementation
551
+ },
552
+ list: async (config) => {
553
+ // Implementation
554
+ },
555
+ destroy: async (config, id) => {
556
+ // Implementation
557
+ }
558
+ }
290
559
  }
291
- };
560
+ });
292
561
  ```
293
562
 
294
- ## Error Handling
563
+ ## TypeScript Support
295
564
 
296
- ComputeSDK provides comprehensive error handling:
565
+ ComputeSDK is fully typed with comprehensive TypeScript definitions:
297
566
 
298
567
  ```typescript
299
- import {
300
- ExecutionError,
301
- TimeoutError,
302
- AuthenticationError,
303
- QuotaExceededError
568
+ import type {
569
+ Sandbox,
570
+ Provider,
571
+ ExecutionResult,
572
+ ComputeConfig,
573
+ Runtime
304
574
  } from 'computesdk';
305
-
306
- try {
307
- const result = await executeSandbox({
308
- sandbox: e2b(),
309
- code: 'print("Hello World")'
310
- });
311
- } catch (error) {
312
- if (error instanceof TimeoutError) {
313
- console.error('Execution timed out');
314
- } else if (error instanceof AuthenticationError) {
315
- console.error('Check your API credentials');
316
- } else if (error instanceof QuotaExceededError) {
317
- console.error('API quota exceeded');
318
- } else if (error instanceof ExecutionError) {
319
- console.error('Code execution failed:', error.stderr);
320
- } else {
321
- console.error('Unknown error:', error.message);
322
- }
323
- }
324
575
  ```
325
576
 
326
577
  ## Provider Comparison
327
578
 
328
- | Provider | Runtimes | Max Timeout | Use Cases |
329
- |----------|----------|-------------|-----------|
330
- | E2B | Python | 5 minutes | Data science, AI/ML |
331
- | Vercel | Node.js, Python | 45 minutes | Web apps, APIs |
332
- | Cloudflare | Python, Node.js | 30 seconds | Edge computing, real-time |
333
- | Fly.io | Custom | Variable | Custom containers |
579
+ | Provider | Code Execution | Filesystem | Terminal | Use Cases |
580
+ |----------|----------------|------------|----------|-----------|
581
+ | **E2B** | Python, Node.js | Full | ✅ PTY | Data science, AI/ML, interactive development |
582
+ | **Vercel** | Node.js, Python | Full | ❌ | Web apps, APIs, serverless functions |
583
+ | **Daytona** | Python, Node.js | Full | | Development workspaces, custom environments |
334
584
 
335
- ## Contributing
585
+ ### Key Differences
336
586
 
337
- We welcome contributions! Please see our [Contributing Guide](https://github.com/computesdk/computesdk/blob/main/CONTRIBUTING.md) for details.
587
+ - **E2B**: Full development environment with data science libraries and interactive terminals
588
+ - **Vercel**: Ephemeral sandboxes optimized for serverless execution (up to 45 minutes)
589
+ - **Daytona**: Development workspaces with persistent environments
338
590
 
339
- ### Adding New Providers
591
+ ## Examples
340
592
 
341
- 1. Implement the `ComputeSpecification` interface
342
- 2. Add comprehensive tests
343
- 3. Include documentation and examples
344
- 4. Submit a pull request
593
+ Check out the [examples directory](./examples) for complete implementations with different web frameworks:
345
594
 
346
- ## License
595
+ - [Next.js](./examples/nextjs)
596
+ - [Nuxt](./examples/nuxt)
597
+ - [SvelteKit](./examples/sveltekit)
598
+ - [Remix](./examples/remix)
599
+ - [Astro](./examples/astro)
347
600
 
348
- MIT - see [LICENSE](https://github.com/computesdk/computesdk/blob/main/LICENSE) for details.
601
+ ## Resources
349
602
 
350
- ## Support
603
+ - 📖 **[Full Documentation](https://computesdk.com)** - Complete guides and API reference
604
+ - 🚀 **[Getting Started](https://computesdk.com/getting-started)** - Quick setup guide
605
+ - 💡 **[Examples](./examples)** - Real-world usage examples
606
+ - 🎯 **[Providers](https://computesdk.com/providers)** - Provider-specific guides
607
+
608
+ ## Contributing
609
+
610
+ ComputeSDK is open source and welcomes contributions! Whether you're fixing bugs, adding features, or improving documentation, we'd love your help.
611
+
612
+ 1. Fork the repository
613
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
614
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
615
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
616
+ 5. Open a Pull Request
617
+
618
+ ## Community & Support
619
+
620
+ - 💬 **[GitHub Discussions](https://github.com/computesdk/computesdk/discussions)** - Ask questions and share ideas
621
+ - 🐛 **[GitHub Issues](https://github.com/computesdk/computesdk/issues)** - Report bugs and request features
622
+ - 📧 **[Contact Us](https://computesdk.com/contact)** - Get in touch with the team
623
+
624
+ ## License
351
625
 
352
- - [GitHub Issues](https://github.com/computesdk/computesdk/issues)
353
- - [Documentation](https://github.com/computesdk/computesdk)
354
- - [Examples](https://github.com/computesdk/computesdk/tree/main/examples)
626
+ MIT License - see the [LICENSE](LICENSE) file for details.
355
627
 
356
628
  ---
357
629
 
358
- Made with ❤️ by the ComputeSDK team
630
+ <div align="center">
631
+ <strong>Built with ❤️ by the ComputeSDK team</strong><br>
632
+ <a href="https://computesdk.com">computesdk.com</a>
633
+ </div>