computesdk 1.8.7 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,174 +1,49 @@
1
- import * as _computesdk_client from '@computesdk/client';
1
+ import { Runtime, CodeResult, RunCommandOptions, CommandResult, ProviderSandboxInfo, SandboxFileSystem, CreateSandboxOptions, FileEntry, Sandbox } from '@computesdk/client';
2
+ export { CodeLanguage, CodeResult, CodeRunOptions, CommandExitError, CommandResult, CommandRunOptions, CreateSandboxOptions, FileEntry, RunCommandOptions, Runtime, Sandbox, SandboxConfig, SandboxFileSystem, SandboxStatus, isCommandExitError } from '@computesdk/client';
2
3
 
3
4
  /**
4
- * Sandbox Types
5
- *
6
- * Types related to sandbox execution, filesystem, terminal operations
5
+ * Information about a sandbox (provider-agnostic)
6
+ * @see ProviderSandboxInfo in @computesdk/client for the canonical definition
7
7
  */
8
- interface Provider$1 {
8
+ type SandboxInfo = ProviderSandboxInfo;
9
+
10
+ interface Provider$1<TSandbox = any> {
9
11
  readonly name: string;
10
12
  readonly sandbox: any;
11
13
  }
12
14
  /**
13
- * Type mapping for provider names to their sandbox types
14
- * Manually defined for known providers since declaration merging isn't working reliably
15
- */
16
- interface ProviderSandboxTypeMap {
17
- e2b: any;
18
- vercel: any;
19
- daytona: any;
20
- }
21
- /**
22
- * Utility type to extract the native instance type from a provider
23
- * Uses provider name and manual type inference
24
- */
25
- type ExtractSandboxInstanceType<TProvider extends Provider$1> = TProvider extends {
26
- readonly name: 'e2b';
27
- } ? any : TProvider extends {
28
- readonly name: 'vercel';
29
- } ? any : TProvider extends {
30
- readonly name: 'daytona';
31
- } ? any : any;
32
- /**
33
- * Supported runtime environments
34
- */
35
- type Runtime = 'node' | 'python';
36
- /**
37
- * Sandbox status types
38
- */
39
- type SandboxStatus = 'running' | 'stopped' | 'error';
40
- /**
41
- * Options for running commands
42
- */
43
- interface RunCommandOptions {
44
- /** Run command in background (non-blocking) */
45
- background?: boolean;
46
- }
47
- /**
48
- * Result of code execution
49
- */
50
- interface ExecutionResult {
51
- /** Standard output from the execution */
52
- stdout: string;
53
- /** Standard error from the execution */
54
- stderr: string;
55
- /** Exit code from the execution */
56
- exitCode: number;
57
- /** Time taken for execution in milliseconds */
58
- executionTime: number;
59
- /** ID of the sandbox where the code was executed */
60
- sandboxId: string;
61
- /** Provider that executed the code */
62
- provider: string;
63
- /** Process ID for background jobs (if applicable) */
64
- pid?: number;
65
- /** Whether this command is running in background */
66
- isBackground?: boolean;
67
- }
68
- /**
69
- * Information about a sandbox
70
- */
71
- interface SandboxInfo {
72
- /** Unique identifier for the sandbox */
73
- id: string;
74
- /** Provider hosting the sandbox */
75
- provider: string;
76
- /** Runtime environment in the sandbox */
77
- runtime: Runtime;
78
- /** Current status of the sandbox */
79
- status: SandboxStatus;
80
- /** When the sandbox was created */
81
- createdAt: Date;
82
- /** Execution timeout in milliseconds */
83
- timeout: number;
84
- /** Additional provider-specific metadata */
85
- metadata?: Record<string, any>;
86
- }
87
- /**
88
- * Options for creating a sandbox
89
- */
90
- interface CreateSandboxOptions {
91
- /** Runtime environment (defaults to 'node' if not specified) */
92
- runtime?: Runtime;
93
- /** Execution timeout in milliseconds */
94
- timeout?: number;
95
- /** Custom sandbox ID (if supported by provider) */
96
- sandboxId?: string;
97
- /** Template ID for sandbox creation (provider-specific) */
98
- templateId?: string;
99
- /** Additional metadata for the sandbox */
100
- metadata?: Record<string, any>;
101
- /** Domain for sandbox connection (provider-specific) */
102
- domain?: string;
103
- /** Environment variables for the sandbox */
104
- envs?: Record<string, string>;
105
- }
106
- /**
107
- * File system entry information
108
- */
109
- interface FileEntry {
110
- /** File/directory name */
111
- name: string;
112
- /** Full path to the entry */
113
- path: string;
114
- /** Whether this is a directory */
115
- isDirectory: boolean;
116
- /** File size in bytes (0 for directories) */
117
- size: number;
118
- /** Last modified timestamp */
119
- lastModified: Date;
120
- }
121
- /**
122
- * File system interface for sandbox operations
123
- */
124
- interface SandboxFileSystem {
125
- /** Read file contents */
126
- readFile(path: string): Promise<string>;
127
- /** Write file contents */
128
- writeFile(path: string, content: string): Promise<void>;
129
- /** Create directory */
130
- mkdir(path: string): Promise<void>;
131
- /** List directory contents */
132
- readdir(path: string): Promise<FileEntry[]>;
133
- /** Check if file/directory exists */
134
- exists(path: string): Promise<boolean>;
135
- /** Remove file or directory */
136
- remove(path: string): Promise<void>;
137
- }
138
- /**
139
- * Error thrown when a command exits with a non-zero status
140
- */
141
- declare class CommandExitError extends Error {
142
- result: {
143
- exitCode: number;
144
- stdout: string;
145
- stderr: string;
146
- error: boolean;
147
- };
148
- name: string;
149
- constructor(result: {
150
- exitCode: number;
151
- stdout: string;
152
- stderr: string;
153
- error: boolean;
154
- });
155
- }
156
- /**
157
- * Type guard to check if an error is a CommandExitError
158
- */
159
- declare function isCommandExitError(error: unknown): error is CommandExitError;
160
- /**
161
- * Base sandbox interface - what developers interact with
15
+ * Provider sandbox interface - what external providers (e2b, railway, etc.) return
16
+ *
17
+ * This is the base interface that all provider sandboxes must implement.
18
+ * The gateway provider returns the full Sandbox from @computesdk/client which
19
+ * extends this with ComputeClient features (terminals, watchers, signals).
20
+ *
21
+ * @example Provider implementation
22
+ * ```typescript
23
+ * // In @computesdk/e2b
24
+ * const e2bProvider = createProvider<E2BSandbox, E2BConfig>({
25
+ * name: 'e2b',
26
+ * methods: {
27
+ * sandbox: {
28
+ * create: async (config, options) => {
29
+ * const sandbox = await E2BSandbox.create({ ... });
30
+ * return { sandbox, sandboxId: sandbox.id };
31
+ * },
32
+ * // ... other methods
33
+ * }
34
+ * }
35
+ * });
36
+ * ```
162
37
  */
163
- interface Sandbox<TSandbox = any> {
38
+ interface ProviderSandbox<TSandbox = any> {
164
39
  /** Unique identifier for the sandbox */
165
40
  readonly sandboxId: string;
166
41
  /** Provider that created this sandbox */
167
42
  readonly provider: string;
168
43
  /** Execute code in the sandbox */
169
- runCode(code: string, runtime?: Runtime): Promise<ExecutionResult>;
44
+ runCode(code: string, runtime?: Runtime): Promise<CodeResult>;
170
45
  /** Execute shell commands */
171
- runCommand(command: string, args?: string[], options?: RunCommandOptions): Promise<ExecutionResult>;
46
+ runCommand(commandOrArray: string | [string, ...string[]], argsOrOptions?: string[] | RunCommandOptions, maybeOptions?: RunCommandOptions): Promise<CommandResult>;
172
47
  /** Get information about the sandbox */
173
48
  getInfo(): Promise<SandboxInfo>;
174
49
  /** Get URL for accessing the sandbox on a specific port */
@@ -186,102 +61,42 @@ interface Sandbox<TSandbox = any> {
186
61
  destroy(): Promise<void>;
187
62
  /** File system operations */
188
63
  readonly filesystem: SandboxFileSystem;
64
+ /**
65
+ * Create an interactive terminal (PTY or exec mode)
66
+ * @optional Available when using gateway provider
67
+ */
68
+ createTerminal?(options?: {
69
+ shell?: string;
70
+ pty?: boolean;
71
+ encoding?: 'utf8' | 'binary';
72
+ }): Promise<any>;
73
+ /**
74
+ * Create a file system watcher
75
+ * @optional Available when using gateway provider
76
+ */
77
+ createWatcher?(path: string, options?: {
78
+ recursive?: boolean;
79
+ includeContent?: boolean;
80
+ }): Promise<any>;
81
+ /**
82
+ * Send a signal to a process
83
+ * @optional Available when using gateway provider
84
+ */
85
+ sendSignal?(pid: number, signal: string): Promise<void>;
189
86
  }
190
87
  /**
191
- * Extract the sandbox type from a provider
88
+ * Extract the sandbox type from a provider using generic inference
192
89
  */
193
- type ExtractProviderSandboxType<TProvider extends Provider$1> = TProvider extends {
194
- readonly __sandboxType: infer TSandbox;
195
- } ? TSandbox : any;
90
+ type ExtractProviderSandboxType<TProvider> = TProvider extends Provider$1<infer TSandbox> ? TSandbox : any;
196
91
  /**
197
- * Typed sandbox interface that preserves the provider's native instance type
92
+ * Typed provider sandbox interface that preserves the provider's native instance type
198
93
  */
199
- interface TypedSandbox<TProvider extends Provider$1> extends Omit<Sandbox<ExtractProviderSandboxType<TProvider>>, 'getProvider'> {
94
+ interface TypedProviderSandbox<TProvider extends Provider$1> extends Omit<ProviderSandbox<ExtractProviderSandboxType<TProvider>>, 'getProvider'> {
200
95
  /** Get the provider instance that created this sandbox with proper typing */
201
96
  getProvider(): TProvider;
202
97
  /** Get the native provider sandbox instance with proper typing */
203
98
  getInstance(): ExtractProviderSandboxType<TProvider>;
204
99
  }
205
- /**
206
- * Enhanced sandbox type that includes ComputeClient features
207
- *
208
- * When a sandbox is created with an API key/JWT, it gets wrapped with ComputeClient
209
- * which adds powerful features like WebSocket terminals, file watchers, and signals.
210
- *
211
- * @example
212
- * ```typescript
213
- * const sandbox = await compute.sandbox.create();
214
- *
215
- * // ComputeClient features (only available when API key is configured)
216
- * const terminal = await sandbox.createTerminal();
217
- * const watcher = await sandbox.createWatcher('/home/project');
218
- * const signals = await sandbox.startSignals();
219
- *
220
- * // Original sandbox features still work
221
- * await sandbox.runCommand('ls');
222
- * const instance = sandbox.getInstance();
223
- * ```
224
- */
225
- type ComputeEnhancedSandbox<TSandbox = any> = Sandbox<TSandbox> & {
226
- /** The original provider sandbox instance */
227
- __originalSandbox: Sandbox<TSandbox>;
228
- /** Create a persistent terminal session with WebSocket integration */
229
- createTerminal(shell?: string, encoding?: 'raw' | 'base64'): Promise<_computesdk_client.Terminal>;
230
- /** Create a file watcher with real-time change notifications */
231
- createWatcher(path: string, options?: {
232
- includeContent?: boolean;
233
- ignored?: string[];
234
- encoding?: 'raw' | 'base64';
235
- }): Promise<_computesdk_client.FileWatcher>;
236
- /** Start the signal service for port and error monitoring */
237
- startSignals(): Promise<_computesdk_client.SignalService>;
238
- /** Execute a one-off command without creating a persistent terminal */
239
- execute(options: {
240
- command: string;
241
- shell?: string;
242
- }): Promise<any>;
243
- /** List all active terminals */
244
- listTerminals(): Promise<any[]>;
245
- /** Get terminal by ID */
246
- getTerminal(id: string): Promise<any>;
247
- /** List all active file watchers */
248
- listWatchers(): Promise<any>;
249
- /** Get file watcher by ID */
250
- getWatcher(id: string): Promise<any>;
251
- /** Get signal service status */
252
- getSignalStatus(): Promise<any>;
253
- /** Create a session token (requires access token) */
254
- createSessionToken(options?: {
255
- description?: string;
256
- expiresIn?: number;
257
- }): Promise<any>;
258
- /** List all session tokens (requires access token) */
259
- listSessionTokens(): Promise<any>;
260
- /** Get session token details (requires access token) */
261
- getSessionToken(tokenId: string): Promise<any>;
262
- /** Revoke a session token (requires access token) */
263
- revokeSessionToken(tokenId: string): Promise<void>;
264
- /** Create a magic link for browser authentication (requires access token) */
265
- createMagicLink(options?: {
266
- redirectUrl?: string;
267
- }): Promise<any>;
268
- /** Check authentication status */
269
- getAuthStatus(): Promise<any>;
270
- /** Get authentication information */
271
- getAuthInfo(): Promise<any>;
272
- /** Set authentication token manually */
273
- setToken(token: string): void;
274
- /** Get current authentication token */
275
- getToken(): string | null;
276
- /** Get current sandbox URL */
277
- getSandboxUrl(): string;
278
- /** Disconnect WebSocket connection */
279
- disconnect(): Promise<void>;
280
- };
281
- /**
282
- * Typed enhanced sandbox that preserves both provider typing and ComputeClient features
283
- */
284
- type TypedEnhancedSandbox<TProvider extends Provider$1> = ComputeEnhancedSandbox<ExtractProviderSandboxType<TProvider>> & Omit<TypedSandbox<TProvider>, keyof Sandbox>;
285
100
 
286
101
  /**
287
102
  * Common options for creating snapshots
@@ -321,23 +136,26 @@ interface ListTemplatesOptions {
321
136
  }
322
137
  /**
323
138
  * Provider sandbox manager interface - handles sandbox lifecycle
139
+ *
140
+ * For most providers (e2b, railway, etc.), this returns ProviderSandbox.
141
+ * The gateway provider returns the full Sandbox with ComputeClient features.
324
142
  */
325
143
  interface ProviderSandboxManager<TSandbox = any> {
326
144
  /** Create a new sandbox */
327
- create(options?: CreateSandboxOptions): Promise<Sandbox<TSandbox>>;
145
+ create(options?: CreateSandboxOptions): Promise<ProviderSandbox<TSandbox>>;
328
146
  /** Get an existing sandbox by ID */
329
- getById(sandboxId: string): Promise<Sandbox<TSandbox> | null>;
147
+ getById(sandboxId: string): Promise<ProviderSandbox<TSandbox> | null>;
330
148
  /** List all active sandboxes */
331
- list(): Promise<Sandbox<TSandbox>[]>;
149
+ list(): Promise<ProviderSandbox<TSandbox>[]>;
332
150
  /** Destroy a sandbox */
333
151
  destroy(sandboxId: string): Promise<void>;
334
152
  }
335
153
  /**
336
154
  * Provider template manager interface - handles template/blueprint lifecycle
337
155
  */
338
- interface ProviderTemplateManager<TTemplate = any> {
156
+ interface ProviderTemplateManager<TTemplate = any, TCreateOptions extends CreateTemplateOptions = CreateTemplateOptions> {
339
157
  /** Create a new template */
340
- create(options: CreateTemplateOptions | any): Promise<TTemplate>;
158
+ create(options: TCreateOptions): Promise<TTemplate>;
341
159
  /** List all available templates */
342
160
  list(options?: ListTemplatesOptions): Promise<TTemplate[]>;
343
161
  /** Delete a template */
@@ -368,8 +186,6 @@ interface Provider<TSandbox = any, TTemplate = any, TSnapshot = any> {
368
186
  readonly snapshot?: ProviderSnapshotManager<TSnapshot>;
369
187
  /** Get the list of supported runtime environments */
370
188
  getSupportedRuntimes(): Runtime[];
371
- /** Phantom type property for TypeScript inference - not used at runtime */
372
- readonly __sandboxType: TSandbox;
373
189
  }
374
190
  /**
375
191
  * Configuration for the compute singleton
@@ -406,6 +222,10 @@ interface CreateSandboxParamsWithOptionalProvider {
406
222
  }
407
223
  /**
408
224
  * Base Compute API interface (non-generic)
225
+ *
226
+ * Returns ProviderSandbox which is the common interface for all sandboxes.
227
+ * When using gateway provider, the returned sandbox will have full Sandbox
228
+ * capabilities (terminals, watchers, signals) accessible via getInstance().
409
229
  */
410
230
  interface ComputeAPI {
411
231
  /** Configuration management */
@@ -414,29 +234,31 @@ interface ComputeAPI {
414
234
  clearConfig(): void;
415
235
  sandbox: {
416
236
  /** Create a sandbox from a provider (or default provider if configured) */
417
- create(params?: CreateSandboxParams | CreateSandboxParamsWithOptionalProvider): Promise<Sandbox>;
237
+ create(params?: CreateSandboxParams | CreateSandboxParamsWithOptionalProvider): Promise<ProviderSandbox>;
418
238
  /** Get an existing sandbox by ID from a provider (or default provider if configured) */
419
- getById(providerOrSandboxId: Provider | string, sandboxId?: string): Promise<Sandbox | null>;
239
+ getById(providerOrSandboxId: Provider | string, sandboxId?: string): Promise<ProviderSandbox | null>;
420
240
  /** List all active sandboxes from a provider (or default provider if configured) */
421
- list(provider?: Provider): Promise<Sandbox[]>;
241
+ list(provider?: Provider): Promise<ProviderSandbox[]>;
422
242
  /** Destroy a sandbox via a provider (or default provider if configured) */
423
243
  destroy(providerOrSandboxId: Provider | string, sandboxId?: string): Promise<void>;
424
244
  };
425
245
  }
426
246
  /**
427
247
  * Typed Compute API interface that preserves provider type information
428
- * When auth (apiKey/accessToken) is configured, returns enhanced sandboxes with ComputeClient features
248
+ *
249
+ * When using gateway provider, returns full Sandbox with ComputeClient features.
250
+ * When using other providers, returns TypedProviderSandbox.
429
251
  */
430
- interface TypedComputeAPI<TProvider extends Provider, TIsEnhanced extends boolean = boolean> extends Omit<ComputeAPI, 'sandbox' | 'setConfig'> {
252
+ interface TypedComputeAPI<TProvider extends Provider> extends Omit<ComputeAPI, 'sandbox' | 'setConfig'> {
431
253
  /** Configuration management that returns typed compute instance */
432
254
  setConfig<T extends Provider>(config: ComputeConfig<T>): TypedComputeAPI<T>;
433
255
  sandbox: {
434
256
  /** Create a sandbox from the configured provider with proper typing */
435
- create(params?: Omit<CreateSandboxParamsWithOptionalProvider, 'provider'>): Promise<TIsEnhanced extends true ? TypedEnhancedSandbox<TProvider> : TypedSandbox<TProvider>>;
257
+ create(params?: Omit<CreateSandboxParamsWithOptionalProvider, 'provider'>): Promise<TypedProviderSandbox<TProvider>>;
436
258
  /** Get an existing sandbox by ID from the configured provider with proper typing */
437
- getById(sandboxId: string): Promise<TIsEnhanced extends true ? TypedEnhancedSandbox<TProvider> : TypedSandbox<TProvider> | null>;
259
+ getById(sandboxId: string): Promise<TypedProviderSandbox<TProvider> | null>;
438
260
  /** List all active sandboxes from the configured provider with proper typing */
439
- list(): Promise<TIsEnhanced extends true ? TypedEnhancedSandbox<TProvider>[] : TypedSandbox<TProvider>[]>;
261
+ list(): Promise<TypedProviderSandbox<TProvider>[]>;
440
262
  /** Destroy a sandbox via the configured provider */
441
263
  destroy(sandboxId: string): Promise<void>;
442
264
  };
@@ -460,88 +282,21 @@ declare const compute: ComputeAPI;
460
282
  * import { e2b } from '@computesdk/e2b'
461
283
  * import { createCompute } from 'computesdk'
462
284
  *
463
- * // With API key (automatically gets access token from license server)
464
- * const compute = createCompute({
465
- * defaultProvider: e2b({ apiKey: 'your-key' }),
466
- * apiKey: 'computesdk_live_...' // Returns enhanced sandboxes
467
- * });
285
+ * // Zero-config mode (auto-detects from environment)
286
+ * const compute = createCompute();
287
+ * const sandbox = await compute.sandbox.create();
468
288
  *
469
- * // Or with direct access token
289
+ * // Explicit mode
470
290
  * const compute2 = createCompute({
471
291
  * defaultProvider: e2b({ apiKey: 'your-key' }),
472
- * accessToken: 'your-access-token' // Returns enhanced sandboxes
473
292
  * });
474
293
  *
475
- * const sandbox = await compute.sandbox.create();
476
- * const instance = sandbox.getInstance(); // ✅ Properly typed E2B Sandbox!
477
- * await sandbox.createTerminal(); // ✅ Enhanced sandbox features!
294
+ * const sandbox2 = await compute2.sandbox.create();
295
+ * const instance = sandbox2.getInstance(); // ✅ Properly typed!
478
296
  * ```
479
297
  */
480
- declare function createCompute<TProvider extends Provider>(config: ComputeConfig<TProvider> & {
481
- apiKey: string;
482
- }): TypedComputeAPI<TProvider, true>;
483
- declare function createCompute<TProvider extends Provider>(config: ComputeConfig<TProvider> & {
484
- accessToken: string;
485
- }): TypedComputeAPI<TProvider, true>;
486
- declare function createCompute<TProvider extends Provider>(config: ComputeConfig<TProvider> & {
487
- jwt: string;
488
- }): TypedComputeAPI<TProvider, true>;
489
- declare function createCompute<TProvider extends Provider>(config: ComputeConfig<TProvider>): TypedComputeAPI<TProvider, false>;
490
-
491
- /**
492
- * Simplified Request Handler for Web Framework Integration
493
- *
494
- * Handles JSON requests for sandbox and code execution operations.
495
- * Terminal support removed - will be re-added with WebSocket VM connections.
496
- */
497
-
498
- /**
499
- * Request structure supporting sandbox and code execution capabilities
500
- */
501
- interface ComputeRequest {
502
- /** Action in dot notation (e.g., 'compute.sandbox.create') */
503
- action: string;
504
- /** Parameters for the action */
505
- sandboxId?: string;
506
- code?: string;
507
- command?: string;
508
- args?: string[];
509
- runtime?: Runtime;
510
- path?: string;
511
- content?: string;
512
- /** Command options (for runCommand action) */
513
- commandOptions?: {
514
- background?: boolean;
515
- };
516
- /** Sandbox creation options */
517
- options?: {
518
- runtime?: Runtime;
519
- timeout?: number;
520
- sandboxId?: string;
521
- };
522
- }
523
- /**
524
- * Response structure for compute operations
525
- */
526
- interface ComputeResponse {
527
- success: boolean;
528
- error?: string;
529
- sandboxId: string;
530
- provider: string;
531
- [key: string]: any;
532
- }
533
- /**
534
- * Main request handler - handles HTTP requests and pre-parsed bodies
535
- */
536
- declare function handleComputeRequest(params: HandleComputeRequestParams): Promise<ComputeResponse>;
537
- declare function handleComputeRequest(requestOrBody: Request | ComputeRequest, provider: Provider): Promise<Response>;
538
- /**
539
- * Legacy export for backward compatibility
540
- */
541
- interface HandleComputeRequestParams {
542
- request: ComputeRequest;
543
- provider: Provider;
544
- }
298
+ declare function createCompute(): ComputeAPI;
299
+ declare function createCompute<TProvider extends Provider>(config: ComputeConfig<TProvider>): TypedComputeAPI<TProvider>;
545
300
 
546
301
  /**
547
302
  * Provider Factory - Creates providers from method definitions
@@ -550,15 +305,6 @@ interface HandleComputeRequestParams {
550
305
  * from simple method definitions with automatic feature detection.
551
306
  */
552
307
 
553
- /**
554
- * Helper function to handle background command execution
555
- * Providers can use this to implement background job support
556
- */
557
- declare function createBackgroundCommand(command: string, args?: string[], options?: RunCommandOptions): {
558
- command: string;
559
- args: string[];
560
- isBackground: boolean;
561
- };
562
308
  /**
563
309
  * Flat sandbox method implementations - all operations in one place
564
310
  */
@@ -576,8 +322,8 @@ interface SandboxMethods<TSandbox = any, TConfig = any> {
576
322
  sandboxId: string;
577
323
  }>>;
578
324
  destroy: (config: TConfig, sandboxId: string) => Promise<void>;
579
- runCode: (sandbox: TSandbox, code: string, runtime?: Runtime, config?: TConfig) => Promise<ExecutionResult>;
580
- runCommand: (sandbox: TSandbox, command: string, args?: string[], options?: RunCommandOptions) => Promise<ExecutionResult>;
325
+ runCode: (sandbox: TSandbox, code: string, runtime?: Runtime, config?: TConfig) => Promise<CodeResult>;
326
+ runCommand: (sandbox: TSandbox, command: string, args?: string[], options?: RunCommandOptions) => Promise<CommandResult>;
581
327
  getInfo: (sandbox: TSandbox) => Promise<SandboxInfo>;
582
328
  getUrl: (sandbox: TSandbox, options: {
583
329
  port: number;
@@ -585,19 +331,19 @@ interface SandboxMethods<TSandbox = any, TConfig = any> {
585
331
  }) => Promise<string>;
586
332
  getInstance?: (sandbox: TSandbox) => TSandbox;
587
333
  filesystem?: {
588
- readFile: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<ExecutionResult>) => Promise<string>;
589
- writeFile: (sandbox: TSandbox, path: string, content: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<ExecutionResult>) => Promise<void>;
590
- mkdir: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<ExecutionResult>) => Promise<void>;
591
- readdir: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<ExecutionResult>) => Promise<FileEntry[]>;
592
- exists: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<ExecutionResult>) => Promise<boolean>;
593
- remove: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<ExecutionResult>) => Promise<void>;
334
+ readFile: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<CommandResult>) => Promise<string>;
335
+ writeFile: (sandbox: TSandbox, path: string, content: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<CommandResult>) => Promise<void>;
336
+ mkdir: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<CommandResult>) => Promise<void>;
337
+ readdir: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<CommandResult>) => Promise<FileEntry[]>;
338
+ exists: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<CommandResult>) => Promise<boolean>;
339
+ remove: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<CommandResult>) => Promise<void>;
594
340
  };
595
341
  }
596
342
  /**
597
343
  * Template method implementations
598
344
  */
599
- interface TemplateMethods<TTemplate = any, TConfig = any> {
600
- create: (config: TConfig, options: CreateTemplateOptions | any) => Promise<TTemplate>;
345
+ interface TemplateMethods<TTemplate = any, TConfig = any, TCreateOptions extends CreateTemplateOptions = CreateTemplateOptions> {
346
+ create: (config: TConfig, options: TCreateOptions) => Promise<TTemplate>;
601
347
  list: (config: TConfig, options?: ListTemplatesOptions) => Promise<TTemplate[]>;
602
348
  delete: (config: TConfig, templateId: string) => Promise<void>;
603
349
  }
@@ -609,17 +355,50 @@ interface SnapshotMethods<TSnapshot = any, TConfig = any> {
609
355
  list: (config: TConfig, options?: ListSnapshotsOptions) => Promise<TSnapshot[]>;
610
356
  delete: (config: TConfig, snapshotId: string) => Promise<void>;
611
357
  }
358
+ /**
359
+ * Provider execution modes
360
+ *
361
+ * - 'raw': Use raw provider methods directly (for gateway internal use)
362
+ * - 'direct': Use provider's native SDK directly (for providers with sandbox capabilities)
363
+ * - 'gateway': Route through ComputeSDK gateway (for providers without native sandbox)
364
+ */
365
+ type ProviderMode = 'raw' | 'direct' | 'gateway';
612
366
  /**
613
367
  * Provider configuration for createProvider()
614
368
  */
615
369
  interface ProviderConfig<TSandbox = any, TConfig = any, TTemplate = any, TSnapshot = any> {
616
370
  name: string;
371
+ /**
372
+ * Default execution mode for this provider (defaults to 'gateway' if not specified)
373
+ *
374
+ * - 'direct': Provider has native sandbox capabilities (e.g., E2B) - uses provider SDK directly
375
+ * - 'gateway': Provider only has infrastructure (e.g., Railway) - routes through gateway
376
+ *
377
+ * Can be overridden at runtime with `mode` in config.
378
+ */
379
+ defaultMode?: 'direct' | 'gateway';
617
380
  methods: {
618
381
  sandbox: SandboxMethods<TSandbox, TConfig>;
619
382
  template?: TemplateMethods<TTemplate, TConfig>;
620
383
  snapshot?: SnapshotMethods<TSnapshot, TConfig>;
621
384
  };
622
385
  }
386
+ /**
387
+ * Base config that all provider configs should extend
388
+ * Includes the `mode` option for controlling execution mode
389
+ */
390
+ interface BaseProviderConfig {
391
+ /**
392
+ * Execution mode override
393
+ *
394
+ * - 'raw': Use raw provider methods directly (for gateway internal use)
395
+ * - 'direct': Use provider's native SDK directly
396
+ * - 'gateway': Route through ComputeSDK gateway
397
+ *
398
+ * If not specified, uses the provider's `defaultMode`.
399
+ */
400
+ mode?: ProviderMode;
401
+ }
623
402
  /**
624
403
  * Create a provider from method definitions
625
404
  *
@@ -628,4 +407,184 @@ interface ProviderConfig<TSandbox = any, TConfig = any, TTemplate = any, TSnapsh
628
407
  */
629
408
  declare function createProvider<TSandbox, TConfig = any, TTemplate = any, TSnapshot = any>(providerConfig: ProviderConfig<TSandbox, TConfig, TTemplate, TSnapshot>): (config: TConfig) => Provider<TSandbox, TTemplate, TSnapshot>;
630
409
 
631
- export { CommandExitError, type ComputeAPI, type ComputeConfig, type ComputeEnhancedSandbox, type ComputeRequest, type ComputeResponse, type CreateSandboxOptions, type CreateSandboxParams, type CreateSandboxParamsWithOptionalProvider, type CreateSnapshotOptions, type CreateTemplateOptions, type ExecutionResult, type ExtractSandboxInstanceType, type FileEntry, type HandleComputeRequestParams, type ListSnapshotsOptions, type ListTemplatesOptions, type Provider, type ProviderConfig, type ProviderSandboxManager, type ProviderSandboxTypeMap, type ProviderSnapshotManager, type ProviderTemplateManager, type RunCommandOptions, type Runtime, type Sandbox, type SandboxFileSystem, type SandboxInfo, type SandboxMethods, type SandboxStatus, type SnapshotMethods, type TemplateMethods, type TypedComputeAPI, type TypedEnhancedSandbox, type TypedSandbox, compute, createBackgroundCommand, createCompute, createProvider, handleComputeRequest, isCommandExitError };
410
+ /**
411
+ * Gateway provider configuration
412
+ */
413
+ interface GatewayConfig extends BaseProviderConfig {
414
+ /** Gateway URL (default: https://gateway.computesdk.com) */
415
+ gatewayUrl?: string;
416
+ /** ComputeSDK API key for authentication */
417
+ apiKey: string;
418
+ /** Backend provider name (e2b, railway, etc.) */
419
+ provider: string;
420
+ /** Provider-specific headers to pass through to gateway */
421
+ providerHeaders?: Record<string, string>;
422
+ /** Request timeout in milliseconds (default: 30000) */
423
+ requestTimeout?: number;
424
+ /** Maximum retry attempts for transient failures (default: 3) */
425
+ maxRetries?: number;
426
+ /** Initial retry delay in milliseconds (default: 1000) */
427
+ retryDelay?: number;
428
+ /** HTTP status codes that should trigger a retry (default: [408, 429, 502, 503, 504]) */
429
+ retryableStatuses?: number[];
430
+ }
431
+ /**
432
+ * Gateway Provider factory
433
+ *
434
+ * Uses ClientSandbox directly as the sandbox type - no wrapper needed.
435
+ */
436
+ declare const gateway: (config: GatewayConfig) => Provider<Sandbox, any, any>;
437
+
438
+ /**
439
+ * Auto-Detection Module
440
+ *
441
+ * Automatically detects gateway mode and provider from environment variables.
442
+ * Enables zero-config usage of ComputeSDK.
443
+ */
444
+
445
+ /**
446
+ * Check if gateway mode is enabled
447
+ * Gateway mode requires COMPUTESDK_API_KEY to be set
448
+ */
449
+ declare function isGatewayModeEnabled(): boolean;
450
+ /**
451
+ * Detect which provider to use from environment variables
452
+ *
453
+ * Detection order:
454
+ * 1. Check for explicit COMPUTESDK_PROVIDER override
455
+ * 2. Auto-detect based on PROVIDER_PRIORITY order
456
+ *
457
+ * @returns Provider name or null if none detected
458
+ */
459
+ declare function detectProvider(): string | null;
460
+ /**
461
+ * Build provider-specific headers from environment variables
462
+ * These headers are passed through to the gateway
463
+ */
464
+ declare function getProviderHeaders(provider: string): Record<string, string>;
465
+ /**
466
+ * Main auto-configuration function
467
+ * Returns configured HTTP provider or null if auto-detection not possible
468
+ *
469
+ * @throws Error if COMPUTESDK_API_KEY is set but no provider detected
470
+ */
471
+ declare function autoConfigureCompute(): Provider | null;
472
+
473
+ /**
474
+ * ComputeSDK Constants
475
+ *
476
+ * Default configuration values and provider definitions
477
+ */
478
+ /**
479
+ * Default gateway URL for sandbox lifecycle operations
480
+ */
481
+ declare const GATEWAY_URL = "https://gateway.computesdk.com";
482
+ /**
483
+ * Provider detection priority order
484
+ * When multiple provider credentials are detected, use the first one in this list
485
+ */
486
+ declare const PROVIDER_PRIORITY: readonly ["e2b", "railway", "daytona", "modal", "runloop", "vercel", "cloudflare", "codesandbox", "blaxel"];
487
+ /**
488
+ * Required environment variables for each provider
489
+ * Used to detect which provider to use from environment
490
+ */
491
+ declare const PROVIDER_ENV_VARS: {
492
+ readonly e2b: readonly ["E2B_API_KEY"];
493
+ readonly railway: readonly ["RAILWAY_API_KEY", "RAILWAY_PROJECT_ID", "RAILWAY_ENVIRONMENT_ID"];
494
+ readonly daytona: readonly ["DAYTONA_API_KEY"];
495
+ readonly modal: readonly ["MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET"];
496
+ readonly runloop: readonly ["RUNLOOP_API_KEY"];
497
+ readonly vercel: readonly ["VERCEL_TOKEN", "VERCEL_TEAM_ID", "VERCEL_PROJECT_ID"];
498
+ readonly cloudflare: readonly ["CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID"];
499
+ readonly codesandbox: readonly ["CSB_API_KEY"];
500
+ readonly blaxel: readonly ["BL_API_KEY", "BL_WORKSPACE"];
501
+ };
502
+ /**
503
+ * Type for provider names
504
+ */
505
+ type ProviderName = keyof typeof PROVIDER_ENV_VARS;
506
+
507
+ /**
508
+ * Utility functions for ComputeSDK
509
+ */
510
+ /**
511
+ * Calculate exponential backoff delay with jitter
512
+ *
513
+ * Uses exponential backoff (2^attempt) multiplied by base delay,
514
+ * plus random jitter to prevent thundering herd.
515
+ *
516
+ * @param attempt - Current retry attempt (0-indexed)
517
+ * @param baseDelay - Base delay in milliseconds (default: 1000)
518
+ * @param jitterMax - Maximum random jitter in milliseconds (default: 100)
519
+ * @returns Delay in milliseconds
520
+ *
521
+ * @example
522
+ * ```typescript
523
+ * // First retry: 1000-1100ms
524
+ * calculateBackoff(0);
525
+ *
526
+ * // Second retry: 2000-2100ms
527
+ * calculateBackoff(1);
528
+ *
529
+ * // Third retry: 4000-4100ms
530
+ * calculateBackoff(2);
531
+ * ```
532
+ */
533
+ declare function calculateBackoff(attempt: number, baseDelay?: number, jitterMax?: number): number;
534
+
535
+ /**
536
+ * Simplified Request Handler for Web Framework Integration
537
+ *
538
+ * Handles JSON requests for sandbox and code execution operations.
539
+ * Terminal support removed - will be re-added with WebSocket VM connections.
540
+ */
541
+
542
+ /**
543
+ * Request structure supporting sandbox and code execution capabilities
544
+ */
545
+ interface ComputeRequest {
546
+ /** Action in dot notation (e.g., 'compute.sandbox.create') */
547
+ action: string;
548
+ /** Parameters for the action */
549
+ sandboxId?: string;
550
+ code?: string;
551
+ command?: string;
552
+ args?: string[];
553
+ runtime?: Runtime;
554
+ path?: string;
555
+ content?: string;
556
+ /** Command options (for runCommand action) */
557
+ commandOptions?: {
558
+ background?: boolean;
559
+ };
560
+ /** Sandbox creation options */
561
+ options?: {
562
+ runtime?: Runtime;
563
+ timeout?: number;
564
+ sandboxId?: string;
565
+ };
566
+ }
567
+ /**
568
+ * Response structure for compute operations
569
+ */
570
+ interface ComputeResponse {
571
+ success: boolean;
572
+ error?: string;
573
+ sandboxId: string;
574
+ provider: string;
575
+ [key: string]: any;
576
+ }
577
+ /**
578
+ * Main request handler - handles HTTP requests and pre-parsed bodies
579
+ */
580
+ declare function handleComputeRequest(params: HandleComputeRequestParams): Promise<ComputeResponse>;
581
+ declare function handleComputeRequest(requestOrBody: Request | ComputeRequest, provider: Provider): Promise<Response>;
582
+ /**
583
+ * Legacy export for backward compatibility
584
+ */
585
+ interface HandleComputeRequestParams {
586
+ request: ComputeRequest;
587
+ provider: Provider;
588
+ }
589
+
590
+ export { type BaseProviderConfig, type ComputeAPI, type ComputeConfig, type ComputeRequest, type ComputeResponse, type CreateSandboxParams, type CreateSandboxParamsWithOptionalProvider, type CreateSnapshotOptions, type CreateTemplateOptions, GATEWAY_URL, type GatewayConfig, type HandleComputeRequestParams, type ListSnapshotsOptions, type ListTemplatesOptions, PROVIDER_ENV_VARS, PROVIDER_PRIORITY, type Provider, type ProviderConfig, type ProviderMode, type ProviderName, type ProviderSandbox, type ProviderSandboxManager, type ProviderSnapshotManager, type ProviderTemplateManager, type SandboxInfo, type SandboxMethods, type SnapshotMethods, type TemplateMethods, type TypedComputeAPI, type TypedProviderSandbox, autoConfigureCompute, calculateBackoff, compute, createCompute, createProvider, detectProvider, gateway, getProviderHeaders, handleComputeRequest, isGatewayModeEnabled };