computesdk 1.10.0 → 1.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,97 +1,2963 @@
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';
3
-
4
- /**
5
- * Information about a sandbox (provider-agnostic)
6
- * @see ProviderSandboxInfo in @computesdk/client for the canonical definition
7
- */
8
- type SandboxInfo = ProviderSandboxInfo;
9
-
10
1
  /**
11
- * Provider sandbox interface - what external providers (e2b, railway, etc.) return
2
+ * Universal Sandbox Interface
3
+ *
4
+ * The canonical interface for all ComputeSDK sandboxes.
5
+ *
6
+ * Core methods (required):
7
+ * - runCode, runCommand, getInfo, getUrl, destroy, filesystem
8
+ *
9
+ * Advanced features (optional):
10
+ * - terminal, server, watcher, auth, env, etc.
11
+ *
12
+ * Providers can implement as much or as little as makes sense for their platform.
13
+ * The gateway Sandbox class implements the full specification.
12
14
  *
13
- * This is the base interface that all provider sandboxes must implement.
14
- * The gateway provider returns the full Sandbox from @computesdk/client which
15
- * extends this with ComputeClient features (terminals, watchers, signals).
15
+ * **Note on naming:** This interface is named "Sandbox" in this file for clarity,
16
+ * but is exported as "SandboxInterface" from the main computesdk package to avoid
17
+ * collision with the gateway Sandbox class. The rename happens at export time in
18
+ * src/index.ts. Providers using @computesdk/provider will only see "SandboxInterface".
16
19
  *
17
- * @example Provider implementation
20
+ * @example Minimal implementation
18
21
  * ```typescript
19
- * // In @computesdk/e2b
20
- * const e2bProvider = createProvider<E2BSandbox, E2BConfig>({
21
- * name: 'e2b',
22
- * methods: {
23
- * sandbox: {
24
- * create: async (config, options) => {
25
- * const sandbox = await E2BSandbox.create({ ... });
26
- * return { sandbox, sandboxId: sandbox.id };
27
- * },
28
- * // ... other methods
29
- * }
30
- * }
31
- * });
22
+ * class MinimalSandbox implements Pick<Sandbox, 'sandboxId' | 'provider' | 'runCode' | 'runCommand' | 'getInfo' | 'getUrl' | 'destroy' | 'filesystem'> {
23
+ * // Just implement core methods
24
+ * }
25
+ * ```
26
+ *
27
+ * @example Full implementation
28
+ * ```typescript
29
+ * class FullSandbox implements Sandbox {
30
+ * // Implement everything - core + advanced features
31
+ * }
32
32
  * ```
33
33
  */
34
- interface ProviderSandbox<TSandbox = any> {
34
+ /**
35
+ * Supported runtime environments
36
+ */
37
+ type Runtime = 'node' | 'python' | 'deno' | 'bun';
38
+ /**
39
+ * Code execution result
40
+ */
41
+ interface CodeResult$1 {
42
+ output: string;
43
+ exitCode: number;
44
+ language: string;
45
+ }
46
+ /**
47
+ * Command execution result
48
+ */
49
+ interface CommandResult$1 {
50
+ stdout: string;
51
+ stderr: string;
52
+ exitCode: number;
53
+ durationMs: number;
54
+ }
55
+ /**
56
+ * Sandbox information
57
+ */
58
+ interface SandboxInfo$1 {
59
+ /** Unique identifier for the sandbox */
60
+ id: string;
61
+ /** Provider hosting the sandbox */
62
+ provider: string;
63
+ /** Runtime environment in the sandbox */
64
+ runtime: Runtime;
65
+ /** Current status of the sandbox */
66
+ status: 'running' | 'stopped' | 'error';
67
+ /** When the sandbox was created */
68
+ createdAt: Date;
69
+ /** Execution timeout in milliseconds */
70
+ timeout: number;
71
+ /** Additional provider-specific metadata */
72
+ metadata?: Record<string, any>;
73
+ }
74
+ /**
75
+ * File entry from directory listing
76
+ */
77
+ interface FileEntry {
78
+ name: string;
79
+ type: 'file' | 'directory';
80
+ size?: number;
81
+ modified?: Date;
82
+ }
83
+ /**
84
+ * Options for running a command
85
+ */
86
+ interface RunCommandOptions {
87
+ cwd?: string;
88
+ env?: Record<string, string>;
89
+ timeout?: number;
90
+ background?: boolean;
91
+ }
92
+ /**
93
+ * Filesystem operations interface
94
+ */
95
+ interface SandboxFileSystem {
96
+ readFile(path: string): Promise<string>;
97
+ writeFile(path: string, content: string): Promise<void>;
98
+ readdir(path: string): Promise<FileEntry[]>;
99
+ mkdir(path: string): Promise<void>;
100
+ exists(path: string): Promise<boolean>;
101
+ remove(path: string): Promise<void>;
102
+ }
103
+ /**
104
+ * Options for creating a sandbox
105
+ *
106
+ * Providers can extend this with additional properties specific to their implementation
107
+ */
108
+ interface CreateSandboxOptions$1 {
109
+ runtime?: Runtime;
110
+ timeout?: number;
111
+ templateId?: string;
112
+ metadata?: Record<string, any>;
113
+ envs?: Record<string, string>;
114
+ name?: string;
115
+ namespace?: string;
116
+ [key: string]: any;
117
+ }
118
+ /**
119
+ * Universal Sandbox Interface
120
+ *
121
+ * All ComputeSDK sandboxes implement this interface.
122
+ * Core methods are required, advanced features are optional.
123
+ *
124
+ * Note: Implementations may use slightly different types for return values
125
+ * as long as they are structurally compatible. For example, getInfo() might
126
+ * return additional fields beyond the base SandboxInfo.
127
+ */
128
+ interface Sandbox$1 {
35
129
  /** Unique identifier for the sandbox */
36
130
  readonly sandboxId: string;
37
- /** Provider that created this sandbox */
131
+ /** Provider name (e2b, railway, modal, gateway, etc.) */
38
132
  readonly provider: string;
39
133
  /** Execute code in the sandbox */
40
- runCode(code: string, runtime?: Runtime): Promise<CodeResult>;
134
+ runCode(code: string, runtime?: Runtime): Promise<CodeResult$1>;
41
135
  /** Execute shell commands */
42
- runCommand(commandOrArray: string | [string, ...string[]], argsOrOptions?: string[] | RunCommandOptions, maybeOptions?: RunCommandOptions): Promise<CommandResult>;
136
+ runCommand(commandOrArray: string | [string, ...string[]], argsOrOptions?: string[] | RunCommandOptions, maybeOptions?: RunCommandOptions): Promise<CommandResult$1>;
43
137
  /** Get information about the sandbox */
44
- getInfo(): Promise<SandboxInfo>;
138
+ getInfo(): Promise<SandboxInfo$1>;
45
139
  /** Get URL for accessing the sandbox on a specific port */
46
140
  getUrl(options: {
47
141
  port: number;
48
142
  protocol?: string;
49
143
  }): Promise<string>;
50
- /** Get the provider instance that created this sandbox */
51
- getProvider(): Provider<TSandbox>;
52
- /** Get the native provider sandbox instance with proper typing */
53
- getInstance(): TSandbox;
54
- /** Kill the sandbox */
55
- kill(): Promise<void>;
56
- /** Destroy the sandbox and clean up resources */
57
- destroy(): Promise<void>;
58
- /** File system operations */
59
- readonly filesystem: SandboxFileSystem;
144
+ /** Destroy the sandbox and clean up resources */
145
+ destroy(): Promise<void>;
146
+ /** File system operations */
147
+ readonly filesystem: SandboxFileSystem;
148
+ /**
149
+ * Terminal management (interactive PTY and exec modes)
150
+ * Available in: gateway, e2b (potentially)
151
+ */
152
+ readonly terminal?: any;
153
+ /**
154
+ * Code and command execution namespace
155
+ * Available in: gateway
156
+ */
157
+ readonly run?: any;
158
+ /**
159
+ * Managed server operations
160
+ * Available in: gateway
161
+ */
162
+ readonly server?: any;
163
+ /**
164
+ * File watcher with real-time change events
165
+ * Available in: gateway
166
+ */
167
+ readonly watcher?: any;
168
+ /**
169
+ * Session token management
170
+ * Available in: gateway
171
+ */
172
+ readonly sessionToken?: any;
173
+ /**
174
+ * Magic link authentication
175
+ * Available in: gateway
176
+ */
177
+ readonly magicLink?: any;
178
+ /**
179
+ * Signal service for port/error events
180
+ * Available in: gateway
181
+ */
182
+ readonly signal?: any;
183
+ /**
184
+ * File operations namespace
185
+ * Available in: gateway
186
+ */
187
+ readonly file?: any;
188
+ /**
189
+ * Environment variable management
190
+ * Available in: gateway
191
+ */
192
+ readonly env?: any;
193
+ /**
194
+ * Authentication operations
195
+ * Available in: gateway
196
+ */
197
+ readonly auth?: any;
198
+ /**
199
+ * Child sandbox management
200
+ * Available in: gateway
201
+ */
202
+ readonly child?: any;
203
+ }
204
+
205
+ /**
206
+ * Terminal created notification
207
+ */
208
+ interface TerminalCreatedMessage {
209
+ type: 'terminal:created';
210
+ channel: string;
211
+ data: {
212
+ id: string;
213
+ status: 'running' | 'stopped';
214
+ };
215
+ }
216
+ /**
217
+ * Terminal output data
218
+ * Note: output field may be base64 encoded depending on encoding field
219
+ */
220
+ interface TerminalOutputMessage {
221
+ type: 'terminal:output';
222
+ channel: string;
223
+ data: {
224
+ output: string;
225
+ encoding?: 'raw' | 'base64';
226
+ };
227
+ }
228
+ /**
229
+ * Terminal destroyed notification
230
+ */
231
+ interface TerminalDestroyedMessage {
232
+ type: 'terminal:destroyed';
233
+ channel: string;
234
+ data: {
235
+ id: string;
236
+ };
237
+ }
238
+ /**
239
+ * Terminal error notification
240
+ */
241
+ interface TerminalErrorMessage {
242
+ type: 'terminal:error';
243
+ channel: string;
244
+ data: {
245
+ error: string;
246
+ };
247
+ }
248
+ /**
249
+ * File watcher created notification
250
+ */
251
+ interface WatcherCreatedMessage {
252
+ type: 'watcher:created';
253
+ channel: string;
254
+ data: {
255
+ id: string;
256
+ path: string;
257
+ };
258
+ }
259
+ /**
260
+ * File change event
261
+ * Note: content field may be base64 encoded depending on encoding field
262
+ */
263
+ interface FileChangedMessage {
264
+ type: 'file:changed';
265
+ channel: string;
266
+ data: {
267
+ event: 'add' | 'change' | 'unlink' | 'addDir' | 'unlinkDir';
268
+ path: string;
269
+ content?: string;
270
+ encoding?: 'raw' | 'base64';
271
+ };
272
+ }
273
+ /**
274
+ * File watcher destroyed notification
275
+ */
276
+ interface WatcherDestroyedMessage {
277
+ type: 'watcher:destroyed';
278
+ channel: string;
279
+ data: {
280
+ id: string;
281
+ };
282
+ }
283
+ /**
284
+ * System signal event
285
+ */
286
+ interface SignalMessage {
287
+ type: 'signal';
288
+ channel: 'signals';
289
+ data: {
290
+ signal: 'port' | 'error' | 'server-ready';
291
+ port?: number;
292
+ url?: string;
293
+ message?: string;
294
+ };
295
+ }
296
+ /**
297
+ * Sandbox created notification
298
+ */
299
+ interface SandboxCreatedMessage {
300
+ type: 'sandbox.created';
301
+ data: {
302
+ subdomain: string;
303
+ url: string;
304
+ };
305
+ }
306
+ /**
307
+ * Sandbox deleted notification
308
+ */
309
+ interface SandboxDeletedMessage {
310
+ type: 'sandbox.deleted';
311
+ data: {
312
+ subdomain: string;
313
+ };
314
+ }
315
+ type WebSocketConstructor$1 = new (url: string) => WebSocket;
316
+ interface WebSocketManagerConfig {
317
+ /** WebSocket URL (will be generated from client config if not provided) */
318
+ url: string;
319
+ /** WebSocket implementation */
320
+ WebSocket: WebSocketConstructor$1;
321
+ /** Enable automatic reconnection on disconnect (default: true) */
322
+ autoReconnect?: boolean;
323
+ /** Reconnection delay in milliseconds (default: 1000) */
324
+ reconnectDelay?: number;
325
+ /** Maximum reconnection attempts (default: 5, 0 = infinite) */
326
+ maxReconnectAttempts?: number;
327
+ /** Enable debug logging (default: false) */
328
+ debug?: boolean;
329
+ /** WebSocket protocol: 'binary' (default, recommended) or 'json' (for debugging) */
330
+ protocol?: 'json' | 'binary';
331
+ }
332
+ type MessageHandler<T = any> = (message: T) => void;
333
+ type ErrorHandler = (error: Event) => void;
334
+ type ConnectionHandler = () => void;
335
+ /**
336
+ * WebSocket Manager for handling real-time communication
337
+ *
338
+ * @example
339
+ * ```typescript
340
+ * import { ComputeClient } from '@computesdk/client'
341
+ *
342
+ * const client = new ComputeClient({ sandboxUrl: 'https://sandbox-123.sandbox.computesdk.com' });
343
+ * await client.generateToken();
344
+ *
345
+ * // Create WebSocket manager
346
+ * const ws = client.createWebSocketManager();
347
+ *
348
+ * // Listen for connection
349
+ * ws.on('open', () => {
350
+ * console.log('Connected!');
351
+ * });
352
+ *
353
+ * // Subscribe to terminal output
354
+ * ws.subscribe('terminal:term_abc123');
355
+ * ws.on('terminal:output', (msg) => {
356
+ * console.log('Terminal output:', msg.data.output);
357
+ * });
358
+ *
359
+ * // Send terminal input
360
+ * ws.sendTerminalInput('term_abc123', 'ls -la\n');
361
+ *
362
+ * // Subscribe to file changes
363
+ * ws.subscribe('watcher:watcher_xyz789');
364
+ * ws.on('file:changed', (msg) => {
365
+ * console.log('File changed:', msg.data.path, msg.data.event);
366
+ * });
367
+ *
368
+ * // Subscribe to signals
369
+ * ws.subscribe('signals');
370
+ * ws.on('signal', (msg) => {
371
+ * console.log('Signal:', msg.data);
372
+ * });
373
+ * ```
374
+ */
375
+ declare class WebSocketManager {
376
+ private config;
377
+ private ws;
378
+ private eventHandlers;
379
+ private reconnectAttempts;
380
+ private reconnectTimer;
381
+ private subscribedChannels;
382
+ private isManualClose;
383
+ constructor(config: WebSocketManagerConfig);
384
+ /**
385
+ * Connect to WebSocket server
386
+ */
387
+ connect(): Promise<void>;
388
+ /**
389
+ * Disconnect from WebSocket server
390
+ */
391
+ disconnect(): void;
392
+ /**
393
+ * Check if WebSocket is connected
394
+ */
395
+ isConnected(): boolean;
396
+ /**
397
+ * Attempt to reconnect to WebSocket server
398
+ */
399
+ private attemptReconnect;
400
+ /**
401
+ * Subscribe to a channel
402
+ * @param channel - Channel name (e.g., 'terminal:term_abc123', 'watcher:watcher_xyz789', 'signals')
403
+ */
404
+ subscribe(channel: string): void;
405
+ /**
406
+ * Unsubscribe from a channel
407
+ */
408
+ unsubscribe(channel: string): void;
409
+ /**
410
+ * Get list of subscribed channels
411
+ */
412
+ getSubscribedChannels(): string[];
413
+ /**
414
+ * Send raw message to server
415
+ */
416
+ private sendRaw;
417
+ /**
418
+ * Send input to a terminal (sent as-is, not encoded)
419
+ */
420
+ sendTerminalInput(terminalId: string, input: string): void;
421
+ /**
422
+ * Resize terminal window
423
+ */
424
+ resizeTerminal(terminalId: string, cols: number, rows: number): void;
425
+ /**
426
+ * Register event handler
427
+ */
428
+ on(event: 'open', handler: ConnectionHandler): void;
429
+ on(event: 'close', handler: ConnectionHandler): void;
430
+ on(event: 'error', handler: ErrorHandler): void;
431
+ on(event: 'reconnect-failed', handler: ConnectionHandler): void;
432
+ on(event: 'terminal:created', handler: MessageHandler<TerminalCreatedMessage>): void;
433
+ on(event: 'terminal:output', handler: MessageHandler<TerminalOutputMessage>): void;
434
+ on(event: 'terminal:destroyed', handler: MessageHandler<TerminalDestroyedMessage>): void;
435
+ on(event: 'terminal:error', handler: MessageHandler<TerminalErrorMessage>): void;
436
+ on(event: 'watcher:created', handler: MessageHandler<WatcherCreatedMessage>): void;
437
+ on(event: 'file:changed', handler: MessageHandler<FileChangedMessage>): void;
438
+ on(event: 'watcher:destroyed', handler: MessageHandler<WatcherDestroyedMessage>): void;
439
+ on(event: 'signal', handler: MessageHandler<SignalMessage>): void;
440
+ on(event: 'sandbox.created', handler: MessageHandler<SandboxCreatedMessage>): void;
441
+ on(event: 'sandbox.deleted', handler: MessageHandler<SandboxDeletedMessage>): void;
442
+ /**
443
+ * Unregister event handler
444
+ */
445
+ off(event: string, handler: MessageHandler): void;
446
+ /**
447
+ * Unregister all event handlers for an event
448
+ */
449
+ offAll(event: string): void;
450
+ /**
451
+ * Emit event to registered handlers
452
+ */
453
+ private emit;
454
+ /**
455
+ * Handle incoming message
456
+ */
457
+ private handleMessage;
458
+ /**
459
+ * Log debug message if debug mode is enabled
460
+ */
461
+ private log;
462
+ /**
463
+ * Get current connection state
464
+ */
465
+ getState(): 'connecting' | 'open' | 'closing' | 'closed';
466
+ /**
467
+ * Get reconnection attempt count
468
+ */
469
+ getReconnectAttempts(): number;
470
+ }
471
+
472
+ /**
473
+ * Command - Represents a command execution in a terminal
474
+ */
475
+
476
+ /**
477
+ * Command execution result with wait capability
478
+ */
479
+ declare class Command {
480
+ readonly id: string;
481
+ readonly terminalId: string;
482
+ readonly command: string;
483
+ private _status;
484
+ private _stdout;
485
+ private _stderr;
486
+ private _exitCode?;
487
+ private _durationMs?;
488
+ private _startedAt;
489
+ private _finishedAt?;
490
+ private waitHandler?;
491
+ private retrieveHandler?;
492
+ constructor(data: {
493
+ cmdId: string;
494
+ terminalId: string;
495
+ command: string;
496
+ status: 'running' | 'completed' | 'failed';
497
+ stdout: string;
498
+ stderr: string;
499
+ exitCode?: number;
500
+ durationMs?: number;
501
+ startedAt: string;
502
+ finishedAt?: string;
503
+ });
504
+ get status(): 'running' | 'completed' | 'failed';
505
+ get stdout(): string;
506
+ get stderr(): string;
507
+ get exitCode(): number | undefined;
508
+ get durationMs(): number | undefined;
509
+ get startedAt(): string;
510
+ get finishedAt(): string | undefined;
511
+ /**
512
+ * Set the wait handler (called by TerminalCommands)
513
+ * @internal
514
+ */
515
+ setWaitHandler(handler: (timeout?: number) => Promise<CommandDetailsResponse>): void;
516
+ /**
517
+ * Set the retrieve handler (called by TerminalCommands)
518
+ * @internal
519
+ */
520
+ setRetrieveHandler(handler: () => Promise<CommandDetailsResponse>): void;
521
+ /**
522
+ * Wait for the command to complete
523
+ * @param timeout - Optional timeout in seconds (0 = no timeout)
524
+ * @returns This command with updated status
525
+ */
526
+ wait(timeout?: number): Promise<this>;
527
+ /**
528
+ * Refresh the command status from the server
529
+ * @returns This command with updated status
530
+ */
531
+ refresh(): Promise<this>;
532
+ /**
533
+ * Update internal state from API response
534
+ */
535
+ private updateFromResponse;
536
+ }
537
+
538
+ /**
539
+ * TerminalCommand - Resource namespace for terminal commands
540
+ */
541
+
542
+ /**
543
+ * Command resource namespace for a terminal
544
+ *
545
+ * @example
546
+ * ```typescript
547
+ * const terminal = await sandbox.terminal.create({ pty: false });
548
+ *
549
+ * // Run a command
550
+ * const cmd = await terminal.command.run('npm test');
551
+ * console.log(cmd.stdout);
552
+ *
553
+ * // Run in background and wait
554
+ * const cmd = await terminal.command.run('npm install', { background: true });
555
+ * await cmd.wait();
556
+ * console.log(cmd.exitCode);
557
+ *
558
+ * // List commands
559
+ * const commands = await terminal.command.list();
560
+ *
561
+ * // Retrieve a specific command
562
+ * const cmd = await terminal.command.retrieve(cmdId);
563
+ * ```
564
+ */
565
+ declare class TerminalCommand {
566
+ private terminalId;
567
+ private runHandler;
568
+ private listHandler;
569
+ private retrieveHandler;
570
+ private waitHandler;
571
+ constructor(terminalId: string, handlers: {
572
+ run: (command: string, background?: boolean) => Promise<CommandExecutionResponse>;
573
+ list: () => Promise<CommandsListResponse>;
574
+ retrieve: (cmdId: string) => Promise<CommandDetailsResponse>;
575
+ wait: (cmdId: string, timeout?: number) => Promise<CommandDetailsResponse>;
576
+ });
577
+ /**
578
+ * Run a command in the terminal
579
+ * @param command - The command to execute
580
+ * @param options - Execution options
581
+ * @param options.background - If true, returns immediately without waiting for completion
582
+ * @returns Command object with results or status
583
+ */
584
+ run(command: string, options?: {
585
+ background?: boolean;
586
+ }): Promise<Command>;
587
+ /**
588
+ * List all commands executed in this terminal
589
+ * @returns Array of Command objects
590
+ */
591
+ list(): Promise<Command[]>;
592
+ /**
593
+ * Retrieve a specific command by ID
594
+ * @param cmdId - The command ID
595
+ * @returns Command object with full details
596
+ */
597
+ retrieve(cmdId: string): Promise<Command>;
598
+ }
599
+
600
+ /**
601
+ * Terminal class for managing terminal sessions with WebSocket integration
602
+ */
603
+
604
+ /**
605
+ * Terminal event handlers
606
+ */
607
+ type TerminalEventHandler = {
608
+ output: (data: string) => void;
609
+ error: (error: string) => void;
610
+ destroyed: () => void;
611
+ };
612
+ /**
613
+ * TerminalInstance - A connected terminal session with WebSocket support
614
+ *
615
+ * This is the object returned by sandbox.terminal.create()
616
+ *
617
+ * @example
618
+ * ```typescript
619
+ * // PTY mode - Interactive shell
620
+ * const pty = await sandbox.terminal.create({ pty: true });
621
+ * pty.on('output', (data) => console.log(data));
622
+ * pty.write('ls -la\n');
623
+ * await pty.destroy();
624
+ *
625
+ * // Exec mode - Command tracking
626
+ * const exec = await sandbox.terminal.create({ pty: false });
627
+ * const cmd = await exec.command.run('npm test');
628
+ * console.log(cmd.exitCode);
629
+ *
630
+ * // Background execution with wait
631
+ * const cmd = await exec.command.run('npm install', { background: true });
632
+ * await cmd.wait();
633
+ * console.log(cmd.stdout);
634
+ * ```
635
+ */
636
+ declare class TerminalInstance {
637
+ private _id;
638
+ private _pty;
639
+ private _status;
640
+ private _channel;
641
+ private _ws;
642
+ private _encoding;
643
+ private _eventHandlers;
644
+ /**
645
+ * Command namespace for exec mode terminals
646
+ */
647
+ readonly command: TerminalCommand;
648
+ private _executeHandler?;
649
+ private _listCommandsHandler?;
650
+ private _retrieveCommandHandler?;
651
+ private _waitCommandHandler?;
652
+ private _destroyHandler?;
653
+ constructor(id: string, pty: boolean, status: 'running' | 'stopped' | 'active' | 'ready', channel: string | null, ws: WebSocketManager | null, encoding?: 'raw' | 'base64');
654
+ /**
655
+ * Set up WebSocket event handlers (PTY mode only)
656
+ */
657
+ private setupWebSocketHandlers;
658
+ /**
659
+ * Terminal ID
660
+ */
661
+ get id(): string;
662
+ /**
663
+ * Get terminal ID (deprecated, use .id property)
664
+ * @deprecated Use .id property instead
665
+ */
666
+ getId(): string;
667
+ /**
668
+ * Terminal status
669
+ */
670
+ get status(): 'running' | 'stopped' | 'active' | 'ready';
671
+ /**
672
+ * Get terminal status (deprecated, use .status property)
673
+ * @deprecated Use .status property instead
674
+ */
675
+ getStatus(): 'running' | 'stopped' | 'active' | 'ready';
676
+ /**
677
+ * Terminal channel (null for exec mode)
678
+ */
679
+ get channel(): string | null;
680
+ /**
681
+ * Get terminal channel (deprecated, use .channel property)
682
+ * @deprecated Use .channel property instead
683
+ */
684
+ getChannel(): string | null;
685
+ /**
686
+ * Whether this is a PTY terminal
687
+ */
688
+ get pty(): boolean;
689
+ /**
690
+ * Get terminal PTY mode (deprecated, use .pty property)
691
+ * @deprecated Use .pty property instead
692
+ */
693
+ isPTY(): boolean;
694
+ /**
695
+ * Check if terminal is running
696
+ */
697
+ isRunning(): boolean;
698
+ /**
699
+ * Write input to the terminal (PTY mode only)
700
+ */
701
+ write(input: string): void;
702
+ /**
703
+ * Resize terminal window (PTY mode only)
704
+ */
705
+ resize(cols: number, rows: number): void;
706
+ /**
707
+ * Set execute command handler (called by Sandbox)
708
+ * @internal
709
+ */
710
+ setExecuteHandler(handler: (command: string, background?: boolean) => Promise<CommandExecutionResponse>): void;
711
+ /**
712
+ * Set list commands handler (called by Sandbox)
713
+ * @internal
714
+ */
715
+ setListCommandsHandler(handler: () => Promise<CommandsListResponse>): void;
716
+ /**
717
+ * Set retrieve command handler (called by Sandbox)
718
+ * @internal
719
+ */
720
+ setRetrieveCommandHandler(handler: (cmdId: string) => Promise<CommandDetailsResponse>): void;
721
+ /**
722
+ * Set wait command handler (called by Sandbox)
723
+ * @internal
724
+ */
725
+ setWaitCommandHandler(handler: (cmdId: string, timeout?: number) => Promise<CommandDetailsResponse>): void;
726
+ /**
727
+ * Set destroy handler (called by Sandbox)
728
+ * @internal
729
+ */
730
+ setDestroyHandler(handler: () => Promise<void>): void;
731
+ /**
732
+ * Execute a command in the terminal (deprecated, use command.run())
733
+ * @deprecated Use terminal.command.run() instead
734
+ */
735
+ execute(command: string, options?: {
736
+ background?: boolean;
737
+ }): Promise<CommandExecutionResponse>;
738
+ /**
739
+ * Destroy the terminal
740
+ */
741
+ destroy(): Promise<void>;
742
+ /**
743
+ * Clean up resources
744
+ */
745
+ private cleanup;
746
+ /**
747
+ * Register event handler
748
+ */
749
+ on<K extends keyof TerminalEventHandler>(event: K, handler: TerminalEventHandler[K]): void;
750
+ /**
751
+ * Unregister event handler
752
+ */
753
+ off<K extends keyof TerminalEventHandler>(event: K, handler: TerminalEventHandler[K]): void;
754
+ /**
755
+ * Emit event to registered handlers
756
+ */
757
+ private emit;
758
+ }
759
+
760
+ /**
761
+ * FileWatcher class for monitoring file system changes with WebSocket integration
762
+ */
763
+
764
+ /**
765
+ * File change event data
766
+ */
767
+ interface FileChangeEvent {
768
+ event: 'add' | 'change' | 'unlink' | 'addDir' | 'unlinkDir';
769
+ path: string;
770
+ content?: string;
771
+ }
772
+ /**
773
+ * FileWatcher event handlers
774
+ */
775
+ type FileWatcherEventHandler = {
776
+ change: (event: FileChangeEvent) => void;
777
+ destroyed: () => void;
778
+ };
779
+ /**
780
+ * FileWatcher class for monitoring file system changes
781
+ *
782
+ * @example
783
+ * ```typescript
784
+ * const client = new ComputeClient({ sandboxUrl: '...' });
785
+ * await client.generateToken();
786
+ *
787
+ * const watcher = await client.createWatcher('/home/project', {
788
+ * ignored: ['node_modules', '.git']
789
+ * });
790
+ *
791
+ * watcher.on('change', (event) => {
792
+ * console.log(`File ${event.event}: ${event.path}`);
793
+ * });
794
+ *
795
+ * await watcher.destroy();
796
+ * ```
797
+ */
798
+ declare class FileWatcher {
799
+ private id;
800
+ private path;
801
+ private status;
802
+ private channel;
803
+ private includeContent;
804
+ private ignored;
805
+ private encoding;
806
+ private ws;
807
+ private eventHandlers;
808
+ constructor(id: string, path: string, status: 'active' | 'stopped', channel: string, includeContent: boolean, ignored: string[], ws: WebSocketManager, encoding?: 'raw' | 'base64');
809
+ /**
810
+ * Set up WebSocket event handlers
811
+ */
812
+ private setupWebSocketHandlers;
813
+ /**
814
+ * Get watcher ID
815
+ */
816
+ getId(): string;
817
+ /**
818
+ * Get watched path
819
+ */
820
+ getPath(): string;
821
+ /**
822
+ * Get watcher status
823
+ */
824
+ getStatus(): 'active' | 'stopped';
825
+ /**
826
+ * Get watcher channel
827
+ */
828
+ getChannel(): string;
829
+ /**
830
+ * Check if content is included in events
831
+ */
832
+ isIncludingContent(): boolean;
833
+ /**
834
+ * Get ignored patterns
835
+ */
836
+ getIgnoredPatterns(): string[];
837
+ /**
838
+ * Check if watcher is active
839
+ */
840
+ isActive(): boolean;
841
+ /**
842
+ * Destroy the watcher (uses REST API, not WebSocket)
843
+ */
844
+ private destroyWatcher?;
845
+ /**
846
+ * Set destroy handler (called by client)
847
+ */
848
+ setDestroyHandler(handler: () => Promise<void>): void;
849
+ /**
850
+ * Destroy the watcher
851
+ */
852
+ destroy(): Promise<void>;
853
+ /**
854
+ * Clean up resources
855
+ */
856
+ private cleanup;
857
+ /**
858
+ * Register event handler
859
+ */
860
+ on<K extends keyof FileWatcherEventHandler>(event: K, handler: FileWatcherEventHandler[K]): void;
861
+ /**
862
+ * Unregister event handler
863
+ */
864
+ off<K extends keyof FileWatcherEventHandler>(event: K, handler: FileWatcherEventHandler[K]): void;
865
+ /**
866
+ * Emit event to registered handlers
867
+ */
868
+ private emit;
869
+ }
870
+
871
+ /**
872
+ * SignalService class for monitoring system signals with WebSocket integration
873
+ */
874
+
875
+ /**
876
+ * Port signal data
877
+ */
878
+ interface PortSignalEvent {
879
+ signal: 'port' | 'server-ready';
880
+ port: number;
881
+ url: string;
882
+ type?: 'open' | 'close';
883
+ }
884
+ /**
885
+ * Error signal data
886
+ */
887
+ interface ErrorSignalEvent {
888
+ signal: 'error';
889
+ message: string;
890
+ }
891
+ /**
892
+ * Generic signal event (union type)
893
+ */
894
+ type SignalEvent = PortSignalEvent | ErrorSignalEvent;
895
+ /**
896
+ * SignalService event handlers
897
+ */
898
+ type SignalServiceEventHandler = {
899
+ port: (event: PortSignalEvent) => void;
900
+ error: (event: ErrorSignalEvent) => void;
901
+ signal: (event: SignalEvent) => void;
902
+ };
903
+ /**
904
+ * SignalService class for monitoring system signals and events
905
+ *
906
+ * @example
907
+ * ```typescript
908
+ * const client = new ComputeClient({ sandboxUrl: '...' });
909
+ * await client.generateToken();
910
+ *
911
+ * const signals = await client.startSignals();
912
+ *
913
+ * signals.on('port', (event) => {
914
+ * console.log(`Port ${event.port} ${event.type}: ${event.url}`);
915
+ * });
916
+ *
917
+ * signals.on('error', (event) => {
918
+ * console.error(`Error: ${event.message}`);
919
+ * });
920
+ *
921
+ * await signals.stop();
922
+ * ```
923
+ */
924
+ declare class SignalService {
925
+ private status;
926
+ private channel;
927
+ private ws;
928
+ private eventHandlers;
929
+ constructor(status: 'active' | 'stopped', channel: string, ws: WebSocketManager);
930
+ /**
931
+ * Set up WebSocket event handlers
932
+ */
933
+ private setupWebSocketHandlers;
934
+ /**
935
+ * Get service status
936
+ */
937
+ getStatus(): 'active' | 'stopped';
938
+ /**
939
+ * Get service channel
940
+ */
941
+ getChannel(): string;
942
+ /**
943
+ * Check if service is active
944
+ */
945
+ isActive(): boolean;
946
+ /**
947
+ * Stop the signal service (uses REST API, not WebSocket)
948
+ */
949
+ private stopService?;
950
+ /**
951
+ * Set stop handler (called by client)
952
+ */
953
+ setStopHandler(handler: () => Promise<void>): void;
954
+ /**
955
+ * Stop the signal service
956
+ */
957
+ stop(): Promise<void>;
958
+ /**
959
+ * Clean up resources
960
+ */
961
+ private cleanup;
962
+ /**
963
+ * Register event handler
964
+ */
965
+ on<K extends keyof SignalServiceEventHandler>(event: K, handler: SignalServiceEventHandler[K]): void;
966
+ /**
967
+ * Unregister event handler
968
+ */
969
+ off<K extends keyof SignalServiceEventHandler>(event: K, handler: SignalServiceEventHandler[K]): void;
970
+ /**
971
+ * Emit event to registered handlers
972
+ */
973
+ private emit;
974
+ }
975
+
976
+ /**
977
+ * Terminal - Resource namespace for terminal management
978
+ */
979
+
980
+ /**
981
+ * Terminal resource namespace
982
+ *
983
+ * @example
984
+ * ```typescript
985
+ * // Create a PTY terminal (interactive shell)
986
+ * const pty = await sandbox.terminal.create({ pty: true, shell: '/bin/bash' });
987
+ * pty.on('output', (data) => console.log(data));
988
+ * pty.write('ls -la\n');
989
+ *
990
+ * // Create an exec terminal (command tracking)
991
+ * const exec = await sandbox.terminal.create({ pty: false });
992
+ * const cmd = await exec.command.run('npm test');
993
+ * console.log(cmd.exitCode);
994
+ *
995
+ * // List all terminals
996
+ * const terminals = await sandbox.terminal.list();
997
+ *
998
+ * // Retrieve a specific terminal
999
+ * const terminal = await sandbox.terminal.retrieve(id);
1000
+ *
1001
+ * // Destroy a terminal
1002
+ * await sandbox.terminal.destroy(id);
1003
+ * ```
1004
+ */
1005
+ declare class Terminal {
1006
+ private createHandler;
1007
+ private listHandler;
1008
+ private retrieveHandler;
1009
+ private destroyHandler;
1010
+ constructor(handlers: {
1011
+ create: (options?: {
1012
+ shell?: string;
1013
+ encoding?: 'raw' | 'base64';
1014
+ pty?: boolean;
1015
+ }) => Promise<TerminalInstance>;
1016
+ list: () => Promise<TerminalResponse[]>;
1017
+ retrieve: (id: string) => Promise<TerminalResponse>;
1018
+ destroy: (id: string) => Promise<void>;
1019
+ });
1020
+ /**
1021
+ * Create a new terminal session
1022
+ *
1023
+ * @param options - Terminal creation options
1024
+ * @param options.shell - Shell to use (e.g., '/bin/bash') - PTY mode only
1025
+ * @param options.encoding - Encoding: 'raw' (default) or 'base64' (binary-safe)
1026
+ * @param options.pty - Terminal mode: true = PTY (interactive), false = exec (command tracking)
1027
+ * @returns TerminalInstance
1028
+ */
1029
+ create(options?: {
1030
+ shell?: string;
1031
+ encoding?: 'raw' | 'base64';
1032
+ pty?: boolean;
1033
+ }): Promise<TerminalInstance>;
1034
+ /**
1035
+ * List all active terminals
1036
+ * @returns Array of terminal responses
1037
+ */
1038
+ list(): Promise<TerminalResponse[]>;
1039
+ /**
1040
+ * Retrieve a specific terminal by ID
1041
+ * @param id - The terminal ID
1042
+ * @returns Terminal response
1043
+ */
1044
+ retrieve(id: string): Promise<TerminalResponse>;
1045
+ /**
1046
+ * Destroy a terminal by ID
1047
+ * @param id - The terminal ID
1048
+ */
1049
+ destroy(id: string): Promise<void>;
1050
+ }
1051
+
1052
+ /**
1053
+ * Server - Resource namespace for managed server operations
1054
+ */
1055
+
1056
+ /**
1057
+ * Server resource namespace
1058
+ *
1059
+ * @example
1060
+ * ```typescript
1061
+ * // Start a new server
1062
+ * const server = await sandbox.server.start({
1063
+ * slug: 'api',
1064
+ * command: 'npm start',
1065
+ * path: '/app',
1066
+ * });
1067
+ *
1068
+ * // List all servers
1069
+ * const servers = await sandbox.server.list();
1070
+ *
1071
+ * // Retrieve a specific server
1072
+ * const server = await sandbox.server.retrieve('api');
1073
+ *
1074
+ * // Stop a server
1075
+ * await sandbox.server.stop('api');
1076
+ *
1077
+ * // Restart a server
1078
+ * await sandbox.server.restart('api');
1079
+ * ```
1080
+ */
1081
+ declare class Server {
1082
+ private startHandler;
1083
+ private listHandler;
1084
+ private retrieveHandler;
1085
+ private stopHandler;
1086
+ private restartHandler;
1087
+ private updateStatusHandler;
1088
+ constructor(handlers: {
1089
+ start: (options: {
1090
+ slug: string;
1091
+ command: string;
1092
+ path?: string;
1093
+ env_file?: string;
1094
+ }) => Promise<ServerResponse>;
1095
+ list: () => Promise<ServersListResponse>;
1096
+ retrieve: (slug: string) => Promise<ServerResponse>;
1097
+ stop: (slug: string) => Promise<ServerStopResponse | void>;
1098
+ restart: (slug: string) => Promise<ServerResponse>;
1099
+ updateStatus: (slug: string, status: ServerStatus) => Promise<void>;
1100
+ });
1101
+ /**
1102
+ * Start a new managed server
1103
+ * @param options - Server configuration
1104
+ * @param options.slug - Unique server slug (URL-safe identifier)
1105
+ * @param options.command - Command to start the server
1106
+ * @param options.path - Working directory (optional)
1107
+ * @param options.env_file - Path to env file (optional)
1108
+ * @returns Server info
1109
+ */
1110
+ start(options: {
1111
+ slug: string;
1112
+ command: string;
1113
+ path?: string;
1114
+ env_file?: string;
1115
+ }): Promise<ServerInfo>;
1116
+ /**
1117
+ * List all managed servers
1118
+ * @returns Array of server info
1119
+ */
1120
+ list(): Promise<ServerInfo[]>;
1121
+ /**
1122
+ * Retrieve a specific server by slug
1123
+ * @param slug - The server slug
1124
+ * @returns Server info
1125
+ */
1126
+ retrieve(slug: string): Promise<ServerInfo>;
1127
+ /**
1128
+ * Stop a server by slug
1129
+ * @param slug - The server slug
1130
+ */
1131
+ stop(slug: string): Promise<void>;
1132
+ /**
1133
+ * Restart a server by slug
1134
+ * @param slug - The server slug
1135
+ * @returns Server info
1136
+ */
1137
+ restart(slug: string): Promise<ServerInfo>;
1138
+ /**
1139
+ * Update server status (internal use)
1140
+ * @param slug - The server slug
1141
+ * @param status - New status
1142
+ */
1143
+ updateStatus(slug: string, status: ServerStatus): Promise<void>;
1144
+ }
1145
+
1146
+ /**
1147
+ * Watcher - Resource namespace for file watcher operations
1148
+ */
1149
+
1150
+ /**
1151
+ * Watcher resource namespace
1152
+ *
1153
+ * @example
1154
+ * ```typescript
1155
+ * // Create a file watcher
1156
+ * const watcher = await sandbox.watcher.create('/project', {
1157
+ * ignored: ['node_modules', '.git'],
1158
+ * includeContent: true,
1159
+ * });
1160
+ * watcher.on('change', (event) => {
1161
+ * console.log(`${event.event}: ${event.path}`);
1162
+ * });
1163
+ *
1164
+ * // List all watchers
1165
+ * const watchers = await sandbox.watcher.list();
1166
+ *
1167
+ * // Retrieve a specific watcher
1168
+ * const watcher = await sandbox.watcher.retrieve(id);
1169
+ *
1170
+ * // Destroy a watcher
1171
+ * await sandbox.watcher.destroy(id);
1172
+ * ```
1173
+ */
1174
+ declare class Watcher {
1175
+ private createHandler;
1176
+ private listHandler;
1177
+ private retrieveHandler;
1178
+ private destroyHandler;
1179
+ constructor(handlers: {
1180
+ create: (path: string, options?: {
1181
+ includeContent?: boolean;
1182
+ ignored?: string[];
1183
+ encoding?: 'raw' | 'base64';
1184
+ }) => Promise<FileWatcher>;
1185
+ list: () => Promise<WatchersListResponse>;
1186
+ retrieve: (id: string) => Promise<WatcherResponse>;
1187
+ destroy: (id: string) => Promise<void>;
1188
+ });
1189
+ /**
1190
+ * Create a new file watcher
1191
+ * @param path - Path to watch
1192
+ * @param options - Watcher options
1193
+ * @param options.includeContent - Include file content in change events
1194
+ * @param options.ignored - Patterns to ignore
1195
+ * @param options.encoding - Encoding: 'raw' (default) or 'base64' (binary-safe)
1196
+ * @returns FileWatcher instance
1197
+ */
1198
+ create(path: string, options?: {
1199
+ includeContent?: boolean;
1200
+ ignored?: string[];
1201
+ encoding?: 'raw' | 'base64';
1202
+ }): Promise<FileWatcher>;
1203
+ /**
1204
+ * List all active file watchers
1205
+ * @returns Array of watcher info
1206
+ */
1207
+ list(): Promise<WatcherInfo[]>;
1208
+ /**
1209
+ * Retrieve a specific watcher by ID
1210
+ * @param id - The watcher ID
1211
+ * @returns Watcher info
1212
+ */
1213
+ retrieve(id: string): Promise<WatcherInfo>;
1214
+ /**
1215
+ * Destroy a watcher by ID
1216
+ * @param id - The watcher ID
1217
+ */
1218
+ destroy(id: string): Promise<void>;
1219
+ }
1220
+
1221
+ /**
1222
+ * SessionToken - Resource namespace for session token management
1223
+ */
1224
+
1225
+ /**
1226
+ * Session token info
1227
+ */
1228
+ interface SessionTokenInfo {
1229
+ id: string;
1230
+ token?: string;
1231
+ description?: string;
1232
+ createdAt: string;
1233
+ expiresAt: string;
1234
+ lastUsedAt?: string;
1235
+ }
1236
+ /**
1237
+ * SessionToken resource namespace
1238
+ *
1239
+ * @example
1240
+ * ```typescript
1241
+ * // Create a session token (requires access token)
1242
+ * const token = await sandbox.sessionToken.create({
1243
+ * description: 'My Application',
1244
+ * expiresIn: 604800, // 7 days
1245
+ * });
1246
+ * console.log(token.token);
1247
+ *
1248
+ * // List all session tokens
1249
+ * const tokens = await sandbox.sessionToken.list();
1250
+ *
1251
+ * // Retrieve a specific token
1252
+ * const token = await sandbox.sessionToken.retrieve(id);
1253
+ *
1254
+ * // Revoke a token
1255
+ * await sandbox.sessionToken.revoke(id);
1256
+ * ```
1257
+ */
1258
+ declare class SessionToken {
1259
+ private createHandler;
1260
+ private listHandler;
1261
+ private retrieveHandler;
1262
+ private revokeHandler;
1263
+ constructor(handlers: {
1264
+ create: (options?: {
1265
+ description?: string;
1266
+ expiresIn?: number;
1267
+ }) => Promise<SessionTokenResponse>;
1268
+ list: () => Promise<SessionTokenListResponse>;
1269
+ retrieve: (id: string) => Promise<SessionTokenResponse>;
1270
+ revoke: (id: string) => Promise<void>;
1271
+ });
1272
+ /**
1273
+ * Create a new session token (requires access token)
1274
+ * @param options - Token configuration
1275
+ * @param options.description - Description for the token
1276
+ * @param options.expiresIn - Expiration time in seconds (default: 7 days)
1277
+ * @returns Session token info including the token value
1278
+ */
1279
+ create(options?: {
1280
+ description?: string;
1281
+ expiresIn?: number;
1282
+ }): Promise<SessionTokenInfo>;
1283
+ /**
1284
+ * List all session tokens
1285
+ * @returns Array of session token info
1286
+ */
1287
+ list(): Promise<SessionTokenInfo[]>;
1288
+ /**
1289
+ * Retrieve a specific session token by ID
1290
+ * @param id - The token ID
1291
+ * @returns Session token info
1292
+ */
1293
+ retrieve(id: string): Promise<SessionTokenInfo>;
1294
+ /**
1295
+ * Revoke a session token
1296
+ * @param id - The token ID to revoke
1297
+ */
1298
+ revoke(id: string): Promise<void>;
1299
+ }
1300
+
1301
+ /**
1302
+ * MagicLink - Resource namespace for magic link operations
1303
+ */
1304
+
1305
+ /**
1306
+ * Magic link info
1307
+ */
1308
+ interface MagicLinkInfo {
1309
+ url: string;
1310
+ expiresAt: string;
1311
+ redirectUrl: string;
1312
+ }
1313
+ /**
1314
+ * MagicLink resource namespace
1315
+ *
1316
+ * @example
1317
+ * ```typescript
1318
+ * // Create a magic link (requires access token)
1319
+ * const link = await sandbox.magicLink.create({
1320
+ * redirectUrl: '/dashboard',
1321
+ * });
1322
+ * console.log(link.url);
1323
+ * ```
1324
+ */
1325
+ declare class MagicLink {
1326
+ private createHandler;
1327
+ constructor(handlers: {
1328
+ create: (options?: {
1329
+ redirectUrl?: string;
1330
+ }) => Promise<MagicLinkResponse>;
1331
+ });
1332
+ /**
1333
+ * Create a magic link for browser authentication (requires access token)
1334
+ *
1335
+ * Magic links are one-time URLs that automatically create a session token
1336
+ * and set it as a cookie in the user's browser.
1337
+ *
1338
+ * @param options - Magic link configuration
1339
+ * @param options.redirectUrl - URL to redirect to after authentication
1340
+ * @returns Magic link info including the URL
1341
+ */
1342
+ create(options?: {
1343
+ redirectUrl?: string;
1344
+ }): Promise<MagicLinkInfo>;
1345
+ }
1346
+
1347
+ /**
1348
+ * Signal - Resource namespace for signal service operations
1349
+ */
1350
+
1351
+ /**
1352
+ * Signal service status info
1353
+ */
1354
+ interface SignalStatusInfo {
1355
+ status: 'active' | 'stopped';
1356
+ channel: string;
1357
+ wsUrl: string;
1358
+ }
1359
+ /**
1360
+ * Signal resource namespace
1361
+ *
1362
+ * @example
1363
+ * ```typescript
1364
+ * // Start the signal service
1365
+ * const signals = await sandbox.signal.start();
1366
+ * signals.on('port', (event) => {
1367
+ * console.log(`Port ${event.port} opened: ${event.url}`);
1368
+ * });
1369
+ *
1370
+ * // Get signal service status
1371
+ * const status = await sandbox.signal.status();
1372
+ *
1373
+ * // Emit signals
1374
+ * await sandbox.signal.emitPort(3000, 'open', 'http://localhost:3000');
1375
+ * await sandbox.signal.emitError('Something went wrong');
1376
+ *
1377
+ * // Stop the signal service
1378
+ * await sandbox.signal.stop();
1379
+ * ```
1380
+ */
1381
+ declare class Signal {
1382
+ private startHandler;
1383
+ private statusHandler;
1384
+ private stopHandler;
1385
+ private emitPortHandler;
1386
+ private emitErrorHandler;
1387
+ private emitServerReadyHandler;
1388
+ constructor(handlers: {
1389
+ start: () => Promise<SignalService>;
1390
+ status: () => Promise<SignalServiceResponse>;
1391
+ stop: () => Promise<void>;
1392
+ emitPort: (port: number, type: 'open' | 'close', url: string) => Promise<PortSignalResponse>;
1393
+ emitError: (message: string) => Promise<GenericSignalResponse>;
1394
+ emitServerReady: (port: number, url: string) => Promise<PortSignalResponse>;
1395
+ });
1396
+ /**
1397
+ * Start the signal service
1398
+ * @returns SignalService instance with event handling
1399
+ */
1400
+ start(): Promise<SignalService>;
1401
+ /**
1402
+ * Get the signal service status
1403
+ * @returns Signal service status info
1404
+ */
1405
+ status(): Promise<SignalStatusInfo>;
1406
+ /**
1407
+ * Stop the signal service
1408
+ */
1409
+ stop(): Promise<void>;
1410
+ /**
1411
+ * Emit a port signal
1412
+ * @param port - Port number
1413
+ * @param type - Signal type ('open' or 'close')
1414
+ * @param url - URL associated with the port
1415
+ */
1416
+ emitPort(port: number, type: 'open' | 'close', url: string): Promise<void>;
1417
+ /**
1418
+ * Emit an error signal
1419
+ * @param message - Error message
1420
+ */
1421
+ emitError(message: string): Promise<void>;
1422
+ /**
1423
+ * Emit a server ready signal
1424
+ * @param port - Port number
1425
+ * @param url - Server URL
1426
+ */
1427
+ emitServerReady(port: number, url: string): Promise<void>;
1428
+ }
1429
+
1430
+ /**
1431
+ * File - Resource namespace for file operations
1432
+ */
1433
+
1434
+ /**
1435
+ * File resource namespace
1436
+ *
1437
+ * @example
1438
+ * ```typescript
1439
+ * // Create a file
1440
+ * const file = await sandbox.file.create('/project/hello.txt', 'Hello, World!');
1441
+ *
1442
+ * // List files in a directory
1443
+ * const files = await sandbox.file.list('/project');
1444
+ *
1445
+ * // Retrieve file content
1446
+ * const content = await sandbox.file.retrieve('/project/hello.txt');
1447
+ *
1448
+ * // Destroy (delete) a file
1449
+ * await sandbox.file.destroy('/project/hello.txt');
1450
+ *
1451
+ * // Batch write multiple files
1452
+ * const results = await sandbox.file.batchWrite([
1453
+ * { path: '/project/a.txt', operation: 'write', content: 'A' },
1454
+ * { path: '/project/b.txt', operation: 'write', content: 'B' },
1455
+ * ]);
1456
+ *
1457
+ * // Batch delete files
1458
+ * const results = await sandbox.file.batchWrite([
1459
+ * { path: '/project/old.txt', operation: 'delete' },
1460
+ * ]);
1461
+ * ```
1462
+ */
1463
+ declare class File {
1464
+ private createHandler;
1465
+ private listHandler;
1466
+ private retrieveHandler;
1467
+ private destroyHandler;
1468
+ private batchWriteHandler;
1469
+ private existsHandler;
1470
+ constructor(handlers: {
1471
+ create: (path: string, content?: string) => Promise<FileResponse>;
1472
+ list: (path: string) => Promise<FilesListResponse>;
1473
+ retrieve: (path: string) => Promise<string>;
1474
+ destroy: (path: string) => Promise<void>;
1475
+ batchWrite: (files: Array<{
1476
+ path: string;
1477
+ operation: BatchFileOperation;
1478
+ content?: string;
1479
+ }>) => Promise<BatchWriteResponse>;
1480
+ exists: (path: string) => Promise<boolean>;
1481
+ });
1482
+ /**
1483
+ * Create a new file with optional content
1484
+ * @param path - File path
1485
+ * @param content - File content (optional)
1486
+ * @returns File info
1487
+ */
1488
+ create(path: string, content?: string): Promise<FileInfo>;
1489
+ /**
1490
+ * List files at the specified path
1491
+ * @param path - Directory path (default: '/')
1492
+ * @returns Array of file info
1493
+ */
1494
+ list(path?: string): Promise<FileInfo[]>;
1495
+ /**
1496
+ * Retrieve file content
1497
+ * @param path - File path
1498
+ * @returns File content as string
1499
+ */
1500
+ retrieve(path: string): Promise<string>;
1501
+ /**
1502
+ * Destroy (delete) a file or directory
1503
+ * @param path - File or directory path
1504
+ */
1505
+ destroy(path: string): Promise<void>;
1506
+ /**
1507
+ * Batch file operations (write or delete multiple files)
1508
+ *
1509
+ * Features:
1510
+ * - Deduplication: Last operation wins per path
1511
+ * - File locking: Prevents race conditions
1512
+ * - Deterministic ordering: Alphabetical path sorting
1513
+ * - Partial failure handling: Returns per-file results
1514
+ *
1515
+ * @param files - Array of file operations
1516
+ * @returns Results for each file operation
1517
+ */
1518
+ batchWrite(files: Array<{
1519
+ path: string;
1520
+ operation: BatchFileOperation;
1521
+ content?: string;
1522
+ }>): Promise<BatchWriteResult[]>;
1523
+ /**
1524
+ * Check if a file exists
1525
+ * @param path - File path
1526
+ * @returns True if file exists
1527
+ */
1528
+ exists(path: string): Promise<boolean>;
1529
+ }
1530
+
1531
+ /**
1532
+ * Env - Resource namespace for environment variable operations
1533
+ */
1534
+
1535
+ /**
1536
+ * Env resource namespace
1537
+ *
1538
+ * @example
1539
+ * ```typescript
1540
+ * // Retrieve environment variables
1541
+ * const vars = await sandbox.env.retrieve('.env');
1542
+ * console.log(vars);
1543
+ *
1544
+ * // Update environment variables (merges with existing)
1545
+ * await sandbox.env.update('.env', {
1546
+ * API_KEY: 'secret',
1547
+ * DEBUG: 'true',
1548
+ * });
1549
+ *
1550
+ * // Remove environment variables
1551
+ * await sandbox.env.remove('.env', ['OLD_KEY', 'DEPRECATED']);
1552
+ * ```
1553
+ */
1554
+ declare class Env {
1555
+ private retrieveHandler;
1556
+ private updateHandler;
1557
+ private removeHandler;
1558
+ private existsHandler;
1559
+ constructor(handlers: {
1560
+ retrieve: (file: string) => Promise<EnvGetResponse>;
1561
+ update: (file: string, variables: Record<string, string>) => Promise<EnvSetResponse>;
1562
+ remove: (file: string, keys: string[]) => Promise<EnvDeleteResponse>;
1563
+ exists: (file: string) => Promise<boolean>;
1564
+ });
1565
+ /**
1566
+ * Retrieve environment variables from a file
1567
+ * @param file - Path to the .env file (relative to sandbox root)
1568
+ * @returns Key-value map of environment variables
1569
+ */
1570
+ retrieve(file: string): Promise<Record<string, string>>;
1571
+ /**
1572
+ * Update (merge) environment variables in a file
1573
+ * @param file - Path to the .env file (relative to sandbox root)
1574
+ * @param variables - Key-value pairs to set
1575
+ * @returns Keys that were updated
1576
+ */
1577
+ update(file: string, variables: Record<string, string>): Promise<string[]>;
1578
+ /**
1579
+ * Remove environment variables from a file
1580
+ * @param file - Path to the .env file (relative to sandbox root)
1581
+ * @param keys - Keys to remove
1582
+ * @returns Keys that were removed
1583
+ */
1584
+ remove(file: string, keys: string[]): Promise<string[]>;
1585
+ /**
1586
+ * Check if an environment file exists
1587
+ * @param file - Path to the .env file (relative to sandbox root)
1588
+ * @returns True if file exists
1589
+ */
1590
+ exists(file: string): Promise<boolean>;
1591
+ }
1592
+
1593
+ /**
1594
+ * Auth - Resource namespace for authentication info
1595
+ */
1596
+
1597
+ /**
1598
+ * Authentication status info
1599
+ */
1600
+ interface AuthStatusInfo {
1601
+ authenticated: boolean;
1602
+ tokenType?: 'access_token' | 'session_token';
1603
+ expiresAt?: string;
1604
+ }
1605
+ /**
1606
+ * Authentication endpoints info
1607
+ */
1608
+ interface AuthEndpointsInfo {
1609
+ createSessionToken: string;
1610
+ listSessionTokens: string;
1611
+ getSessionToken: string;
1612
+ revokeSessionToken: string;
1613
+ createMagicLink: string;
1614
+ authStatus: string;
1615
+ authInfo: string;
1616
+ }
1617
+ /**
1618
+ * Authentication info
1619
+ */
1620
+ interface AuthInfo {
1621
+ message: string;
1622
+ instructions: string;
1623
+ endpoints: AuthEndpointsInfo;
1624
+ }
1625
+ /**
1626
+ * Auth resource namespace
1627
+ *
1628
+ * @example
1629
+ * ```typescript
1630
+ * // Check authentication status
1631
+ * const status = await sandbox.auth.status();
1632
+ * console.log(status.authenticated);
1633
+ * console.log(status.tokenType);
1634
+ *
1635
+ * // Get authentication info and instructions
1636
+ * const info = await sandbox.auth.info();
1637
+ * console.log(info.instructions);
1638
+ * ```
1639
+ */
1640
+ declare class Auth {
1641
+ private statusHandler;
1642
+ private infoHandler;
1643
+ constructor(handlers: {
1644
+ status: () => Promise<AuthStatusResponse>;
1645
+ info: () => Promise<AuthInfoResponse>;
1646
+ });
1647
+ /**
1648
+ * Check authentication status
1649
+ * @returns Authentication status info
1650
+ */
1651
+ status(): Promise<AuthStatusInfo>;
1652
+ /**
1653
+ * Get authentication information and usage instructions
1654
+ * @returns Authentication info
1655
+ */
1656
+ info(): Promise<AuthInfo>;
1657
+ }
1658
+
1659
+ /**
1660
+ * Run - Resource namespace for code and command execution
1661
+ */
1662
+ /**
1663
+ * Code execution result
1664
+ */
1665
+ interface CodeResult {
1666
+ output: string;
1667
+ exitCode: number;
1668
+ language: string;
1669
+ }
1670
+ /**
1671
+ * Command execution result
1672
+ */
1673
+ interface CommandResult {
1674
+ stdout: string;
1675
+ stderr: string;
1676
+ exitCode: number;
1677
+ durationMs: number;
1678
+ }
1679
+ /**
1680
+ * Supported languages for code execution
1681
+ */
1682
+ type CodeLanguage = 'python' | 'python3' | 'node' | 'javascript' | 'js' | 'bash' | 'sh' | 'ruby';
1683
+ /**
1684
+ * Code execution options
1685
+ */
1686
+ interface CodeRunOptions {
1687
+ /** Programming language (optional - will auto-detect if not specified) */
1688
+ language?: CodeLanguage;
1689
+ }
1690
+ /**
1691
+ * Command execution options
1692
+ */
1693
+ interface CommandRunOptions {
1694
+ /** Shell to use (optional) */
1695
+ shell?: string;
1696
+ /** Run in background (optional) */
1697
+ background?: boolean;
1698
+ }
1699
+ /**
1700
+ * Run - Resource namespace for executing code and commands
1701
+ *
1702
+ * @example
1703
+ * ```typescript
1704
+ * // Run code with auto-detection
1705
+ * const result = await sandbox.run.code('print("Hello from Python")');
1706
+ * console.log(result.output); // "Hello from Python\n"
1707
+ * console.log(result.language); // "python"
1708
+ *
1709
+ * // Run code with explicit language
1710
+ * const result = await sandbox.run.code('console.log("Hello")', { language: 'node' });
1711
+ *
1712
+ * // Run a command
1713
+ * const result = await sandbox.run.command('ls -la');
1714
+ * console.log(result.stdout);
1715
+ * console.log(result.exitCode);
1716
+ * ```
1717
+ */
1718
+ declare class Run {
1719
+ private codeHandler;
1720
+ private commandHandler;
1721
+ constructor(handlers: {
1722
+ code: (code: string, options?: CodeRunOptions) => Promise<CodeResult>;
1723
+ command: (command: string, options?: CommandRunOptions) => Promise<CommandResult>;
1724
+ });
1725
+ /**
1726
+ * Execute code with automatic language detection
1727
+ *
1728
+ * Supports: python, python3, node, javascript, js, bash, sh, ruby
1729
+ *
1730
+ * @param code - The code to execute
1731
+ * @param options - Execution options
1732
+ * @param options.language - Programming language (auto-detected if not specified)
1733
+ * @returns Code execution result with output, exit code, and detected language
1734
+ */
1735
+ code(code: string, options?: CodeRunOptions): Promise<CodeResult>;
1736
+ /**
1737
+ * Execute a shell command
1738
+ *
1739
+ * @param command - The command to execute
1740
+ * @param options - Execution options
1741
+ * @param options.shell - Shell to use (optional)
1742
+ * @param options.background - Run in background (optional)
1743
+ * @returns Command execution result with stdout, stderr, exit code, and duration
1744
+ */
1745
+ command(command: string, options?: CommandRunOptions): Promise<CommandResult>;
1746
+ }
1747
+
1748
+ /**
1749
+ * Child - Resource namespace for child sandbox operations
1750
+ */
1751
+
1752
+ /**
1753
+ * Child resource namespace for managing child sandboxes
1754
+ *
1755
+ * Child sandboxes are isolated environments within the parent sandbox,
1756
+ * each with their own filesystem. Available only in multi-tenant mode.
1757
+ *
1758
+ * @example
1759
+ * ```typescript
1760
+ * // Create a new child sandbox
1761
+ * const child = await sandbox.child.create();
1762
+ * console.log(child.url); // https://sandbox-12345.sandbox.computesdk.com
1763
+ *
1764
+ * // List all children
1765
+ * const all = await sandbox.child.list();
1766
+ *
1767
+ * // Get a specific child
1768
+ * const info = await sandbox.child.retrieve('sandbox-12345');
1769
+ *
1770
+ * // Delete a child sandbox
1771
+ * await sandbox.child.destroy('sandbox-12345');
1772
+ *
1773
+ * // Delete child and its files
1774
+ * await sandbox.child.destroy('sandbox-12345', { deleteFiles: true });
1775
+ * ```
1776
+ */
1777
+ declare class Child {
1778
+ private createHandler;
1779
+ private listHandler;
1780
+ private retrieveHandler;
1781
+ private destroyHandler;
1782
+ constructor(handlers: {
1783
+ create: () => Promise<SandboxInfo>;
1784
+ list: () => Promise<SandboxesListResponse>;
1785
+ retrieve: (subdomain: string) => Promise<SandboxInfo>;
1786
+ destroy: (subdomain: string, deleteFiles: boolean) => Promise<void>;
1787
+ });
1788
+ /**
1789
+ * Create a new child sandbox
1790
+ * @returns Child sandbox info including URL and subdomain
1791
+ */
1792
+ create(): Promise<SandboxInfo>;
1793
+ /**
1794
+ * List all child sandboxes
1795
+ * @returns Array of child sandbox info
1796
+ */
1797
+ list(): Promise<SandboxInfo[]>;
1798
+ /**
1799
+ * Retrieve a specific child sandbox by subdomain
1800
+ * @param subdomain - The child subdomain (e.g., 'sandbox-12345')
1801
+ * @returns Child sandbox info
1802
+ */
1803
+ retrieve(subdomain: string): Promise<SandboxInfo>;
1804
+ /**
1805
+ * Destroy (delete) a child sandbox
1806
+ * @param subdomain - The child subdomain
1807
+ * @param options - Destroy options
1808
+ * @param options.deleteFiles - Whether to delete the child's files (default: false)
1809
+ */
1810
+ destroy(subdomain: string, options?: {
1811
+ deleteFiles?: boolean;
1812
+ }): Promise<void>;
1813
+ }
1814
+
1815
+ /**
1816
+ * Binary WebSocket Protocol Implementation
1817
+ *
1818
+ * Implements the ComputeSDK binary protocol for WebSocket communication.
1819
+ * Provides 50-90% size reduction compared to JSON protocol.
1820
+ *
1821
+ * Binary Message Format:
1822
+ * [1 byte: message type]
1823
+ * [2 bytes: channel length (uint16, big-endian)]
1824
+ * [N bytes: channel string (UTF-8)]
1825
+ * [2 bytes: msg type length (uint16, big-endian)]
1826
+ * [N bytes: msg type string (UTF-8)]
1827
+ * [4 bytes: data length (uint32, big-endian)]
1828
+ * [N bytes: data (key-value encoded for complex objects, raw bytes for binary data)]
1829
+ *
1830
+ * Key-Value Encoding Format:
1831
+ * [2 bytes: num_fields (uint16, big-endian)]
1832
+ * For each field:
1833
+ * [2 bytes: key_length (uint16, big-endian)]
1834
+ * [N bytes: key string (UTF-8)]
1835
+ * [1 byte: value_type (0x01=string, 0x02=number, 0x03=boolean, 0x04=bytes)]
1836
+ * [4 bytes: value_length (uint32, big-endian)]
1837
+ * [N bytes: value data]
1838
+ */
1839
+ declare enum MessageType {
1840
+ Subscribe = 1,
1841
+ Unsubscribe = 2,
1842
+ Data = 3,
1843
+ Error = 4,
1844
+ Connected = 5
1845
+ }
1846
+ /**
1847
+ * Encode a WebSocket message to binary format
1848
+ * @param message - The message object to encode
1849
+ * @returns ArrayBuffer containing the encoded binary message
1850
+ */
1851
+ declare function encodeBinaryMessage(message: any): ArrayBuffer;
1852
+ /**
1853
+ * Decode a binary WebSocket message
1854
+ * @param buffer - The binary data to decode (ArrayBuffer or Uint8Array)
1855
+ * @returns Decoded message object
1856
+ */
1857
+ declare function decodeBinaryMessage(buffer: ArrayBuffer | Uint8Array): any;
1858
+
1859
+ /**
1860
+ * Client Types
1861
+ *
1862
+ * Types specific to the gateway Sandbox client implementation.
1863
+ * Core universal types are imported from ../types/universal-sandbox
1864
+ */
1865
+
1866
+ /**
1867
+ * Sandbox status types (client-specific, more limited than universal)
1868
+ */
1869
+ type SandboxStatus = 'running' | 'stopped' | 'error';
1870
+ /**
1871
+ * Provider-agnostic sandbox info (alias for SandboxInfo for backward compatibility)
1872
+ */
1873
+ interface ProviderSandboxInfo {
1874
+ /** Unique identifier for the sandbox */
1875
+ id: string;
1876
+ /** Provider hosting the sandbox */
1877
+ provider: string;
1878
+ /** Runtime environment in the sandbox */
1879
+ runtime: Runtime;
1880
+ /** Current status of the sandbox */
1881
+ status: SandboxStatus;
1882
+ /** When the sandbox was created */
1883
+ createdAt: Date;
1884
+ /** Execution timeout in milliseconds */
1885
+ timeout: number;
1886
+ /** Additional provider-specific metadata */
1887
+ metadata?: Record<string, any>;
1888
+ }
1889
+ /**
1890
+ * Error thrown when a command exits with a non-zero status
1891
+ */
1892
+ declare class CommandExitError extends Error {
1893
+ result: {
1894
+ exitCode: number;
1895
+ stdout: string;
1896
+ stderr: string;
1897
+ error: boolean;
1898
+ };
1899
+ name: string;
1900
+ constructor(result: {
1901
+ exitCode: number;
1902
+ stdout: string;
1903
+ stderr: string;
1904
+ error: boolean;
1905
+ });
1906
+ }
1907
+ /**
1908
+ * Type guard to check if an error is a CommandExitError
1909
+ */
1910
+ declare function isCommandExitError(error: unknown): error is CommandExitError;
1911
+
1912
+ /**
1913
+ * ComputeSDK Client - Universal Sandbox Implementation
1914
+ *
1915
+ * This package provides a Sandbox for interacting with ComputeSDK sandboxes
1916
+ * through API endpoints at ${sandboxId}.sandbox.computesdk.com
1917
+ *
1918
+ * Works in browser, Node.js, and edge runtimes.
1919
+ * Browser: Uses native WebSocket and fetch
1920
+ * Node.js: Pass WebSocket implementation (e.g., 'ws' library)
1921
+ */
1922
+
1923
+ /**
1924
+ * WebSocket constructor type
1925
+ */
1926
+ type WebSocketConstructor = new (url: string) => WebSocket;
1927
+ /**
1928
+ * Configuration options for creating a Sandbox
1929
+ */
1930
+ interface SandboxConfig {
1931
+ /** API endpoint URL (e.g., https://sandbox-123.sandbox.computesdk.com). Optional in browser - can be auto-detected from URL query param or localStorage */
1932
+ sandboxUrl?: string;
1933
+ /** Sandbox ID */
1934
+ sandboxId: string;
1935
+ /** Provider name (e.g., 'e2b', 'gateway') */
1936
+ provider: string;
1937
+ /** Access token or session token for authentication. Optional in browser - can be auto-detected from URL query param or localStorage */
1938
+ token?: string;
1939
+ /** Optional headers to include with all requests */
1940
+ headers?: Record<string, string>;
1941
+ /** Request timeout in milliseconds (default: 30000) */
1942
+ timeout?: number;
1943
+ /** WebSocket implementation (optional, uses global WebSocket if not provided) */
1944
+ WebSocket?: WebSocketConstructor;
1945
+ /** WebSocket protocol: 'binary' (default, recommended) or 'json' (for debugging) */
1946
+ protocol?: 'json' | 'binary';
1947
+ /** Optional metadata associated with the sandbox */
1948
+ metadata?: Record<string, unknown>;
1949
+ }
1950
+ /**
1951
+ * Health check response
1952
+ */
1953
+ interface HealthResponse {
1954
+ status: string;
1955
+ timestamp: string;
1956
+ }
1957
+ /**
1958
+ * Server info response
1959
+ */
1960
+ interface InfoResponse {
1961
+ message: string;
1962
+ data: {
1963
+ auth_enabled: boolean;
1964
+ main_subdomain: string;
1965
+ sandbox_count: number;
1966
+ sandbox_url: string;
1967
+ version: string;
1968
+ };
1969
+ }
1970
+ /**
1971
+ * Session token response
1972
+ */
1973
+ interface SessionTokenResponse {
1974
+ id: string;
1975
+ token: string;
1976
+ description?: string;
1977
+ createdAt: string;
1978
+ expiresAt: string;
1979
+ expiresIn: number;
1980
+ }
1981
+ /**
1982
+ * Session token list response
1983
+ */
1984
+ interface SessionTokenListResponse {
1985
+ message: string;
1986
+ data: {
1987
+ tokens: Array<{
1988
+ id: string;
1989
+ description?: string;
1990
+ created_at: string;
1991
+ expires_at: string;
1992
+ last_used_at?: string;
1993
+ }>;
1994
+ };
1995
+ }
1996
+ /**
1997
+ * Magic link response
1998
+ */
1999
+ interface MagicLinkResponse {
2000
+ message: string;
2001
+ data: {
2002
+ magic_url: string;
2003
+ expires_at: string;
2004
+ redirect_url: string;
2005
+ };
2006
+ }
2007
+ /**
2008
+ * Authentication status response
2009
+ */
2010
+ interface AuthStatusResponse {
2011
+ message: string;
2012
+ data: {
2013
+ authenticated: boolean;
2014
+ token_type?: 'access_token' | 'session_token';
2015
+ expires_at?: string;
2016
+ };
2017
+ }
2018
+ /**
2019
+ * Authentication information response
2020
+ */
2021
+ interface AuthInfoResponse {
2022
+ message: string;
2023
+ data: {
2024
+ message: string;
2025
+ instructions: string;
2026
+ endpoints: {
2027
+ create_session_token: string;
2028
+ list_session_tokens: string;
2029
+ get_session_token: string;
2030
+ revoke_session_token: string;
2031
+ create_magic_link: string;
2032
+ auth_status: string;
2033
+ auth_info: string;
2034
+ };
2035
+ };
2036
+ }
2037
+ /**
2038
+ * File information
2039
+ */
2040
+ interface FileInfo {
2041
+ name: string;
2042
+ path: string;
2043
+ size: number;
2044
+ is_dir: boolean;
2045
+ modified_at: string;
2046
+ }
2047
+ /**
2048
+ * Files list response
2049
+ */
2050
+ interface FilesListResponse {
2051
+ message: string;
2052
+ data: {
2053
+ files: FileInfo[];
2054
+ path: string;
2055
+ };
2056
+ }
2057
+ /**
2058
+ * File response
2059
+ */
2060
+ interface FileResponse {
2061
+ message: string;
2062
+ data: {
2063
+ file: FileInfo;
2064
+ content?: string;
2065
+ };
2066
+ }
2067
+ /**
2068
+ * Command execution response
2069
+ */
2070
+ interface CommandExecutionResponse {
2071
+ message: string;
2072
+ data: {
2073
+ terminal_id?: string;
2074
+ cmd_id?: string;
2075
+ command: string;
2076
+ output?: string;
2077
+ stdout: string;
2078
+ stderr: string;
2079
+ exit_code?: number;
2080
+ duration_ms?: number;
2081
+ status?: 'running' | 'completed' | 'failed';
2082
+ pty?: boolean;
2083
+ };
2084
+ }
2085
+ /**
2086
+ * Command details response
2087
+ */
2088
+ interface CommandDetailsResponse {
2089
+ message: string;
2090
+ data: {
2091
+ cmd_id: string;
2092
+ command: string;
2093
+ status: 'running' | 'completed' | 'failed';
2094
+ stdout: string;
2095
+ stderr: string;
2096
+ started_at: string;
2097
+ finished_at?: string;
2098
+ duration_ms?: number;
2099
+ exit_code?: number;
2100
+ };
2101
+ }
2102
+ /**
2103
+ * Command list item
2104
+ */
2105
+ interface CommandListItem {
2106
+ cmd_id: string;
2107
+ command: string;
2108
+ status: 'running' | 'completed' | 'failed';
2109
+ started_at: string;
2110
+ finished_at?: string;
2111
+ duration_ms?: number;
2112
+ exit_code?: number;
2113
+ }
2114
+ /**
2115
+ * Commands list response
2116
+ */
2117
+ interface CommandsListResponse {
2118
+ message: string;
2119
+ data: {
2120
+ commands: CommandListItem[];
2121
+ count: number;
2122
+ };
2123
+ }
2124
+ /**
2125
+ * Code execution response (POST /run/code)
2126
+ */
2127
+ interface CodeExecutionResponse {
2128
+ data: {
2129
+ output: string;
2130
+ exit_code: number;
2131
+ language: string;
2132
+ };
2133
+ }
2134
+ /**
2135
+ * Run command response (POST /run/command)
2136
+ */
2137
+ interface RunCommandResponse {
2138
+ message: string;
2139
+ data: {
2140
+ terminal_id?: string;
2141
+ cmd_id?: string;
2142
+ command: string;
2143
+ stdout: string;
2144
+ stderr: string;
2145
+ exit_code?: number;
2146
+ duration_ms?: number;
2147
+ status?: 'running' | 'completed' | 'failed';
2148
+ };
2149
+ }
2150
+ /**
2151
+ * File watcher information
2152
+ */
2153
+ interface WatcherInfo {
2154
+ id: string;
2155
+ path: string;
2156
+ includeContent: boolean;
2157
+ ignored: string[];
2158
+ status: 'active' | 'stopped';
2159
+ channel: string;
2160
+ encoding?: 'raw' | 'base64';
2161
+ }
2162
+ /**
2163
+ * File watcher response
2164
+ */
2165
+ interface WatcherResponse {
2166
+ message: string;
2167
+ data: WatcherInfo & {
2168
+ ws_url: string;
2169
+ };
2170
+ }
2171
+ /**
2172
+ * File watchers list response
2173
+ */
2174
+ interface WatchersListResponse {
2175
+ message: string;
2176
+ data: {
2177
+ watchers: WatcherInfo[];
2178
+ };
2179
+ }
2180
+ /**
2181
+ * Signal service response
2182
+ */
2183
+ interface SignalServiceResponse {
2184
+ message: string;
2185
+ data: {
2186
+ status: 'active' | 'stopped';
2187
+ channel: string;
2188
+ ws_url: string;
2189
+ };
2190
+ }
2191
+ /**
2192
+ * Port signal response
2193
+ */
2194
+ interface PortSignalResponse {
2195
+ message: string;
2196
+ data: {
2197
+ port: number;
2198
+ type: 'open' | 'close';
2199
+ url: string;
2200
+ };
2201
+ }
2202
+ /**
2203
+ * Generic signal response
2204
+ */
2205
+ interface GenericSignalResponse {
2206
+ message: string;
2207
+ data: {
2208
+ message: string;
2209
+ };
2210
+ }
2211
+ /**
2212
+ * Sandbox information
2213
+ */
2214
+ interface SandboxInfo {
2215
+ subdomain: string;
2216
+ directory: string;
2217
+ is_main: boolean;
2218
+ created_at: string;
2219
+ url: string;
2220
+ }
2221
+ /**
2222
+ * Sandboxes list response
2223
+ */
2224
+ interface SandboxesListResponse {
2225
+ sandboxes: SandboxInfo[];
2226
+ }
2227
+ /**
2228
+ * Terminal response
2229
+ */
2230
+ interface TerminalResponse {
2231
+ message: string;
2232
+ data: {
2233
+ id: string;
2234
+ pty: boolean;
2235
+ status: 'running' | 'stopped' | 'ready' | 'active';
2236
+ channel?: string;
2237
+ ws_url?: string;
2238
+ encoding?: 'raw' | 'base64';
2239
+ };
2240
+ }
2241
+ /**
2242
+ * Terminal response
2243
+ */
2244
+ interface TerminalResponse {
2245
+ message: string;
2246
+ data: {
2247
+ id: string;
2248
+ pty: boolean;
2249
+ status: 'running' | 'stopped' | 'ready' | 'active';
2250
+ channel?: string;
2251
+ ws_url?: string;
2252
+ encoding?: 'raw' | 'base64';
2253
+ };
2254
+ }
2255
+ /**
2256
+ * Server status types
2257
+ */
2258
+ type ServerStatus = 'starting' | 'running' | 'ready' | 'failed' | 'stopped';
2259
+ /**
2260
+ * Server information
2261
+ */
2262
+ interface ServerInfo {
2263
+ slug: string;
2264
+ command: string;
2265
+ path: string;
2266
+ original_path?: string;
2267
+ env_file?: string;
2268
+ port?: number;
2269
+ url?: string;
2270
+ status: ServerStatus;
2271
+ pid?: number;
2272
+ terminal_id?: string;
2273
+ created_at: string;
2274
+ updated_at: string;
2275
+ }
2276
+ /**
2277
+ * Servers list response
2278
+ */
2279
+ interface ServersListResponse {
2280
+ status: string;
2281
+ message: string;
2282
+ data: {
2283
+ servers: ServerInfo[];
2284
+ };
2285
+ }
2286
+ /**
2287
+ * Server response
2288
+ */
2289
+ interface ServerResponse {
2290
+ status: string;
2291
+ message: string;
2292
+ data: {
2293
+ server: ServerInfo;
2294
+ };
2295
+ }
2296
+ /**
2297
+ * Server stop response
2298
+ */
2299
+ interface ServerStopResponse {
2300
+ status: string;
2301
+ message: string;
2302
+ data: {
2303
+ slug: string;
2304
+ };
2305
+ }
2306
+ /**
2307
+ * Server status update response
2308
+ */
2309
+ interface ServerStatusUpdateResponse {
2310
+ status: string;
2311
+ message: string;
2312
+ data: {
2313
+ slug: string;
2314
+ status: ServerStatus;
2315
+ };
2316
+ }
2317
+ /**
2318
+ * Environment variables response
2319
+ */
2320
+ interface EnvGetResponse {
2321
+ status: string;
2322
+ message: string;
2323
+ data: {
2324
+ file: string;
2325
+ variables: Record<string, string>;
2326
+ };
2327
+ }
2328
+ /**
2329
+ * Environment set response
2330
+ */
2331
+ interface EnvSetResponse {
2332
+ status: string;
2333
+ message: string;
2334
+ data: {
2335
+ file: string;
2336
+ keys: string[];
2337
+ };
2338
+ }
2339
+ /**
2340
+ * Environment delete response
2341
+ */
2342
+ interface EnvDeleteResponse {
2343
+ status: string;
2344
+ message: string;
2345
+ data: {
2346
+ file: string;
2347
+ keys: string[];
2348
+ };
2349
+ }
2350
+ /**
2351
+ * Batch file operation type
2352
+ */
2353
+ type BatchFileOperation = 'write' | 'delete';
2354
+ /**
2355
+ * Batch file operation result
2356
+ */
2357
+ interface BatchWriteResult {
2358
+ path: string;
2359
+ success: boolean;
2360
+ error?: string;
2361
+ file?: FileInfo;
2362
+ }
2363
+ /**
2364
+ * Batch file operation response
2365
+ */
2366
+ interface BatchWriteResponse {
2367
+ message: string;
2368
+ data: {
2369
+ results: BatchWriteResult[];
2370
+ };
2371
+ }
2372
+ /**
2373
+ * Sandbox - Full-featured gateway sandbox implementation
2374
+ *
2375
+ * Provides complete feature set including:
2376
+ * - Interactive terminals (PTY and exec modes)
2377
+ * - Managed servers
2378
+ * - File watchers with real-time events
2379
+ * - Authentication (session tokens, magic links)
2380
+ * - Environment management
2381
+ * - Signal service for port/error events
2382
+ * - Child sandbox creation
2383
+ *
2384
+ * This is the most feature-rich implementation available.
2385
+ *
2386
+ * @example
2387
+ * ```typescript
2388
+ * import { Sandbox } from 'computesdk'
2389
+ *
2390
+ * // Pattern 1: Admin operations (requires access token)
2391
+ * const sandbox = new Sandbox({
2392
+ * sandboxUrl: 'https://sandbox-123.sandbox.computesdk.com',
2393
+ * token: accessToken, // From edge service
2394
+ * });
2395
+ *
2396
+ * // Create session token for delegated operations
2397
+ * const sessionToken = await sandbox.createSessionToken({
2398
+ * description: 'My Application',
2399
+ * expiresIn: 604800, // 7 days
2400
+ * });
2401
+ *
2402
+ * // Pattern 2: Delegated operations (binary protocol by default)
2403
+ * const sandbox2 = new Sandbox({
2404
+ * sandboxUrl: 'https://sandbox-123.sandbox.computesdk.com',
2405
+ * token: sessionToken.data.token,
2406
+ * // protocol: 'binary' is the default (50-90% size reduction)
2407
+ * });
2408
+ *
2409
+ * // Execute a one-off command
2410
+ * const result = await sandbox.execute({ command: 'ls -la' });
2411
+ * console.log(result.data.stdout);
2412
+ *
2413
+ * // Run code
2414
+ * const codeResult = await sandbox.runCode('console.log("Hello!")', 'node');
2415
+ *
2416
+ * // Work with files
2417
+ * const files = await sandbox.listFiles('/home/project');
2418
+ * await sandbox.writeFile('/home/project/test.txt', 'Hello, World!');
2419
+ * const content = await sandbox.readFile('/home/project/test.txt');
2420
+ *
2421
+ * // Create a PTY terminal with real-time output (interactive shell)
2422
+ * const terminal = await sandbox.createTerminal({ pty: true });
2423
+ * terminal.on('output', (data) => console.log(data));
2424
+ * terminal.write('ls -la\n');
2425
+ * await terminal.destroy();
2426
+ *
2427
+ * // Create an exec terminal for command tracking
2428
+ * const execTerminal = await sandbox.createTerminal({ pty: false });
2429
+ * const result = await execTerminal.execute('npm install', { background: true });
2430
+ * const cmd = await sandbox.getCommand(execTerminal.getId(), result.data.cmd_id);
2431
+ * console.log(cmd.data.status); // "running" | "completed" | "failed"
2432
+ * await execTerminal.destroy();
2433
+ *
2434
+ * // Watch for file changes
2435
+ * const watcher = await sandbox.createWatcher('/home/project', {
2436
+ * ignored: ['node_modules', '.git']
2437
+ * });
2438
+ * watcher.on('change', (event) => {
2439
+ * console.log(`${event.event}: ${event.path}`);
2440
+ * });
2441
+ * await watcher.destroy();
2442
+ *
2443
+ * // Monitor system signals
2444
+ * const signals = await sandbox.startSignals();
2445
+ * signals.on('port', (event) => {
2446
+ * console.log(`Port ${event.port} opened: ${event.url}`);
2447
+ * });
2448
+ * await signals.stop();
2449
+ *
2450
+ * // Clean up
2451
+ * await sandbox.disconnect();
2452
+ * ```
2453
+ */
2454
+ declare class Sandbox {
2455
+ readonly sandboxId: string;
2456
+ readonly provider: string;
2457
+ readonly filesystem: SandboxFileSystem;
2458
+ readonly terminal: Terminal;
2459
+ readonly run: Run;
2460
+ readonly server: Server;
2461
+ readonly watcher: Watcher;
2462
+ readonly sessionToken: SessionToken;
2463
+ readonly magicLink: MagicLink;
2464
+ readonly signal: Signal;
2465
+ readonly file: File;
2466
+ readonly env: Env;
2467
+ readonly auth: Auth;
2468
+ readonly child: Child;
2469
+ private config;
2470
+ private _token;
2471
+ private _ws;
2472
+ private WebSocketImpl;
2473
+ constructor(config: SandboxConfig);
2474
+ /**
2475
+ * Get or create internal WebSocket manager
2476
+ */
2477
+ private ensureWebSocket;
2478
+ private request;
2479
+ /**
2480
+ * Check service health
2481
+ */
2482
+ health(): Promise<HealthResponse>;
2483
+ /**
2484
+ * Create a session token (requires access token)
2485
+ *
2486
+ * Session tokens are delegated credentials that can authenticate API requests
2487
+ * without exposing your access token. Only access tokens can create session tokens.
2488
+ *
2489
+ * @param options - Token configuration
2490
+ * @throws {Error} 403 Forbidden if called with a session token
2491
+ */
2492
+ createSessionToken(options?: {
2493
+ description?: string;
2494
+ expiresIn?: number;
2495
+ }): Promise<SessionTokenResponse>;
2496
+ /**
2497
+ * List all session tokens (requires access token)
2498
+ *
2499
+ * @throws {Error} 403 Forbidden if called with a session token
2500
+ */
2501
+ listSessionTokens(): Promise<SessionTokenListResponse>;
2502
+ /**
2503
+ * Get details of a specific session token (requires access token)
2504
+ *
2505
+ * @param tokenId - The token ID
2506
+ * @throws {Error} 403 Forbidden if called with a session token
2507
+ */
2508
+ getSessionToken(tokenId: string): Promise<SessionTokenResponse>;
2509
+ /**
2510
+ * Revoke a session token (requires access token)
2511
+ *
2512
+ * @param tokenId - The token ID to revoke
2513
+ * @throws {Error} 403 Forbidden if called with a session token
2514
+ */
2515
+ revokeSessionToken(tokenId: string): Promise<void>;
2516
+ /**
2517
+ * Generate a magic link for browser authentication (requires access token)
2518
+ *
2519
+ * Magic links are one-time URLs that automatically create a session token
2520
+ * and set it as a cookie in the user's browser. This provides an easy way
2521
+ * to authenticate users in browser-based applications.
2522
+ *
2523
+ * The generated link:
2524
+ * - Expires after 5 minutes or first use (whichever comes first)
2525
+ * - Automatically creates a new session token (7 day expiry)
2526
+ * - Sets the session token as an HttpOnly cookie
2527
+ * - Redirects to the specified URL
2528
+ *
2529
+ * @param options - Magic link configuration
2530
+ * @throws {Error} 403 Forbidden if called with a session token
2531
+ */
2532
+ createMagicLink(options?: {
2533
+ redirectUrl?: string;
2534
+ }): Promise<MagicLinkResponse>;
2535
+ /**
2536
+ * Check authentication status
2537
+ * Does not require authentication
2538
+ */
2539
+ getAuthStatus(): Promise<AuthStatusResponse>;
2540
+ /**
2541
+ * Get authentication information and usage instructions
2542
+ * Does not require authentication
2543
+ */
2544
+ getAuthInfo(): Promise<AuthInfoResponse>;
2545
+ /**
2546
+ * Set authentication token manually
2547
+ * @param token - Access token or session token
2548
+ */
2549
+ setToken(token: string): void;
2550
+ /**
2551
+ * Get current authentication token
2552
+ */
2553
+ getToken(): string | null;
2554
+ /**
2555
+ * Get current sandbox URL
2556
+ */
2557
+ getSandboxUrl(): string;
2558
+ /**
2559
+ * Execute a one-off command without creating a persistent terminal
2560
+ *
2561
+ * @example
2562
+ * ```typescript
2563
+ * // Synchronous execution (waits for completion)
2564
+ * const result = await sandbox.execute({ command: 'npm test' });
2565
+ * console.log(result.data.exit_code);
2566
+ *
2567
+ * // Background execution (returns immediately)
2568
+ * const result = await sandbox.execute({
2569
+ * command: 'npm install',
2570
+ * background: true
2571
+ * });
2572
+ * // Use result.data.terminal_id and result.data.cmd_id to track
2573
+ * const cmd = await sandbox.getCommand(result.data.terminal_id!, result.data.cmd_id!);
2574
+ * ```
2575
+ */
2576
+ execute(options: {
2577
+ command: string;
2578
+ shell?: string;
2579
+ background?: boolean;
2580
+ }): Promise<CommandExecutionResponse>;
2581
+ /**
2582
+ * Execute code with automatic language detection (POST /run/code)
2583
+ *
2584
+ * @param code - The code to execute
2585
+ * @param language - Programming language (optional - auto-detects if not specified)
2586
+ * @returns Code execution result with output, exit code, and detected language
2587
+ *
2588
+ * @example
2589
+ * ```typescript
2590
+ * // Auto-detect language
2591
+ * const result = await sandbox.runCodeRequest('print("Hello")');
2592
+ * console.log(result.data.output); // "Hello\n"
2593
+ * console.log(result.data.language); // "python"
2594
+ *
2595
+ * // Explicit language
2596
+ * const result = await sandbox.runCodeRequest('console.log("Hi")', 'node');
2597
+ * ```
2598
+ */
2599
+ runCodeRequest(code: string, language?: string): Promise<CodeExecutionResponse>;
2600
+ /**
2601
+ * Execute a shell command (POST /run/command)
2602
+ *
2603
+ * @param options - Command options
2604
+ * @param options.command - The command to execute
2605
+ * @param options.shell - Shell to use (optional)
2606
+ * @param options.background - Run in background (optional)
2607
+ * @returns Command execution result
2608
+ *
2609
+ * @example
2610
+ * ```typescript
2611
+ * const result = await sandbox.runCommandRequest({ command: 'ls -la' });
2612
+ * console.log(result.data.stdout);
2613
+ * ```
2614
+ */
2615
+ runCommandRequest(options: {
2616
+ command: string;
2617
+ shell?: string;
2618
+ background?: boolean;
2619
+ }): Promise<RunCommandResponse>;
2620
+ /**
2621
+ * List files at the specified path
2622
+ */
2623
+ listFiles(path?: string): Promise<FilesListResponse>;
2624
+ /**
2625
+ * Create a new file with optional content
2626
+ */
2627
+ createFile(path: string, content?: string): Promise<FileResponse>;
2628
+ /**
2629
+ * Get file metadata (without content)
2630
+ */
2631
+ getFile(path: string): Promise<FileResponse>;
2632
+ /**
2633
+ * Read file content
2634
+ */
2635
+ readFile(path: string): Promise<string>;
2636
+ /**
2637
+ * Write file content (creates or updates)
2638
+ */
2639
+ writeFile(path: string, content: string): Promise<FileResponse>;
2640
+ /**
2641
+ * Delete a file or directory
2642
+ */
2643
+ deleteFile(path: string): Promise<void>;
2644
+ /**
2645
+ * Check if a file exists (HEAD request)
2646
+ * @returns true if file exists, false otherwise
2647
+ */
2648
+ checkFileExists(path: string): Promise<boolean>;
2649
+ /**
2650
+ * Batch file operations (write or delete multiple files)
2651
+ *
2652
+ * Features:
2653
+ * - Deduplication: Last operation wins per path
2654
+ * - File locking: Prevents race conditions
2655
+ * - Deterministic ordering: Alphabetical path sorting
2656
+ * - Partial failure handling: Returns 207 Multi-Status with per-file results
2657
+ *
2658
+ * @param files - Array of file operations
2659
+ * @returns Results for each file operation
2660
+ *
2661
+ * @example
2662
+ * ```typescript
2663
+ * // Write multiple files
2664
+ * const results = await sandbox.batchWriteFiles([
2665
+ * { path: '/app/file1.txt', operation: 'write', content: 'Hello' },
2666
+ * { path: '/app/file2.txt', operation: 'write', content: 'World' },
2667
+ * ]);
2668
+ *
2669
+ * // Mixed operations (write and delete)
2670
+ * const results = await sandbox.batchWriteFiles([
2671
+ * { path: '/app/new.txt', operation: 'write', content: 'New file' },
2672
+ * { path: '/app/old.txt', operation: 'delete' },
2673
+ * ]);
2674
+ * ```
2675
+ */
2676
+ batchWriteFiles(files: Array<{
2677
+ path: string;
2678
+ operation: 'write' | 'delete';
2679
+ content?: string;
2680
+ }>): Promise<BatchWriteResponse>;
2681
+ /**
2682
+ * Create a new persistent terminal session
2683
+ *
2684
+ * Terminal Modes:
2685
+ * - **PTY mode** (pty: true): Interactive shell with real-time WebSocket streaming
2686
+ * - Use for: Interactive shells, vim/nano, real-time output
2687
+ * - Methods: write(), resize(), on('output')
2688
+ *
2689
+ * - **Exec mode** (pty: false, default): Command tracking with HTTP polling
2690
+ * - Use for: CI/CD, automation, command tracking, exit codes
2691
+ * - Methods: execute(), getCommand(), listCommands(), waitForCommand()
2692
+ *
2693
+ * @example
2694
+ * ```typescript
2695
+ * // PTY mode - Interactive shell
2696
+ * const pty = await sandbox.createTerminal({ pty: true, shell: '/bin/bash' });
2697
+ * pty.on('output', (data) => console.log(data));
2698
+ * pty.write('npm install\n');
2699
+ *
2700
+ * // Exec mode - Command tracking
2701
+ * const exec = await sandbox.createTerminal({ pty: false });
2702
+ * const result = await exec.execute('npm test', { background: true });
2703
+ * const cmd = await sandbox.waitForCommand(exec.getId(), result.data.cmd_id);
2704
+ * console.log(cmd.data.exit_code);
2705
+ *
2706
+ * // Backward compatible - creates PTY terminal
2707
+ * const terminal = await sandbox.createTerminal('/bin/bash');
2708
+ * ```
2709
+ *
2710
+ * @param options - Terminal creation options
2711
+ * @param options.shell - Shell to use (e.g., '/bin/bash', '/bin/sh') - PTY mode only
2712
+ * @param options.encoding - Encoding for terminal I/O: 'raw' (default) or 'base64' (binary-safe)
2713
+ * @param options.pty - Terminal mode: true = PTY (interactive shell), false = exec (command tracking, default)
2714
+ * @returns Terminal instance with event handling
2715
+ */
2716
+ createTerminal(shellOrOptions?: string | {
2717
+ shell?: string;
2718
+ encoding?: 'raw' | 'base64';
2719
+ pty?: boolean;
2720
+ }, encoding?: 'raw' | 'base64'): Promise<TerminalInstance>;
2721
+ /**
2722
+ * List all active terminals (fetches from API)
2723
+ */
2724
+ listTerminals(): Promise<TerminalResponse[]>;
2725
+ /**
2726
+ * Get terminal by ID
2727
+ */
2728
+ getTerminal(id: string): Promise<TerminalResponse>;
2729
+ /**
2730
+ * List all commands executed in a terminal (exec mode only)
2731
+ * @param terminalId - The terminal ID
2732
+ * @returns List of all commands with their status
2733
+ * @throws {Error} If terminal is in PTY mode (command tracking not available)
2734
+ */
2735
+ listCommands(terminalId: string): Promise<CommandsListResponse>;
2736
+ /**
2737
+ * Get details of a specific command execution (exec mode only)
2738
+ * @param terminalId - The terminal ID
2739
+ * @param cmdId - The command ID
2740
+ * @returns Command execution details including stdout, stderr, and exit code
2741
+ * @throws {Error} If terminal is in PTY mode or command not found
2742
+ */
2743
+ getCommand(terminalId: string, cmdId: string): Promise<CommandDetailsResponse>;
2744
+ /**
2745
+ * Wait for a command to complete (HTTP long-polling, exec mode only)
2746
+ * @param terminalId - The terminal ID
2747
+ * @param cmdId - The command ID
2748
+ * @param timeout - Optional timeout in seconds (0 = no timeout)
2749
+ * @returns Command execution details when completed
2750
+ * @throws {Error} If terminal is in PTY mode, command not found, or timeout occurs
2751
+ */
2752
+ waitForCommand(terminalId: string, cmdId: string, timeout?: number): Promise<CommandDetailsResponse>;
2753
+ /**
2754
+ * Create a new file watcher with WebSocket integration
2755
+ * @param path - Path to watch
2756
+ * @param options - Watcher options
2757
+ * @param options.includeContent - Include file content in change events
2758
+ * @param options.ignored - Patterns to ignore
2759
+ * @param options.encoding - Encoding for file content: 'raw' (default) or 'base64' (binary-safe)
2760
+ * @returns FileWatcher instance with event handling
2761
+ */
2762
+ createWatcher(path: string, options?: {
2763
+ includeContent?: boolean;
2764
+ ignored?: string[];
2765
+ encoding?: 'raw' | 'base64';
2766
+ }): Promise<FileWatcher>;
2767
+ /**
2768
+ * List all active file watchers (fetches from API)
2769
+ */
2770
+ listWatchers(): Promise<WatchersListResponse>;
2771
+ /**
2772
+ * Get file watcher by ID
2773
+ */
2774
+ getWatcher(id: string): Promise<WatcherResponse>;
2775
+ /**
2776
+ * Start the signal service with WebSocket integration
2777
+ * @returns SignalService instance with event handling
2778
+ */
2779
+ startSignals(): Promise<SignalService>;
2780
+ /**
2781
+ * Get the signal service status (fetches from API)
2782
+ */
2783
+ getSignalStatus(): Promise<SignalServiceResponse>;
2784
+ /**
2785
+ * Emit a port signal
2786
+ */
2787
+ emitPortSignal(port: number, type: 'open' | 'close', url: string): Promise<PortSignalResponse>;
2788
+ /**
2789
+ * Emit a port signal (alternative endpoint using path parameters)
2790
+ */
2791
+ emitPortSignalAlt(port: number, type: 'open' | 'close'): Promise<PortSignalResponse>;
2792
+ /**
2793
+ * Emit an error signal
2794
+ */
2795
+ emitErrorSignal(message: string): Promise<GenericSignalResponse>;
2796
+ /**
2797
+ * Emit a server ready signal
2798
+ */
2799
+ emitServerReadySignal(port: number, url: string): Promise<PortSignalResponse>;
2800
+ /**
2801
+ * Get environment variables from a .env file
2802
+ * @param file - Path to the .env file (relative to sandbox root)
2803
+ */
2804
+ getEnv(file: string): Promise<EnvGetResponse>;
2805
+ /**
2806
+ * Set (merge) environment variables in a .env file
2807
+ * @param file - Path to the .env file (relative to sandbox root)
2808
+ * @param variables - Key-value pairs to set
2809
+ */
2810
+ setEnv(file: string, variables: Record<string, string>): Promise<EnvSetResponse>;
2811
+ /**
2812
+ * Delete environment variables from a .env file
2813
+ * @param file - Path to the .env file (relative to sandbox root)
2814
+ * @param keys - Keys to delete
2815
+ */
2816
+ deleteEnv(file: string, keys: string[]): Promise<EnvDeleteResponse>;
2817
+ /**
2818
+ * Check if an environment file exists (HEAD request)
2819
+ * @param file - Path to the .env file (relative to sandbox root)
2820
+ * @returns true if file exists, false otherwise
2821
+ */
2822
+ checkEnvFile(file: string): Promise<boolean>;
2823
+ /**
2824
+ * List all managed servers
2825
+ */
2826
+ listServers(): Promise<ServersListResponse>;
2827
+ /**
2828
+ * Start a new managed server
2829
+ * @param options - Server configuration
2830
+ */
2831
+ startServer(options: {
2832
+ slug: string;
2833
+ command: string;
2834
+ path?: string;
2835
+ env_file?: string;
2836
+ }): Promise<ServerResponse>;
2837
+ /**
2838
+ * Get information about a specific server
2839
+ * @param slug - Server slug
2840
+ */
2841
+ getServer(slug: string): Promise<ServerResponse>;
2842
+ /**
2843
+ * Stop a managed server
2844
+ * @param slug - Server slug
2845
+ */
2846
+ stopServer(slug: string): Promise<ServerStopResponse>;
2847
+ /**
2848
+ * Restart a managed server
2849
+ * @param slug - Server slug
2850
+ */
2851
+ restartServer(slug: string): Promise<ServerResponse>;
2852
+ /**
2853
+ * Update server status (internal use)
2854
+ * @param slug - Server slug
2855
+ * @param status - New server status
2856
+ */
2857
+ updateServerStatus(slug: string, status: ServerStatus): Promise<ServerStatusUpdateResponse>;
2858
+ /**
2859
+ * Create a new sandbox environment
2860
+ */
2861
+ createSandbox(): Promise<SandboxInfo>;
2862
+ /**
2863
+ * List all sandboxes
2864
+ */
2865
+ listSandboxes(): Promise<SandboxesListResponse>;
2866
+ /**
2867
+ * Get sandbox details
2868
+ */
2869
+ getSandbox(subdomain: string): Promise<SandboxInfo>;
2870
+ /**
2871
+ * Delete a sandbox
2872
+ */
2873
+ deleteSandbox(subdomain: string, deleteFiles?: boolean): Promise<void>;
2874
+ /**
2875
+ * Get WebSocket URL for real-time communication
2876
+ * @private
2877
+ */
2878
+ private getWebSocketUrl;
2879
+ /**
2880
+ * Execute code in the sandbox (convenience method)
2881
+ *
2882
+ * Delegates to sandbox.run.code() - prefer using that directly for new code.
2883
+ *
2884
+ * @param code - The code to execute
2885
+ * @param language - Programming language (auto-detected if not specified)
2886
+ * @returns Code execution result
2887
+ */
2888
+ runCode(code: string, language?: 'node' | 'python'): Promise<{
2889
+ output: string;
2890
+ exitCode: number;
2891
+ language: string;
2892
+ }>;
2893
+ /**
2894
+ * Execute shell command in the sandbox (convenience method)
2895
+ *
2896
+ * Delegates to sandbox.run.command() - prefer using that directly for new code.
2897
+ *
2898
+ * @param command - The command to execute (string or array form)
2899
+ * @param argsOrOptions - Arguments array or options object
2900
+ * @param maybeOptions - Options when using (command, args, options) form
2901
+ * @returns Command execution result
2902
+ */
2903
+ runCommand(commandOrArray: string | [string, ...string[]], argsOrOptions?: string[] | {
2904
+ background?: boolean;
2905
+ cwd?: string;
2906
+ }, maybeOptions?: {
2907
+ background?: boolean;
2908
+ cwd?: string;
2909
+ }): Promise<{
2910
+ stdout: string;
2911
+ stderr: string;
2912
+ exitCode: number;
2913
+ durationMs: number;
2914
+ }>;
2915
+ /**
2916
+ * Get server information
2917
+ * Returns details about the server including auth status, main subdomain, sandbox count, and version
2918
+ */
2919
+ getServerInfo(): Promise<InfoResponse>;
2920
+ /**
2921
+ * Get sandbox information
2922
+ */
2923
+ getInfo(): Promise<{
2924
+ id: string;
2925
+ provider: string;
2926
+ runtime: 'node' | 'python';
2927
+ status: 'running' | 'stopped' | 'error';
2928
+ createdAt: Date;
2929
+ timeout: number;
2930
+ metadata?: Record<string, any>;
2931
+ }>;
2932
+ /**
2933
+ * Get URL for accessing sandbox on a specific port (Sandbox interface method)
2934
+ */
2935
+ getUrl(options: {
2936
+ port: number;
2937
+ protocol?: string;
2938
+ }): Promise<string>;
60
2939
  /**
61
- * Create an interactive terminal (PTY or exec mode)
62
- * @optional Available when using gateway provider
2940
+ * Get provider instance
2941
+ * Note: Not available when using Sandbox directly - only available through gateway provider
63
2942
  */
64
- createTerminal?(options?: {
65
- shell?: string;
66
- pty?: boolean;
67
- encoding?: 'utf8' | 'binary';
68
- }): Promise<any>;
2943
+ getProvider(): never;
69
2944
  /**
70
- * Create a file system watcher
71
- * @optional Available when using gateway provider
2945
+ * Get native provider instance
2946
+ * Returns the Sandbox itself since this IS the sandbox implementation
72
2947
  */
73
- createWatcher?(path: string, options?: {
74
- recursive?: boolean;
75
- includeContent?: boolean;
76
- }): Promise<any>;
2948
+ getInstance(): this;
77
2949
  /**
78
- * Send a signal to a process
79
- * @optional Available when using gateway provider
2950
+ * Destroy the sandbox (Sandbox interface method)
80
2951
  */
81
- sendSignal?(pid: number, signal: string): Promise<void>;
82
- }
83
- /**
84
- * Extract the sandbox type from a provider using generic inference
85
- */
86
- type ExtractProviderSandboxType<TProvider> = TProvider extends Provider<infer TSandbox, any, any> ? TSandbox : any;
87
- /**
88
- * Typed provider sandbox interface that preserves the provider's native instance type
89
- */
90
- interface TypedProviderSandbox<TProvider extends Provider<any, any, any>> extends Omit<ProviderSandbox<ExtractProviderSandboxType<TProvider>>, 'getProvider'> {
91
- /** Get the provider instance that created this sandbox with proper typing */
92
- getProvider(): TProvider;
93
- /** Get the native provider sandbox instance with proper typing */
94
- getInstance(): ExtractProviderSandboxType<TProvider>;
2952
+ destroy(): Promise<void>;
2953
+ /**
2954
+ * Disconnect WebSocket
2955
+ *
2956
+ * Note: This only disconnects the WebSocket. Terminals, watchers, and signals
2957
+ * will continue running on the server until explicitly destroyed via their
2958
+ * respective destroy() methods or the DELETE endpoints.
2959
+ */
2960
+ disconnect(): Promise<void>;
95
2961
  }
96
2962
 
97
2963
  /**
@@ -164,342 +3030,173 @@ declare function isProviderAuthComplete(provider: ProviderName): boolean;
164
3030
  declare function getMissingEnvVars(provider: ProviderName): string[];
165
3031
 
166
3032
  /**
167
- * Common options for creating snapshots
168
- */
169
- interface CreateSnapshotOptions {
170
- /** Optional name for the snapshot */
171
- name?: string;
172
- /** Optional metadata for the snapshot */
173
- metadata?: Record<string, string>;
174
- }
175
- /**
176
- * Common options for listing snapshots
3033
+ * Compute API - Gateway HTTP Implementation
3034
+ *
3035
+ * Provides the unified compute.* API using direct HTTP calls to the gateway.
3036
+ * The `compute` export works as both a singleton and a callable function:
3037
+ *
3038
+ * - Singleton: `compute.sandbox.create()` (auto-detects from env vars)
3039
+ * - Callable: `compute({ provider: 'e2b', ... }).sandbox.create()` (explicit config)
177
3040
  */
178
- interface ListSnapshotsOptions {
179
- /** Filter by sandbox ID */
180
- sandboxId?: string;
181
- /** Limit the number of results */
182
- limit?: number;
183
- }
3041
+
184
3042
  /**
185
- * Common options for creating templates/blueprints
3043
+ * Explicit compute configuration for callable mode
186
3044
  */
187
- interface CreateTemplateOptions {
188
- /** Name of the template */
189
- name: string;
190
- /** Optional description */
191
- description?: string;
192
- /** Optional metadata for the template */
193
- metadata?: Record<string, string>;
3045
+ interface ExplicitComputeConfig {
3046
+ /** Provider name to use */
3047
+ provider: ProviderName;
3048
+ /** ComputeSDK API key (required for gateway mode) */
3049
+ apiKey: string;
3050
+ /** Optional gateway URL override */
3051
+ gatewayUrl?: string;
3052
+ /** Provider-specific configurations */
3053
+ e2b?: {
3054
+ apiKey?: string;
3055
+ projectId?: string;
3056
+ templateId?: string;
3057
+ };
3058
+ modal?: {
3059
+ tokenId?: string;
3060
+ tokenSecret?: string;
3061
+ };
3062
+ railway?: {
3063
+ apiToken?: string;
3064
+ projectId?: string;
3065
+ environmentId?: string;
3066
+ };
3067
+ daytona?: {
3068
+ apiKey?: string;
3069
+ };
3070
+ vercel?: {
3071
+ oidcToken?: string;
3072
+ token?: string;
3073
+ teamId?: string;
3074
+ projectId?: string;
3075
+ };
3076
+ runloop?: {
3077
+ apiKey?: string;
3078
+ };
3079
+ cloudflare?: {
3080
+ apiToken?: string;
3081
+ accountId?: string;
3082
+ };
3083
+ codesandbox?: {
3084
+ apiKey?: string;
3085
+ };
3086
+ blaxel?: {
3087
+ apiKey?: string;
3088
+ workspace?: string;
3089
+ };
194
3090
  }
195
3091
  /**
196
- * Common options for listing templates
3092
+ * Options for creating a sandbox via the gateway
3093
+ *
3094
+ * Note: Runtime is determined by the provider, not specified at creation time.
3095
+ * Use sandbox.runCode(code, runtime) to specify which runtime to use for execution.
197
3096
  */
198
- interface ListTemplatesOptions {
199
- /** Limit the number of results */
200
- limit?: number;
3097
+ interface CreateSandboxOptions {
3098
+ timeout?: number;
3099
+ templateId?: string;
3100
+ metadata?: Record<string, any>;
3101
+ envs?: Record<string, string>;
3102
+ name?: string;
3103
+ namespace?: string;
201
3104
  }
202
3105
  /**
203
3106
  * Options for finding or creating a named sandbox
204
3107
  */
205
3108
  interface FindOrCreateSandboxOptions extends CreateSandboxOptions {
206
- /** User-provided stable identifier (e.g., "my-app", "frontend") */
207
3109
  name: string;
208
- /** Isolation scope (e.g., "user-123", "org-456"). Defaults to "default" */
209
3110
  namespace?: string;
210
3111
  }
211
3112
  /**
212
- * Options for finding a named sandbox (without creating)
3113
+ * Options for finding a named sandbox
213
3114
  */
214
3115
  interface FindSandboxOptions {
215
- /** User-provided stable identifier */
216
3116
  name: string;
217
- /** Isolation scope. Defaults to "default" */
218
3117
  namespace?: string;
219
3118
  }
220
3119
  /**
221
3120
  * Options for extending sandbox timeout
222
3121
  */
223
3122
  interface ExtendTimeoutOptions {
224
- /** Additional time to extend in milliseconds. Defaults to 900000 (15 minutes) */
225
3123
  duration?: number;
226
3124
  }
227
3125
  /**
228
- * Provider sandbox manager interface - handles sandbox lifecycle
229
- *
230
- * For most providers (e2b, railway, etc.), this returns ProviderSandbox.
231
- * The gateway provider returns the full Sandbox with ComputeClient features.
232
- */
233
- interface ProviderSandboxManager<TSandbox = any> {
234
- /** Create a new sandbox */
235
- create(options?: CreateSandboxOptions): Promise<ProviderSandbox<TSandbox>>;
236
- /** Get an existing sandbox by ID */
237
- getById(sandboxId: string): Promise<ProviderSandbox<TSandbox> | null>;
238
- /** List all active sandboxes */
239
- list(): Promise<ProviderSandbox<TSandbox>[]>;
240
- /** Destroy a sandbox */
241
- destroy(sandboxId: string): Promise<void>;
242
- /** Find existing or create new sandbox by (namespace, name) */
243
- findOrCreate?(options: FindOrCreateSandboxOptions): Promise<ProviderSandbox<TSandbox>>;
244
- /** Find existing sandbox by (namespace, name) without creating */
245
- find?(options: FindSandboxOptions): Promise<ProviderSandbox<TSandbox> | null>;
246
- /** Extend sandbox timeout/expiration */
247
- extendTimeout?(sandboxId: string, options?: ExtendTimeoutOptions): Promise<void>;
248
- }
249
- /**
250
- * Provider template manager interface - handles template/blueprint lifecycle
251
- */
252
- interface ProviderTemplateManager<TTemplate = any, TCreateOptions extends CreateTemplateOptions = CreateTemplateOptions> {
253
- /** Create a new template */
254
- create(options: TCreateOptions): Promise<TTemplate>;
255
- /** List all available templates */
256
- list(options?: ListTemplatesOptions): Promise<TTemplate[]>;
257
- /** Delete a template */
258
- delete(templateId: string): Promise<void>;
259
- }
260
- /**
261
- * Provider snapshot manager interface - handles snapshot lifecycle
262
- */
263
- interface ProviderSnapshotManager<TSnapshot = any> {
264
- /** Create a snapshot from a sandbox */
265
- create(sandboxId: string, options?: CreateSnapshotOptions): Promise<TSnapshot>;
266
- /** List all snapshots */
267
- list(options?: ListSnapshotsOptions): Promise<TSnapshot[]>;
268
- /** Delete a snapshot */
269
- delete(snapshotId: string): Promise<void>;
270
- }
271
- /**
272
- * Provider interface - creates and manages resources
273
- */
274
- interface Provider<TSandbox = any, TTemplate = any, TSnapshot = any> {
275
- /** Provider name/type */
276
- readonly name: string;
277
- /** Sandbox management operations */
278
- readonly sandbox: ProviderSandboxManager<TSandbox>;
279
- /** Optional template management operations */
280
- readonly template?: ProviderTemplateManager<TTemplate>;
281
- /** Optional snapshot management operations */
282
- readonly snapshot?: ProviderSnapshotManager<TSnapshot>;
283
- /** Get the list of supported runtime environments */
284
- getSupportedRuntimes(): Runtime[];
285
- }
286
- /**
287
- * Configuration for the compute singleton
288
- */
289
- interface ComputeConfig<TProvider extends Provider = Provider> {
290
- /** Default provider to use when none is specified */
291
- defaultProvider?: TProvider;
292
- /** @deprecated Use defaultProvider instead. Kept for backwards compatibility */
293
- provider?: TProvider;
294
- /** API key for compute CLI authentication */
295
- apiKey?: string;
296
- /** Access token for compute CLI authentication */
297
- accessToken?: string;
298
- /** @deprecated Use accessToken instead. Kept for backwards compatibility */
299
- jwt?: string;
300
- }
301
- /**
302
- * Parameters for compute.sandbox.create()
303
- */
304
- interface CreateSandboxParams {
305
- /** Provider instance to use */
306
- provider: Provider;
307
- /** Optional sandbox creation options */
308
- options?: CreateSandboxOptions;
309
- }
310
- /**
311
- * Parameters for compute.sandbox.create() with optional provider
312
- */
313
- interface CreateSandboxParamsWithOptionalProvider {
314
- /** Provider instance to use (optional if default is set) */
315
- provider?: Provider;
316
- /** Optional sandbox creation options */
317
- options?: CreateSandboxOptions;
318
- }
319
- /**
320
- * Base Compute API interface (non-generic)
321
- *
322
- * Returns ProviderSandbox which is the common interface for all sandboxes.
323
- * When using gateway provider, the returned sandbox will have full Sandbox
324
- * capabilities (terminals, watchers, signals) accessible via getInstance().
3126
+ * Compute singleton implementation
325
3127
  */
326
- interface ComputeAPI {
327
- /** Configuration management */
328
- setConfig<TProvider extends Provider>(config: ComputeConfig<TProvider>): void;
329
- getConfig(): ComputeConfig | null;
330
- clearConfig(): void;
331
- sandbox: {
332
- /** Create a sandbox from a provider (or default provider if configured) */
333
- create(params?: CreateSandboxParams | CreateSandboxParamsWithOptionalProvider): Promise<ProviderSandbox>;
334
- /** Get an existing sandbox by ID from a provider (or default provider if configured) */
335
- getById(providerOrSandboxId: Provider | string, sandboxId?: string): Promise<ProviderSandbox | null>;
336
- /** List all active sandboxes from a provider (or default provider if configured) */
337
- list(provider?: Provider): Promise<ProviderSandbox[]>;
338
- /** Destroy a sandbox via a provider (or default provider if configured) */
339
- destroy(providerOrSandboxId: Provider | string, sandboxId?: string): Promise<void>;
340
- /** Find existing or create new sandbox by (namespace, name) */
341
- findOrCreate(options: FindOrCreateSandboxOptions): Promise<ProviderSandbox>;
342
- /** Find existing sandbox by (namespace, name) without creating */
343
- find(options: FindSandboxOptions): Promise<ProviderSandbox | null>;
344
- /** Extend sandbox timeout/expiration */
345
- extendTimeout(sandboxId: string, options?: ExtendTimeoutOptions): Promise<void>;
346
- };
347
- }
348
- /**
349
- * Typed Compute API interface that preserves provider type information
350
- *
351
- * When using gateway provider, returns full Sandbox with ComputeClient features.
352
- * When using other providers, returns TypedProviderSandbox.
353
- */
354
- interface TypedComputeAPI<TProvider extends Provider> extends Omit<ComputeAPI, 'sandbox' | 'setConfig'> {
355
- /** Configuration management that returns typed compute instance */
356
- setConfig<T extends Provider>(config: ComputeConfig<T>): TypedComputeAPI<T>;
3128
+ declare class ComputeManager {
3129
+ private config;
3130
+ private autoConfigured;
3131
+ /**
3132
+ * Lazy auto-configure from environment if not explicitly configured
3133
+ */
3134
+ private ensureConfigured;
3135
+ /**
3136
+ * Get gateway config, throwing if not configured
3137
+ */
3138
+ private getGatewayConfig;
3139
+ /**
3140
+ * Explicitly configure the compute singleton
3141
+ *
3142
+ * @example
3143
+ * ```typescript
3144
+ * import { compute } from 'computesdk';
3145
+ *
3146
+ * compute.setConfig({
3147
+ * provider: 'e2b',
3148
+ * apiKey: 'computesdk_xxx',
3149
+ * e2b: { apiKey: 'e2b_xxx' }
3150
+ * });
3151
+ *
3152
+ * const sandbox = await compute.sandbox.create();
3153
+ * ```
3154
+ */
3155
+ setConfig(config: ExplicitComputeConfig): void;
357
3156
  sandbox: {
358
- /** Create a sandbox from the configured provider with proper typing */
359
- create(params?: Omit<CreateSandboxParamsWithOptionalProvider, 'provider'>): Promise<TypedProviderSandbox<TProvider>>;
360
- /** Get an existing sandbox by ID from the configured provider with proper typing */
361
- getById(sandboxId: string): Promise<TypedProviderSandbox<TProvider> | null>;
362
- /** List all active sandboxes from the configured provider with proper typing */
363
- list(): Promise<TypedProviderSandbox<TProvider>[]>;
364
- /** Destroy a sandbox via the configured provider */
365
- destroy(sandboxId: string): Promise<void>;
366
- /** Find existing or create new sandbox by (namespace, name) */
367
- findOrCreate(options: FindOrCreateSandboxOptions): Promise<TypedProviderSandbox<TProvider>>;
368
- /** Find existing sandbox by (namespace, name) without creating */
369
- find(options: FindSandboxOptions): Promise<TypedProviderSandbox<TProvider> | null>;
370
- /** Extend sandbox timeout/expiration */
371
- extendTimeout(sandboxId: string, options?: ExtendTimeoutOptions): Promise<void>;
372
- };
373
- }
374
- /**
375
- * E2B provider configuration for explicit compute mode
376
- */
377
- interface E2BProviderConfig {
378
- /** E2B API key */
379
- apiKey?: string;
380
- /** E2B project ID */
381
- projectId?: string;
382
- /** E2B environment/template ID */
383
- templateId?: string;
384
- }
385
- /**
386
- * Modal provider configuration for explicit compute mode
387
- */
388
- interface ModalProviderConfig {
389
- /** Modal token ID */
390
- tokenId?: string;
391
- /** Modal token secret */
392
- tokenSecret?: string;
393
- }
394
- /**
395
- * Railway provider configuration for explicit compute mode
396
- */
397
- interface RailwayProviderConfig {
398
- /** Railway API token */
399
- apiToken?: string;
400
- /** Railway project ID */
401
- projectId?: string;
402
- /** Railway environment ID */
403
- environmentId?: string;
404
- }
405
- /**
406
- * Daytona provider configuration for explicit compute mode
407
- */
408
- interface DaytonaProviderConfig {
409
- /** Daytona API key */
410
- apiKey?: string;
411
- }
412
- /**
413
- * Vercel provider configuration for explicit compute mode
414
- */
415
- interface VercelProviderConfig {
416
- /** Vercel OIDC token (preferred, simpler auth) */
417
- oidcToken?: string;
418
- /** Vercel API token (traditional auth) */
419
- token?: string;
420
- /** Vercel team ID (required with token) */
421
- teamId?: string;
422
- /** Vercel project ID (required with token) */
423
- projectId?: string;
424
- }
425
- /**
426
- * Runloop provider configuration for explicit compute mode
427
- */
428
- interface RunloopProviderConfig {
429
- /** Runloop API key */
430
- apiKey?: string;
431
- }
432
- /**
433
- * Cloudflare provider configuration for explicit compute mode
434
- */
435
- interface CloudflareProviderConfig {
436
- /** Cloudflare API token */
437
- apiToken?: string;
438
- /** Cloudflare account ID */
439
- accountId?: string;
440
- }
441
- /**
442
- * CodeSandbox provider configuration for explicit compute mode
443
- */
444
- interface CodesandboxProviderConfig {
445
- /** CodeSandbox API key */
446
- apiKey?: string;
447
- }
448
- /**
449
- * Blaxel provider configuration for explicit compute mode
450
- */
451
- interface BlaxelProviderConfig {
452
- /** Blaxel API key */
453
- apiKey?: string;
454
- /** Blaxel workspace */
455
- workspace?: string;
3157
+ /**
3158
+ * Create a new sandbox
3159
+ */
3160
+ create: (options?: CreateSandboxOptions) => Promise<Sandbox>;
3161
+ /**
3162
+ * Get an existing sandbox by ID
3163
+ */
3164
+ getById: (sandboxId: string) => Promise<Sandbox | null>;
3165
+ /**
3166
+ * List all active sandboxes
3167
+ */
3168
+ list: () => Promise<Sandbox[]>;
3169
+ /**
3170
+ * Destroy a sandbox
3171
+ */
3172
+ destroy: (sandboxId: string) => Promise<void>;
3173
+ /**
3174
+ * Find existing or create new sandbox by (namespace, name)
3175
+ */
3176
+ findOrCreate: (options: FindOrCreateSandboxOptions) => Promise<Sandbox>;
3177
+ /**
3178
+ * Find existing sandbox by (namespace, name) without creating
3179
+ */
3180
+ find: (options: FindSandboxOptions) => Promise<Sandbox | null>;
3181
+ /**
3182
+ * Extend sandbox timeout/expiration
3183
+ */
3184
+ extendTimeout: (sandboxId: string, options?: ExtendTimeoutOptions) => Promise<void>;
3185
+ };
456
3186
  }
457
-
458
3187
  /**
459
- * Explicit compute configuration for callable compute()
460
- *
461
- * Used when calling compute as a function: compute({ provider: 'e2b', ... })
462
- * Always uses gateway mode.
463
- */
464
- interface ExplicitComputeConfig {
465
- /** Provider name to use */
466
- provider: ProviderName;
467
- /** ComputeSDK API key (required for gateway mode) */
468
- apiKey: string;
469
- /** E2B provider configuration */
470
- e2b?: E2BProviderConfig;
471
- /** Modal provider configuration */
472
- modal?: ModalProviderConfig;
473
- /** Railway provider configuration */
474
- railway?: RailwayProviderConfig;
475
- /** Daytona provider configuration */
476
- daytona?: DaytonaProviderConfig;
477
- /** Vercel provider configuration */
478
- vercel?: VercelProviderConfig;
479
- /** Runloop provider configuration */
480
- runloop?: RunloopProviderConfig;
481
- /** Cloudflare provider configuration */
482
- cloudflare?: CloudflareProviderConfig;
483
- /** CodeSandbox provider configuration */
484
- codesandbox?: CodesandboxProviderConfig;
485
- /** Blaxel provider configuration */
486
- blaxel?: BlaxelProviderConfig;
487
- }
488
- /**
489
- * Callable compute type - works as both singleton and factory function
490
- */
491
- type CallableCompute = ComputeAPI & ((config: ExplicitComputeConfig) => ComputeAPI);
492
-
493
- /**
494
- * Compute Singleton - Main API Orchestrator
495
- *
496
- * Provides the unified compute.* API and delegates to specialized managers.
497
- * The `compute` export works as both a singleton and a callable function:
3188
+ * Callable compute interface - dual nature as both singleton and factory
498
3189
  *
499
- * - Singleton: `compute.sandbox.create()` (auto-detects from env vars)
500
- * - Callable: `compute({ provider: 'e2b', ... }).sandbox.create()` (explicit config, uses gateway)
501
- */
502
-
3190
+ * This interface represents the compute export's two modes:
3191
+ * 1. As a ComputeManager singleton (accessed via properties like compute.sandbox)
3192
+ * 2. As a factory function (called with config to create new instances)
3193
+ */
3194
+ interface CallableCompute extends ComputeManager {
3195
+ /** Create a new compute instance with explicit configuration */
3196
+ (config: ExplicitComputeConfig): ComputeManager;
3197
+ /** Explicitly configure the singleton */
3198
+ setConfig(config: ExplicitComputeConfig): void;
3199
+ }
503
3200
  /**
504
3201
  * Callable compute - works as both singleton and factory function
505
3202
  *
@@ -510,7 +3207,7 @@ type CallableCompute = ComputeAPI & ((config: ExplicitComputeConfig) => ComputeA
510
3207
  * // Singleton mode (auto-detects from env vars)
511
3208
  * const sandbox1 = await compute.sandbox.create();
512
3209
  *
513
- * // Callable mode (explicit config, uses gateway)
3210
+ * // Callable mode (explicit config)
514
3211
  * const sandbox2 = await compute({
515
3212
  * provider: 'e2b',
516
3213
  * apiKey: 'computesdk_xxx',
@@ -519,190 +3216,6 @@ type CallableCompute = ComputeAPI & ((config: ExplicitComputeConfig) => ComputeA
519
3216
  * ```
520
3217
  */
521
3218
  declare const compute: CallableCompute;
522
- /**
523
- * Create a compute instance with proper typing
524
- *
525
- * @example
526
- * ```typescript
527
- * import { e2b } from '@computesdk/e2b'
528
- * import { createCompute } from 'computesdk'
529
- *
530
- * // Zero-config mode (auto-detects from environment)
531
- * const compute = createCompute();
532
- * const sandbox = await compute.sandbox.create();
533
- *
534
- * // Explicit mode
535
- * const compute2 = createCompute({
536
- * defaultProvider: e2b({ apiKey: 'your-key' }),
537
- * });
538
- *
539
- * const sandbox2 = await compute2.sandbox.create();
540
- * const instance = sandbox2.getInstance(); // ✅ Properly typed!
541
- * ```
542
- */
543
- declare function createCompute(): ComputeAPI;
544
- declare function createCompute<TProvider extends Provider>(config: ComputeConfig<TProvider>): TypedComputeAPI<TProvider>;
545
-
546
- /**
547
- * Explicit Config
548
- *
549
- * Converts explicit compute configuration to a gateway provider.
550
- * Used when compute() is called as a function with configuration.
551
- */
552
-
553
- /**
554
- * Create a gateway provider from explicit configuration
555
- *
556
- * @param config - Explicit compute configuration
557
- * @returns A configured gateway provider
558
- */
559
- declare function createProviderFromConfig(config: ExplicitComputeConfig): Provider;
560
-
561
- /**
562
- * Provider Factory - Creates providers from method definitions
563
- *
564
- * Eliminates boilerplate by auto-generating Provider/Sandbox classes
565
- * from simple method definitions with automatic feature detection.
566
- */
567
-
568
- /**
569
- * Flat sandbox method implementations - all operations in one place
570
- */
571
- interface SandboxMethods<TSandbox = any, TConfig = any> {
572
- create: (config: TConfig, options?: CreateSandboxOptions) => Promise<{
573
- sandbox: TSandbox;
574
- sandboxId: string;
575
- }>;
576
- getById: (config: TConfig, sandboxId: string) => Promise<{
577
- sandbox: TSandbox;
578
- sandboxId: string;
579
- } | null>;
580
- list: (config: TConfig) => Promise<Array<{
581
- sandbox: TSandbox;
582
- sandboxId: string;
583
- }>>;
584
- destroy: (config: TConfig, sandboxId: string) => Promise<void>;
585
- findOrCreate?: (config: TConfig, options: FindOrCreateSandboxOptions) => Promise<{
586
- sandbox: TSandbox;
587
- sandboxId: string;
588
- }>;
589
- find?: (config: TConfig, options: FindSandboxOptions) => Promise<{
590
- sandbox: TSandbox;
591
- sandboxId: string;
592
- } | null>;
593
- extendTimeout?: (config: TConfig, sandboxId: string, options?: ExtendTimeoutOptions) => Promise<void>;
594
- runCode: (sandbox: TSandbox, code: string, runtime?: Runtime, config?: TConfig) => Promise<CodeResult>;
595
- runCommand: (sandbox: TSandbox, command: string, args?: string[], options?: RunCommandOptions) => Promise<CommandResult>;
596
- getInfo: (sandbox: TSandbox) => Promise<SandboxInfo>;
597
- getUrl: (sandbox: TSandbox, options: {
598
- port: number;
599
- protocol?: string;
600
- }) => Promise<string>;
601
- getInstance?: (sandbox: TSandbox) => TSandbox;
602
- filesystem?: {
603
- readFile: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<CommandResult>) => Promise<string>;
604
- writeFile: (sandbox: TSandbox, path: string, content: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<CommandResult>) => Promise<void>;
605
- mkdir: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<CommandResult>) => Promise<void>;
606
- readdir: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<CommandResult>) => Promise<FileEntry[]>;
607
- exists: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<CommandResult>) => Promise<boolean>;
608
- remove: (sandbox: TSandbox, path: string, runCommand: (sandbox: TSandbox, command: string, args?: string[]) => Promise<CommandResult>) => Promise<void>;
609
- };
610
- }
611
- /**
612
- * Template method implementations
613
- */
614
- interface TemplateMethods<TTemplate = any, TConfig = any, TCreateOptions extends CreateTemplateOptions = CreateTemplateOptions> {
615
- create: (config: TConfig, options: TCreateOptions) => Promise<TTemplate>;
616
- list: (config: TConfig, options?: ListTemplatesOptions) => Promise<TTemplate[]>;
617
- delete: (config: TConfig, templateId: string) => Promise<void>;
618
- }
619
- /**
620
- * Snapshot method implementations
621
- */
622
- interface SnapshotMethods<TSnapshot = any, TConfig = any> {
623
- create: (config: TConfig, sandboxId: string, options?: CreateSnapshotOptions) => Promise<TSnapshot>;
624
- list: (config: TConfig, options?: ListSnapshotsOptions) => Promise<TSnapshot[]>;
625
- delete: (config: TConfig, snapshotId: string) => Promise<void>;
626
- }
627
- /**
628
- * Provider execution modes
629
- *
630
- * - 'raw': Use raw provider methods directly (for gateway internal use)
631
- * - 'direct': Use provider's native SDK directly (for providers with sandbox capabilities)
632
- * - 'gateway': Route through ComputeSDK gateway (for providers without native sandbox)
633
- */
634
- type ProviderMode = 'raw' | 'direct' | 'gateway';
635
- /**
636
- * Provider configuration for createProvider()
637
- */
638
- interface ProviderConfig<TSandbox = any, TConfig = any, TTemplate = any, TSnapshot = any> {
639
- name: string;
640
- /**
641
- * Default execution mode for this provider (defaults to 'gateway' if not specified)
642
- *
643
- * - 'direct': Provider has native sandbox capabilities (e.g., E2B) - uses provider SDK directly
644
- * - 'gateway': Provider only has infrastructure (e.g., Railway) - routes through gateway
645
- *
646
- * Can be overridden at runtime with `mode` in config.
647
- */
648
- defaultMode?: 'direct' | 'gateway';
649
- methods: {
650
- sandbox: SandboxMethods<TSandbox, TConfig>;
651
- template?: TemplateMethods<TTemplate, TConfig>;
652
- snapshot?: SnapshotMethods<TSnapshot, TConfig>;
653
- };
654
- }
655
- /**
656
- * Base config that all provider configs should extend
657
- * Includes the `mode` option for controlling execution mode
658
- */
659
- interface BaseProviderConfig {
660
- /**
661
- * Execution mode override
662
- *
663
- * - 'raw': Use raw provider methods directly (for gateway internal use)
664
- * - 'direct': Use provider's native SDK directly
665
- * - 'gateway': Route through ComputeSDK gateway
666
- *
667
- * If not specified, uses the provider's `defaultMode`.
668
- */
669
- mode?: ProviderMode;
670
- }
671
- /**
672
- * Create a provider from method definitions
673
- *
674
- * Auto-generates all boilerplate classes and provides feature detection
675
- * based on which methods are implemented.
676
- */
677
- declare function createProvider<TSandbox, TConfig = any, TTemplate = any, TSnapshot = any>(providerConfig: ProviderConfig<TSandbox, TConfig, TTemplate, TSnapshot>): (config: TConfig & BaseProviderConfig) => Provider<TSandbox, TTemplate, TSnapshot>;
678
-
679
- /**
680
- * Gateway provider configuration
681
- */
682
- interface GatewayConfig extends BaseProviderConfig {
683
- /** Gateway URL (default: https://gateway.computesdk.com) */
684
- gatewayUrl?: string;
685
- /** ComputeSDK API key for authentication */
686
- apiKey: string;
687
- /** Backend provider name (e2b, railway, etc.) */
688
- provider: string;
689
- /** Provider-specific headers to pass through to gateway */
690
- providerHeaders?: Record<string, string>;
691
- /** Request timeout in milliseconds (default: 30000) */
692
- requestTimeout?: number;
693
- /** Maximum retry attempts for transient failures (default: 3) */
694
- maxRetries?: number;
695
- /** Initial retry delay in milliseconds (default: 1000) */
696
- retryDelay?: number;
697
- /** HTTP status codes that should trigger a retry (default: [408, 429, 502, 503, 504]) */
698
- retryableStatuses?: number[];
699
- }
700
- /**
701
- * Gateway Provider factory
702
- *
703
- * Uses ClientSandbox directly as the sandbox type - no wrapper needed.
704
- */
705
- declare const gateway: (config: GatewayConfig & BaseProviderConfig) => Provider<Sandbox, any, any>;
706
3219
 
707
3220
  /**
708
3221
  * Auto-Detection Module
@@ -710,7 +3223,6 @@ declare const gateway: (config: GatewayConfig & BaseProviderConfig) => Provider<
710
3223
  * Automatically detects gateway mode and provider from environment variables.
711
3224
  * Enables zero-config usage of ComputeSDK.
712
3225
  */
713
-
714
3226
  /**
715
3227
  * Check if gateway mode is enabled
716
3228
  * Gateway mode requires COMPUTESDK_API_KEY to be set
@@ -731,13 +3243,22 @@ declare function detectProvider(): string | null;
731
3243
  * These headers are passed through to the gateway
732
3244
  */
733
3245
  declare function getProviderHeaders(provider: string): Record<string, string>;
3246
+ /**
3247
+ * Gateway configuration object
3248
+ */
3249
+ interface GatewayConfig {
3250
+ apiKey: string;
3251
+ gatewayUrl: string;
3252
+ provider: string;
3253
+ providerHeaders: Record<string, string>;
3254
+ }
734
3255
  /**
735
3256
  * Main auto-configuration function
736
- * Returns configured HTTP provider or null if auto-detection not possible
3257
+ * Returns gateway configuration or null if auto-detection not possible
737
3258
  *
738
3259
  * @throws Error if COMPUTESDK_API_KEY is set but no provider detected
739
3260
  */
740
- declare function autoConfigureCompute(): Provider | null;
3261
+ declare function autoConfigureCompute(): GatewayConfig | null;
741
3262
 
742
3263
  /**
743
3264
  * ComputeSDK Constants
@@ -770,87 +3291,4 @@ declare const PROVIDER_ENV_VARS: {
770
3291
  readonly blaxel: readonly ["BL_API_KEY", "BL_WORKSPACE"];
771
3292
  };
772
3293
 
773
- /**
774
- * Utility functions for ComputeSDK
775
- */
776
- /**
777
- * Calculate exponential backoff delay with jitter
778
- *
779
- * Uses exponential backoff (2^attempt) multiplied by base delay,
780
- * plus random jitter to prevent thundering herd.
781
- *
782
- * @param attempt - Current retry attempt (0-indexed)
783
- * @param baseDelay - Base delay in milliseconds (default: 1000)
784
- * @param jitterMax - Maximum random jitter in milliseconds (default: 100)
785
- * @returns Delay in milliseconds
786
- *
787
- * @example
788
- * ```typescript
789
- * // First retry: 1000-1100ms
790
- * calculateBackoff(0);
791
- *
792
- * // Second retry: 2000-2100ms
793
- * calculateBackoff(1);
794
- *
795
- * // Third retry: 4000-4100ms
796
- * calculateBackoff(2);
797
- * ```
798
- */
799
- declare function calculateBackoff(attempt: number, baseDelay?: number, jitterMax?: number): number;
800
-
801
- /**
802
- * Simplified Request Handler for Web Framework Integration
803
- *
804
- * Handles JSON requests for sandbox and code execution operations.
805
- * Terminal support removed - will be re-added with WebSocket VM connections.
806
- */
807
-
808
- /**
809
- * Request structure supporting sandbox and code execution capabilities
810
- */
811
- interface ComputeRequest {
812
- /** Action in dot notation (e.g., 'compute.sandbox.create') */
813
- action: string;
814
- /** Parameters for the action */
815
- sandboxId?: string;
816
- code?: string;
817
- command?: string;
818
- args?: string[];
819
- runtime?: Runtime;
820
- path?: string;
821
- content?: string;
822
- /** Command options (for runCommand action) */
823
- commandOptions?: {
824
- background?: boolean;
825
- };
826
- /** Sandbox creation options */
827
- options?: {
828
- runtime?: Runtime;
829
- timeout?: number;
830
- sandboxId?: string;
831
- };
832
- }
833
- /**
834
- * Response structure for compute operations
835
- */
836
- interface ComputeResponse {
837
- success: boolean;
838
- error?: string;
839
- sandboxId: string;
840
- provider: string;
841
- [key: string]: any;
842
- }
843
- /**
844
- * Main request handler - handles HTTP requests and pre-parsed bodies
845
- */
846
- declare function handleComputeRequest(params: HandleComputeRequestParams): Promise<ComputeResponse>;
847
- declare function handleComputeRequest(requestOrBody: Request | ComputeRequest, provider: Provider): Promise<Response>;
848
- /**
849
- * Legacy export for backward compatibility
850
- */
851
- interface HandleComputeRequestParams {
852
- request: ComputeRequest;
853
- provider: Provider;
854
- }
855
-
856
- export { type BaseProviderConfig, type BlaxelProviderConfig, type CallableCompute, type CloudflareProviderConfig, type CodesandboxProviderConfig, type ComputeAPI, type ComputeConfig, type ComputeRequest, type ComputeResponse, type CreateSandboxParams, type CreateSandboxParamsWithOptionalProvider, type CreateSnapshotOptions, type CreateTemplateOptions, type DaytonaProviderConfig, type E2BProviderConfig, type ExplicitComputeConfig, type ProviderName as ExplicitProviderName, type ExtendTimeoutOptions, type ExtractProviderSandboxType, type FindOrCreateSandboxOptions, type FindSandboxOptions, GATEWAY_URL, type GatewayConfig, type HandleComputeRequestParams, type ListSnapshotsOptions, type ListTemplatesOptions, type ModalProviderConfig, PROVIDER_AUTH, PROVIDER_DASHBOARD_URLS, PROVIDER_ENV_MAP, PROVIDER_ENV_VARS, PROVIDER_HEADERS, PROVIDER_NAMES, PROVIDER_PRIORITY, type Provider, type ProviderConfig, type ProviderMode, type ProviderName, type ProviderSandbox, type ProviderSandboxManager, type ProviderSnapshotManager, type ProviderTemplateManager, type RailwayProviderConfig, type RunloopProviderConfig, type SandboxInfo, type SandboxMethods, type SnapshotMethods, type TemplateMethods, type TypedComputeAPI, type TypedProviderSandbox, type VercelProviderConfig, autoConfigureCompute, buildProviderHeaders, calculateBackoff, compute, createCompute, createProvider, createProviderFromConfig, detectProvider, gateway, getMissingEnvVars, getProviderConfigFromEnv, getProviderHeaders, handleComputeRequest, isGatewayModeEnabled, isProviderAuthComplete, isValidProvider };
3294
+ export { type CodeResult$1 as CodeResult, CommandExitError, type CommandResult$1 as CommandResult, type CreateSandboxOptions$1 as CreateSandboxOptions, type FileEntry, FileWatcher, GATEWAY_URL, Sandbox as GatewaySandbox, MessageType, PROVIDER_AUTH, PROVIDER_DASHBOARD_URLS, PROVIDER_ENV_MAP, PROVIDER_ENV_VARS, PROVIDER_HEADERS, PROVIDER_NAMES, PROVIDER_PRIORITY, type ProviderName, type ProviderSandboxInfo, type RunCommandOptions, type Runtime, Sandbox, type SandboxFileSystem, type SandboxInfo$1 as SandboxInfo, type Sandbox$1 as SandboxInterface, type SandboxStatus, SignalService, TerminalInstance, autoConfigureCompute, buildProviderHeaders, compute, decodeBinaryMessage, detectProvider, encodeBinaryMessage, getMissingEnvVars, getProviderConfigFromEnv, getProviderHeaders, isCommandExitError, isGatewayModeEnabled, isProviderAuthComplete, isValidProvider };