# ComputeSDK ## Introduction Source: https://computesdk-docs.docsalot.dev/getting-started/introduction ## What is ComputeSDK? ComputeSDK gives you one consistent API to control sandboxes across multiple providers. Spin up isolated environments, execute shell commands, work with filesystems, and more without worrying about vendor-specific APIs. Perfect for building AI agents that execute code, running untrusted code safely, or orchestrating cloud workloads all while remaining provider-agnostic. ## How It Works ComputeSDK is built around provider packages. Each provider has its own package under the `@computesdk/` scope that you install directly. You only install the providers you need, keeping your dependencies lean. **Sandboxes** - Isolated compute environments where code executes safely **Providers** - Cloud platforms hosting the sandboxes, each available as a standalone package When you install a provider package like `@computesdk/e2b`, you get a factory function that creates a compute instance configured for that provider. Every provider returns the same unified sandbox interface, so your application code stays the same even if you swap providers later. ## Available Providers | Package | Provider | |---------|----------| | `@computesdk/archil` | Archil | | `@computesdk/blaxel` | Blaxel | | `@computesdk/cloudflare` | Cloudflare | | `@computesdk/codesandbox` | CodeSandbox | | `@computesdk/daytona` | Daytona | | `@computesdk/declaw` | Declaw | | `@computesdk/e2b` | E2B | | `@computesdk/hopx` | HopX | | `@computesdk/modal` | Modal | | `@computesdk/namespace` | Namespace | | `@computesdk/runloop` | Runloop | | `@computesdk/tensorlake` | Tensorlake | | `@computesdk/upstash` | Upstash | | `@computesdk/vercel` | Vercel | ## Why ComputeSDK? **Provider-agnostic** - Switch between providers without code changes **Pick what you need** - Install only the provider packages your project requires **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: - **Code execution platforms** - Run user-submitted code safely - **Educational tools** - Interactive coding environments - **Data analysis applications** - Process code with filesystem access - **AI-powered development tools** - Let AI agents write and execute code - **Testing & CI/CD systems** - Isolated test environments ## Features **Multi-provider support** - 10+ providers available as individual packages **Filesystem operations** - Read, write, create directories **Command execution** - Run shell commands directly **Type-safe** - Full TypeScript support with comprehensive error handling ## Quick Example Install the provider package for the platform you want to use: ```bash npm install @computesdk/e2b ``` Set the provider's credentials: ```bash export E2B_API_KEY=your_e2b_api_key ``` Create a sandbox and run a command: ```typescript import { e2b } from '@computesdk/e2b'; // Create a compute instance for E2B const compute = e2b({ apiKey: process.env.E2B_API_KEY }); // Create a sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello World!"'); console.log(result.stdout); // "Hello World!" // Clean up await sandbox.destroy(); ``` ### Using Multiple Providers You can use multiple providers in the same project. Install the packages you need and create separate compute instances: ```bash npm install @computesdk/e2b @computesdk/modal ``` ```typescript import { e2b } from '@computesdk/e2b'; import { modal } from '@computesdk/modal'; // Create compute instances for each provider const e2bCompute = e2b({ apiKey: process.env.E2B_API_KEY }); const modalCompute = modal({ tokenId: process.env.MODAL_TOKEN_ID, tokenSecret: process.env.MODAL_TOKEN_SECRET, }); // Use one provider for lightweight tasks const lightSandbox = await e2bCompute.sandbox.create(); await lightSandbox.runCommand('echo "Quick task"'); await lightSandbox.destroy(); // Use another provider for GPU-intensive workloads const gpuSandbox = await modalCompute.sandbox.create(); await gpuSandbox.runCommand('python -c "import torch; print(torch.cuda.is_available())"'); await gpuSandbox.destroy(); ``` The sandbox API is identical across providers, so you can write helper functions that work with any provider's sandboxes interchangeably. ### Multi-Provider in a Single Config If you'd rather configure several providers together — for resilience, routing, or load balancing — install the `computesdk` core package alongside the providers you want: ```bash npm install computesdk @computesdk/e2b @computesdk/modal ``` Register multiple providers with `compute.setConfig` and choose a strategy: ```typescript import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; import { modal } from '@computesdk/modal'; compute.setConfig({ providers: [ e2b({ apiKey: process.env.E2B_API_KEY }), modal({ tokenId: process.env.MODAL_TOKEN_ID, tokenSecret: process.env.MODAL_TOKEN_SECRET, }), ], providerStrategy: 'priority', // 'priority' (default) or 'round-robin' fallbackOnError: true, // try the next provider if one fails }); // Uses the configured strategy const sandbox = await compute.sandbox.create(); // Override per call to target a specific provider by name const gpuSandbox = await compute.sandbox.create({ provider: 'modal' }); ``` **Strategies** - `priority` — always try providers in order; combine with `fallbackOnError: true` to cascade on failure - `round-robin` — distribute new sandboxes evenly across providers Operations like `destroy` and snapshots automatically route to the provider that owns each sandbox, so you don't need to track affinity yourself. ## Next Steps Ready to get started? Check out our [installation guide](/docs/getting-started/installation) or dive into the [quick start](/docs/getting-started/quick-start) to begin building with ComputeSDK. --- ## Installation Source: https://computesdk-docs.docsalot.dev/getting-started/installation ## Install a Provider Package Install the provider package for the platform you want to use: ```bash # Pick one (or more) providers npm install @computesdk/archil npm install @computesdk/blaxel npm install @computesdk/cloudflare npm install @computesdk/codesandbox npm install @computesdk/daytona npm install @computesdk/declaw npm install @computesdk/e2b npm install @computesdk/hopx npm install @computesdk/modal npm install @computesdk/namespace npm install @computesdk/runloop npm install @computesdk/tensorlake npm install @computesdk/upstash npm install @computesdk/vercel ``` You only need to install the providers your project uses. ## Provider Credentials Each provider requires its own API credentials. Add them to a `.env` file in the root of your project or export them in your shell: ### Archil ```bash ARCHIL_API_KEY=your_archil_api_key ARCHIL_REGION=aws-us-east-1 ARCHIL_DISK_ID=your_archil_disk_id ``` ### Blaxel ```bash BL_API_KEY=your_blaxel_api_key BL_WORKSPACE=your_blaxel_workspace ``` ### Cloudflare ```bash CLOUDFLARE_API_TOKEN=your_cloudflare_api_token CLOUDFLARE_ACCOUNT_ID=your_cloudflare_account_id ``` ### CodeSandbox ```bash CSB_API_KEY=your_codesandbox_api_key ``` ### Daytona ```bash DAYTONA_API_KEY=your_daytona_api_key ``` ### Declaw ```bash DECLAW_API_KEY=your_declaw_api_key ``` ### E2B ```bash E2B_API_KEY=your_e2b_api_key ``` ### HopX ```bash HOPX_API_KEY=your_hopx_api_key ``` ### Modal ```bash MODAL_TOKEN_ID=your_modal_token_id MODAL_TOKEN_SECRET=your_modal_token_secret ``` ### Namespace ```bash NSC_TOKEN=your_namespace_nsc_token ``` ### Runloop ```bash RUNLOOP_API_KEY=your_runloop_api_key ``` ### Tensorlake ```bash TENSORLAKE_API_KEY=your_tensorlake_api_key ``` ### Upstash ```bash UPSTASH_BOX_API_KEY=your_upstash_box_api_key ``` ### Vercel ```bash VERCEL_TOKEN=your_vercel_token VERCEL_TEAM_ID=your_team_id VERCEL_PROJECT_ID=your_project_id ``` Refer to each provider's documentation page for the full list of supported environment variables and configuration options. ## Verify Your Setup After installing a provider and setting credentials, verify everything works: ```typescript import { e2b } from '@computesdk/e2b'; const compute = e2b({ apiKey: process.env.E2B_API_KEY }); const sandbox = await compute.sandbox.create(); const result = await sandbox.runCommand('echo "Hello from ComputeSDK!"'); console.log(result.stdout); // "Hello from ComputeSDK!" await sandbox.destroy(); ``` Replace the import and configuration with whichever provider you installed. --- ## Quick Start Source: https://computesdk-docs.docsalot.dev/getting-started/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 Install the provider package for the platform you want to use. This guide uses E2B as an example, but the sandbox API is the same across all providers. ```bash npm install @computesdk/e2b ``` Then add your provider credentials to a `.env` file: ```bash E2B_API_KEY=your_e2b_api_key ``` ## Basic Usage A **sandbox** is an isolated compute environment where you can safely execute code. Each sandbox runs on your chosen cloud provider (E2B, Modal, Vercel, etc.) with a unified interface. The `create()` method provisions a new sandbox, `runCommand()` executes shell commands and returns the result, and `destroy()` tears down the sandbox to free resources. ```typescript import { e2b } from '@computesdk/e2b'; // Create a compute instance for your provider const compute = e2b({ apiKey: process.env.E2B_API_KEY }); // Create a sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello World!"'); console.log(result.stdout); // "Hello World!" // Clean up await sandbox.destroy(); ``` ## Filesystem Operations Each sandbox has its own isolated filesystem. You can read, write, and manage files using absolute paths (starting with `/`). Files persist for the sandbox lifetime and are destroyed when you call `destroy()`. ```typescript // 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 Use `runCommand()` for shell operations, package installation, or system commands. It provides full shell access with detailed execution results including stdout, stderr, exit codes, and execution time. ```typescript // 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 ComputeSDK methods throw exceptions for API/network failures. For command execution errors, check the `exitCode` in the result rather than relying on exceptions. Exit code `0` indicates success, non-zero indicates failure. ```typescript try { const sandbox = await compute.sandbox.create(); const result = await sandbox.runCommand('some-command'); } catch (error) { console.error('Failed:', error.message); } ``` ## Essential Patterns ### Resource Cleanup (Critical for Production) Always destroy sandboxes when done to avoid resource leaks and unnecessary costs. Sandboxes consume resources until explicitly destroyed or they timeout. ```typescript // ✅ Recommended: Use try-finally let sandbox; try { sandbox = await compute.sandbox.create(); await sandbox.runCommand('echo "Hello"'); } finally { await sandbox?.destroy(); } ``` ### Error Handling with Exit Codes Commands return exit codes following Unix conventions: `0` means success, non-zero indicates failure. Always check `exitCode` rather than catching exceptions for command failures. ```typescript const result = await sandbox.runCommand('npm test'); if (result.exitCode !== 0) { console.error('Tests failed:', result.stderr); } else { console.log('Tests passed!', result.stdout); } ``` ## Understanding Results ### Command Execution Results When you call `runCommand()`, you receive: - `stdout`: Standard output (normal program output) - `stderr`: Standard error (error messages and warnings) - `exitCode`: `0` for success, non-zero for failures - `durationMs`: Execution time in milliseconds ```typescript const result = await sandbox.runCommand('npm install'); console.log(result.stdout); // Installation logs console.log(result.stderr); // Warnings or errors console.log(result.exitCode); // 0 console.log(result.durationMs); // 2341 ``` --- ## compute Source: https://computesdk-docs.docsalot.dev/reference/compute ## Overview `compute` is ComputeSDK's unified entrypoint for managing sandboxes across one or more providers. There are two import styles you can use: 1. **Direct provider mode** — import a provider package (e.g. `@computesdk/e2b`) and use the returned instance as your compute object. Best for single-provider apps. 2. **Core `compute` from `computesdk`** — import `compute` from the `computesdk` package and configure it with one or more provider instances. Best when you want resilient routing, round-robin load balancing, or a single module-level entrypoint that multiple files share. Both modes expose the same shape: `compute.sandbox.*` for sandbox lifecycle and operations, and `compute.snapshot.*` for snapshot management (when supported by the provider). Every provider package depends on `computesdk`, so it is always installed alongside them — the choice between the two modes is purely about what you import. ## Installation Install the provider packages you need. `computesdk` is pulled in automatically as a dependency of every provider package, so you don't need to list it separately (though listing it explicitly is harmless and makes the intent clear when you use the `compute` import). ```bash # Single provider — computesdk is installed transitively npm install @computesdk/e2b # Multiple providers npm install @computesdk/e2b @computesdk/modal # Explicit (equivalent to the above, just makes the dependency visible) npm install computesdk @computesdk/e2b @computesdk/modal ``` ## Provider Credentials Each provider reads its own environment variables. See the [installation guide](../getting-started/installation.md) for the full list or the individual provider reference pages under `/docs/providers`. ```bash # Example: E2B E2B_API_KEY=your_e2b_api_key # Example: Modal MODAL_TOKEN_ID=your_modal_token_id MODAL_TOKEN_SECRET=your_modal_token_secret ``` --- ## Direct Provider Mode Call the provider factory with credentials and use the returned object as your `compute` instance. This is the fastest path for a single-provider app. ```typescript import { e2b } from '@computesdk/e2b'; const compute = e2b({ apiKey: process.env.E2B_API_KEY }); const sandbox = await compute.sandbox.create(); const result = await sandbox.runCommand('echo "Hello!"'); console.log(result.stdout); await sandbox.destroy(); ``` **Notes:** - Every provider factory (`e2b`, `modal`, `vercel`, `daytona`, etc.) returns an object with the same shape. - Swapping providers is usually a one-line change: replace the import and factory call. - No core `computesdk` import is required in this mode.
--- ## Core `compute` Mode Import `compute` from `computesdk` and register one or more providers. The same `compute` singleton is used throughout your app. ### Single Provider ```typescript 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(); await sandbox.runCommand('echo "Hello!"'); await sandbox.destroy(); ``` ### Multi-Provider Pass a `providers` array to configure several providers under the same `compute` entrypoint: ```typescript import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; import { modal } from '@computesdk/modal'; compute.setConfig({ providers: [ e2b({ apiKey: process.env.E2B_API_KEY }), modal({ tokenId: process.env.MODAL_TOKEN_ID, tokenSecret: process.env.MODAL_TOKEN_SECRET, }), ], providerStrategy: 'priority', // 'priority' (default) or 'round-robin' fallbackOnError: true, // default: true }); // Uses the configured strategy const sandbox = await compute.sandbox.create(); // Override for one call const gpuSandbox = await compute.sandbox.create({ provider: 'modal' }); ``` ### Callable Form You can also call `compute(config)` to get a new, isolated instance without touching the singleton — useful for request-scoped configuration, testing, or running multiple independent configurations side by side. ```typescript import { compute } from 'computesdk'; import { vercel } from '@computesdk/vercel'; const scoped = compute({ provider: vercel({ token: process.env.VERCEL_TOKEN, teamId: process.env.VERCEL_TEAM_ID, projectId: process.env.VERCEL_PROJECT_ID, }), }); const sandbox = await scoped.sandbox.create(); ```
--- ## `compute.setConfig(config)` Configure the module-level `compute` singleton. **Parameters:** - `config` (ExplicitComputeConfig, required): - `provider` (DirectProvider, optional) — single primary provider - `providers` (DirectProvider[], optional) — ordered list of providers - `providerStrategy` (`'priority' | 'round-robin'`, optional) — default `'priority'` - `fallbackOnError` (boolean, optional) — default `true` At least one of `provider` or `providers` must be supplied. When both are provided, `provider` is treated as the first provider, and duplicates (by `.name`) are removed from `providers`. **Returns:** `void` **Examples:** ```typescript import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; import { modal } from '@computesdk/modal'; // Single provider compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY }), }); // Multi-provider with priority routing + failover compute.setConfig({ providers: [ e2b({ apiKey: process.env.E2B_API_KEY }), modal({ tokenId: process.env.MODAL_TOKEN_ID, tokenSecret: process.env.MODAL_TOKEN_SECRET, }), ], providerStrategy: 'priority', fallbackOnError: true, }); // Multi-provider with round-robin load balancing compute.setConfig({ providers: [ e2b({ apiKey: process.env.E2B_API_KEY }), modal({ tokenId: process.env.MODAL_TOKEN_ID, tokenSecret: process.env.MODAL_TOKEN_SECRET, }), ], providerStrategy: 'round-robin', }); // Primary + fallback pool compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY }), // primary providers: [ // fallbacks modal({ tokenId: process.env.MODAL_TOKEN_ID, tokenSecret: process.env.MODAL_TOKEN_SECRET, }), ], }); ``` **Notes:** - Re-calling `setConfig` replaces the prior configuration and resets internal routing state (round-robin cursor, sandbox-to-provider affinity cache). - Providers are deduplicated by their `name` property, so the same provider registered twice is only called once.
--- ## Provider Selection Strategies When more than one provider is configured, ComputeSDK picks which one to use per call based on `providerStrategy`. ### `priority` (default) Providers are tried in the order you passed them. The first successful one handles the call. If `fallbackOnError` is `true`, failures cascade to the next provider. ```typescript compute.setConfig({ providers: [e2b({...}), modal({...})], providerStrategy: 'priority', fallbackOnError: true, }); // Tries e2b first; falls back to modal only if e2b throws await compute.sandbox.create(); ``` Use when you have a preferred provider and want the others purely as a safety net. ### `round-robin` New sandboxes rotate through providers in order. Good for distributing load evenly across providers with similar capability profiles. ```typescript compute.setConfig({ providers: [e2b({...}), modal({...})], providerStrategy: 'round-robin', }); await compute.sandbox.create(); // e2b await compute.sandbox.create(); // modal await compute.sandbox.create(); // e2b ``` Failover via `fallbackOnError` still applies: if the round-robin pick fails, the next provider is tried.
--- ## `fallbackOnError` Controls whether `create` tries the next provider after a failure. - `true` (default) — on failure, move to the next candidate and keep going until one succeeds or all fail - `false` — the first failure throws immediately ```typescript compute.setConfig({ providers: [e2b({...}), modal({...})], fallbackOnError: false, }); // If e2b throws, the error propagates — modal is never tried await compute.sandbox.create(); ``` **Notes:** - When a caller specifies `{ provider: 'modal' }` explicitly, `fallbackOnError` is ignored for that call — the target provider is the only one tried. - Failover only applies to `create`. Operations on an existing sandbox (`destroy`, snapshot work) use provider affinity instead — see below.
--- ## Per-Call Provider Override Most `compute.sandbox.*` methods accept an optional `provider` field to target a specific provider by name, bypassing the strategy: ```typescript // Force this sandbox onto Modal, regardless of strategy const gpuSandbox = await compute.sandbox.create({ provider: 'modal' }); // Target a specific provider for a snapshot const snap = await compute.snapshot.create(sandboxId, { provider: 'e2b' }); ``` The override must match a configured provider's `.name` exactly. If not, a descriptive error is thrown listing the configured providers.
--- ## Provider Affinity For sandboxes created through `compute`, the owning provider is tracked internally. Operations that act on an existing sandbox prefer the owning provider first: - `compute.sandbox.destroy(sandboxId)` - `compute.sandbox.getById(sandboxId)` - `compute.snapshot.create(sandboxId, options)` - `compute.snapshot.delete(snapshotId)` Affinity is **preferred, not exclusive**: if the owning provider fails, ComputeSDK falls through to the other configured providers. **Caveats:** - Affinity is kept in an in-memory map that is reset every time `setConfig` is called. - Sandbox IDs minted outside the current `compute` instance (e.g., from a different process, or fetched via raw SDK) have no recorded affinity — every configured provider is probed. - This means, in long-running processes, the happy path is one call to the owning provider; in fresh processes with only a stored ID, expect a probe across providers.
--- ## `compute.sandbox.*` The full sandbox API is documented in [compute.sandbox](./computesandbox/). Summary of available methods: | Method | Purpose | |--------|---------| | `create(options?)` | Provision a new sandbox | | `getById(sandboxId)` | Reconnect to an existing sandbox | | `list()` | List active sandboxes (aggregated across providers in multi-provider mode) | | `destroy(sandboxId)` | Tear down a sandbox | All of these accept a `provider` override where applicable. See [Sandbox](./sandbox/) for the instance methods (`runCommand`, `filesystem.*`). > **Reserved methods.** The TypeScript surface also declares `compute.sandbox.find`, `compute.sandbox.findOrCreate`, and `compute.sandbox.extendTimeout`. These are reserved for a future gateway / named-sandbox mode and are not implemented by the currently shipped provider packages — calling them today throws `Provider 'X' does not support …`. Don't rely on them in direct-mode code.
--- ## `compute.snapshot.*` Available when at least one configured provider supports snapshots. | Method | Purpose | |--------|---------| | `create(sandboxId, options?)` | Capture a snapshot of a running sandbox | | `list()` | List snapshots across providers that support listing | | `delete(snapshotId)` | Delete a snapshot | ```typescript const sandbox = await compute.sandbox.create(); const snap = await compute.snapshot.create(sandbox.sandboxId, { name: 'post-setup', metadata: { owner: 'team-backend' }, }); const snapshots = await compute.snapshot.list(); await compute.snapshot.delete(snap.id); ``` **Notes:** - `create` routes to the sandbox's owning provider first; otherwise tries any snapshot-capable provider. - `delete` tracks the owning provider of each snapshot so deletes land on the right platform. - If no configured provider supports snapshots, calls throw a descriptive error.
--- ## Error Handling ComputeSDK surfaces descriptive, aggregated errors when all candidates fail: ```typescript try { const sandbox = await compute.sandbox.create(); } catch (error) { // Example message: // Failed to create sandbox across 2 provider(s). // - e2b: rate limited // - modal: authentication failed console.error(error.message); } ``` Common error cases: - **No provider configured** — Call `compute.setConfig({ provider: ... })` or `compute.setConfig({ providers: [...] })` before any sandbox call. - **`provider: 'foo'` override with no matching provider** — The error lists the configured provider names. - **All providers failed** — The message includes one line per provider with its failure reason.
--- ## End-to-End Example ```typescript import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; import { modal } from '@computesdk/modal'; compute.setConfig({ providers: [ e2b({ apiKey: process.env.E2B_API_KEY }), modal({ tokenId: process.env.MODAL_TOKEN_ID, tokenSecret: process.env.MODAL_TOKEN_SECRET, }), ], providerStrategy: 'priority', fallbackOnError: true, }); async function runUserCode(userId: string, code: string) { const sandbox = await compute.sandbox.create({ timeout: 5 * 60 * 1000, metadata: { userId }, envs: { USER_ID: userId }, }); try { await sandbox.filesystem.writeFile('/tmp/main.py', code); const result = await sandbox.runCommand('python /tmp/main.py'); return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode, provider: sandbox.provider, }; } finally { await sandbox.destroy(); } } ```
--- ## Related - [compute.sandbox](./computesandbox/) — sandbox lifecycle methods - [Sandbox](./sandbox/) — sandbox instance methods (code, commands, filesystem, terminal) - [Introduction](../getting-started/introduction/) — high-level overview - [Installation](../getting-started/installation/) — provider setup and credentials - [Quick Start](../getting-started/quick-start/) — minimal end-to-end walkthrough --- ## compute.sandbox Source: https://computesdk-docs.docsalot.dev/reference/compute.sandbox ## Overview Core methods for creating, destroying, listing, and retrieving sandbox instances. --- ## `create(options?)` Create a new compute sandbox instance. **Parameters:** - `options` (CreateSandboxOptions, optional): Configuration options for sandbox creation - `timeout` (number, optional): Sandbox execution timeout in milliseconds - `templateId` (string, optional): Provider-specific template or image identifier - `metadata` (`Record`, optional): Custom metadata to attach to the sandbox - `envs` (`Record`, optional): Environment variables to set in the sandbox **Returns:** `Promise` - New sandbox instance ready for code execution and commands **Sandbox instance properties:** - `sandboxId` (string): Unique identifier for the sandbox - `provider` (string): Provider hosting the sandbox (e.g., 'e2b', 'modal', 'vercel') - `filesystem` (SandboxFileSystem): File system operations interface - Core methods: `runCommand()`, `getInfo()`, `getUrl()`, `destroy()` - See [Sandbox API Reference](./Sandbox.md) for complete interface documentation **CreateSandboxOptions interface:** ```typescript { timeout?: number; // Execution timeout in milliseconds templateId?: string; // Provider template/image identifier metadata?: Record; // Custom metadata envs?: Record; // Environment variables } ``` **Examples:** ```typescript import { e2b } from '@computesdk/e2b'; const compute = e2b({ apiKey: process.env.E2B_API_KEY }); // Basic sandbox creation const sandbox = await compute.sandbox.create(); console.log(sandbox.sandboxId); // "sb_abc123..." console.log(sandbox.provider); // "e2b" // With timeout (30 minutes) const sandbox = await compute.sandbox.create({ timeout: 30 * 60 * 1000 }); // With environment variables const sandbox = await compute.sandbox.create({ envs: { API_KEY: 'your-api-key', NODE_ENV: 'production', DATABASE_URL: 'postgresql://...' } }); // With provider template/image const sandbox = await compute.sandbox.create({ templateId: 'your-template-id' }); // With custom metadata const sandbox = await compute.sandbox.create({ metadata: { userId: 'user-123', projectId: 'proj-456', environment: 'staging' } }); // With multiple options combined const sandbox = await compute.sandbox.create({ timeout: 60 * 60 * 1000, // 1 hour templateId: 'your-template-id', envs: { NODE_ENV: 'production', DEBUG: 'true' }, metadata: { owner: 'team-backend', purpose: 'integration-tests' } }); // Error handling - missing credentials try { const sandbox = await compute.sandbox.create(); } catch (error) { console.error('Failed to create sandbox:', error.message); } ``` **Notes:** - Configure your provider by importing and initializing a provider package (e.g., `@computesdk/e2b`) with your credentials - Each call creates a new sandbox instance with a unique `sandboxId` - The `timeout` option sets maximum sandbox lifetime; sandboxes auto-terminate after this period - The `templateId` parameter is provider-specific (refers to templates, images, or runtime environments) - Environment variables set via `envs` are available to all commands and code executed in the sandbox - Throws an error if the provider is missing required credentials (e.g., API key)

--- ## `destroy(sandboxId)` Destroy a sandbox and clean up all associated resources. **Parameters:** - `sandboxId` (string, required): Unique identifier of the sandbox to destroy **Returns:** `Promise` - Resolves when sandbox is successfully destroyed > **⚠️ CAUTION:** Destroying a sandbox is a permanent operation. All data, files, and running processes in the sandbox will be irreversibly deleted. **Examples:** ```typescript import { e2b } from '@computesdk/e2b'; const compute = e2b({ apiKey: process.env.E2B_API_KEY }); // Basic cleanup after use const sandbox = await compute.sandbox.create(); // ... use sandbox ... await sandbox.destroy(); // Alternative: destroy by ID await compute.sandbox.destroy(sandbox.sandboxId); // Batch cleanup - destroy multiple sandboxes const sandboxIds = ['sb_123...', 'sb_456...', 'sb_789...']; await Promise.all(sandboxIds.map(id => compute.sandbox.destroy(id))); // With error handling try { await sandbox.destroy(); console.log('Sandbox destroyed successfully'); } catch (error) { console.error('Failed to destroy sandbox:', error.message); } // Best practice: ensure cleanup with finally block let sandbox; try { sandbox = await compute.sandbox.create(); await sandbox.runCommand('echo "Hello"'); } finally { if (sandbox) { await sandbox.destroy(); } } ``` **Notes:** - You can call `sandbox.destroy()` directly on the sandbox instance, or `compute.sandbox.destroy(sandboxId)` with the ID - Destroying a sandbox terminates all running processes and releases all allocated resources - This operation is idempotent - calling destroy on an already-destroyed sandbox succeeds without error - Best practice: Use `finally` blocks or cleanup handlers to ensure sandboxes are destroyed even if errors occur - All sandbox data and files are permanently lost after destruction

--- ## `getById(sandboxId)` Retrieve an existing sandbox instance by its unique identifier. **Parameters:** - `sandboxId` (string, required): Unique identifier of the sandbox to retrieve **Returns:** `Promise` - Sandbox instance if found, or `null` if the sandbox doesn't exist **Sandbox instance properties:** - `sandboxId` (string): Unique identifier for the sandbox - `provider` (string): Provider hosting the sandbox - `filesystem` (SandboxFileSystem): File system operations interface - Core methods: `runCommand()`, `getInfo()`, `getUrl()`, `destroy()` - See [Sandbox API Reference](./Sandbox.md) for complete interface documentation **Examples:** ```typescript import { e2b } from '@computesdk/e2b'; const compute = e2b({ apiKey: process.env.E2B_API_KEY }); // Reconnect to existing sandbox by ID const sandboxId = 'sb_abc123...'; const sandbox = await compute.sandbox.getById(sandboxId); if (sandbox) { const result = await sandbox.runCommand('echo "Reconnected!"'); console.log(result.stdout); // "Reconnected!" } // Store ID and reconnect later // Step 1: Create and store ID const newSandbox = await compute.sandbox.create(); const storedId = newSandbox.sandboxId; // Store storedId in database, config file, etc. // Step 2: Later, retrieve using stored ID const retrievedSandbox = await compute.sandbox.getById(storedId); if (retrievedSandbox) { await retrievedSandbox.runCommand('npm install'); } // Check if sandbox exists before using const sandbox = await compute.sandbox.getById(sandboxId); if (sandbox === null) { console.log('Sandbox not found - creating new one'); const newSandbox = await compute.sandbox.create(); } else { console.log('Sandbox found - using existing one'); await sandbox.runCommand('echo "Still active!"'); } // Graceful handling of missing sandbox const sandboxId = 'sb_might_not_exist...'; const sandbox = await compute.sandbox.getById(sandboxId); if (sandbox) { // Sandbox exists - use it await sandbox.runCommand('npm test'); console.log('Tests completed on existing sandbox'); } else { // Sandbox not found - handle accordingly console.log('Sandbox no longer exists'); } ``` **Notes:** - Returns `null` for non-existent or destroyed sandboxes (does not throw errors) - Retrieved sandboxes have full functionality identical to newly created sandboxes - Useful for reconnecting to long-lived sandboxes or implementing persistent sandbox patterns - Sandbox IDs can be stored and used to reconnect later across application restarts

--- ## `list()` Retrieve a list of your active sandboxes from your provider. ```typescript import { e2b } from '@computesdk/e2b'; const compute = e2b({ apiKey: process.env.E2B_API_KEY }); const sandboxes = await compute.sandbox.list(); for (const sandbox of sandboxes) { console.log(sandbox.sandboxId); } ``` **Notes:** - Returns all active sandboxes for the configured provider - Provider support for listing sandboxes varies — check your provider's documentation for details

--- --- ## Sandbox (interface) Source: https://computesdk-docs.docsalot.dev/reference/Sandbox ## Overview Methods available for interacting with a compute sandbox.

--- ## `runCommand(command, options?)` Execute shell commands in the sandbox with full control over execution environment. **Parameters:** - `command` (string, required): The shell command to execute as a single string - `options` (RunCommandOptions, optional): Execution options - `cwd` (string, optional): Working directory for command execution - `env` (`Record`, optional): Environment variables to set - `timeout` (number, optional): Command timeout in milliseconds - `background` (boolean, optional): Run command in background without waiting for completion **Returns:** `Promise` - Command execution result with output streams, exit code, and duration **CommandResult interface:** - `stdout` (string): Standard output from the command - `stderr` (string): Standard error output from the command - `exitCode` (number): Exit code (0 for success, non-zero for errors) - `durationMs` (number): Command execution duration in milliseconds **Examples:** ```typescript // Simple command execution const result = await sandbox.runCommand('ls -la'); console.log(result.stdout); // Directory listing console.log(result.exitCode); // 0 console.log(result.durationMs); // 45 // Command with working directory const result = await sandbox.runCommand('npm install', { cwd: '/app' }); console.log(result.stdout); // Command with environment variables const result = await sandbox.runCommand('node server.js', { env: { NODE_ENV: 'production', PORT: '3000' } }); // Background command execution const result = await sandbox.runCommand('npm run dev', { background: true }); // Command runs in background, result returns immediately // Combined options const result = await sandbox.runCommand('python script.py', { cwd: '/app/scripts', env: { DEBUG: 'true' }, timeout: 30000 }); // Error handling with exit codes const result = await sandbox.runCommand('grep pattern file.txt'); if (result.exitCode !== 0) { console.error('Command failed:', result.stderr); } else { console.log('Match found:', result.stdout); } // Multi-command execution (use shell operators) const result = await sandbox.runCommand('cd /app && npm install && npm test'); // Command with shell pipes and redirects const result = await sandbox.runCommand('cat data.txt | grep "error" | wc -l'); ``` **Notes:** - Commands are executed as a single string, not as separate command + arguments arrays - Use shell operators (`&&`, `||`, `|`, etc.) within the command string for complex operations - Non-zero exit codes indicate command failure but do not throw errors - check `exitCode` in the result - Background commands return immediately with `exitCode: 0` without waiting for completion - The command runs in a shell context, so all shell features (pipes, redirects, etc.) are available - Available on all sandbox instances regardless of provider

--- ## `getInfo()` Get information about the sandbox including status, provider, and metadata. **Parameters:** None **Returns:** `Promise` - Sandbox information including status and configuration **SandboxInfo interface:** - `id` (string): Unique identifier for the sandbox - `provider` (string): Provider hosting the sandbox (e.g., 'e2b', 'modal', 'docker') - `status` (string): Current sandbox status ('running' | 'stopped' | 'error') - `createdAt` (Date): Timestamp when the sandbox was created - `timeout` (number): Execution timeout in milliseconds - `metadata` (`Record`, optional): Additional provider-specific metadata **Examples:** ```typescript // Basic usage - inspect sandbox info const info = await sandbox.getInfo(); console.log(info.id); // "sb_abc123..." console.log(info.provider); // "e2b" console.log(info.status); // "running" // Check sandbox status const info = await sandbox.getInfo(); if (info.status === 'running') { console.log('Sandbox is active'); await sandbox.runCommand('echo "Hello"'); } else { console.log('Sandbox is not available'); } // Access provider info const info = await sandbox.getInfo(); console.log(`Running on ${info.provider}`); console.log(`Created: ${info.createdAt.toISOString()}`); console.log(`Timeout: ${info.timeout}ms`); // Full info inspection for debugging const info = await sandbox.getInfo(); console.log('Sandbox Information:'); console.log(` ID: ${info.id}`); console.log(` Provider: ${info.provider}`); console.log(` Status: ${info.status}`); console.log(` Created: ${info.createdAt}`); console.log(` Timeout: ${info.timeout}ms`); if (info.metadata) { console.log(` Metadata:`, info.metadata); } ``` **Notes:** - Returns information about the sandbox's current state and configuration - May return locally cached information depending on provider implementation - The `metadata` field contains any custom metadata set during sandbox creation - Available on all sandbox instances regardless of provider

--- ## `getUrl(options)` Get a publicly accessible URL for accessing services running on a specific port in the sandbox. **Parameters:** - `options` (object, required): URL configuration options - `port` (number, required): Port number where the service is running in the sandbox - `protocol` (string, optional): Protocol to use ('http' | 'https'). Defaults to 'https' **Returns:** `Promise` - Publicly accessible URL for the specified port **Examples:** ```typescript // Access web server on port 3000 const url = await sandbox.getUrl({ port: 3000 }); console.log(url); // "https://sandbox-123-3000.preview.computesdk.com" // Use URL to make HTTP request const url = await sandbox.getUrl({ port: 8080 }); const response = await fetch(url); console.log(await response.text()); // Specify HTTP protocol const url = await sandbox.getUrl({ port: 5000, protocol: 'http' }); console.log(url); // "http://sandbox-123-5000.preview.computesdk.com" // Multiple services on different ports const apiUrl = await sandbox.getUrl({ port: 3000 }); const wsUrl = await sandbox.getUrl({ port: 8080 }); console.log('API:', apiUrl); console.log('WebSocket:', wsUrl); // Start server and get URL await sandbox.runCommand('npm start', { background: true }); await new Promise(resolve => setTimeout(resolve, 2000)); // Wait for server const url = await sandbox.getUrl({ port: 3000 }); console.log(`Server running at: ${url}`); // Error case - accessing URL before service is ready const url = await sandbox.getUrl({ port: 3000 }); try { const response = await fetch(url); console.log('Server is ready:', response.status); } catch (error) { console.error('Service not running on port 3000 yet'); // Wait and retry, or start the service first } ``` **Notes:** - Returns a publicly accessible URL that routes to the specified port in your sandbox - URL construction is instantaneous (no network calls) - the URL is available immediately - The service must be running on the specified port for the URL to be accessible

--- ## `sandbox.filesystem` ComputeSDK provides filesystem operations for managing files and directories within sandboxes. All filesystem operations are accessed through the `sandbox.filesystem` object. ### `filesystem.readFile(path)` Read the contents of a file from the sandbox filesystem. **Parameters:** - `path` (string, required): Absolute path to the file to read within the sandbox **Returns:** `Promise` - File contents as UTF-8 encoded string **Examples:** ```typescript // Basic file reading const content = await sandbox.filesystem.readFile('/app/config.txt'); console.log(content); // "port=3000\nhost=localhost" // Read a JSON file const jsonContent = await sandbox.filesystem.readFile('/app/package.json'); const packageData = JSON.parse(jsonContent); console.log(packageData.name); // "my-app" console.log(packageData.version); // "1.0.0" // Read configuration files const envContent = await sandbox.filesystem.readFile('/app/.env'); console.log(envContent); // "API_KEY=secret\nDEBUG=true" // Error handling for non-existent files try { const content = await sandbox.filesystem.readFile('/nonexistent.txt'); } catch (error) { console.error('Failed to read file:', error.message); // "Failed to read file: File not found: /nonexistent.txt" } // Check existence before reading const filePath = '/app/optional-config.json'; if (await sandbox.filesystem.exists(filePath)) { const content = await sandbox.filesystem.readFile(filePath); console.log('Config loaded:', content); } else { console.log('Config file not found, using defaults'); } // Read after writing await sandbox.filesystem.writeFile('/app/output.txt', 'Hello, World!'); const content = await sandbox.filesystem.readFile('/app/output.txt'); console.log(content); // "Hello, World!" // Read code files const scriptContent = await sandbox.filesystem.readFile('/app/server.js'); console.log(scriptContent); // "const express = require('express');\n..." // Read markdown files const readme = await sandbox.filesystem.readFile('/app/README.md'); console.log(readme); // "# My Project\n\nDescription..." ``` **Notes:** - Always returns UTF-8 encoded strings - Throws an error if the file does not exist - Requires absolute paths (paths should start with `/`) - No encoding options available - always returns UTF-8

--- ### `filesystem.writeFile(path, content)` Write content to a file in the sandbox filesystem, creating the file if it doesn't exist. **Parameters:** - `path` (string, required): Absolute path where the file should be written - `content` (string, required): Content to write to the file as UTF-8 text **Returns:** `Promise` - Resolves when the file is successfully written **Examples:** ```typescript // Basic file writing await sandbox.filesystem.writeFile('/app/config.txt', 'port=3000\nhost=localhost'); console.log('File written successfully'); // Write JSON data const data = { name: 'my-app', version: '1.0.0' }; await sandbox.filesystem.writeFile('/app/package.json', JSON.stringify(data, null, 2)); // Write configuration files const envContent = 'API_KEY=secret\nDEBUG=true\nPORT=3000'; await sandbox.filesystem.writeFile('/app/.env', envContent); // Overwrite existing files await sandbox.filesystem.writeFile('/app/log.txt', 'First entry'); await sandbox.filesystem.writeFile('/app/log.txt', 'Second entry'); const content = await sandbox.filesystem.readFile('/app/log.txt'); console.log(content); // "Second entry" (first entry was overwritten) // Error handling try { await sandbox.filesystem.writeFile('/app/data.json', JSON.stringify({ key: 'value' })); console.log('File created successfully'); } catch (error) { console.error('Failed to write file:', error.message); } // Write multiline content with template literals const script = `#!/bin/bash echo "Starting application..." npm install npm start `; await sandbox.filesystem.writeFile('/app/start.sh', script); // Write then read to verify const newContent = 'Hello, World!'; await sandbox.filesystem.writeFile('/app/greeting.txt', newContent); const readBack = await sandbox.filesystem.readFile('/app/greeting.txt'); console.log(readBack === newContent); // true ``` **Notes:** - Always writes UTF-8 encoded text - Creates the file if it doesn't exist - Overwrites existing files completely (previous content is lost) - Requires absolute paths (paths should start with `/`) - No encoding options available - always UTF-8

--- ### `filesystem.mkdir(path)` Create a directory in the sandbox filesystem, automatically creating parent directories as needed. **Parameters:** - `path` (string, required): Absolute path of the directory to create **Returns:** `Promise` - Resolves when the directory is successfully created **Examples:** ```typescript // Basic directory creation await sandbox.filesystem.mkdir('/app/data'); console.log('Directory created'); // Multiple directories for project structure await sandbox.filesystem.mkdir('/app/src'); await sandbox.filesystem.mkdir('/app/tests'); await sandbox.filesystem.mkdir('/app/dist'); // Directory already exists - succeeds silently await sandbox.filesystem.mkdir('/app/data'); await sandbox.filesystem.mkdir('/app/data'); // No error thrown console.log('Both calls succeeded'); // Error handling try { await sandbox.filesystem.mkdir('/app/project/data'); console.log('Directory created successfully'); } catch (error) { console.error('Failed to create directory:', error.message); } ``` **Notes:** - Automatically creates parent directories as needed - Does not throw an error if the directory already exists - Requires absolute paths (paths should start with `/`) - Throws errors only on actual failures (permissions, invalid paths, disk space issues)

--- ### `filesystem.readdir(path)` List the contents of a directory in the sandbox filesystem. **Parameters:** - `path` (string, required): Absolute path to the directory to list **Returns:** `Promise` - Array of entries in the directory **FileEntry interface:** - `name` (string): Name of the file or directory - `type` ('file' | 'directory'): Type of the entry - `size` (number, optional): Size in bytes (for files) - `modified` (Date, optional): Last modification timestamp **Examples:** ```typescript // Basic directory listing const entries = await sandbox.filesystem.readdir('/app'); console.log(entries); // [ // { name: 'config.json', type: 'file', size: 245 }, // { name: 'src', type: 'directory' }, // { name: 'package.json', type: 'file', size: 512 } // ] // List and display all entries const entries = await sandbox.filesystem.readdir('/app'); entries.forEach(entry => { console.log(`${entry.type === 'directory' ? '📁' : '📄'} ${entry.name}`); }); // 📄 config.json // 📁 src // 📄 package.json // Find specific files by extension const entries = await sandbox.filesystem.readdir('/app/src'); const jsFiles = entries.filter(e => e.type === 'file' && e.name.endsWith('.js') ); console.log('JavaScript files:', jsFiles.map(f => f.name)); // Count files and directories const entries = await sandbox.filesystem.readdir('/app'); const fileCount = entries.filter(e => e.type === 'file').length; const dirCount = entries.filter(e => e.type === 'directory').length; console.log(`Found ${fileCount} files and ${dirCount} directories`); // Check if directory is empty const entries = await sandbox.filesystem.readdir('/app/temp'); if (entries.length === 0) { console.log('Directory is empty'); } else { console.log(`Directory contains ${entries.length} items`); } // Error handling for non-existent directories try { const entries = await sandbox.filesystem.readdir('/nonexistent'); console.log(entries); } catch (error) { console.error('Failed to read directory:', error.message); // "Failed to read directory: Directory not found: /nonexistent" } // Check existence before reading const dirPath = '/app/optional-data'; if (await sandbox.filesystem.exists(dirPath)) { const entries = await sandbox.filesystem.readdir(dirPath); console.log(`Found ${entries.length} entries in ${dirPath}`); } else { console.log('Directory does not exist'); } ``` **Notes:** - Returns an array of FileEntry objects with file/directory metadata - Requires absolute paths (paths should start with `/`) - Only lists direct children - does not recursively list subdirectories - Throws an error if the directory does not exist - The `size` and `modified` fields may not be available on all providers - Empty directories return an empty array (not an error)

--- ### `filesystem.exists(path)` Check if a file or directory exists at the specified path in the sandbox filesystem. **Parameters:** - `path` (string, required): Absolute path to the file or directory to check **Returns:** `Promise` - Returns `true` if the path exists (file or directory), `false` otherwise **Examples:** ```typescript // Basic file existence check const exists = await sandbox.filesystem.exists('/app/config.json'); console.log(exists); // true // Basic directory existence check const dirExists = await sandbox.filesystem.exists('/app/src'); console.log(dirExists); // true // Check for non-existent path (returns false, doesn't throw error) const missing = await sandbox.filesystem.exists('/app/nonexistent.txt'); console.log(missing); // false // Check before reading to avoid errors const configPath = '/app/config.json'; if (await sandbox.filesystem.exists(configPath)) { const content = await sandbox.filesystem.readFile(configPath); console.log('Config loaded:', content); } else { console.log('Config file not found, using defaults'); } // Check before writing to avoid overwriting const outputPath = '/app/output.txt'; if (await sandbox.filesystem.exists(outputPath)) { console.log('File already exists, skipping write'); } else { await sandbox.filesystem.writeFile(outputPath, 'New content'); console.log('File created'); } // Verify file creation await sandbox.filesystem.writeFile('/app/data.json', '{}'); const created = await sandbox.filesystem.exists('/app/data.json'); console.log('File created successfully:', created); // true // Verify file deletion await sandbox.filesystem.writeFile('/app/temp.txt', 'temporary'); await sandbox.filesystem.remove('/app/temp.txt'); const stillExists = await sandbox.filesystem.exists('/app/temp.txt'); console.log('File still exists:', stillExists); // false // Verify directory creation await sandbox.filesystem.mkdir('/app/logs'); const dirCreated = await sandbox.filesystem.exists('/app/logs'); console.log('Directory created:', dirCreated); // true // Check multiple files at once const requiredFiles = ['/app/package.json', '/app/src/index.js', '/app/README.md']; const checks = await Promise.all( requiredFiles.map(path => sandbox.filesystem.exists(path)) ); const allExist = checks.every(exists => exists); console.log('All required files present:', allExist); ``` **Notes:** - Returns a boolean value - never throws errors (unlike `readFile` or `readdir`) - Works for both files and directories - no distinction in the return value - Requires absolute paths (paths should start with `/`) - Returns `false` for non-existent paths, not an error - Cannot distinguish between a file and directory from the return value alone - Useful for defensive programming to prevent errors before operations

--- ### `filesystem.remove(path)` Remove a file or directory from the sandbox filesystem. For directories, this recursively removes all contents. **Parameters:** - `path` (string, required): Absolute path to the file or directory to remove **Returns:** `Promise` - Resolves when the file or directory is successfully removed **Examples:** ```typescript // Basic file removal await sandbox.filesystem.writeFile('/app/temp.txt', 'temporary data'); await sandbox.filesystem.remove('/app/temp.txt'); console.log('File removed'); // Basic directory removal (recursive) await sandbox.filesystem.mkdir('/app/old-data'); await sandbox.filesystem.writeFile('/app/old-data/file1.txt', 'data'); await sandbox.filesystem.writeFile('/app/old-data/file2.txt', 'data'); await sandbox.filesystem.remove('/app/old-data'); console.log('Directory and all contents removed'); // Remove file and verify deletion await sandbox.filesystem.writeFile('/app/output.txt', 'content'); await sandbox.filesystem.remove('/app/output.txt'); const exists = await sandbox.filesystem.exists('/app/output.txt'); console.log('File still exists:', exists); // false // Remove directory with nested contents await sandbox.filesystem.mkdir('/app/cache/images/thumbnails'); await sandbox.filesystem.writeFile('/app/cache/data.json', '{}'); await sandbox.filesystem.writeFile('/app/cache/images/photo.jpg', 'image data'); await sandbox.filesystem.remove('/app/cache'); console.log('Entire cache directory tree removed'); // Error handling for non-existent paths try { await sandbox.filesystem.remove('/app/nonexistent.txt'); } catch (error) { console.error('Failed to remove:', error.message); // "Failed to remove: File not found: /app/nonexistent.txt" } // Safe removal with existence check const filePath = '/app/optional-cache.json'; if (await sandbox.filesystem.exists(filePath)) { await sandbox.filesystem.remove(filePath); console.log('Cache file removed'); } else { console.log('No cache file to remove'); } ``` **Notes:** - Works for both files and directories - no distinction needed - **Recursive deletion for directories** - removes all contents and subdirectories (like `rm -rf`) - Requires absolute paths (paths should start with `/`) - Throws an error if the path does not exist - **Deletion is permanent** - no recycle bin, trash, or undo capability - **Use with caution** - destructive operation that cannot be reversed - For directories, all nested files and subdirectories are removed automatically - No confirmation prompt - removal happens immediately --- ## Archil Source: https://computesdk-docs.docsalot.dev/providers/archil Archil provider for ComputeSDK ## Installation & Setup ```bash npm install @computesdk/archil ``` Add your Archil credentials to a `.env` file: ```bash ARCHIL_API_KEY=your_archil_api_key ARCHIL_REGION=aws-us-east-1 ARCHIL_DISK_ID=your_archil_disk_id ``` ## Usage Archil is exec-only — `create()` resolves a handle to an existing Archil disk id. Each command runs in an Archil-managed container with that disk attached. ```typescript import { archil } from '@computesdk/archil'; const compute = archil({ apiKey: process.env.ARCHIL_API_KEY, region: process.env.ARCHIL_REGION, }); // Attach to an existing Archil disk by id const diskId = process.env.ARCHIL_DISK_ID; if (!diskId) throw new Error('ARCHIL_DISK_ID is not set'); const sandbox = await compute.sandbox.create({ diskId }); // Run a shell command against the mounted disk const result = await sandbox.runCommand('echo hello > /mnt/note && cat /mnt/note'); console.log(result.stdout); // "hello" // destroy() is a no-op — disk lifecycle is managed by Archil await sandbox.destroy(); ``` ### Configuration Options ```typescript interface ArchilConfig { /** Archil API key - if not provided, will use ARCHIL_API_KEY env var */ apiKey?: string; /** Archil region (e.g. "aws-us-east-1") - if not provided, will use ARCHIL_REGION env var */ region?: string; /** Override the control-plane base URL (useful for testing) */ baseUrl?: string; } ``` ### Supported Operations | Method | Supported | Notes | | ------------- | --------- | --------------------------------------------------------------------- | | `create` | ✅ | Resolves an existing disk from top-level `diskId`. | | `getById` | ✅ | Requires the disk id. | | `list` | ✅ | Lists all disks visible to the API key. | | `destroy` | no-op | Disk lifecycle is managed by Archil. | | `runCommand` | ✅ | Calls Archil's HTTP `exec` endpoint and waits for completion. | | `getInfo` | ✅ | | | `getUrl` | ❌ | Each exec runs in a fresh ephemeral container — no port to expose. | | `filesystem` | ✅ | Implemented via shell commands (`cat`, `find`, `mkdir`, etc.). | ### Limitations - Each `exec` call provisions a fresh container — no persistent state between calls beyond what is written to the disk. - Responses are truncated to ~5 MB by the Archil control plane. - `getUrl` is not supported — each exec runs in a fresh ephemeral container, so there is no long-lived process to expose a port on. - Filesystem operations are implemented as shell commands, so each call costs one HTTP round trip. --- ## Blaxel Source: https://computesdk-docs.docsalot.dev/providers/blaxel Blaxel provider for ComputeSDK ## Installation & Setup ```bash npm install @computesdk/blaxel ``` Add your Blaxel credentials to a `.env` file: ```bash BL_API_KEY=your_blaxel_api_key BL_WORKSPACE=your_blaxel_workspace ``` ## Usage ```typescript import { blaxel } from '@computesdk/blaxel'; const compute = blaxel({ apiKey: process.env.BL_API_KEY, workspace: process.env.BL_WORKSPACE, }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello from Blaxel!"'); console.log(result.stdout); // "Hello from Blaxel!" // Clean up await sandbox.destroy(); ``` ### Configuration Options ```typescript interface BlaxelConfig { /** Blaxel API key - if not provided, will use BL_API_KEY env var */ apiKey?: string; /** Blaxel workspace ID - if not provided, will use BL_WORKSPACE env var */ workspace?: string; /** Default image for sandboxes */ image?: string; /** Default region for sandbox deployment */ region?: string; /** Default memory allocation in MB (default: 4096) */ memory?: number; } ``` ### Default Images The provider automatically selects images based on the configured runtime: - **Python:** `blaxel/prod-py-app:latest` - **Node.js:** `blaxel/prod-ts-app:latest` - **Default:** `blaxel/prod-base:latest` --- ## Cloudflare Source: https://computesdk-docs.docsalot.dev/providers/cloudflare Cloudflare provider for ComputeSDK - Execute code in secure, isolated sandboxes on Cloudflare's edge network. ## Installation ```bash npm install @computesdk/cloudflare ``` ## Setup Before using the Cloudflare provider, you need to deploy a gateway Worker to your Cloudflare account. This only needs to be done once. ### Step 1: Set Cloudflare credentials Add your Cloudflare credentials to a `.env` file or export them in your shell: ```bash CLOUDFLARE_API_TOKEN=your_cloudflare_api_token CLOUDFLARE_ACCOUNT_ID=your_cloudflare_account_id ``` Your API token needs the following permissions: - Workers Scripts: Read & Edit - Workers KV Storage: Read & Edit - Account Settings: Read - Workers Tail: Read Get your API token at [dash.cloudflare.com/profile/api-tokens](https://dash.cloudflare.com/profile/api-tokens). ### Step 2: Deploy the gateway Worker Run the setup command to deploy the gateway Worker: ```bash npx @computesdk/cloudflare ``` > **Note:** Docker must be installed for the setup command to build the sandbox container image. The setup command will output two values: ``` CLOUDFLARE_SANDBOX_URL=https://computesdk-sandbox..workers.dev CLOUDFLARE_SANDBOX_SECRET= ``` Add these to your `.env` file. These are the only env vars needed at runtime. ## Usage ```typescript import { cloudflare } from '@computesdk/cloudflare'; const compute = cloudflare({ sandboxUrl: process.env.CLOUDFLARE_SANDBOX_URL, sandboxSecret: process.env.CLOUDFLARE_SANDBOX_SECRET, }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello from Cloudflare!"'); console.log(result.stdout); // "Hello from Cloudflare!" // Clean up await sandbox.destroy(); ``` ### Run Commands ```typescript const result = await sandbox.runCommand('ls -la /app'); console.log(result.stdout); ``` ### Filesystem ```typescript await sandbox.filesystem.writeFile('/app/config.json', JSON.stringify({ key: 'value' })); const content = await sandbox.filesystem.readFile('/app/config.json'); await sandbox.filesystem.mkdir('/app/data'); const files = await sandbox.filesystem.readdir('/app'); const exists = await sandbox.filesystem.exists('/app/config.json'); await sandbox.filesystem.remove('/app/temp.txt'); ``` ### Port Forwarding ```typescript const url = await sandbox.getUrl({ port: 3000 }); console.log(`Service available at: ${url}`); ``` ### Environment Variables Pass environment variables at the provider level: ```typescript const compute = cloudflare({ sandboxUrl: process.env.CLOUDFLARE_SANDBOX_URL, sandboxSecret: process.env.CLOUDFLARE_SANDBOX_SECRET, envVars: { API_KEY: 'your-api-key', DATABASE_URL: 'postgresql://localhost:5432/mydb', }, }); ``` Or per-sandbox at creation time: ```typescript const sandbox = await compute.sandbox.create({ envs: { NODE_ENV: 'production' }, }); ``` ### Configuration Options ```typescript interface CloudflareConfig { /** URL of the deployed gateway Worker */ sandboxUrl?: string; /** Shared secret for authenticating with the gateway Worker */ sandboxSecret?: string; /** Durable Object binding (direct mode only - see below) */ sandboxBinding?: any; /** Execution timeout in milliseconds */ timeout?: number; /** Environment variables to pass to sandbox */ envVars?: Record; } ``` ## Limitations - Resource limits apply based on your Cloudflare plan - Some system calls may be restricted in the container environment - Listing all sandboxes is not supported — use `getById` to reconnect to a specific sandbox --- ## CodeSandbox Source: https://computesdk-docs.docsalot.dev/providers/codesandbox CodeSandbox provider for ComputeSDK - Execute code in CodeSandbox development environments. ## Installation & Setup ```bash npm install @computesdk/codesandbox ``` Add your CodeSandbox credentials to a `.env` file: ```bash CSB_API_KEY=your_codesandbox_api_key ``` ## Usage ```typescript import { codesandbox } from '@computesdk/codesandbox'; const compute = codesandbox({ apiKey: process.env.CSB_API_KEY, }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello from CodeSandbox!"'); console.log(result.stdout); // "Hello from CodeSandbox!" // Clean up await sandbox.destroy(); ``` ### Configuration Options ```typescript interface CodesandboxConfig { /** CodeSandbox API key - if not provided, will fallback to CSB_API_KEY environment variable */ apiKey?: string; /** Template to use for new sandboxes */ templateId?: string; /** Execution timeout in milliseconds */ timeout?: number; } ``` --- ## Daytona Source: https://computesdk-docs.docsalot.dev/providers/daytona Daytona provider for ComputeSDK - Execute code in Daytona development workspaces. ## Installation & Setup ```bash npm install @computesdk/daytona ``` Add your Daytona credentials to a `.env` file: ```bash DAYTONA_API_KEY=your_daytona_api_key ``` ## Usage ```typescript import { daytona } from '@computesdk/daytona'; const compute = daytona({ apiKey: process.env.DAYTONA_API_KEY, }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello from Daytona!"'); console.log(result.stdout); // "Hello from Daytona!" // Clean up await sandbox.destroy(); ``` ### Configuration Options ```typescript interface DaytonaConfig { /** Daytona API key - if not provided, will use DAYTONA_API_KEY env var */ apiKey?: string; /** Default runtime environment (e.g. 'node', 'python') */ runtime?: string; /** Execution timeout in milliseconds */ timeout?: number; } ``` --- ## Declaw Source: https://computesdk-docs.docsalot.dev/providers/declaw Declaw provider for ComputeSDK Declaw runs Firecracker microVMs with a built-in security stack: PII scanning, prompt-injection defense, TLS-intercepting egress proxy, and per-sandbox network policies. ## Installation & Setup ```bash npm install @computesdk/declaw ``` Add your Declaw credentials to a `.env` file: ```bash DECLAW_API_KEY=your_declaw_api_key ``` API keys must start with `dcl_`. ## Usage ```typescript import { declaw } from '@computesdk/declaw'; const compute = declaw({ apiKey: process.env.DECLAW_API_KEY, }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('node -v'); console.log(result.stdout); // v20.x.x // Clean up await sandbox.destroy(); ``` ### Configuration Options ```typescript interface DeclawConfig { /** Declaw API key - if not provided, will use DECLAW_API_KEY env var */ apiKey?: string; /** API domain - if not provided, will use DECLAW_DOMAIN env var (default: api.declaw.ai) */ domain?: string; /** Default create-time timeout in milliseconds (default: 300000) */ timeout?: number; } ``` ## Templates `templateId` maps to a Declaw template alias. Defaults to `node` (Ubuntu 22.04 + Node.js 20). **Built-in templates:** - `base` - `node` (default) - `python` - `code-interpreter` - `ai-agent` - `mcp-server` - `web-dev` - `devops` ```typescript const sandbox = await compute.sandbox.create({ templateId: 'python', }); ``` Custom templates can be built through the Declaw CLI — see the [Declaw docs](https://docs.declaw.ai/). --- ## E2B Source: https://computesdk-docs.docsalot.dev/providers/e2b E2B provider for ComputeSDK ## Installation & Setup ```bash npm install @computesdk/e2b ``` Add your E2B credentials to a `.env` file: ```bash E2B_API_KEY=your_e2b_api_key ``` ## Usage ```typescript import { e2b } from '@computesdk/e2b'; const compute = e2b({ apiKey: process.env.E2B_API_KEY, }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello from E2B!"'); console.log(result.stdout); // "Hello from E2B!" // Clean up await sandbox.destroy(); ``` ### Configuration Options ```typescript interface E2BConfig { /** E2B API key - if not provided, will use E2B_API_KEY env var */ apiKey?: string; /** Execution timeout in milliseconds */ timeout?: number; } ``` --- ## HopX Source: https://computesdk-docs.docsalot.dev/providers/hopx HopX provider for ComputeSDK ## Installation & Setup ```bash npm install @computesdk/hopx ``` Add your HopX credentials to a `.env` file: ```bash HOPX_API_KEY=your_hopx_api_key ``` ## Usage ```typescript import { hopx } from '@computesdk/hopx'; const compute = hopx({ apiKey: process.env.HOPX_API_KEY, }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello from HopX!"'); console.log(result.stdout); // "Hello from HopX!" // Clean up await sandbox.destroy(); ``` ### Configuration Options ```typescript interface HopxConfig { /** HopX API key - if not provided, will use HOPX_API_KEY env var */ apiKey?: string; /** Execution timeout in milliseconds */ timeout?: number; /** Template name for sandbox creation (e.g. 'code-interpreter') */ template?: string; /** Base API URL for custom/staging environments */ baseURL?: string; } ``` --- ## Kubernetes Source: https://computesdk-docs.docsalot.dev/providers/k8s Kubernetes provider for ComputeSDK — run each sandbox as a Pod in your cluster and execute commands via `pods/exec`. ## Installation ```bash npm install @computesdk/k8s ``` ## Setup The provider uses your current kubeconfig context by default. It calls `loadFromDefault()` from `@kubernetes/client-node`, which reads `$KUBECONFIG` if set, otherwise `~/.kube/config`. Override with `kubeConfigPath` or `context` in the provider config if you need to target a specific cluster. The identity used by your kubeconfig needs the following RBAC in the target namespace: | Resource | Verbs | |---|---| | `pods` | `create`, `get`, `list`, `delete` | | `pods/exec` | `create` | | `services` | `delete` | Local clusters (kind, k3d, minikube, Docker Desktop) grant cluster-admin by default and need no extra setup. ## Usage ```typescript import { k8s } from '@computesdk/k8s'; const compute = k8s({ namespace: 'default', runtime: 'node', }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello from k8s!"'); console.log(result.stdout); // "Hello from k8s!" // Clean up await sandbox.destroy(); ``` ### Run Commands ```typescript const result = await sandbox.runCommand('ls -la /'); console.log(result.stdout); // Pipes, redirects, cwd, env, background await sandbox.runCommand('node app.js', { cwd: '/app', env: { NODE_ENV: 'production' }, }); await sandbox.runCommand('python server.py', { background: true }); ``` ### Environment Variables Pass environment variables to the Pod at creation time: ```typescript const sandbox = await compute.sandbox.create({ envs: { API_KEY: 'your-api-key', DATABASE_URL: 'postgresql://localhost:5432/mydb', }, }); ``` These are set on the Pod's container spec and available to every command in the sandbox. ### Port Forwarding `getUrl` is template-based in this MVP — set `urlTemplate` to construct routable URLs through your own ingress, gateway, or DNS pattern. The provider substitutes these placeholders: | Placeholder | Value | |---|---| | `{protocol}` | From the `protocol` option (default `http`) | | `{service}` | `-svc` | | `{namespace}` | Pod namespace | | `{port}` | From the `port` option | ```typescript const compute = k8s({ urlTemplate: '{protocol}://{service}.{namespace}.svc.cluster.local:{port}', }); const sandbox = await compute.sandbox.create(); const url = await sandbox.getUrl({ port: 3000 }); // http://computesdk-sbx-abc123-svc.default.svc.cluster.local:3000 ``` If `urlTemplate` is not set, `getUrl` returns a placeholder URL ending in `.invalid` so misconfiguration is obvious. ### Configuration Options ```typescript interface K8sConfig { /** Path to kubeconfig file - if not set, uses $KUBECONFIG or ~/.kube/config */ kubeConfigPath?: string; /** Raw kubeconfig YAML/JSON string - takes precedence over path-based loading */ kubeConfigRaw?: string; /** Kubeconfig context to use - defaults to the current-context */ context?: string; /** Target namespace for created Pods - defaults to "default" */ namespace?: string; /** Container image - defaults to node:20-alpine or python:3.11-slim based on runtime */ image?: string; /** Runtime - defaults to "node" */ runtime?: 'node' | 'python'; /** Time to wait for Pod to reach Running state, in ms - defaults to 120000 */ timeout?: number; /** Service type used when constructing URLs - defaults to "ClusterIP" */ serviceType?: 'ClusterIP' | 'NodePort'; /** Prefix for generated Pod names - defaults to "computesdk-sbx" */ podNamePrefix?: string; /** URL template for getUrl - see Port Forwarding section */ urlTemplate?: string; } ``` Kubeconfig loading precedence: 1. `kubeConfigRaw` 2. `KUBECONFIG_B64` (base64-encoded kubeconfig) 3. `kubeConfigPath` 4. default kubeconfig resolution ## Limitations - Filesystem methods are not implemented in this MVP — use `runCommand` with `cat`, `tee`, etc. to read and write files. - `getUrl` does not provision Kubernetes Services automatically. Set `urlTemplate` to match your existing routing setup. - Pod resource requests and limits are fixed (250m / 256Mi requests, 1 CPU / 1Gi limits). --- ## Modal Source: https://computesdk-docs.docsalot.dev/providers/modal Modal provider for ComputeSDK - Execute code with GPU support for machine learning workloads. ## Installation & Setup ```bash npm install @computesdk/modal ``` Add your Modal credentials to a `.env` file: ```bash MODAL_TOKEN_ID=your_modal_token_id MODAL_TOKEN_SECRET=your_modal_token_secret ``` ## Usage ```typescript import { modal } from '@computesdk/modal'; const compute = modal({ tokenId: process.env.MODAL_TOKEN_ID, tokenSecret: process.env.MODAL_TOKEN_SECRET, }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello from Modal!"'); console.log(result.stdout); // "Hello from Modal!" // Clean up await sandbox.destroy(); ``` ### Configuration Options ```typescript interface ModalConfig { /** Modal token ID - if not provided, will use MODAL_TOKEN_ID env var */ tokenId?: string; /** Modal token secret - if not provided, will use MODAL_TOKEN_SECRET env var */ tokenSecret?: string; /** Execution timeout in milliseconds */ timeout?: number; /** Modal environment (sandbox or main) */ environment?: string; /** Ports to expose (unencrypted by default) */ ports?: number[]; } ``` Ports are exposed with unencrypted tunnels by default for maximum compatibility. --- ## Namespace Source: https://computesdk-docs.docsalot.dev/providers/namespace Namespace provider for ComputeSDK - Deploy and manage containerized sandboxes on Namespace's cloud infrastructure. ## Installation & Setup ```bash npm install @computesdk/namespace ``` Add your Namespace credentials to a `.env` file: ```bash NSC_TOKEN=your_namespace_nsc_token ``` ## Usage ```typescript import { namespace } from '@computesdk/namespace'; const compute = namespace({ token: process.env.NSC_TOKEN, }); // Create a new sandbox const sandbox = await compute.sandbox.create(); console.log(`Sandbox created: ${sandbox.sandboxId}`); // Get sandbox info const info = await sandbox.getInfo(); console.log(`Sandbox status: ${info.status}`); // Clean up when done await sandbox.destroy(); ``` ### Customizing Instance Resources You can customize the compute resources allocated to your sandboxes: ```typescript const compute = namespace({ token: process.env.NSC_TOKEN, virtualCpu: 4, memoryMegabytes: 8192, }); const sandbox = await compute.sandbox.create(); ``` ### Configuration Reference | Option | Environment Variable | Required | Description | |--------|---------------------|----------|-------------| | `token` | `NSC_TOKEN` | Yes | Your Namespace API token | | `virtualCpu` | - | No | Number of virtual CPU cores (default: 2) | | `memoryMegabytes` | - | No | Memory allocation in MB (default: 4096) | | `machineArch` | - | No | Machine architecture (default: 'amd64') | | `os` | - | No | Operating system (default: 'linux') | ```typescript interface NamespaceConfig { /** Namespace API token - if not provided, uses NSC_TOKEN env var */ token?: string; /** Virtual CPU cores for the instance (default: 2) */ virtualCpu?: number; /** Memory in megabytes for the instance (default: 4096) */ memoryMegabytes?: number; /** Machine architecture (default: 'amd64') */ machineArch?: string; /** Operating system (default: 'linux') */ os?: string; } ``` ## Next Steps - Learn about [sandbox lifecycle management](/docs/reference/compute.sandbox) - Explore [Sandbox methods](/docs/reference/sandbox) - View the [@computesdk/namespace package](https://github.com/computesdk/computesdk/blob/main/packages/namespace/README.md) --- ## Runloop Source: https://computesdk-docs.docsalot.dev/providers/runloop Runloop provider for ComputeSDK ## Installation & Setup ```bash npm install @computesdk/runloop ``` Add your Runloop credentials to a `.env` file: ```bash RUNLOOP_API_KEY=your_runloop_api_key ``` ## Usage ```typescript import { runloop } from '@computesdk/runloop'; const compute = runloop({ apiKey: process.env.RUNLOOP_API_KEY, }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello from Runloop!"'); console.log(result.stdout); // "Hello from Runloop!" // Clean up await sandbox.destroy(); ``` ### Configuration Options ```typescript interface RunloopConfig { /** Runloop API key - if not provided, will use RUNLOOP_API_KEY env var */ apiKey?: string; /** Execution timeout in milliseconds */ timeout?: number; } ``` --- ## Tensorlake Source: https://computesdk-docs.docsalot.dev/providers/tensorlake Tensorlake provider for ComputeSDK - Stateful MicroVM sandboxes for agentic applications and LLM-generated code execution. ## Installation & Setup ```bash npm install @computesdk/tensorlake ``` Add your Tensorlake credentials to a `.env` file: ```bash TENSORLAKE_API_KEY=your_tensorlake_api_key ``` ## Usage ```typescript import { tensorlake } from '@computesdk/tensorlake'; const compute = tensorlake({ apiKey: process.env.TENSORLAKE_API_KEY, }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello from Tensorlake!"'); console.log(result.stdout); // "Hello from Tensorlake!" // Clean up await sandbox.destroy(); ``` ### Configuration Options ```typescript interface TensorlakeConfig { /** Tensorlake API key - if not provided, will use TENSORLAKE_API_KEY env var */ apiKey?: string; /** Override for the management API base URL */ apiUrl?: string; /** Override for the sandbox proxy URL */ proxyUrl?: string; /** Default container image for new sandboxes (default: ubuntu-minimal) */ image?: string; /** Execution timeout in milliseconds */ timeout?: number; } ``` ### Sandbox Images Tensorlake supports custom container images. The default is `ubuntu-minimal`: ```typescript const sandbox = await compute.sandbox.create({ image: 'ubuntu-minimal' }); ``` ### Snapshots Tensorlake supports snapshotting sandboxes for fast restores: ```typescript // Create a snapshot from a running sandbox const snapshot = await compute.snapshot.create(sandboxId); // Restore from a snapshot const sandbox = await compute.sandbox.create({ snapshotId: snapshot.id }); ``` --- ## Upstash Source: https://computesdk-docs.docsalot.dev/providers/upstash Upstash provider for ComputeSDK ## Installation & Setup ```bash npm install @computesdk/upstash ``` Add your Upstash credentials to a `.env` file: ```bash UPSTASH_BOX_API_KEY=your_upstash_box_api_key ``` ## Usage ```typescript import { upstash } from '@computesdk/upstash'; const compute = upstash({ apiKey: process.env.UPSTASH_BOX_API_KEY, }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello from Upstash!"'); console.log(result.stdout); // "Hello from Upstash!" // Clean up await sandbox.destroy(); ``` ## Box Types Upstash supports two box variants: - **Default Box** — Full sandbox with filesystem, shell, snapshots, and preview URLs. Best for persistent or long-running work. - **Ephemeral Box** *(optional)* — Lightweight, instant-ready box with code execution and filesystem only. No preview URLs. Best for short-lived, one-off tasks. For more details, see the [Upstash Box documentation](https://upstash.com/docs/box/overall/quickstart). ```typescript // Default box const sandbox = await compute.sandbox.create(); // Ephemeral box const sandbox = await compute.sandbox.create({ ephemeral: true }); ``` ### Configuration Options ```typescript interface UpstashConfig { /** Upstash Box API key - if not provided, will use UPSTASH_BOX_API_KEY env var */ apiKey?: string; /** Default runtime environment (e.g. 'node', 'python') */ runtime?: string; /** Execution timeout in milliseconds (default: 600000) */ timeout?: number; } ``` --- ## Vercel Source: https://computesdk-docs.docsalot.dev/providers/vercel Vercel provider for ComputeSDK - Execute code in globally distributed serverless environments. ## Installation & Setup ```bash npm install @computesdk/vercel ``` Add your Vercel credentials to a `.env` file: ```bash VERCEL_TOKEN=your_vercel_token VERCEL_TEAM_ID=your_vercel_team_id VERCEL_PROJECT_ID=your_vercel_project_id ``` ## Usage ```typescript import { vercel } from '@computesdk/vercel'; const compute = vercel({ token: process.env.VERCEL_TOKEN, teamId: process.env.VERCEL_TEAM_ID, projectId: process.env.VERCEL_PROJECT_ID, }); // Create sandbox const sandbox = await compute.sandbox.create(); // Run a command const result = await sandbox.runCommand('echo "Hello from Vercel!"'); console.log(result.stdout); // "Hello from Vercel!" // Clean up await sandbox.destroy(); ``` ### Configuration Options ```typescript interface VercelConfig { /** Vercel token - if not provided, will use env vars */ token?: string; /** Team ID for team accounts */ teamId?: string; /** Project ID */ projectId?: string; /** Execution timeout in milliseconds */ timeout?: number; } ``` --- ## LLM Documentation Files Source: https://computesdk-docs.docsalot.dev/llm-docs ComputeSDK provides AI-optimized documentation files specifically designed for training large language models (LLMs) and AI assistants. These files contain our complete documentation in a format that's easy for AI systems to understand and use. ## Available Files ### [llms-small.txt](/llms-small.txt) A minimal version containing essential information about ComputeSDK, perfect for quick AI context. ### [llms-full.txt](/llms-full.txt) The complete documentation including all guides, API references, and provider information. This comprehensive file contains everything an AI needs to help users with ComputeSDK. ---