This is the full developer documentation for ComputeSDK # Introduction > What is ComputeSDK and why use it? # What is ComputeSDK? [Section titled “What is ComputeSDK?”](#what-is-computesdk) 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. ## Why ComputeSDK? [Section titled “Why ComputeSDK?”](#why-computesdk) * 🔄 **Provider-agnostic** - Switch between E2B, Vercel, Daytona and more (coming soon) without code changes * 🛡️ **Security-first** - Isolated sandboxes protect your infrastructure * ⚡ **Developer experience** - Simple, TypeScript-native API * 🌍 **Production-ready** - Used by teams building the next generation of developer tools ## Perfect for building: [Section titled “Perfect for building:”](#perfect-for-building) * **Code execution platforms** - Run user-submitted code safely * **Educational tools** - Interactive coding environments * **Data analysis applications** - Process code with full filesystem access * **AI-powered development tools** - Let AI agents write and execute code * **Testing & CI/CD systems** - Isolated test environments ## Features [Section titled “Features”](#features) * 🚀 **Multi-provider support** - E2B, Vercel, Daytona * 📁 **Filesystem operations** - Read, write, create directories across providers * 🖥️ **Terminal support** - Interactive PTY terminals (E2B) * ⚡ **Command execution** - Run shell commands directly * 🛡️ **Type-safe** - Full TypeScript support with comprehensive error handling * 📦 **Modular** - Install only the providers you need * 🔧 **Extensible** - Easy to add custom providers * 🌐 **Web Framework Integration** - Built-in request handlers for Next.js, Nuxt, SvelteKit, etc. * 🎨 **Frontend Integration** - Client-side hooks and utilities via @computesdk/ui ## Quick Example [Section titled “Quick Example”](#quick-example) ``` import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; // Set default provider compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); // Create a sandbox const sandbox = await compute.sandbox.create({}); // Execute code const result = await sandbox.runCode('print("Hello World!")'); console.log(result.stdout); // "Hello World!" // Clean up await compute.sandbox.destroy(sandbox.sandboxId); ``` ## Next Steps [Section titled “Next Steps”](#next-steps) Ready to get started? Check out our [installation guide](./installation) or dive into the [quick start](./quick-start) to begin building with ComputeSDK. # Quick Start > Get up and running with ComputeSDK ## Quick Start [Section titled “Quick Start”](#quick-start) Welcome to ComputeSDK! This guide will get you up and running with secure, isolated code execution across multiple cloud providers using a unified TypeScript interface. ### Installation [Section titled “Installation”](#installation) ``` # Core SDK npm install computesdk # Provider packages (install only what you need) npm install @computesdk/e2b # E2B provider npm install @computesdk/vercel # Vercel provider npm install @computesdk/daytona # Daytona provider # Frontend integration (optional) npm install @computesdk/ui # React hooks and utilities ``` ### Basic Usage [Section titled “Basic Usage”](#basic-usage) ``` import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; // Set default provider compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); // Create a sandbox const sandbox = await compute.sandbox.create({}); // Execute code const result = await sandbox.runCode('print("Hello World!")'); console.log(result.stdout); // "Hello World!" // Clean up await compute.sandbox.destroy(sandbox.sandboxId); ``` ### Provider-Specific Setup [Section titled “Provider-Specific Setup”](#provider-specific-setup) #### E2B - Full Development Environment [Section titled “E2B - Full Development Environment”](#e2b---full-development-environment) ``` import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); const sandbox = await compute.sandbox.create({}); // Execute Python with data science libraries const result = await sandbox.runCode(` import pandas as pd import numpy as np data = {'A': [1, 2, 3], 'B': [4, 5, 6]} df = pd.DataFrame(data) print(df) print(f"Sum: {df.sum().sum()}") `); console.log(result.stdout); ``` #### Vercel - Serverless Execution [Section titled “Vercel - Serverless Execution”](#vercel---serverless-execution) ``` import { compute } from 'computesdk'; import { vercel } from '@computesdk/vercel'; compute.setConfig({ provider: vercel({ runtime: 'node' }) }); const sandbox = await compute.sandbox.create({}); // Execute Node.js or Python const result = await sandbox.runCode(` console.log('Node.js version:', process.version); console.log('Hello from Vercel!'); `); console.log(result.stdout); ``` #### Daytona - Development Workspaces [Section titled “Daytona - Development Workspaces”](#daytona---development-workspaces) ``` import { compute } from 'computesdk'; import { daytona } from '@computesdk/daytona'; compute.setConfig({ provider: daytona({ apiKey: process.env.DAYTONA_API_KEY }) }); const sandbox = await compute.sandbox.create({}); // Execute in development workspace const result = await sandbox.runCode(` print('Hello from Daytona!') import sys print(f'Python version: {sys.version}') `); console.log(result.stdout); ``` ### Filesystem Operations [Section titled “Filesystem Operations”](#filesystem-operations) ``` // Write file await sandbox.filesystem.writeFile('/tmp/hello.py', 'print("Hello")'); // Read file const content = await sandbox.filesystem.readFile('/tmp/hello.py'); // Create directory await sandbox.filesystem.mkdir('/tmp/mydir'); // List directory const files = await sandbox.filesystem.readdir('/tmp'); // Check if exists const exists = await sandbox.filesystem.exists('/tmp/hello.py'); // Remove file/directory await sandbox.filesystem.remove('/tmp/hello.py'); ``` ### Shell Commands [Section titled “Shell Commands”](#shell-commands) ``` // Run shell command const result = await sandbox.runCommand('ls', ['-la']); console.log(result.stdout); // With different working directory const result2 = await sandbox.runCommand('pwd', [], { cwd: '/tmp' }); ``` ### Error Handling [Section titled “Error Handling”](#error-handling) ``` try { const sandbox = await compute.sandbox.create({}); const result = await sandbox.runCode('invalid code'); } catch (error) { console.error('Execution failed:', error.message); // Handle specific error types as needed } ``` # Introducing ComputeSDK: A free and open-source toolkit for running other people's code in your applications I’m excited to share something we’ve been building that addresses a fundamental challenge in modern application development. As applications increasingly need to execute user-submitted or dynamically generated code, developers face a critical challenge: running untrusted code is hard and vastly different from running your own code. ## The infrastructure complexity problem [Section titled “The infrastructure complexity problem”](#the-infrastructure-complexity-problem) I’ve talked with several teams building app builders who have replaced their compute environment multiple times. Each migration required significant engineering effort—rewriting integrations, updating authentication flows, and ensuring feature parity. This pattern of switching providers and rebuilding infrastructure diverts resources from core product development. This scenario plays out repeatedly across teams building AI agents, educational tools, and any application requiring dynamic code execution. Developers find themselves reaching for something that they thought to be simple, but end up vastly underestimating the complexity involved. ## A unified approach to compute [Section titled “A unified approach to compute”](#a-unified-approach-to-compute) With ComputeSDK we’ve built a unified interface that allows you to hot swap providers at ease. You can think of it like CloudFormation or Terraform, but for running other people’s code. Our simple interface masks considerable technical complexity. Here’s what implementation looks like: ``` import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; // Set default provider compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); // Create a sandbox const sandbox = await compute.sandbox.create(); // Execute code const result = await sandbox.runCode('print("Hello World!")'); console.log(result.stdout); // "Hello World!" // Clean up await sandbox.destroy(); ``` ## Multi-provider benefits [Section titled “Multi-provider benefits”](#multi-provider-benefits) By aggregating multiple providers, ComputeSDK delivers several key advantages: **Vendor neutrality**: Like Terraform abstracts cloud infrastructure or CloudFormation standardizes AWS resources, ComputeSDK provides a consistent interface across compute providers. This means your application logic remains portable while you leverage the unique strengths of different platforms. **Operational resilience**: When demand spikes or you need additional capacity, you can seamlessly scale across multiple providers rather than being constrained by a single platform’s limitations. **Development velocity**: Focus on your application logic rather than learning multiple provider APIs, authentication schemes, and deployment models. ## Target applications [Section titled “Target applications”](#target-applications) ComputeSDK is particularly valuable for: * **AI applications** that need to execute LLM-generated code safely * **Educational platforms** requiring isolated coding environments * **Developer tools** embedding live code execution capabilities * **API services** processing user-submitted code securely The SDK serves teams ranging from individual developers to enterprises, with particular appeal for organizations building agentic workflows where code generation and execution are core components. ## Backed by a provider model [Section titled “Backed by a provider model”](#backed-by-a-provider-model) ComputeSDK’s architecture is built on top of proven compute providers, each bringing their own strengths to the platform. E2B provides enterprise-grade security through Firecracker microVMs with sub-second startup times. Vercel offers global serverless execution with support for both Node.js and Python runtimes. Daytona delivers full development workspace environments for complex application scenarios. Rather than reinventing compute infrastructure, we focus on creating the abstraction layer that makes these powerful platforms accessible through a single, consistent interface. For teams requiring additional control or on-premises deployment, we’re also developing premium infrastructure solutions that maintain the same unified API while providing enhanced capabilities. This approach means you benefit from the continued innovation of established providers while maintaining the flexibility to adapt as your needs evolve—whether through cloud providers or self-hosted environments. ## Roadmap and availability [Section titled “Roadmap and availability”](#roadmap-and-availability) ComputeSDK is free and open-source, available now. Near-term development includes: * A premium Kubernetes-based self-hosted compute environment * Additional primitives and services (think git, databases, and blob storage) * Additional provider support (think Neon, Supabase, and/or Turso) * Enhanced monitoring and observability features ## Looking ahead [Section titled “Looking ahead”](#looking-ahead) ComputeSDK represents our bet on the future of development infrastructure: simpler, more flexible, and designed for the AI-assisted development era. We believe developers should focus on creating value rather than managing infrastructure complexity. The platform is now available on GitHub at [github.com/computesdk/computesdk](https://github.com/computesdk/computesdk) with documentation at [computesdk.com/docs](https://computesdk.com/docs). I’d welcome the opportunity to discuss how ComputeSDK might fit into your development workflow and hear about the challenges you’re solving. Whether you’re building the next generation of AI applications or simply need reliable, flexible compute capabilities, ComputeSDK is designed to simplify that journey. Garrison Snelling\ Founder, ComputeSDK *** *We’re expanding our team. If you’re interested in building developer infrastructure that actually makes developers’ lives easier, let’s connect.* # Contact Us > Get in touch with the ComputeSDK team We’d love to hear from you! Whether you have questions, feedback, or need support, there are several ways to get in touch with the ComputeSDK team. ## GitHub [Section titled “GitHub”](#github) The best way to report bugs, request features, or contribute to the project is through our GitHub repository: * **Repository**: [github.com/computesdk/computesdk](https://github.com/computesdk/computesdk) * **Issues**: [Report bugs or request features](https://github.com/computesdk/computesdk/issues) * **Discussions**: [Community discussions](https://github.com/computesdk/computesdk/discussions) ## Support [Section titled “Support”](#support) For technical support and questions: * Check our [documentation](/start/introduction) first * Search existing [GitHub issues](https://github.com/computesdk/computesdk/issues) * Create a new issue if you can’t find an answer ## Contributing [Section titled “Contributing”](#contributing) Interested in contributing to ComputeSDK? We welcome contributions of all kinds: * Code contributions via pull requests * Documentation improvements * Bug reports and feature requests * Community support and discussions ## Business Inquiries [Section titled “Business Inquiries”](#business-inquiries) For business partnerships, enterprise support, or other commercial inquiries, please reach out at , or book a quick call with our CEO (he loves meeting new people) [here](https://cal.com/heygarrison/15min). # Astro > Use ComputeSDK in Astro applications # ComputeSDK + Astro [Section titled “ComputeSDK + Astro”](#computesdk--astro) Use ComputeSDK to execute code in secure sandboxes from your Astro API endpoints. ## Setup [Section titled “Setup”](#setup) ### 1. Install Dependencies [Section titled “1. Install Dependencies”](#1-install-dependencies) ``` npm install computesdk # Provider packages (install what you need) npm install @computesdk/e2b # E2B provider npm install @computesdk/vercel # Vercel provider npm install @computesdk/daytona # Daytona provider ``` ### 2. Configure Environment Variables [Section titled “2. Configure Environment Variables”](#2-configure-environment-variables) Create a `.env` file and add your provider credentials: ``` # E2B (get from e2b.dev) E2B_API_KEY=e2b_your_api_key_here # Vercel # Method 1: OIDC Token (recommended) vercel env pull # Downloads VERCEL_OIDC_TOKEN # Method 2: Traditional VERCEL_TOKEN=your_vercel_token_here VERCEL_TEAM_ID=your_team_id_here VERCEL_PROJECT_ID=your_project_id_here # Daytona (get from your Daytona instance) DAYTONA_API_KEY=your_daytona_api_key_here ``` ### 3. Run Development Server [Section titled “3. Run Development Server”](#3-run-development-server) ``` npm run dev ``` Navigate to ## Implementation [Section titled “Implementation”](#implementation) ### API Route with Request Handler [Section titled “API Route with Request Handler”](#api-route-with-request-handler) The simplest way to use ComputeSDK in Astro is with the built-in request handler: ``` // src/pages/api/compute.ts import type { APIRoute } from 'astro'; import { handleComputeRequest } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export const POST: APIRoute = async ({ request }) => { const computeRequest = await request.json(); const response = await handleComputeRequest({ request: computeRequest, provider: e2b({ apiKey: import.meta.env.E2B_API_KEY! }) }); return new Response( JSON.stringify(response), { status: response.success ? 200 : 500, headers: { 'Content-Type': 'application/json' } } ); }; ``` ### Custom API Route [Section titled “Custom API Route”](#custom-api-route) For more control, create a custom API route: ``` // src/pages/api/sandbox.ts import type { APIRoute } from 'astro'; import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export const POST: APIRoute = async ({ request }) => { try { const { code, runtime } = await request.json(); // Set provider compute.setConfig({ provider: e2b({ apiKey: import.meta.env.E2B_API_KEY! }) }); // Create sandbox and execute code const sandbox = await compute.sandbox.create({}); const result = await sandbox.runCode(code, runtime); // Clean up await compute.sandbox.destroy(sandbox.sandboxId); return new Response(JSON.stringify({ success: true, stdout: result.stdout, stderr: result.stderr, executionTime: result.executionTime }), { status: 200, headers: { 'Content-Type': 'application/json' } }); } catch (error: any) { return new Response(JSON.stringify({ success: false, error: error.message || 'Unknown error' }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } }; ``` ### Frontend Integration [Section titled “Frontend Integration”](#frontend-integration) Call your API from Astro components: ``` --- // src/pages/playground.astro --- ComputeSDK Playground

Code Executor

``` ### With React Component [Section titled “With React Component”](#with-react-component) ``` // src/components/CodeExecutor.tsx import { useState } from 'react'; export default function CodeExecutor() { const [code, setCode] = useState('print("Hello World!")'); const [output, setOutput] = useState(''); const [loading, setLoading] = useState(false); const [runtime, setRuntime] = useState<'python' | 'node'>('python'); const executeCode = async () => { setLoading(true); try { const response = await fetch('/api/compute', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'compute.sandbox.runCode', code, runtime }) }); const data = await response.json(); if (data.success) { setOutput(data.result.stdout); } else { setOutput(`Error: ${data.error}`); } } catch (error: any) { setOutput(`Error: ${error.message}`); } finally { setLoading(false); } }; return (

Code Executor

{#if output}
{output}
{/if}
``` ### Using Form Actions [Section titled “Using Form Actions”](#using-form-actions) SvelteKit form actions provide another way to handle server-side execution: ``` // src/routes/form-demo/+page.server.ts import { fail } from '@sveltejs/kit'; import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export const actions = { execute: async ({ request }) => { const formData = await request.formData(); const code = formData.get('code') as string; const runtime = formData.get('runtime') as string; if (!code) { return fail(400, { error: 'Code is required' }); } try { compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }) }); const sandbox = await compute.sandbox.create({}); const result = await sandbox.runCode(code, runtime); await compute.sandbox.destroy(sandbox.sandboxId); return { success: true, output: result.stdout, stderr: result.stderr }; } catch (error: any) { return fail(500, { error: error.message }); } } }; ``` ```
{ loading = true; return async ({ result, update }) => { loading = false; await update(); }; }}>
{#if form?.success}
{form.output}
{:else if form?.error}
Error: {form.error}
{/if} ``` ## Advanced Examples [Section titled “Advanced Examples”](#advanced-examples) ### Data Analysis Route [Section titled “Data Analysis Route”](#data-analysis-route) ``` // src/routes/api/analyze/+server.ts import { json, error } from '@sveltejs/kit'; import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export const POST = async ({ request }) => { try { const { csvData } = await request.json(); compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }) }); const sandbox = await compute.sandbox.create({}); // Save CSV data await sandbox.filesystem.writeFile('/data/input.csv', csvData); // Process data const result = await sandbox.runCode(` import pandas as pd import json # Read and analyze data df = pd.read_csv('/data/input.csv') analysis = { 'rows': len(df), 'columns': len(df.columns), 'summary': df.describe().to_dict(), 'missing_values': df.isnull().sum().to_dict() } print(json.dumps(analysis, indent=2)) `); await compute.sandbox.destroy(sandbox.sandboxId); return json({ success: true, analysis: JSON.parse(result.stdout) }); } catch (err: any) { throw error(500, err.message); } }; ``` ### File Upload and Processing [Section titled “File Upload and Processing”](#file-upload-and-processing) ``` // src/routes/api/upload/+server.ts import { json, error } from '@sveltejs/kit'; import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export const POST = async ({ request }) => { try { const formData = await request.formData(); const file = formData.get('file') as File; if (!file) { throw error(400, 'No file provided'); } const fileContent = await file.text(); const sandbox = await compute.sandbox.create({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }) }); // Save uploaded file await sandbox.filesystem.writeFile(`/uploads/${file.name}`, fileContent); // Process file const result = await sandbox.runCode(` import os # Get file info file_path = '/uploads/${file.name}' file_size = os.path.getsize(file_path) with open(file_path, 'r') as f: content = f.read() lines = len(content.split('\\n')) chars = len(content) print(f"File: {file.name}") print(f"Size: {file_size} bytes") print(f"Lines: {lines}") print(f"Characters: {chars}") `); await compute.sandbox.destroy(sandbox.sandboxId); return json({ success: true, info: result.stdout }); } catch (err: any) { throw error(500, err.message); } }; ``` ### Multi-Step Workflow [Section titled “Multi-Step Workflow”](#multi-step-workflow) ``` // src/routes/api/workflow/+server.ts import { json, error } from '@sveltejs/kit'; import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export const POST = async ({ request }) => { const sandbox = await compute.sandbox.create({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }) }); try { const steps: any[] = []; // Step 1: Setup environment await sandbox.filesystem.mkdir('/workspace'); const setupResult = await sandbox.runCommand('pip', ['install', 'requests', 'beautifulsoup4']); steps.push({ step: 1, action: 'setup', output: setupResult.stdout }); // Step 2: Fetch data const fetchResult = await sandbox.runCode(` import requests import json # Simulate data fetch data = {"message": "Hello World", "timestamp": "2024-01-01"} # Save to file with open('/workspace/data.json', 'w') as f: json.dump(data, f) print("Data fetched and saved") `); steps.push({ step: 2, action: 'fetch', output: fetchResult.stdout }); // Step 3: Process data const processResult = await sandbox.runCode(` import json with open('/workspace/data.json', 'r') as f: data = json.load(f) # Process data result = { 'original': data, 'processed': data['message'].upper(), 'length': len(data['message']) } print(json.dumps(result)) `); steps.push({ step: 3, action: 'process', result: JSON.parse(processResult.stdout) }); return json({ success: true, steps }); } catch (err: any) { throw error(500, err.message); } finally { await compute.sandbox.destroy(sandbox.sandboxId); } }; ``` ## Best Practices [Section titled “Best Practices”](#best-practices) ### 1. Environment Variable Access [Section titled “1. Environment Variable Access”](#1-environment-variable-access) ``` // src/lib/env.ts import { env } from '$env/dynamic/private'; import { E2B_API_KEY, VERCEL_TOKEN } from '$env/static/private'; export const getProvider = () => { if (E2B_API_KEY) { return e2b({ apiKey: E2B_API_KEY }); } if (VERCEL_TOKEN) { return vercel({ token: VERCEL_TOKEN }); } throw new Error('No compute provider configured'); }; ``` ### 2. Error Handling [Section titled “2. Error Handling”](#2-error-handling) ``` // src/routes/api/safe/+server.ts import { json, error } from '@sveltejs/kit'; export const POST = async ({ request }) => { try { // ComputeSDK operations } catch (err: any) { console.error('Sandbox error:', err); // Don't expose sensitive error details in production const message = import.meta.env.DEV ? err.message : 'Internal server error'; throw error(500, message); } }; ``` ### 3. Input Validation [Section titled “3. Input Validation”](#3-input-validation) ``` // src/lib/validation.ts import { z } from 'zod'; export const executeSchema = z.object({ code: z.string().min(1).max(10000), runtime: z.enum(['python', 'node']), timeout: z.number().optional().default(30000) }); // In your route export const POST = async ({ request }) => { const body = await request.json(); const validation = executeSchema.safeParse(body); if (!validation.success) { throw error(400, 'Invalid request data'); } const { code, runtime, timeout } = validation.data; // Use validated data }; ``` ### 4. Resource Management [Section titled “4. Resource Management”](#4-resource-management) ``` // src/routes/api/managed/+server.ts export const POST = async ({ request }) => { let sandbox = null; try { sandbox = await compute.sandbox.create({}); // Use sandbox } catch (err: any) { throw error(500, err.message); } finally { // Always clean up if (sandbox) { await compute.sandbox.destroy(sandbox.sandboxId); } } }; ``` ## Layout and Stores [Section titled “Layout and Stores”](#layout-and-stores) ### Global Error Handling [Section titled “Global Error Handling”](#global-error-handling) ``` {#if showError}

{errorMessage}

{/if}
``` ### Compute Store [Section titled “Compute Store”](#compute-store) ``` // src/lib/stores/compute.ts import { writable } from 'svelte/store'; interface ExecutionState { loading: boolean; output: string; error: string | null; } function createComputeStore() { const { subscribe, set, update } = writable({ loading: false, output: '', error: null }); return { subscribe, execute: async (code: string, runtime: 'python' | 'node' = 'python') => { update(state => ({ ...state, loading: true, error: null })); try { const response = await fetch('/api/compute', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'compute.sandbox.runCode', code, runtime }) }); const data = await response.json(); if (data.success) { update(state => ({ ...state, loading: false, output: data.result.stdout, error: null })); } else { update(state => ({ ...state, loading: false, error: data.error })); } } catch (error: any) { update(state => ({ ...state, loading: false, error: error.message })); } }, clear: () => set({ loading: false, output: '', error: null }) }; } export const computeStore = createComputeStore(); ``` ## Deployment [Section titled “Deployment”](#deployment) ### Environment Variables [Section titled “Environment Variables”](#environment-variables) Set your environment variables in your deployment platform: ``` # Production environment variables E2B_API_KEY=your_production_e2b_key VERCEL_TOKEN=your_production_vercel_token VERCEL_TEAM_ID=your_team_id VERCEL_PROJECT_ID=your_project_id DAYTONA_API_KEY=your_production_daytona_key ``` ### Build Configuration [Section titled “Build Configuration”](#build-configuration) ``` // vite.config.ts import { sveltekit } from '@sveltejs/kit/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [sveltekit()], define: { // Ensure environment variables are properly handled 'process.env': process.env } }); ``` ## Troubleshooting [Section titled “Troubleshooting”](#troubleshooting) **Environment variables not loading?** * Check `.env` file exists and has correct format * Restart dev server after changes * Use `$env/static/private` for build-time variables * Use `$env/dynamic/private` for runtime variables **Sandbox creation fails?** * Verify API keys are correct and have proper format * Check provider-specific setup requirements * Monitor rate limits and quotas **Server-side only errors?** * ComputeSDK must run on server-side only * Use server routes (`+server.ts`) or form actions * Don’t import ComputeSDK in client-side components **Build errors?** * Ensure all ComputeSDK imports are in server-side code only * Check that environment variables are properly typed * Verify provider packages are correctly installed **CORS issues?** * All ComputeSDK operations happen server-side * Frontend calls your API routes, not ComputeSDK directly * Check that your API routes are properly configured # Compute SDK [What's new Read the post: Announcing ComputeSDK ](/blog/announcement/) # Embedded Compute for Your Apps A developer-first primitive to embed compute into your app, agent, or network with the ability to connect directly from the browser. [Get Started](https://github.com/computesdk/computesdk) [ GitHub](https://github.com/computesdk/computesdk) index.jsx ``` import { compute } from 'computesdk'; import { provider } from '@computesdk/provider'; // Set default provider compute.setConfig({ provider: provider({ apiKey: process.env.PROVIDER_API_KEY }) }); // Create a sandbox const sandbox = await compute.sandbox.create({}); // Execute code const result = await sandbox.runCode('print("Hello World!")'); console.log(result.stdout); // "Hello World!" // Clean up await sandbox.destroy(); ``` Introducing # All of a sudden everyone is a coder now. I remember scouring through the Joomla! documentation site for a website I was building when I was 13. I remember that the concepts were not the gotchas, but syntax or one little piece of information was. Every bit of detail was worth reading because you weren't sure when you would need it for recall. On June 20, 2024 anthropic released Claude 3.5 Sonnet and the internet changed. All of a sudden an AI studio had released a model that was good enough to output code for all of us. All of a sudden everyone could be a coder. A vibe coder. However, just like any experienced programmer can tell you. Creating something is addicting. The next million developers haven't learned to code by building Joomla, WordPress or Magento sites like me. They've learned or are learning to code by vibe coding. Simplicity is more important than ever. These next sets of coders don't want to fiddle with Terraform, CDK, or some vendor's docs. They don't even want to waste context window space on this. The next set of coders want to build even more complex applications and therefore need to simplify. They don't want to be forced to make "The Right Decision". They want optionality in their compute layer. ComputeSDK is a primitive to help you build any application. To start, we're building the primitive around raw compute. We've aggregated some of the best integrations from E2B, Vercel, Fly, and Cloudflare so that you can get started quickly without needing to manage the complexity of a specific vendor. We can't wait to see what you build. ![GS Logo](/GS.svg) ![GS Logo](/GS-dark.svg) Garrison Snelling CEO, ComputeSDK [X ](https://x.com/computesdk)[GitHub ](https://github.com/computesdk/computesdk) © 2025 ComputeSDK, Inc. All rights reserved. # LLM.txt > Access ComputeSDK documentation optimized for AI code agents and language models This page provides access to ComputeSDK documentation formatted specifically for AI code agents and large language models. ## Documentation Formats [Section titled “Documentation Formats”](#documentation-formats) ### Complete Documentation Sets [Section titled “Complete Documentation Sets”](#complete-documentation-sets) * **[Full Documentation](/llms-full.txt)** - Complete documentation for ComputeSDK * Contains all content from the official documentation * Best for comprehensive understanding and complex tasks * File size: \~194KB * **[Compact Documentation](/llms-small.txt)** - Abridged version with non-essential content removed * Optimized for smaller context windows * Excludes tips, notes, and other secondary content * File size: \~178KB ## For LLMs [Section titled “For LLMs”](#for-llms) If you’re an AI assistant accessing this documentation, you can also reference the main entrypoint at `/llms.txt` which contains links to all available documentation sets with descriptions. ## About the Format [Section titled “About the Format”](#about-the-format) These files follow the [llms.txt specification](https://llmstxt.org/) and are automatically generated from the same source as our official documentation, ensuring they’re always up-to-date. # Daytona > Execute code in Daytona development workspaces # @computesdk/daytona [Section titled “@computesdk/daytona”](#computesdkdaytona) Daytona provider for ComputeSDK - Execute code in Daytona development workspaces. ## Installation [Section titled “Installation”](#installation) ``` npm install @computesdk/daytona ``` ## Usage [Section titled “Usage”](#usage) ### With ComputeSDK [Section titled “With ComputeSDK”](#with-computesdk) ``` import { compute } from 'computesdk'; import { daytona } from '@computesdk/daytona'; // Set as default provider compute.setConfig({ provider: daytona({ apiKey: process.env.DAYTONA_API_KEY }) }); // Create sandbox const sandbox = await compute.sandbox.create({}); // Execute code const result = await sandbox.runCode('print("Hello from Daytona!")'); console.log(result.stdout); // "Hello from Daytona!" // Clean up await compute.sandbox.destroy(sandbox.sandboxId); ``` ### Direct Usage [Section titled “Direct Usage”](#direct-usage) ``` import { daytona } from '@computesdk/daytona'; // Create provider const provider = daytona({ apiKey: 'your-api-key', runtime: 'python' }); // Use with compute singleton const sandbox = await compute.sandbox.create({ provider }); ``` ## Configuration [Section titled “Configuration”](#configuration) ### Environment Variables [Section titled “Environment Variables”](#environment-variables) ``` export DAYTONA_API_KEY=your_api_key_here ``` ### Configuration Options [Section titled “Configuration Options”](#configuration-options) ``` interface DaytonaConfig { /** Daytona API key - if not provided, will use DAYTONA_API_KEY env var */ apiKey?: string; /** Default runtime environment */ runtime?: 'python' | 'node'; /** Execution timeout in milliseconds */ timeout?: number; } ``` ## Features [Section titled “Features”](#features) * ✅ **Code Execution** - Python and Node.js runtime support * ✅ **Command Execution** - Run shell commands in workspace * ✅ **Filesystem Operations** - Full file system access * ✅ **Auto Runtime Detection** - Automatically detects Python vs Node.js ## API Reference [Section titled “API Reference”](#api-reference) ### Code Execution [Section titled “Code Execution”](#code-execution) ``` // Execute Python code const result = await sandbox.runCode(` import json data = {"message": "Hello from Python"} print(json.dumps(data)) `, 'python'); // Execute Node.js code const result = await sandbox.runCode(` const data = { message: "Hello from Node.js" }; console.log(JSON.stringify(data)); `, 'node'); // Auto-detection (based on code patterns) const result = await sandbox.runCode('print("Auto-detected as Python")'); ``` ### Command Execution [Section titled “Command Execution”](#command-execution) ``` // List files const result = await sandbox.runCommand('ls', ['-la']); // Install packages const result = await sandbox.runCommand('pip', ['install', 'requests']); // Run scripts const result = await sandbox.runCommand('python', ['script.py']); ``` ### Filesystem Operations [Section titled “Filesystem Operations”](#filesystem-operations) ``` // Write file await sandbox.filesystem.writeFile('/workspace/hello.py', 'print("Hello World")'); // Read file const content = await sandbox.filesystem.readFile('/workspace/hello.py'); // Create directory await sandbox.filesystem.mkdir('/workspace/data'); // List directory contents const files = await sandbox.filesystem.readdir('/workspace'); // Check if file exists const exists = await sandbox.filesystem.exists('/workspace/hello.py'); // Remove file or directory await sandbox.filesystem.remove('/workspace/hello.py'); ``` ### Sandbox Management [Section titled “Sandbox Management”](#sandbox-management) ``` // Get sandbox info const info = await sandbox.getInfo(); console.log(info.id, info.provider, info.status); // List all sandboxes const sandboxes = await compute.sandbox.list(provider); // Get existing sandbox const existing = await compute.sandbox.getById(provider, 'sandbox-id'); // Destroy sandbox await compute.sandbox.destroy(provider, 'sandbox-id'); ``` ## Runtime Detection [Section titled “Runtime Detection”](#runtime-detection) The provider automatically detects the runtime based on code patterns: **Python indicators:** * `print(` statements * `import` statements * `def` function definitions * Python-specific syntax (`f"`, `__`, etc.) **Default:** Node.js for all other cases ## Error Handling [Section titled “Error Handling”](#error-handling) ``` try { const result = await sandbox.runCode('invalid code'); } catch (error) { if (error.message.includes('Syntax error')) { console.error('Code has syntax errors'); } else if (error.message.includes('authentication failed')) { console.error('Check your DAYTONA_API_KEY'); } else if (error.message.includes('quota exceeded')) { console.error('Daytona usage limits reached'); } } ``` ## Web Framework Integration [Section titled “Web Framework Integration”](#web-framework-integration) Use with web frameworks via the request handler: ``` import { handleComputeRequest } from 'computesdk'; import { daytona } from '@computesdk/daytona'; export async function POST(request: Request) { return handleComputeRequest({ request, provider: daytona({ apiKey: process.env.DAYTONA_API_KEY }) }); } ``` ## Examples [Section titled “Examples”](#examples) ### Data Processing [Section titled “Data Processing”](#data-processing) ``` const result = await sandbox.runCode(` import json # Process data data = [1, 2, 3, 4, 5] result = { "sum": sum(data), "average": sum(data) / len(data), "max": max(data) } print(json.dumps(result)) `); const output = JSON.parse(result.stdout); console.log(output); // { sum: 15, average: 3, max: 5 } ``` ### File Processing [Section titled “File Processing”](#file-processing) ``` // Create data file await sandbox.filesystem.writeFile('/workspace/data.json', JSON.stringify({ users: ['Alice', 'Bob', 'Charlie'] }) ); // Process file const result = await sandbox.runCode(` import json with open('/workspace/data.json', 'r') as f: data = json.load(f) # Process users user_count = len(data['users']) print(f"Found {user_count} users") # Save result result = {"user_count": user_count, "processed": True} with open('/workspace/result.json', 'w') as f: json.dump(result, f) `); // Read result const resultData = await sandbox.filesystem.readFile('/workspace/result.json'); console.log(JSON.parse(resultData)); ``` # E2B > Execute code in secure E2B sandboxes with full filesystem and terminal support # @computesdk/e2b [Section titled “@computesdk/e2b”](#computesdke2b) E2B provider for ComputeSDK - Execute code in secure, isolated E2B sandboxes with full filesystem and terminal support. ## Installation [Section titled “Installation”](#installation) ``` npm install @computesdk/e2b ``` ## Setup [Section titled “Setup”](#setup) 1. Get your E2B API key from [e2b.dev](https://e2b.dev/) 2. Set the environment variable: ``` export E2B_API_KEY=e2b_your_api_key_here ``` ## Usage [Section titled “Usage”](#usage) ### With ComputeSDK [Section titled “With ComputeSDK”](#with-computesdk) ``` import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; // Set as default provider compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); // Create sandbox const sandbox = await compute.sandbox.create({}); // Execute Python code const result = await sandbox.runCode(` import pandas as pd import numpy as np data = {'A': [1, 2, 3], 'B': [4, 5, 6]} df = pd.DataFrame(data) print(df) print(f"Sum: {df.sum().sum()}") `); console.log(result.stdout); // Output: // A B // 0 1 4 // 1 2 5 // 2 3 6 // Sum: 21 // Clean up await compute.sandbox.destroy(sandbox.sandboxId); ``` ### Direct Usage [Section titled “Direct Usage”](#direct-usage) ``` import { e2b } from '@computesdk/e2b'; // Create provider const provider = e2b({ apiKey: 'e2b_your_api_key', timeout: 600000 // 10 minutes }); // Use with compute singleton const sandbox = await compute.sandbox.create({ provider }); ``` ## Configuration [Section titled “Configuration”](#configuration) ### Environment Variables [Section titled “Environment Variables”](#environment-variables) ``` export E2B_API_KEY=e2b_your_api_key_here ``` ### Configuration Options [Section titled “Configuration Options”](#configuration-options) ``` interface E2BConfig { /** E2B API key - if not provided, will use E2B_API_KEY env var */ apiKey?: string; /** Default runtime environment */ runtime?: 'python' | 'node'; /** Execution timeout in milliseconds */ timeout?: number; } ``` ## Features [Section titled “Features”](#features) * ✅ **Code Execution** - Python and Node.js runtime support * ✅ **Command Execution** - Run shell commands in sandbox * ✅ **Filesystem Operations** - Full file system access via E2B API * ✅ **Terminal Support** - Interactive PTY terminals * ✅ **Auto Runtime Detection** - Automatically detects Python vs Node.js * ✅ **Data Science Ready** - Pre-installed pandas, numpy, matplotlib, etc. ## API Reference [Section titled “API Reference”](#api-reference) ### Code Execution [Section titled “Code Execution”](#code-execution) ``` // Execute Python code const result = await sandbox.runCode(` import json data = {"message": "Hello from Python"} print(json.dumps(data)) `, 'python'); // Execute Node.js code const result = await sandbox.runCode(` const data = { message: "Hello from Node.js" }; console.log(JSON.stringify(data)); `, 'node'); // Auto-detection (based on code patterns) const result = await sandbox.runCode('print("Auto-detected as Python")'); ``` ### Command Execution [Section titled “Command Execution”](#command-execution) ``` // List files const result = await sandbox.runCommand('ls', ['-la']); // Install packages const result = await sandbox.runCommand('pip', ['install', 'requests']); // Run scripts const result = await sandbox.runCommand('python', ['script.py']); ``` ### Filesystem Operations [Section titled “Filesystem Operations”](#filesystem-operations) ``` // Write file await sandbox.filesystem.writeFile('/tmp/hello.py', 'print("Hello World")'); // Read file const content = await sandbox.filesystem.readFile('/tmp/hello.py'); // Create directory await sandbox.filesystem.mkdir('/tmp/data'); // List directory contents const files = await sandbox.filesystem.readdir('/tmp'); // Check if file exists const exists = await sandbox.filesystem.exists('/tmp/hello.py'); // Remove file or directory await sandbox.filesystem.remove('/tmp/hello.py'); ``` ### Terminal Operations [Section titled “Terminal Operations”](#terminal-operations) ``` // Create terminal const terminal = await sandbox.terminal.create({ command: 'bash', cols: 80, rows: 24, onData: (data: Uint8Array) => { const output = new TextDecoder().decode(data); console.log('Terminal output:', output); } }); // Write to terminal await terminal.write('echo "Hello Terminal!"\n'); // Resize terminal await terminal.resize(120, 30); // Kill terminal await terminal.kill(); // List all terminals const terminals = await sandbox.terminal.list(); // Get terminal by ID const existingTerminal = await sandbox.terminal.getById('terminal-id'); ``` ### Sandbox Management [Section titled “Sandbox Management”](#sandbox-management) ``` // Get sandbox info const info = await sandbox.getInfo(); console.log(info.id, info.provider, info.status); // Get existing sandbox (reconnect) const existing = await compute.sandbox.getById(provider, 'sandbox-id'); // Destroy sandbox await compute.sandbox.destroy(provider, 'sandbox-id'); ``` ## Runtime Detection [Section titled “Runtime Detection”](#runtime-detection) The provider automatically detects the runtime based on code patterns: **Python indicators:** * `print(` statements * `import` statements * `def` function definitions * Python-specific syntax (`f"`, `__`, etc.) **Default:** Node.js for all other cases ## Error Handling [Section titled “Error Handling”](#error-handling) ``` try { const result = await sandbox.runCode('invalid code'); } catch (error) { if (error.message.includes('Missing E2B API key')) { console.error('Set E2B_API_KEY environment variable'); } else if (error.message.includes('Invalid E2B API key format')) { console.error('E2B API keys should start with "e2b_"'); } else if (error.message.includes('authentication failed')) { console.error('Check your E2B API key'); } else if (error.message.includes('quota exceeded')) { console.error('E2B usage limits reached'); } else if (error.message.includes('Syntax error')) { console.error('Code has syntax errors'); } } ``` ## Web Framework Integration [Section titled “Web Framework Integration”](#web-framework-integration) Use with web frameworks via the request handler: ``` import { handleComputeRequest } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export async function POST(request: Request) { return handleComputeRequest({ request, provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); } ``` ## Examples [Section titled “Examples”](#examples) ### Data Science Workflow [Section titled “Data Science Workflow”](#data-science-workflow) ``` const sandbox = await compute.sandbox.create({}); // Create project structure await sandbox.filesystem.mkdir('/analysis'); await sandbox.filesystem.mkdir('/analysis/data'); await sandbox.filesystem.mkdir('/analysis/output'); // Write input data const csvData = `name,age,city Alice,25,New York Bob,30,San Francisco Charlie,35,Chicago`; await sandbox.filesystem.writeFile('/analysis/data/people.csv', csvData); // Process data with Python const result = await sandbox.runCode(` import pandas as pd import matplotlib.pyplot as plt # Read data df = pd.read_csv('/analysis/data/people.csv') print("Data loaded:") print(df) # Calculate statistics avg_age = df['age'].mean() print(f"\\nAverage age: {avg_age}") # Create visualization plt.figure(figsize=(8, 6)) plt.bar(df['name'], df['age']) plt.title('Age by Person') plt.xlabel('Name') plt.ylabel('Age') plt.savefig('/analysis/output/age_chart.png') print("\\nChart saved to /analysis/output/age_chart.png") # Save results results = { 'total_people': len(df), 'average_age': avg_age, 'cities': df['city'].unique().tolist() } import json with open('/analysis/output/results.json', 'w') as f: json.dump(results, f, indent=2) print("Results saved!") `); console.log(result.stdout); // Read the results const results = await sandbox.filesystem.readFile('/analysis/output/results.json'); console.log('Analysis results:', JSON.parse(results)); // Check if chart was created const chartExists = await sandbox.filesystem.exists('/analysis/output/age_chart.png'); console.log('Chart created:', chartExists); ``` ### Interactive Terminal Session [Section titled “Interactive Terminal Session”](#interactive-terminal-session) ``` const sandbox = await compute.sandbox.create({}); // Create interactive Python terminal const terminal = await sandbox.terminal.create({ command: 'python3', cols: 80, rows: 24, onData: (data: Uint8Array) => { const output = new TextDecoder().decode(data); process.stdout.write(output); // Forward to console } }); // Send Python commands await terminal.write('import numpy as np\n'); await terminal.write('import pandas as pd\n'); await terminal.write('print("Libraries loaded!")\n'); await terminal.write('data = np.array([1, 2, 3, 4, 5])\n'); await terminal.write('print(f"Mean: {data.mean()}")\n'); await terminal.write('exit()\n'); // Wait for commands to execute await new Promise(resolve => setTimeout(resolve, 2000)); await terminal.kill(); ``` ### Machine Learning Pipeline [Section titled “Machine Learning Pipeline”](#machine-learning-pipeline) ``` const sandbox = await compute.sandbox.create({ options: { timeout: 600000 } // 10 minutes for ML tasks }); // Create ML project structure await sandbox.filesystem.mkdir('/ml-project'); await sandbox.filesystem.mkdir('/ml-project/data'); await sandbox.filesystem.mkdir('/ml-project/models'); // Generate and process data const result = await sandbox.runCode(` import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score import joblib # Generate sample dataset np.random.seed(42) X = np.random.randn(1000, 5) y = X.sum(axis=1) + np.random.randn(1000) * 0.1 # Create DataFrame feature_names = [f'feature_{i}' for i in range(5)] df = pd.DataFrame(X, columns=feature_names) df['target'] = y print(f"Dataset shape: {df.shape}") print("\\nDataset info:") print(df.describe()) # Save dataset df.to_csv('/ml-project/data/dataset.csv', index=False) print("\\nDataset saved to /ml-project/data/dataset.csv") # Split data X_train, X_test, y_train, y_test = train_test_split( df[feature_names], df['target'], test_size=0.2, random_state=42 ) # Train model model = LinearRegression() model.fit(X_train, y_train) # Make predictions y_pred = model.predict(X_test) # Evaluate mse = mean_squared_error(y_test, y_pred) r2 = r2_score(y_test, y_pred) print(f"\\nModel Performance:") print(f"MSE: {mse:.4f}") print(f"R²: {r2:.4f}") # Save model joblib.dump(model, '/ml-project/models/linear_model.pkl') print("\\nModel saved to /ml-project/models/linear_model.pkl") # Save results results = { 'mse': mse, 'r2': r2, 'feature_importance': dict(zip(feature_names, model.coef_)), 'intercept': model.intercept_ } import json with open('/ml-project/results.json', 'w') as f: json.dump(results, f, indent=2) print("Results saved!") `); console.log(result.stdout); // Read the results const results = await sandbox.filesystem.readFile('/ml-project/results.json'); console.log('ML Results:', JSON.parse(results)); // Verify model file exists const modelExists = await sandbox.filesystem.exists('/ml-project/models/linear_model.pkl'); console.log('Model saved:', modelExists); ``` ## Best Practices [Section titled “Best Practices”](#best-practices) 1. **Resource Management**: Always destroy sandboxes when done to free resources 2. **Error Handling**: Use try-catch blocks for robust error handling 3. **Timeouts**: Set appropriate timeouts for long-running tasks 4. **File Organization**: Use the filesystem API to organize project files 5. **Terminal Sessions**: Clean up terminal sessions with `terminal.kill()` 6. **API Key Security**: Never commit API keys to version control ## Limitations [Section titled “Limitations”](#limitations) * **Memory Limits**: Subject to E2B sandbox memory constraints * **Network Access**: Limited outbound network access * **File Persistence**: Files are not persisted between sandbox sessions * **Execution Time**: Subject to E2B timeout limits ## Support [Section titled “Support”](#support) * [E2B Documentation](https://e2b.dev/docs) * [ComputeSDK Issues](https://github.com/computesdk/computesdk/issues) * [E2B Support](https://e2b.dev/support) # More > Open Source - add more providers! #### Open Source [Section titled “Open Source”](#open-source) We welcome contributions to the Compute SDK! If you have a provider you’d like to add, please open a pull request. ### Providers [Section titled “Providers”](#providers) * [Daytona](/providers/daytona) * [E2B](/providers/e2b) * [Vercel](/providers/vercel) * [More](/providers/more) # Vercel > Execute Node.js and Python code in secure Vercel sandboxes # @computesdk/vercel [Section titled “@computesdk/vercel”](#computesdkvercel) Vercel provider for ComputeSDK - Execute Node.js and Python code in secure, isolated Vercel sandboxes. ## Installation [Section titled “Installation”](#installation) ``` npm install @computesdk/vercel ``` ## Authentication [Section titled “Authentication”](#authentication) Vercel provider supports two authentication methods: ### Method 1: OIDC Token (Recommended) [Section titled “Method 1: OIDC Token (Recommended)”](#method-1-oidc-token-recommended) The simplest way to authenticate. Vercel manages token expiration automatically. **Development:** ``` vercel env pull # Downloads VERCEL_OIDC_TOKEN to .env.local ``` **Production:** Vercel automatically provides `VERCEL_OIDC_TOKEN` in your deployment environment. ### Method 2: Access Token + Team/Project IDs [Section titled “Method 2: Access Token + Team/Project IDs”](#method-2-access-token--teamproject-ids) Alternative method using explicit credentials: ``` export VERCEL_TOKEN=your_vercel_token_here export VERCEL_TEAM_ID=your_team_id_here export VERCEL_PROJECT_ID=your_project_id_here ``` Get your token from [Vercel Account Tokens](https://vercel.com/account/tokens) ## Usage [Section titled “Usage”](#usage) ### With ComputeSDK [Section titled “With ComputeSDK”](#with-computesdk) ``` import { compute } from 'computesdk'; import { vercel } from '@computesdk/vercel'; // Set as default provider compute.setConfig({ provider: vercel({ runtime: 'node' }) }); // Create sandbox const sandbox = await compute.sandbox.create({}); // Execute Node.js code const result = await sandbox.runCode('console.log("Hello from Vercel!");'); console.log(result.stdout); // "Hello from Vercel!" // Execute Python code const pythonResult = await sandbox.runCode('print("Hello from Python!")', 'python'); console.log(pythonResult.stdout); // "Hello from Python!" // Clean up await compute.sandbox.destroy(sandbox.sandboxId); ``` ### Direct Usage [Section titled “Direct Usage”](#direct-usage) ``` import { vercel } from '@computesdk/vercel'; // Create provider with explicit config const provider = vercel({ token: 'your-token', teamId: 'your-team-id', projectId: 'your-project-id', runtime: 'python', timeout: 600000 // 10 minutes }); // Use with compute singleton const sandbox = await compute.sandbox.create({ provider }); ``` ## Configuration [Section titled “Configuration”](#configuration) ### Environment Variables [Section titled “Environment Variables”](#environment-variables) ``` # Method 1: OIDC Token (Recommended) export VERCEL_OIDC_TOKEN=your_oidc_token_here # Method 2: Traditional export VERCEL_TOKEN=your_vercel_token_here export VERCEL_TEAM_ID=your_team_id_here export VERCEL_PROJECT_ID=your_project_id_here ``` ### Configuration Options [Section titled “Configuration Options”](#configuration-options) ``` interface VercelConfig { /** Vercel API token - if not provided, will use VERCEL_TOKEN env var */ token?: string; /** Vercel team ID - if not provided, will use VERCEL_TEAM_ID env var */ teamId?: string; /** Vercel project ID - if not provided, will use VERCEL_PROJECT_ID env var */ projectId?: string; /** Default runtime environment */ runtime?: 'node' | 'python'; /** Execution timeout in milliseconds */ timeout?: number; } ``` ## Features [Section titled “Features”](#features) * ✅ **Code Execution** - Node.js 22 and Python 3.13 runtime support * ✅ **Command Execution** - Run shell commands in sandbox * ✅ **Filesystem Operations** - Full file system access via shell commands * ✅ **Auto Runtime Detection** - Automatically detects Python vs Node.js * ✅ **Long-running Tasks** - Up to 45 minutes execution time * ✅ **Global Infrastructure** - Runs on Vercel’s global network ## API Reference [Section titled “API Reference”](#api-reference) ### Code Execution [Section titled “Code Execution”](#code-execution) ``` // Execute Node.js code const result = await sandbox.runCode(` const data = { message: "Hello from Node.js" }; console.log(JSON.stringify(data)); `, 'node'); // Execute Python code const result = await sandbox.runCode(` import json data = {"message": "Hello from Python"} print(json.dumps(data)) `, 'python'); // Auto-detection (based on code patterns) const result = await sandbox.runCode('print("Auto-detected as Python")'); ``` ### Command Execution [Section titled “Command Execution”](#command-execution) ``` // List files const result = await sandbox.runCommand('ls', ['-la']); // Install packages (Node.js) const result = await sandbox.runCommand('npm', ['install', 'lodash']); // Install packages (Python) const result = await sandbox.runCommand('pip', ['install', 'requests']); // Run scripts const result = await sandbox.runCommand('node', ['script.js']); ``` ### Filesystem Operations [Section titled “Filesystem Operations”](#filesystem-operations) ``` // Write file await sandbox.filesystem.writeFile('/tmp/hello.py', 'print("Hello World")'); // Read file const content = await sandbox.filesystem.readFile('/tmp/hello.py'); // Create directory await sandbox.filesystem.mkdir('/tmp/data'); // List directory contents const files = await sandbox.filesystem.readdir('/tmp'); // Check if file exists const exists = await sandbox.filesystem.exists('/tmp/hello.py'); // Remove file or directory await sandbox.filesystem.remove('/tmp/hello.py'); ``` ### Sandbox Management [Section titled “Sandbox Management”](#sandbox-management) ``` // Get sandbox info const info = await sandbox.getInfo(); console.log(info.id, info.provider, info.status); // Get existing sandbox const existing = await compute.sandbox.getById(provider, 'sandbox-id'); // Destroy sandbox await compute.sandbox.destroy(provider, 'sandbox-id'); // Note: Vercel doesn't support listing all sandboxes // Each sandbox is ephemeral and single-use ``` ## Runtime Detection [Section titled “Runtime Detection”](#runtime-detection) The provider automatically detects the runtime based on code patterns: **Python indicators:** * `print(` statements * `import` statements * `def` function definitions * Python-specific syntax (`f"`, `__`, etc.) **Default:** Node.js for all other cases ## Error Handling [Section titled “Error Handling”](#error-handling) ``` try { const result = await sandbox.runCode('invalid code'); } catch (error) { if (error.message.includes('Missing Vercel authentication')) { console.error('Set VERCEL_OIDC_TOKEN or VERCEL_TOKEN environment variables'); } else if (error.message.includes('authentication failed')) { console.error('Check your Vercel credentials'); } else if (error.message.includes('team/project configuration failed')) { console.error('Check your VERCEL_TEAM_ID and VERCEL_PROJECT_ID'); } else if (error.message.includes('Syntax error')) { console.error('Code has syntax errors'); } } ``` ## Web Framework Integration [Section titled “Web Framework Integration”](#web-framework-integration) Use with web frameworks via the request handler: ``` import { handleComputeRequest } from 'computesdk'; import { vercel } from '@computesdk/vercel'; export async function POST(request: Request) { return handleComputeRequest({ request, provider: vercel({ runtime: 'node' }) }); } ``` ## Examples [Section titled “Examples”](#examples) ### Node.js Web Server Simulation [Section titled “Node.js Web Server Simulation”](#nodejs-web-server-simulation) ``` const sandbox = await compute.sandbox.create({ provider: vercel({ runtime: 'node' }) }); const result = await sandbox.runCode(` const http = require('http'); const url = require('url'); // Simulate API endpoints const routes = { '/api/users': () => ({ users: [ { id: 1, name: 'Alice', role: 'Developer' }, { id: 2, name: 'Bob', role: 'Designer' } ] }), '/api/health': () => ({ status: 'healthy', timestamp: new Date().toISOString() }) }; // Process request const path = '/api/users'; const response = routes[path] ? routes[path]() : { error: 'Not found' }; console.log('Response:', JSON.stringify(response, null, 2)); `); console.log(result.stdout); ``` ### Python Data Processing [Section titled “Python Data Processing”](#python-data-processing) ``` const sandbox = await compute.sandbox.create({ provider: vercel({ runtime: 'python' }) }); const result = await sandbox.runCode(` import json import statistics from collections import Counter # Sample data sales_data = [ {"product": "laptop", "quantity": 5, "price": 999}, {"product": "mouse", "quantity": 20, "price": 25}, {"product": "keyboard", "quantity": 15, "price": 75}, {"product": "laptop", "quantity": 3, "price": 999}, {"product": "mouse", "quantity": 10, "price": 25} ] # Aggregate sales product_sales = {} for sale in sales_data: product = sale["product"] revenue = sale["quantity"] * sale["price"] product_sales[product] = product_sales.get(product, 0) + revenue # Calculate statistics revenues = list(product_sales.values()) total_revenue = sum(revenues) avg_revenue = statistics.mean(revenues) print(f"Total Revenue: ${total_revenue}") print(f"Average Revenue per Product: ${avg_revenue:.2f}") print("\\nRevenue by Product:") for product, revenue in sorted(product_sales.items(), key=lambda x: x[1], reverse=True): print(f" {product}: ${revenue}") `); console.log(result.stdout); ``` ### Filesystem Operations Pipeline [Section titled “Filesystem Operations Pipeline”](#filesystem-operations-pipeline) ``` const sandbox = await compute.sandbox.create({ provider: vercel({ runtime: 'python' }) }); // Create project structure await sandbox.filesystem.mkdir('/tmp/project'); await sandbox.filesystem.mkdir('/tmp/project/data'); await sandbox.filesystem.mkdir('/tmp/project/output'); // Create configuration file const config = { project_name: "Vercel Data Pipeline", version: "1.0.0", settings: { input_format: "json", output_format: "csv", debug: true } }; await sandbox.filesystem.writeFile( '/tmp/project/config.json', JSON.stringify(config, null, 2) ); // Create sample data const sampleData = [ { id: 1, name: "Alice", department: "Engineering", salary: 95000 }, { id: 2, name: "Bob", department: "Marketing", salary: 75000 }, { id: 3, name: "Charlie", department: "Engineering", salary: 105000 }, { id: 4, name: "Diana", department: "Sales", salary: 85000 } ]; await sandbox.filesystem.writeFile( '/tmp/project/data/employees.json', JSON.stringify(sampleData, null, 2) ); // Process data const result = await sandbox.runCode(` import json import csv from collections import defaultdict # Read configuration with open('/tmp/project/config.json', 'r') as f: config = json.load(f) print(f"Running {config['project_name']} v{config['version']}") # Read employee data with open('/tmp/project/data/employees.json', 'r') as f: employees = json.load(f) # Process data - calculate department statistics dept_stats = defaultdict(list) for emp in employees: dept_stats[emp['department']].append(emp['salary']) # Calculate averages results = [] for dept, salaries in dept_stats.items(): avg_salary = sum(salaries) / len(salaries) results.append({ 'department': dept, 'employee_count': len(salaries), 'average_salary': round(avg_salary, 2), 'total_salary': sum(salaries) }) # Sort by average salary results.sort(key=lambda x: x['average_salary'], reverse=True) # Write results as JSON with open('/tmp/project/output/department_stats.json', 'w') as f: json.dump(results, f, indent=2) # Write results as CSV with open('/tmp/project/output/department_stats.csv', 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=['department', 'employee_count', 'average_salary', 'total_salary']) writer.writeheader() writer.writerows(results) print("Processing complete!") print(f"Generated {len(results)} department statistics") # Print summary for result in results: print(f"{result['department']}: {result['employee_count']} employees, avg salary ${result['average_salary']}") `); console.log('Execution Output:', result.stdout); // Read and display results const jsonResults = await sandbox.filesystem.readFile('/tmp/project/output/department_stats.json'); const csvResults = await sandbox.filesystem.readFile('/tmp/project/output/department_stats.csv'); console.log('JSON Results:', jsonResults); console.log('CSV Results:', csvResults); // List all generated files const outputFiles = await sandbox.filesystem.readdir('/tmp/project/output'); console.log('Generated files:'); outputFiles.forEach(file => { console.log(` ${file.name} (${file.size} bytes)`); }); ``` ### Package Installation and Usage [Section titled “Package Installation and Usage”](#package-installation-and-usage) ``` // Node.js example with package installation const sandbox = await compute.sandbox.create({ provider: vercel({ runtime: 'node' }) }); // Install lodash const installResult = await sandbox.runCommand('npm', ['install', 'lodash']); console.log('Install result:', installResult.stdout); // Use lodash in code const result = await sandbox.runCode(` const _ = require('lodash'); const data = [ { name: 'Alice', age: 25, city: 'New York' }, { name: 'Bob', age: 30, city: 'San Francisco' }, { name: 'Charlie', age: 35, city: 'Chicago' } ]; // Group by city const grouped = _.groupBy(data, 'city'); console.log('Grouped by city:', JSON.stringify(grouped, null, 2)); // Calculate average age const avgAge = _.meanBy(data, 'age'); console.log('Average age:', avgAge); // Find oldest person const oldest = _.maxBy(data, 'age'); console.log('Oldest person:', oldest.name); `); console.log(result.stdout); ``` ## Best Practices [Section titled “Best Practices”](#best-practices) 1. **Authentication**: Use OIDC token method when possible for simpler setup 2. **Resource Management**: Destroy sandboxes when done (they’re ephemeral anyway) 3. **Error Handling**: Use try-catch blocks for robust error handling 4. **Timeouts**: Set appropriate timeouts for long-running tasks (up to 45 minutes) 5. **File Organization**: Use the filesystem API to organize project files 6. **Package Installation**: Install packages at runtime as needed ## Limitations [Section titled “Limitations”](#limitations) * **Ephemeral Sandboxes**: Each sandbox is single-use and cannot be reconnected to * **No Sandbox Listing**: Vercel doesn’t support listing all sandboxes * **No Interactive Terminals**: Terminal operations are not supported * **Memory Limits**: Subject to Vercel sandbox memory constraints (2048 MB per vCPU) * **Execution Time**: Maximum 45 minutes execution time * **Network Access**: Limited outbound network access ## Support [Section titled “Support”](#support) * [Vercel Documentation](https://vercel.com/docs) * [ComputeSDK Issues](https://github.com/computesdk/computesdk/issues) * [Vercel Support](https://vercel.com/support) # API Reference > Complete API reference for ComputeSDK Complete reference documentation for ComputeSDK’s APIs and interfaces. ## Overview [Section titled “Overview”](#overview) ComputeSDK provides a unified abstraction layer for executing code in secure, isolated sandboxed environments across multiple cloud providers. The API is designed to be consistent across all providers while allowing for provider-specific features. ## Basic Usage Pattern [Section titled “Basic Usage Pattern”](#basic-usage-pattern) ``` import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; // 1. Configure provider compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); // 2. Create sandbox const sandbox = await compute.sandbox.create({}); // 3. Execute operations const result = await sandbox.runCode('print("Hello World!")'); console.log(result.stdout); // 4. Clean up await compute.sandbox.destroy(sandbox.sandboxId); ``` ## Available Methods [Section titled “Available Methods”](#available-methods) ### Configuration [Section titled “Configuration”](#configuration) * `compute.setConfig(config)` - Set global configuration * `compute.getConfig()` - Get current configuration * `compute.clearConfig()` - Clear configuration ### Sandbox Management [Section titled “Sandbox Management”](#sandbox-management) * `compute.sandbox.create(options)` - Create new sandbox * `compute.sandbox.getById(id)` - Get existing sandbox * `compute.sandbox.list()` - List all sandboxes * `compute.sandbox.destroy(id)` - Destroy sandbox ### Code Execution [Section titled “Code Execution”](#code-execution) * `sandbox.runCode(code, runtime?)` - Execute code * `sandbox.runCommand(command, args?)` - Run shell command ### Filesystem Operations [Section titled “Filesystem Operations”](#filesystem-operations) * `sandbox.filesystem.writeFile(path, content)` - Write file * `sandbox.filesystem.readFile(path)` - Read file * `sandbox.filesystem.mkdir(path)` - Create directory * `sandbox.filesystem.readdir(path)` - List directory * `sandbox.filesystem.exists(path)` - Check if exists * `sandbox.filesystem.remove(path)` - Remove file/directory ### Terminal Operations (E2B only) [Section titled “Terminal Operations (E2B only)”](#terminal-operations-e2b-only) * `sandbox.terminal.create(options)` - Create terminal * `sandbox.terminal.list()` - List terminals * `sandbox.terminal.getById(id)` - Get terminal by ID * `terminal.write(data)` - Write to terminal * `terminal.resize(cols, rows)` - Resize terminal * `terminal.kill()` - Kill terminal ### API Integration [Section titled “API Integration”](#api-integration) * `handleComputeRequest(options)` - Process web requests ## Supported Runtimes [Section titled “Supported Runtimes”](#supported-runtimes) * **Python** - Python 3.x with data science libraries * **Node.js** - Node.js runtime with npm packages ## Error Handling [Section titled “Error Handling”](#error-handling) All methods can throw errors. Always wrap calls in try-catch blocks: ``` try { const result = await sandbox.runCode('invalid code'); } catch (error) { console.error('Execution failed:', error.message); } ``` ## TypeScript Support [Section titled “TypeScript Support”](#typescript-support) ComputeSDK is fully typed. Import types as needed: ``` import type { Sandbox, Provider, ExecutionResult, ComputeConfig, Runtime } from 'computesdk'; ``` # API Integration > Use ComputeSDK with web frameworks via request handlers ComputeSDK provides a built-in request handler for seamless integration with web frameworks. ## Request Handler [Section titled “Request Handler”](#request-handler) ### `handleComputeRequest(options)` [Section titled “handleComputeRequest(options)”](#handlecomputerequestoptions) Process compute requests from web clients. ``` import { handleComputeRequest } from 'computesdk'; import { e2b } from '@computesdk/e2b'; // Next.js API route export async function POST(request: Request) { return handleComputeRequest({ request, provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); } ``` **Parameters:** * `options` - Request handling options * `request` - Request object containing action and parameters * `provider` - Provider instance to use **Returns:** Response with execution results ## Supported Actions [Section titled “Supported Actions”](#supported-actions) All ComputeSDK operations are available via the request handler: ### Sandbox Management [Section titled “Sandbox Management”](#sandbox-management) * `compute.sandbox.create` - Create new sandbox * `compute.sandbox.destroy` - Destroy sandbox * `compute.sandbox.getInfo` - Get sandbox information * `compute.sandbox.list` - List all sandboxes ### Code Execution [Section titled “Code Execution”](#code-execution) * `compute.sandbox.runCode` - Execute code * `compute.sandbox.runCommand` - Run shell command ### Filesystem Operations [Section titled “Filesystem Operations”](#filesystem-operations) * `compute.sandbox.filesystem.readFile` - Read file * `compute.sandbox.filesystem.writeFile` - Write file * `compute.sandbox.filesystem.mkdir` - Create directory * `compute.sandbox.filesystem.readdir` - List directory * `compute.sandbox.filesystem.exists` - Check if path exists * `compute.sandbox.filesystem.remove` - Remove file/directory ### Terminal Operations [Section titled “Terminal Operations”](#terminal-operations) * `compute.sandbox.terminal.create` - Create terminal * `compute.sandbox.terminal.list` - List terminals * `compute.sandbox.terminal.getById` - Get terminal by ID * `compute.sandbox.terminal.destroy` - Destroy terminal * `compute.sandbox.terminal.write` - Write to terminal * `compute.sandbox.terminal.resize` - Resize terminal * `compute.sandbox.terminal.kill` - Kill terminal ## Client Usage [Section titled “Client Usage”](#client-usage) ### Execute Code [Section titled “Execute Code”](#execute-code) ``` const response = await fetch('/api/compute', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'compute.sandbox.runCode', code: 'print("Hello from web!")', runtime: 'python' }) }); const result = await response.json(); if (result.success) { console.log(result.result.stdout); // "Hello from web!" } ``` ### Filesystem Operations [Section titled “Filesystem Operations”](#filesystem-operations-1) ``` // Write file await fetch('/api/compute', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'compute.sandbox.filesystem.writeFile', sandboxId: 'sandbox-123', path: '/tmp/data.json', content: JSON.stringify({ message: 'Hello' }) }) }); // Read file const response = await fetch('/api/compute', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'compute.sandbox.filesystem.readFile', sandboxId: 'sandbox-123', path: '/tmp/data.json' }) }); const result = await response.json(); if (result.success) { const data = JSON.parse(result.result); console.log(data.message); // "Hello" } ``` ### Sandbox Management [Section titled “Sandbox Management”](#sandbox-management-1) ``` // Create sandbox const createResponse = await fetch('/api/compute', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'compute.sandbox.create', options: { runtime: 'python', timeout: 300000 } }) }); const { result: sandbox } = await createResponse.json(); console.log('Created sandbox:', sandbox.sandboxId); // Use sandbox... // Destroy sandbox await fetch('/api/compute', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'compute.sandbox.destroy', sandboxId: sandbox.sandboxId }) }); ``` ## Framework Examples [Section titled “Framework Examples”](#framework-examples) ### Next.js App Router [Section titled “Next.js App Router”](#nextjs-app-router) ``` // app/api/compute/route.ts import { handleComputeRequest } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export async function POST(request: Request) { return handleComputeRequest({ request, provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); } ``` ### Next.js Pages Router [Section titled “Next.js Pages Router”](#nextjs-pages-router) ``` // pages/api/compute.ts import { handleComputeRequest } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export default async function handler(req: any, res: any) { const request = new Request(`http://localhost:3000${req.url}`, { method: req.method, headers: req.headers, body: JSON.stringify(req.body), }); const response = await handleComputeRequest({ request, provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); const data = await response.json(); res.status(response.status).json(data); } ``` ### Nuxt [Section titled “Nuxt”](#nuxt) ``` // server/api/compute.post.ts import { handleComputeRequest } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export default defineEventHandler(async (event) => { const computeRequest = await readBody(event); const response = await handleComputeRequest({ request: computeRequest, provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); if (!response.success) { throw createError({ statusCode: 500, statusMessage: response.error || 'Unknown error occurred' }); } return response; }); ``` ### SvelteKit [Section titled “SvelteKit”](#sveltekit) ``` // src/routes/api/compute/+server.ts import { json, error } from '@sveltejs/kit'; import { handleComputeRequest } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export const POST = async ({ request }) => { const computeRequest = await request.json(); const response = await handleComputeRequest({ request: computeRequest, provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); if (!response.success) { throw error(500, response.error || 'Unknown error occurred'); } return json(response); }; ``` ### Remix [Section titled “Remix”](#remix) ``` // app/routes/api.compute.tsx import type { ActionFunctionArgs } from "@remix-run/node"; import { json } from "@remix-run/node"; import { handleComputeRequest } from "computesdk"; import { e2b } from "@computesdk/e2b"; export const action = async ({ request }: ActionFunctionArgs) => { const computeRequest = await request.json(); const response = await handleComputeRequest({ request: computeRequest, provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); if (!response.success) { throw json({ error: response.error || 'Unknown error' }, { status: 500 }); } return json(response); }; ``` ### Astro [Section titled “Astro”](#astro) ``` // src/pages/api/compute.ts import type { APIRoute } from 'astro'; import { handleComputeRequest } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export const POST: APIRoute = async ({ request }) => { const computeRequest = await request.json(); const response = await handleComputeRequest({ request: computeRequest, provider: e2b({ apiKey: import.meta.env.E2B_API_KEY }) }); return new Response( JSON.stringify(response), { status: response.success ? 200 : 500, headers: { 'Content-Type': 'application/json' } } ); }; ``` ## Response Format [Section titled “Response Format”](#response-format) All web integration responses follow a consistent format: ``` interface ComputeResponse { success: boolean; result?: any; // Operation result error?: string; // Error message if success is false } ``` **Success Response:** ``` { "success": true, "result": { "stdout": "Hello World!", "stderr": "", "exitCode": 0, "executionTime": 127, "sandboxId": "sb_123", "provider": "e2b" } } ``` **Error Response:** ``` { "success": false, "error": "Sandbox not found" } ``` # Code Execution > Execute code and shell commands in sandboxes Execute code and shell commands within sandboxes. ## Methods [Section titled “Methods”](#methods) ### `sandbox.runCode(code, runtime?)` [Section titled “sandbox.runCode(code, runtime?)”](#sandboxruncodecode-runtime) Execute code in the specified runtime. ``` // Execute Python code const result = await sandbox.runCode('print("Hello World!")', 'python'); // Execute Node.js code const result = await sandbox.runCode('console.log("Hello World!")', 'node'); // Auto-detect runtime (based on code patterns) const result = await sandbox.runCode('print("Auto-detected as Python")'); ``` **Parameters:** * `code` - Code string to execute * `runtime?` - Runtime environment (‘python’ | ‘node’), auto-detected if not specified **Returns:** `ExecutionResult` ### `sandbox.runCommand(command, args?)` [Section titled “sandbox.runCommand(command, args?)”](#sandboxruncommandcommand-args) Execute a shell command. ``` // List files const result = await sandbox.runCommand('ls', ['-la']); // Install Python package const result = await sandbox.runCommand('pip', ['install', 'requests']); // Run script const result = await sandbox.runCommand('python', ['script.py']); ``` **Parameters:** * `command` - Command to execute * `args?` - Array of command arguments **Returns:** `ExecutionResult` ## ExecutionResult [Section titled “ExecutionResult”](#executionresult) All execution methods return a standardized result object. ``` interface ExecutionResult { stdout: string; // Standard output stderr: string; // Standard error exitCode: number; // Exit code (0 = success) executionTime: number; // Execution time in milliseconds sandboxId: string; // Sandbox ID provider: string; // Provider name } ``` ## Examples [Section titled “Examples”](#examples) ### Python Data Processing [Section titled “Python Data Processing”](#python-data-processing) ``` const result = await sandbox.runCode(` import json import pandas as pd # Create sample data data = {'A': [1, 2, 3], 'B': [4, 5, 6]} df = pd.DataFrame(data) # Process and output result = { 'shape': df.shape, 'sum': df.sum().to_dict() } print(json.dumps(result)) `, 'python'); const output = JSON.parse(result.stdout); console.log(output); // { shape: [3, 2], sum: { A: 6, B: 15 } } ``` ### Node.js API Simulation [Section titled “Node.js API Simulation”](#nodejs-api-simulation) ``` const result = await sandbox.runCode(` const data = { users: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ] }; console.log(JSON.stringify(data, null, 2)); `, 'node'); console.log(result.stdout); // Formatted JSON output ``` ### Shell Commands [Section titled “Shell Commands”](#shell-commands) ``` // Create directory and files await sandbox.runCommand('mkdir', ['-p', '/workspace/data']); await sandbox.runCommand('touch', ['/workspace/data/file1.txt', '/workspace/data/file2.txt']); // List contents const result = await sandbox.runCommand('ls', ['-la', '/workspace/data']); console.log(result.stdout); ``` # Configuration > Configure ComputeSDK with providers and settings Configure ComputeSDK with providers and global settings. ## Methods [Section titled “Methods”](#methods) ### `compute.setConfig(config)` [Section titled “compute.setConfig(config)”](#computesetconfigconfig) Set the global configuration including default provider. ``` import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY }) }); ``` **Parameters:** * `config` - Configuration object * `provider` - Default provider instance ### `compute.getConfig()` [Section titled “compute.getConfig()”](#computegetconfig) Get the current global configuration. ``` const config = compute.getConfig(); console.log(config.provider); // Current provider ``` **Returns:** Current configuration object ### `compute.clearConfig()` [Section titled “compute.clearConfig()”](#computeclearconfig) Clear the global configuration. ``` compute.clearConfig(); ``` ## Types [Section titled “Types”](#types) ``` interface ComputeConfig { provider?: Provider; } ``` # Filesystem > File and directory operations in sandboxes Perform file and directory operations within sandbox environments. ## Methods [Section titled “Methods”](#methods) ### `sandbox.filesystem.writeFile(path, content)` [Section titled “sandbox.filesystem.writeFile(path, content)”](#sandboxfilesystemwritefilepath-content) Write content to a file. ``` await sandbox.filesystem.writeFile('/tmp/hello.py', 'print("Hello World!")'); // Write JSON data const data = { message: "Hello", timestamp: new Date().toISOString() }; await sandbox.filesystem.writeFile('/tmp/data.json', JSON.stringify(data, null, 2)); ``` **Parameters:** * `path` - File path string * `content` - File content string ### `sandbox.filesystem.readFile(path)` [Section titled “sandbox.filesystem.readFile(path)”](#sandboxfilesystemreadfilepath) Read content from a file. ``` const content = await sandbox.filesystem.readFile('/tmp/hello.py'); console.log(content); // "print("Hello World!")" // Read JSON data const jsonContent = await sandbox.filesystem.readFile('/tmp/data.json'); const data = JSON.parse(jsonContent); ``` **Parameters:** * `path` - File path string **Returns:** File content as string ### `sandbox.filesystem.mkdir(path)` [Section titled “sandbox.filesystem.mkdir(path)”](#sandboxfilesystemmkdirpath) Create a directory (and parent directories if needed). ``` await sandbox.filesystem.mkdir('/tmp/myproject'); await sandbox.filesystem.mkdir('/tmp/myproject/data/output'); // Creates nested dirs ``` **Parameters:** * `path` - Directory path string ### `sandbox.filesystem.readdir(path)` [Section titled “sandbox.filesystem.readdir(path)”](#sandboxfilesystemreaddirpath) List directory contents. ``` const files = await sandbox.filesystem.readdir('/tmp'); files.forEach(file => { console.log(`${file.name} (${file.isDirectory ? 'directory' : 'file'})`); }); ``` **Parameters:** * `path` - Directory path string **Returns:** Array of file/directory entries ### `sandbox.filesystem.exists(path)` [Section titled “sandbox.filesystem.exists(path)”](#sandboxfilesystemexistspath) Check if a file or directory exists. ``` const exists = await sandbox.filesystem.exists('/tmp/hello.py'); if (exists) { console.log('File exists'); } ``` **Parameters:** * `path` - File or directory path string **Returns:** Boolean indicating existence ### `sandbox.filesystem.remove(path)` [Section titled “sandbox.filesystem.remove(path)”](#sandboxfilesystemremovepath) Remove a file or directory. ``` // Remove file await sandbox.filesystem.remove('/tmp/hello.py'); // Remove directory and contents await sandbox.filesystem.remove('/tmp/myproject'); ``` **Parameters:** * `path` - File or directory path string ## Types [Section titled “Types”](#types) ``` interface DirectoryEntry { name: string; isDirectory: boolean; size?: number; modified?: Date; } ``` ## Examples [Section titled “Examples”](#examples) ### Project Structure Creation [Section titled “Project Structure Creation”](#project-structure-creation) ``` // Create project structure await sandbox.filesystem.mkdir('/workspace/myapp'); await sandbox.filesystem.mkdir('/workspace/myapp/src'); await sandbox.filesystem.mkdir('/workspace/myapp/data'); await sandbox.filesystem.mkdir('/workspace/myapp/output'); // Create configuration file const config = { name: "MyApp", version: "1.0.0", description: "Sample application" }; await sandbox.filesystem.writeFile( '/workspace/myapp/config.json', JSON.stringify(config, null, 2) ); // Create main script await sandbox.filesystem.writeFile('/workspace/myapp/src/main.py', ` import json import os # Read configuration with open('/workspace/myapp/config.json', 'r') as f: config = json.load(f) print(f"Running {config['name']} v{config['version']}") print(f"Description: {config['description']}") `); ``` ### File Processing Workflow [Section titled “File Processing Workflow”](#file-processing-workflow) ``` // Write input data const csvData = `name,age,city Alice,25,New York Bob,30,San Francisco Charlie,35,Chicago`; await sandbox.filesystem.writeFile('/data/input.csv', csvData); // Process with Python await sandbox.runCode(` import pandas as pd import json # Read and process data df = pd.read_csv('/data/input.csv') result = { 'total_records': len(df), 'average_age': df['age'].mean(), 'cities': df['city'].unique().tolist() } # Write results with open('/data/results.json', 'w') as f: json.dump(result, f, indent=2) print("Processing complete!") `); // Read results const results = await sandbox.filesystem.readFile('/data/results.json'); const analysis = JSON.parse(results); console.log(analysis); ``` ### Directory Management [Section titled “Directory Management”](#directory-management) ``` // Check if directory exists, create if not const dataDir = '/workspace/data'; if (!(await sandbox.filesystem.exists(dataDir))) { await sandbox.filesystem.mkdir(dataDir); } // List all files in directory const files = await sandbox.filesystem.readdir('/workspace'); console.log('Workspace contents:'); files.forEach(file => { const type = file.isDirectory ? 'DIR' : 'FILE'; console.log(` ${type}: ${file.name}`); }); // Clean up temporary files const tempFiles = await sandbox.filesystem.readdir('/tmp'); for (const file of tempFiles) { if (file.name.endsWith('.tmp')) { await sandbox.filesystem.remove(`/tmp/${file.name}`); } } ``` # Sandbox Management > Create, manage, and destroy sandboxes Create, retrieve, list, and destroy sandboxes. ## Methods [Section titled “Methods”](#methods) ### `compute.sandbox.create(options)` [Section titled “compute.sandbox.create(options)”](#computesandboxcreateoptions) Create a new sandbox instance. ``` // With explicit provider const sandbox = await compute.sandbox.create({ provider: e2b({ apiKey: 'your-key' }), options: { runtime: 'python', timeout: 300000 } }); // With default provider const sandbox = await compute.sandbox.create({ options: { runtime: 'python' } }); ``` **Parameters:** * `options` - Creation options * `provider?` - Specific provider to use (overrides global config) * `options?` - Provider-specific options * `runtime?` - Runtime environment (‘python’ | ‘node’) * `timeout?` - Execution timeout in milliseconds **Returns:** Sandbox instance with unique `sandboxId` ### `compute.sandbox.getById(id)` [Section titled “compute.sandbox.getById(id)”](#computesandboxgetbyidid) Retrieve an existing sandbox by ID. ``` const sandbox = await compute.sandbox.getById('sandbox-id'); ``` **Parameters:** * `id` - Sandbox ID string **Returns:** Sandbox instance ### `compute.sandbox.list()` [Section titled “compute.sandbox.list()”](#computesandboxlist) List all active sandboxes. ``` const sandboxes = await compute.sandbox.list(); console.log(sandboxes.length); // Number of active sandboxes ``` **Returns:** Array of sandbox instances ### `compute.sandbox.destroy(id)` [Section titled “compute.sandbox.destroy(id)”](#computesandboxdestroyid) Destroy a sandbox and clean up resources. ``` await compute.sandbox.destroy('sandbox-id'); // Or using sandbox instance await compute.sandbox.destroy(sandbox.sandboxId); ``` **Parameters:** * `id` - Sandbox ID string **Returns:** Promise that resolves when sandbox is destroyed ## Sandbox Instance [Section titled “Sandbox Instance”](#sandbox-instance) Once created, a sandbox instance provides methods for code execution, filesystem operations, and terminal management. ``` interface Sandbox { sandboxId: string; provider: string; runCode(code: string, runtime?: Runtime): Promise; runCommand(command: string, args?: string[]): Promise; filesystem: FilesystemAPI; terminal: TerminalAPI; getInfo(): Promise; } ``` # Terminal > Interactive terminal operations in sandboxes Create and manage interactive terminal sessions within sandboxes. > **Note:** Terminal operations are currently only supported by the E2B provider. ## Methods [Section titled “Methods”](#methods) ### `sandbox.terminal.create(options)` [Section titled “sandbox.terminal.create(options)”](#sandboxterminalcreateoptions) Create a new terminal session. ``` const terminal = await sandbox.terminal.create({ command: 'bash', cols: 80, rows: 24, onData: (data: Uint8Array) => { const output = new TextDecoder().decode(data); console.log('Terminal output:', output); } }); ``` **Parameters:** * `options` - Terminal configuration * `command` - Shell command to run (‘bash’, ‘sh’, ‘python3’, etc.) * `cols` - Terminal width in columns * `rows` - Terminal height in rows * `onData?` - Callback for terminal output **Returns:** Terminal instance ### `sandbox.terminal.list()` [Section titled “sandbox.terminal.list()”](#sandboxterminallist) List all terminal sessions. ``` const terminals = await sandbox.terminal.list(); console.log(`Active terminals: ${terminals.length}`); ``` **Returns:** Array of terminal instances ### `sandbox.terminal.getById(id)` [Section titled “sandbox.terminal.getById(id)”](#sandboxterminalgetbyidid) Get a terminal session by ID. ``` const terminal = await sandbox.terminal.getById('terminal-id'); ``` **Parameters:** * `id` - Terminal ID string **Returns:** Terminal instance ## Terminal Instance Methods [Section titled “Terminal Instance Methods”](#terminal-instance-methods) ### `terminal.write(data)` [Section titled “terminal.write(data)”](#terminalwritedata) Write data to the terminal. ``` // Send commands await terminal.write('ls -la\n'); await terminal.write('cd /workspace\n'); await terminal.write('python3 script.py\n'); // Interactive input await terminal.write('y\n'); // Respond to prompt ``` **Parameters:** * `data` - Data string to write ### `terminal.resize(cols, rows)` [Section titled “terminal.resize(cols, rows)”](#terminalresizecols-rows) Resize the terminal. ``` await terminal.resize(120, 30); // Larger terminal ``` **Parameters:** * `cols` - New width in columns * `rows` - New height in rows ### `terminal.kill()` [Section titled “terminal.kill()”](#terminalkill) Terminate the terminal session. ``` await terminal.kill(); ``` ### `terminal.destroy()` [Section titled “terminal.destroy()”](#terminaldestroy) Destroy the terminal (alias for kill). ``` await terminal.destroy(); ``` ## Types [Section titled “Types”](#types) ``` interface Terminal { id: string; command: string; cols: number; rows: number; write(data: string): Promise; resize(cols: number, rows: number): Promise; kill(): Promise; destroy(): Promise; } interface TerminalOptions { command: string; cols: number; rows: number; onData?: (data: Uint8Array) => void; } ``` ## Examples [Section titled “Examples”](#examples) ### Interactive Python Session [Section titled “Interactive Python Session”](#interactive-python-session) ``` const terminal = await sandbox.terminal.create({ command: 'python3', cols: 80, rows: 24, onData: (data) => { const output = new TextDecoder().decode(data); process.stdout.write(output); // Forward to console } }); // Send Python commands await terminal.write('import numpy as np\n'); await terminal.write('import pandas as pd\n'); await terminal.write('print("Libraries loaded!")\n'); // Create data and analyze await terminal.write('data = np.array([1, 2, 3, 4, 5])\n'); await terminal.write('print(f"Mean: {data.mean()}")\n'); await terminal.write('print(f"Sum: {data.sum()}")\n'); // Exit Python await terminal.write('exit()\n'); // Clean up await terminal.kill(); ``` ### Interactive Shell Session [Section titled “Interactive Shell Session”](#interactive-shell-session) ``` const terminal = await sandbox.terminal.create({ command: 'bash', cols: 100, rows: 30, onData: (data) => { const output = new TextDecoder().decode(data); console.log('Shell:', output); } }); // Set up environment await terminal.write('cd /workspace\n'); await terminal.write('export PATH=$PATH:/usr/local/bin\n'); // Create and run script await terminal.write('cat > hello.sh << EOF\n'); await terminal.write('#!/bin/bash\n'); await terminal.write('echo "Hello from terminal script!"\n'); await terminal.write('echo "Current directory: $(pwd)"\n'); await terminal.write('echo "Current user: $(whoami)"\n'); await terminal.write('EOF\n'); await terminal.write('chmod +x hello.sh\n'); await terminal.write('./hello.sh\n'); // List files await terminal.write('ls -la\n'); // Clean up await terminal.kill(); ``` ### Long-running Process Management [Section titled “Long-running Process Management”](#long-running-process-management) ``` const terminal = await sandbox.terminal.create({ command: 'bash', cols: 80, rows: 24, onData: (data) => { const output = new TextDecoder().decode(data); // Handle different types of output if (output.includes('ERROR')) { console.error('Process error:', output); } else if (output.includes('COMPLETE')) { console.log('Process completed:', output); } else { console.log('Process output:', output); } } }); // Start long-running process await terminal.write('python3 -c "\n'); await terminal.write('import time\n'); await terminal.write('for i in range(10):\n'); await terminal.write(' print(f"Step {i+1}/10")\n'); await terminal.write(' time.sleep(1)\n'); await terminal.write('print("COMPLETE")\n'); await terminal.write('"\n'); // Wait for process to complete (in real app, use proper event handling) await new Promise(resolve => setTimeout(resolve, 12000)); // Check if still active const terminals = await sandbox.terminal.list(); const activeTerminal = terminals.find(t => t.id === terminal.id); if (activeTerminal) { await terminal.kill(); } ``` ### Multiple Terminal Sessions [Section titled “Multiple Terminal Sessions”](#multiple-terminal-sessions) ``` // Create multiple terminals for different tasks const shellTerminal = await sandbox.terminal.create({ command: 'bash', cols: 80, rows: 24 }); const pythonTerminal = await sandbox.terminal.create({ command: 'python3', cols: 80, rows: 24 }); // Use shell terminal for setup await shellTerminal.write('mkdir -p /workspace/data\n'); await shellTerminal.write('cd /workspace/data\n'); await shellTerminal.write('echo "sample data" > input.txt\n'); // Use Python terminal for processing await pythonTerminal.write('import os\n'); await pythonTerminal.write('os.chdir("/workspace/data")\n'); await pythonTerminal.write('with open("input.txt", "r") as f:\n'); await pythonTerminal.write(' data = f.read().strip()\n'); await pythonTerminal.write('print(f"Data: {data}")\n'); // Clean up both terminals await shellTerminal.kill(); await pythonTerminal.kill(); ``` # UI Package > Frontend integration utilities for ComputeSDK - Types, hooks, and utilities for building compute interfaces across any framework # @computesdk/ui [Section titled “@computesdk/ui”](#computesdkui) Frontend integration utilities for ComputeSDK - Types, hooks, and utilities for building compute interfaces across any framework. ## Installation [Section titled “Installation”](#installation) ``` npm install @computesdk/ui ``` ## What’s Included [Section titled “What’s Included”](#whats-included) ### Types [Section titled “Types”](#types) Complete TypeScript definitions for ComputeSDK API integration: ``` import type { ComputeRequest, ComputeResponse, ComputeConfig, Runtime, FrontendSandbox, FrontendTerminal } from '@computesdk/ui' ``` ### useCompute Hook [Section titled “useCompute Hook”](#usecompute-hook) Framework-agnostic hook for compute operations: ``` import { useCompute } from '@computesdk/ui' const compute = useCompute({ apiEndpoint: '/api/compute', defaultRuntime: 'python' }) // Create sandbox const sandbox = await compute.sandbox.create() // Execute code const result = await sandbox.runCode('print("Hello World!")') ``` ### API Utilities [Section titled “API Utilities”](#api-utilities) Helper functions for making requests to ComputeSDK APIs: ``` import { executeComputeRequest, APIError } from '@computesdk/ui' const response = await executeComputeRequest({ action: 'compute.sandbox.runCode', code: 'print("Hello World!")', runtime: 'python' }, '/api/compute') ``` ### Validation Utilities [Section titled “Validation Utilities”](#validation-utilities) Input validation for compute operations: ``` import { validateCode, validateRuntime, validateComputeRequest } from '@computesdk/ui' const codeValidation = validateCode('print("hello")') if (!codeValidation.isValid) { console.error(codeValidation.errors) } ``` ## API Reference [Section titled “API Reference”](#api-reference) ### useCompute Hook [Section titled “useCompute Hook”](#usecompute-hook-1) The main hook for compute operations. Returns a `ComputeHook` object with sandbox management capabilities. ``` function useCompute(config?: UseComputeConfig): ComputeHook ``` **Configuration:** ``` interface UseComputeConfig { apiEndpoint?: string; // Default: '/api/compute' defaultRuntime?: Runtime; // Default: 'python' timeout?: number; // Request timeout in ms retries?: number; // Number of retry attempts } ``` **Returns:** ``` interface ComputeHook { sandbox: { create: (options?: { runtime?: Runtime; timeout?: number }) => Promise; get: (sandboxId: string) => Promise; list: () => Promise; destroy: (sandboxId: string) => Promise; }; } ``` ### FrontendSandbox [Section titled “FrontendSandbox”](#frontendsandbox) Mirrors the server-side sandbox API with all operations: ``` interface FrontendSandbox { id: string; provider: string; // Code execution runCode: (code: string, runtime?: Runtime) => Promise; runCommand: (command: string, args?: string[]) => Promise; // Sandbox management getInfo: () => Promise; destroy: () => Promise; // Filesystem operations filesystem: { readFile: (path: string) => Promise; writeFile: (path: string, content: string) => Promise; mkdir: (path: string) => Promise; readdir: (path: string) => Promise; exists: (path: string) => Promise; remove: (path: string) => Promise; }; // Terminal operations terminal: { create: (options?: TerminalOptions) => Promise; getById: (terminalId: string) => Promise; list: () => Promise; destroy: (terminalId: string) => Promise; }; } ``` ### FrontendTerminal [Section titled “FrontendTerminal”](#frontendterminal) Interactive terminal with real-time I/O via Server-Sent Events: ``` interface FrontendTerminal { pid: number; command: string; status: 'running' | 'exited'; cols: number; rows: number; exitCode?: number; // Terminal operations write: (data: Uint8Array | string) => Promise; resize: (cols: number, rows: number) => Promise; kill: () => Promise; // Event handlers onData?: (data: Uint8Array) => void; // Auto-starts SSE streaming onExit?: (exitCode: number) => void; } ``` ### Core Types [Section titled “Core Types”](#core-types) #### ComputeRequest [Section titled “ComputeRequest”](#computerequest) Request structure for all compute operations: ``` interface ComputeRequest { action: 'compute.sandbox.create' | 'compute.sandbox.runCode' | /* ... */; sandboxId?: string; code?: string; runtime?: Runtime; path?: string; content?: string; // ... more fields for specific operations } ``` #### ComputeResponse [Section titled “ComputeResponse”](#computeresponse) Response structure from compute operations: ``` interface ComputeResponse { success: boolean; error?: string; sandboxId: string; provider: string; result?: ExecutionResult; fileContent?: string; files?: FileEntry[]; // ... more fields for specific operations } ``` ### Utility Functions [Section titled “Utility Functions”](#utility-functions) #### executeComputeRequest [Section titled “executeComputeRequest”](#executecomputerequest) Generic function for any compute operation: ``` async function executeComputeRequest( request: ComputeRequest, endpoint?: string ): Promise ``` #### Validation Functions [Section titled “Validation Functions”](#validation-functions) Input validation utilities: ``` function validateCode(code: string): ValidationResult function validateRuntime(runtime: string): ValidationResult function validateComputeRequest(request: ComputeRequest): ValidationResult function validateComputeConfig(config: ComputeConfig): ValidationResult ``` #### Formatting Utilities [Section titled “Formatting Utilities”](#formatting-utilities) Display helpers: ``` function formatExecutionTime(milliseconds: number): string function formatOutput(output: string): string function isComputeError(response: ComputeResponse): boolean function getErrorMessage(response: ComputeResponse): string ``` ## Framework Integration [Section titled “Framework Integration”](#framework-integration) This package is framework-agnostic. Use it with any frontend framework: ### React Example [Section titled “React Example”](#react-example) ``` import React, { useState } from 'react' import { useCompute, type ComputeResponse } from '@computesdk/ui' function CodeExecutor() { const [code, setCode] = useState('print("Hello World!")') const [result, setResult] = useState(null) const [loading, setLoading] = useState(false) const compute = useCompute({ apiEndpoint: '/api/compute', defaultRuntime: 'python' }) const executeCode = async () => { setLoading(true) try { const sandbox = await compute.sandbox.create() const response = await sandbox.runCode(code) setResult(response) await sandbox.destroy() } catch (error) { console.error('Execution failed:', error) } finally { setLoading(false) } } return (