computesdk 2.6.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,44 +1,13 @@
1
1
  /**
2
2
  * Universal Sandbox Interface
3
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 Sandbox client class implements the full specification.
14
- *
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 Sandbox client class. The rename happens at export time in
18
- * src/index.ts. Providers using @computesdk/provider will only see "SandboxInterface".
19
- *
20
- * @example Minimal implementation
21
- * ```typescript
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
- * ```
33
- */
34
- /**
35
- * Supported runtime environments
4
+ * The canonical interface for all ComputeSDK sandboxes. Providers using
5
+ * @computesdk/provider implement this shape (re-exported as SandboxInterface).
36
6
  */
37
- type Runtime = 'node' | 'python' | 'deno' | 'bun';
38
7
  /**
39
8
  * Code execution result
40
9
  */
41
- interface CodeResult$1 {
10
+ interface CodeResult {
42
11
  output: string;
43
12
  exitCode: number;
44
13
  language: string;
@@ -46,7 +15,7 @@ interface CodeResult$1 {
46
15
  /**
47
16
  * Command execution result
48
17
  */
49
- interface CommandResult$1 {
18
+ interface CommandResult {
50
19
  stdout: string;
51
20
  stderr: string;
52
21
  exitCode: number;
@@ -55,13 +24,11 @@ interface CommandResult$1 {
55
24
  /**
56
25
  * Sandbox information
57
26
  */
58
- interface SandboxInfo$1 {
27
+ interface SandboxInfo {
59
28
  /** Unique identifier for the sandbox */
60
29
  id: string;
61
30
  /** Provider hosting the sandbox */
62
31
  provider: string;
63
- /** Runtime environment in the sandbox */
64
- runtime: Runtime;
65
32
  /** Current status of the sandbox */
66
33
  status: 'running' | 'stopped' | 'error';
67
34
  /** When the sandbox was created */
@@ -119,7 +86,6 @@ interface SandboxFileSystem {
119
86
  * Providers can extend this with additional properties specific to their implementation
120
87
  */
121
88
  interface CreateSandboxOptions$1 {
122
- runtime?: Runtime;
123
89
  timeout?: number;
124
90
  templateId?: string;
125
91
  metadata?: Record<string, any>;
@@ -127,49 +93,8 @@ interface CreateSandboxOptions$1 {
127
93
  name?: string;
128
94
  namespace?: string;
129
95
  directory?: string;
130
- overlays?: SandboxOverlayConfig[];
131
- servers?: SandboxServerConfig[];
132
96
  [key: string]: any;
133
97
  }
134
- interface SandboxOverlayConfig {
135
- source: string;
136
- target: string;
137
- ignore?: string[];
138
- strategy?: 'copy' | 'smart';
139
- }
140
- type SandboxRestartPolicy = 'never' | 'on-failure' | 'always';
141
- /**
142
- * Health check configuration for servers
143
- */
144
- interface SandboxHealthCheckConfig {
145
- /** Path to poll for health checks (default: "/") */
146
- path?: string;
147
- /** Interval between health checks in milliseconds (default: 2000) */
148
- interval_ms?: number;
149
- /** Timeout for each health check request in milliseconds (default: 1500) */
150
- timeout_ms?: number;
151
- /** Delay before starting health checks after port detection in milliseconds (default: 5000) */
152
- delay_ms?: number;
153
- }
154
- interface SandboxServerConfig {
155
- slug: string;
156
- start: string;
157
- install?: string;
158
- path?: string;
159
- port?: number;
160
- strict_port?: boolean;
161
- autostart?: boolean;
162
- env_file?: string;
163
- environment?: Record<string, string>;
164
- restart_policy?: SandboxRestartPolicy;
165
- max_restarts?: number;
166
- restart_delay_ms?: number;
167
- stop_timeout_ms?: number;
168
- depends_on?: string[];
169
- overlay?: SandboxOverlayConfig;
170
- overlays?: SandboxOverlayConfig[];
171
- health_check?: SandboxHealthCheckConfig;
172
- }
173
98
  /**
174
99
  * Universal Sandbox Interface
175
100
  *
@@ -180,22 +105,20 @@ interface SandboxServerConfig {
180
105
  * as long as they are structurally compatible. For example, getInfo() might
181
106
  * return additional fields beyond the base SandboxInfo.
182
107
  */
183
- interface Sandbox$1 {
108
+ interface Sandbox {
184
109
  /** Unique identifier for the sandbox */
185
110
  readonly sandboxId: string;
186
111
  /** Provider name (e2b, railway, modal, etc.) */
187
112
  readonly provider: string;
188
- /** Execute code in the sandbox */
189
- runCode(code: string, runtime?: Runtime): Promise<CodeResult$1>;
190
113
  /**
191
114
  * Execute shell command
192
115
  *
193
116
  * Send raw command string to the sandbox - no preprocessing.
194
117
  * The provider/server handles shell invocation and execution details.
195
118
  */
196
- runCommand(command: string, options?: RunCommandOptions): Promise<CommandResult$1>;
119
+ runCommand(command: string, options?: RunCommandOptions): Promise<CommandResult>;
197
120
  /** Get information about the sandbox */
198
- getInfo(): Promise<SandboxInfo$1>;
121
+ getInfo(): Promise<SandboxInfo>;
199
122
  /** Get URL for accessing the sandbox on a specific port */
200
123
  getUrl(options: {
201
124
  port: number;
@@ -205,3658 +128,18 @@ interface Sandbox$1 {
205
128
  destroy(): Promise<void>;
206
129
  /** File system operations */
207
130
  readonly filesystem: SandboxFileSystem;
208
- /**
209
- * Terminal management (interactive PTY and exec modes)
210
- * Available in: sandbox client, e2b (potentially)
211
- */
212
- readonly terminal?: any;
213
- /**
214
- * Code and command execution namespace
215
- * Available in: sandbox client
216
- */
217
- readonly run?: any;
218
- /**
219
- * Managed server operations
220
- * Available in: sandbox client
221
- */
222
- readonly server?: any;
223
- /**
224
- * File watcher with real-time change events
225
- * Available in: sandbox client
226
- */
227
- readonly watcher?: any;
228
- /**
229
- * Session token management
230
- * Available in: sandbox client
231
- */
232
- readonly sessionToken?: any;
233
- /**
234
- * Magic link authentication
235
- * Available in: sandbox client
236
- */
237
- readonly magicLink?: any;
238
- /**
239
- * Signal service for port/error events
240
- * Available in: sandbox client
241
- */
242
- readonly signal?: any;
243
- /**
244
- * File operations namespace
245
- * Available in: sandbox client
246
- */
247
- readonly file?: any;
248
- /**
249
- * Environment variable management
250
- * Available in: sandbox client
251
- */
252
- readonly env?: any;
253
- /**
254
- * Authentication operations
255
- * Available in: sandbox client
256
- */
257
- readonly auth?: any;
258
- /**
259
- * Child sandbox management
260
- * Available in: sandbox client
261
- */
262
- readonly child?: any;
263
- }
264
-
265
- /**
266
- * Terminal created notification
267
- */
268
- interface TerminalCreatedMessage {
269
- type: 'terminal:created';
270
- channel: string;
271
- data: {
272
- id: string;
273
- status: 'running' | 'stopped';
274
- };
275
- }
276
- /**
277
- * Terminal output data
278
- * Note: output field may be base64 encoded depending on encoding field
279
- */
280
- interface TerminalOutputMessage {
281
- type: 'terminal:output';
282
- channel: string;
283
- data: {
284
- output: string;
285
- encoding?: 'raw' | 'base64';
286
- };
287
- }
288
- /**
289
- * Terminal destroyed notification
290
- */
291
- interface TerminalDestroyedMessage {
292
- type: 'terminal:destroyed';
293
- channel: string;
294
- data: {
295
- id: string;
296
- };
297
- }
298
- /**
299
- * Terminal error notification
300
- */
301
- interface TerminalErrorMessage {
302
- type: 'terminal:error';
303
- channel: string;
304
- data: {
305
- error: string;
306
- };
307
- }
308
- /**
309
- * Command stdout streaming message (exec mode with stream: true)
310
- */
311
- interface CommandStdoutMessage {
312
- type: 'command:stdout';
313
- channel: string;
314
- data: {
315
- terminal_id: string;
316
- cmd_id: string;
317
- output: string;
318
- };
319
- }
320
- /**
321
- * Command stderr streaming message (exec mode with stream: true)
322
- */
323
- interface CommandStderrMessage {
324
- type: 'command:stderr';
325
- channel: string;
326
- data: {
327
- terminal_id: string;
328
- cmd_id: string;
329
- output: string;
330
- };
331
- }
332
- /**
333
- * Command exit message (exec mode with stream: true)
334
- */
335
- interface CommandExitMessage {
336
- type: 'command:exit';
337
- channel: string;
338
- data: {
339
- terminal_id: string;
340
- cmd_id: string;
341
- exit_code: number;
342
- };
343
- }
344
- /**
345
- * File watcher created notification
346
- */
347
- interface WatcherCreatedMessage {
348
- type: 'watcher:created';
349
- channel: string;
350
- data: {
351
- id: string;
352
- path: string;
353
- };
354
- }
355
- /**
356
- * File change event
357
- * Note: content field may be base64 encoded depending on encoding field
358
- */
359
- interface FileChangedMessage {
360
- type: 'file:changed';
361
- channel: string;
362
- data: {
363
- event: 'add' | 'change' | 'unlink' | 'addDir' | 'unlinkDir';
364
- path: string;
365
- content?: string;
366
- encoding?: 'raw' | 'base64';
367
- };
368
- }
369
- /**
370
- * File watcher destroyed notification
371
- */
372
- interface WatcherDestroyedMessage {
373
- type: 'watcher:destroyed';
374
- channel: string;
375
- data: {
376
- id: string;
377
- };
378
- }
379
- /**
380
- * System signal event
381
- */
382
- interface SignalMessage {
383
- type: 'signal';
384
- channel: 'signals';
385
- data: {
386
- signal: 'port' | 'error' | 'server-ready';
387
- port?: number;
388
- url?: string;
389
- message?: string;
390
- };
391
- }
392
- /**
393
- * Sandbox created notification
394
- */
395
- interface SandboxCreatedMessage {
396
- type: 'sandbox.created';
397
- data: {
398
- subdomain: string;
399
- url: string;
400
- };
401
- }
402
- /**
403
- * Sandbox deleted notification
404
- */
405
- interface SandboxDeletedMessage {
406
- type: 'sandbox.deleted';
407
- data: {
408
- subdomain: string;
409
- };
410
- }
411
- type WebSocketConstructor$1 = new (url: string) => WebSocket;
412
- interface WebSocketManagerConfig {
413
- /** WebSocket URL (will be generated from client config if not provided) */
414
- url: string;
415
- /** WebSocket implementation */
416
- WebSocket: WebSocketConstructor$1;
417
- /** Enable automatic reconnection on disconnect (default: true) */
418
- autoReconnect?: boolean;
419
- /** Reconnection delay in milliseconds (default: 1000) */
420
- reconnectDelay?: number;
421
- /** Maximum reconnection attempts (default: 5, 0 = infinite) */
422
- maxReconnectAttempts?: number;
423
- /** Enable debug logging (default: false) */
424
- debug?: boolean;
425
- /** WebSocket protocol: 'binary' (default, recommended) or 'json' (for debugging) */
426
- protocol?: 'json' | 'binary';
427
- }
428
- type MessageHandler<T = any> = (message: T) => void;
429
- type ErrorHandler = (error: Event) => void;
430
- type ConnectionHandler = () => void;
431
- /**
432
- * WebSocket Manager for handling real-time communication
433
- *
434
- * @example
435
- * ```typescript
436
- * import { ComputeClient } from '@computesdk/client'
437
- *
438
- * const client = new ComputeClient({ sandboxUrl: 'https://sandbox-123.sandbox.computesdk.com' });
439
- * await client.generateToken();
440
- *
441
- * // Create WebSocket manager
442
- * const ws = client.createWebSocketManager();
443
- *
444
- * // Listen for connection
445
- * ws.on('open', () => {
446
- * console.log('Connected!');
447
- * });
448
- *
449
- * // Subscribe to terminal output
450
- * ws.subscribe('terminal:term_abc123');
451
- * ws.on('terminal:output', (msg) => {
452
- * console.log('Terminal output:', msg.data.output);
453
- * });
454
- *
455
- * // Send terminal input
456
- * ws.sendTerminalInput('term_abc123', 'ls -la\n');
457
- *
458
- * // Subscribe to file changes
459
- * ws.subscribe('watcher:watcher_xyz789');
460
- * ws.on('file:changed', (msg) => {
461
- * console.log('File changed:', msg.data.path, msg.data.event);
462
- * });
463
- *
464
- * // Subscribe to signals
465
- * ws.subscribe('signals');
466
- * ws.on('signal', (msg) => {
467
- * console.log('Signal:', msg.data);
468
- * });
469
- * ```
470
- */
471
- declare class WebSocketManager {
472
- private config;
473
- private ws;
474
- private eventHandlers;
475
- private reconnectAttempts;
476
- private reconnectTimer;
477
- private subscribedChannels;
478
- private isManualClose;
479
- constructor(config: WebSocketManagerConfig);
480
- /**
481
- * Connect to WebSocket server
482
- */
483
- connect(): Promise<void>;
484
- /**
485
- * Disconnect from WebSocket server
486
- */
487
- disconnect(): void;
488
- /**
489
- * Check if WebSocket is connected
490
- */
491
- isConnected(): boolean;
492
- /**
493
- * Attempt to reconnect to WebSocket server
494
- */
495
- private attemptReconnect;
496
- /**
497
- * Subscribe to a channel
498
- * @param channel - Channel name (e.g., 'terminal:term_abc123', 'watcher:watcher_xyz789', 'signals')
499
- */
500
- subscribe(channel: string): void;
501
- /**
502
- * Unsubscribe from a channel
503
- */
504
- unsubscribe(channel: string): void;
505
- /**
506
- * Get list of subscribed channels
507
- */
508
- getSubscribedChannels(): string[];
509
- /**
510
- * Send raw message to server
511
- */
512
- private sendRaw;
513
- /**
514
- * Send input to a terminal (sent as-is, not encoded)
515
- */
516
- sendTerminalInput(terminalId: string, input: string): void;
517
- /**
518
- * Resize terminal window
519
- */
520
- resizeTerminal(terminalId: string, cols: number, rows: number): void;
521
- /**
522
- * Start a pending streaming command
523
- * Used in two-phase streaming flow: HTTP request creates pending command,
524
- * then this signal triggers execution after client has subscribed.
525
- */
526
- startCommand(cmdId: string): void;
527
- /**
528
- * Register event handler
529
- */
530
- on(event: 'open', handler: ConnectionHandler): void;
531
- on(event: 'close', handler: ConnectionHandler): void;
532
- on(event: 'error', handler: ErrorHandler): void;
533
- on(event: 'reconnect-failed', handler: ConnectionHandler): void;
534
- on(event: 'terminal:created', handler: MessageHandler<TerminalCreatedMessage>): void;
535
- on(event: 'terminal:output', handler: MessageHandler<TerminalOutputMessage>): void;
536
- on(event: 'terminal:destroyed', handler: MessageHandler<TerminalDestroyedMessage>): void;
537
- on(event: 'terminal:error', handler: MessageHandler<TerminalErrorMessage>): void;
538
- on(event: 'command:stdout', handler: MessageHandler<CommandStdoutMessage>): void;
539
- on(event: 'command:stderr', handler: MessageHandler<CommandStderrMessage>): void;
540
- on(event: 'command:exit', handler: MessageHandler<CommandExitMessage>): void;
541
- on(event: 'watcher:created', handler: MessageHandler<WatcherCreatedMessage>): void;
542
- on(event: 'file:changed', handler: MessageHandler<FileChangedMessage>): void;
543
- on(event: 'watcher:destroyed', handler: MessageHandler<WatcherDestroyedMessage>): void;
544
- on(event: 'signal', handler: MessageHandler<SignalMessage>): void;
545
- on(event: 'sandbox.created', handler: MessageHandler<SandboxCreatedMessage>): void;
546
- on(event: 'sandbox.deleted', handler: MessageHandler<SandboxDeletedMessage>): void;
547
- /**
548
- * Unregister event handler
549
- */
550
- off(event: string, handler: MessageHandler): void;
551
- /**
552
- * Unregister all event handlers for an event
553
- */
554
- offAll(event: string): void;
555
- /**
556
- * Emit event to registered handlers
557
- */
558
- private emit;
559
- /**
560
- * Handle incoming message
561
- */
562
- private handleMessage;
563
- /**
564
- * Log debug message if debug mode is enabled
565
- */
566
- private log;
567
- /**
568
- * Get current connection state
569
- */
570
- getState(): 'connecting' | 'open' | 'closing' | 'closed';
571
- /**
572
- * Get reconnection attempt count
573
- */
574
- getReconnectAttempts(): number;
575
- }
576
-
577
- /**
578
- * Command - Represents a command execution in a terminal
579
- */
580
-
581
- /**
582
- * Command execution result with wait capability
583
- */
584
- declare class Command {
585
- readonly id: string;
586
- readonly terminalId: string;
587
- readonly command: string;
588
- private _status;
589
- private _stdout;
590
- private _stderr;
591
- private _exitCode?;
592
- private _durationMs?;
593
- private _startedAt;
594
- private _finishedAt?;
595
- private waitHandler?;
596
- private retrieveHandler?;
597
- constructor(data: {
598
- cmdId: string;
599
- terminalId: string;
600
- command: string;
601
- status: 'running' | 'completed' | 'failed';
602
- stdout: string;
603
- stderr: string;
604
- exitCode?: number;
605
- durationMs?: number;
606
- startedAt: string;
607
- finishedAt?: string;
608
- });
609
- get status(): 'running' | 'completed' | 'failed';
610
- get stdout(): string;
611
- get stderr(): string;
612
- get exitCode(): number | undefined;
613
- get durationMs(): number | undefined;
614
- get startedAt(): string;
615
- get finishedAt(): string | undefined;
616
- /**
617
- * Set the wait handler (called by TerminalCommands)
618
- * @internal
619
- */
620
- setWaitHandler(handler: (timeout?: number) => Promise<CommandDetailsResponse>): void;
621
- /**
622
- * Set the retrieve handler (called by TerminalCommands)
623
- * @internal
624
- */
625
- setRetrieveHandler(handler: () => Promise<CommandDetailsResponse>): void;
626
- /**
627
- * Wait for the command to complete
628
- * @param timeout - Optional timeout in seconds (0 = no timeout)
629
- * @returns This command with updated status
630
- */
631
- wait(timeout?: number): Promise<this>;
632
- /**
633
- * Refresh the command status from the server
634
- * @returns This command with updated status
635
- */
636
- refresh(): Promise<this>;
637
- /**
638
- * Update internal state from API response
639
- */
640
- private updateFromResponse;
641
- }
642
-
643
- /**
644
- * TerminalCommand - Resource namespace for terminal commands
645
- */
646
-
647
- /**
648
- * Command resource namespace for a terminal
649
- *
650
- * @example
651
- * ```typescript
652
- * const terminal = await sandbox.terminal.create({ pty: false });
653
- *
654
- * // Run a command
655
- * const cmd = await terminal.command.run('npm test');
656
- * console.log(cmd.stdout);
657
- *
658
- * // Run in background and wait
659
- * const cmd = await terminal.command.run('npm install', { background: true });
660
- * await cmd.wait();
661
- * console.log(cmd.exitCode);
662
- *
663
- * // List commands
664
- * const commands = await terminal.command.list();
665
- *
666
- * // Retrieve a specific command
667
- * const cmd = await terminal.command.retrieve(cmdId);
668
- * ```
669
- */
670
- declare class TerminalCommand {
671
- private terminalId;
672
- private runHandler;
673
- private listHandler;
674
- private retrieveHandler;
675
- private waitHandler;
676
- constructor(terminalId: string, handlers: {
677
- run: (command: string, background?: boolean) => Promise<CommandExecutionResponse>;
678
- list: () => Promise<CommandsListResponse>;
679
- retrieve: (cmdId: string) => Promise<CommandDetailsResponse>;
680
- wait: (cmdId: string, timeout?: number) => Promise<CommandDetailsResponse>;
681
- });
682
- /**
683
- * Run a command in the terminal
684
- * @param command - The command to execute
685
- * @param options - Execution options
686
- * @param options.background - If true, returns immediately without waiting for completion
687
- * @returns Command object with results or status
688
- */
689
- run(command: string, options?: {
690
- background?: boolean;
691
- }): Promise<Command>;
692
- /**
693
- * List all commands executed in this terminal
694
- * @returns Array of Command objects
695
- */
696
- list(): Promise<Command[]>;
697
- /**
698
- * Retrieve a specific command by ID
699
- * @param cmdId - The command ID
700
- * @returns Command object with full details
701
- */
702
- retrieve(cmdId: string): Promise<Command>;
703
131
  }
704
132
 
705
133
  /**
706
- * Terminal class for managing terminal sessions with WebSocket integration
707
- */
708
-
709
- /**
710
- * Terminal event handlers
711
- */
712
- type TerminalEventHandler = {
713
- output: (data: string) => void;
714
- error: (error: string) => void;
715
- destroyed: () => void;
716
- };
717
- /**
718
- * TerminalInstance - A connected terminal session with WebSocket support
719
- *
720
- * This is the object returned by sandbox.terminal.create()
721
- *
722
- * @example
723
- * ```typescript
724
- * // PTY mode - Interactive shell
725
- * const pty = await sandbox.terminal.create({ pty: true });
726
- * pty.on('output', (data) => console.log(data));
727
- * pty.write('ls -la\n');
728
- * await pty.destroy();
729
- *
730
- * // Exec mode - Command tracking
731
- * const exec = await sandbox.terminal.create({ pty: false });
732
- * const cmd = await exec.command.run('npm test');
733
- * console.log(cmd.exitCode);
134
+ * Compute API - Direct Provider Implementation
734
135
  *
735
- * // Background execution with wait
736
- * const cmd = await exec.command.run('npm install', { background: true });
737
- * await cmd.wait();
738
- * console.log(cmd.stdout);
739
- * ```
740
- */
741
- declare class TerminalInstance {
742
- private _id;
743
- private _pty;
744
- private _status;
745
- private _channel;
746
- private _ws;
747
- private _encoding;
748
- private _eventHandlers;
749
- /**
750
- * Command namespace for exec mode terminals
751
- */
752
- readonly command: TerminalCommand;
753
- private _executeHandler?;
754
- private _listCommandsHandler?;
755
- private _retrieveCommandHandler?;
756
- private _waitCommandHandler?;
757
- private _destroyHandler?;
758
- constructor(id: string, pty: boolean, status: 'running' | 'stopped' | 'active' | 'ready', channel: string | null, ws: WebSocketManager | null, encoding?: 'raw' | 'base64');
759
- /**
760
- * Set up WebSocket event handlers (PTY mode only)
761
- */
762
- private setupWebSocketHandlers;
763
- /**
764
- * Terminal ID
765
- */
766
- get id(): string;
767
- /**
768
- * Get terminal ID (deprecated, use .id property)
769
- * @deprecated Use .id property instead
770
- */
771
- getId(): string;
772
- /**
773
- * Terminal status
774
- */
775
- get status(): 'running' | 'stopped' | 'active' | 'ready';
776
- /**
777
- * Get terminal status (deprecated, use .status property)
778
- * @deprecated Use .status property instead
779
- */
780
- getStatus(): 'running' | 'stopped' | 'active' | 'ready';
781
- /**
782
- * Terminal channel (null for exec mode)
783
- */
784
- get channel(): string | null;
785
- /**
786
- * Get terminal channel (deprecated, use .channel property)
787
- * @deprecated Use .channel property instead
788
- */
789
- getChannel(): string | null;
790
- /**
791
- * Whether this is a PTY terminal
792
- */
793
- get pty(): boolean;
794
- /**
795
- * Get terminal PTY mode (deprecated, use .pty property)
796
- * @deprecated Use .pty property instead
797
- */
798
- isPTY(): boolean;
799
- /**
800
- * Check if terminal is running
801
- */
802
- isRunning(): boolean;
803
- /**
804
- * Write input to the terminal (PTY mode only)
805
- */
806
- write(input: string): void;
807
- /**
808
- * Resize terminal window (PTY mode only)
809
- */
810
- resize(cols: number, rows: number): void;
811
- /**
812
- * Set execute command handler (called by Sandbox)
813
- * @internal
814
- */
815
- setExecuteHandler(handler: (command: string, background?: boolean) => Promise<CommandExecutionResponse>): void;
816
- /**
817
- * Set list commands handler (called by Sandbox)
818
- * @internal
819
- */
820
- setListCommandsHandler(handler: () => Promise<CommandsListResponse>): void;
821
- /**
822
- * Set retrieve command handler (called by Sandbox)
823
- * @internal
824
- */
825
- setRetrieveCommandHandler(handler: (cmdId: string) => Promise<CommandDetailsResponse>): void;
826
- /**
827
- * Set wait command handler (called by Sandbox)
828
- * @internal
829
- */
830
- setWaitCommandHandler(handler: (cmdId: string, timeout?: number) => Promise<CommandDetailsResponse>): void;
831
- /**
832
- * Set destroy handler (called by Sandbox)
833
- * @internal
834
- */
835
- setDestroyHandler(handler: () => Promise<void>): void;
836
- /**
837
- * Execute a command in the terminal (deprecated, use command.run())
838
- * @deprecated Use terminal.command.run() instead
839
- */
840
- execute(command: string, options?: {
841
- background?: boolean;
842
- }): Promise<CommandExecutionResponse>;
843
- /**
844
- * Destroy the terminal
845
- */
846
- destroy(): Promise<void>;
847
- /**
848
- * Clean up resources
849
- */
850
- private cleanup;
851
- /**
852
- * Register event handler
853
- */
854
- on<K extends keyof TerminalEventHandler>(event: K, handler: TerminalEventHandler[K]): void;
855
- /**
856
- * Unregister event handler
857
- */
858
- off<K extends keyof TerminalEventHandler>(event: K, handler: TerminalEventHandler[K]): void;
859
- /**
860
- * Emit event to registered handlers
861
- */
862
- private emit;
863
- }
864
-
865
- /**
866
- * FileWatcher class for monitoring file system changes with WebSocket integration
136
+ * `compute` delegates to one or more configured provider instances directly.
867
137
  */
868
138
 
869
- /**
870
- * File change event data
871
- */
872
- interface FileChangeEvent {
873
- event: 'add' | 'change' | 'unlink' | 'addDir' | 'unlinkDir';
874
- path: string;
875
- content?: string;
876
- }
877
- /**
878
- * FileWatcher event handlers
879
- */
880
- type FileWatcherEventHandler = {
881
- change: (event: FileChangeEvent) => void;
882
- destroyed: () => void;
883
- };
884
- /**
885
- * FileWatcher class for monitoring file system changes
886
- *
887
- * @example
888
- * ```typescript
889
- * const client = new ComputeClient({ sandboxUrl: '...' });
890
- * await client.generateToken();
891
- *
892
- * const watcher = await client.createWatcher('/home/project', {
893
- * ignored: ['node_modules', '.git']
894
- * });
895
- *
896
- * watcher.on('change', (event) => {
897
- * console.log(`File ${event.event}: ${event.path}`);
898
- * });
899
- *
900
- * await watcher.destroy();
901
- * ```
902
- */
903
- declare class FileWatcher {
904
- private id;
905
- private path;
906
- private status;
907
- private channel;
908
- private includeContent;
909
- private ignored;
910
- private encoding;
911
- private ws;
912
- private eventHandlers;
913
- constructor(id: string, path: string, status: 'active' | 'stopped', channel: string, includeContent: boolean, ignored: string[], ws: WebSocketManager, encoding?: 'raw' | 'base64');
914
- /**
915
- * Set up WebSocket event handlers
916
- */
917
- private setupWebSocketHandlers;
918
- /**
919
- * Get watcher ID
920
- */
921
- getId(): string;
922
- /**
923
- * Get watched path
924
- */
925
- getPath(): string;
926
- /**
927
- * Get watcher status
928
- */
929
- getStatus(): 'active' | 'stopped';
930
- /**
931
- * Get watcher channel
932
- */
933
- getChannel(): string;
934
- /**
935
- * Check if content is included in events
936
- */
937
- isIncludingContent(): boolean;
938
- /**
939
- * Get ignored patterns
940
- */
941
- getIgnoredPatterns(): string[];
942
- /**
943
- * Check if watcher is active
944
- */
945
- isActive(): boolean;
946
- /**
947
- * Destroy the watcher (uses REST API, not WebSocket)
948
- */
949
- private destroyWatcher?;
950
- /**
951
- * Set destroy handler (called by client)
952
- */
953
- setDestroyHandler(handler: () => Promise<void>): void;
954
- /**
955
- * Destroy the watcher
956
- */
957
- destroy(): Promise<void>;
958
- /**
959
- * Clean up resources
960
- */
961
- private cleanup;
962
- /**
963
- * Register event handler
964
- */
965
- on<K extends keyof FileWatcherEventHandler>(event: K, handler: FileWatcherEventHandler[K]): void;
966
- /**
967
- * Unregister event handler
968
- */
969
- off<K extends keyof FileWatcherEventHandler>(event: K, handler: FileWatcherEventHandler[K]): void;
970
- /**
971
- * Emit event to registered handlers
972
- */
973
- private emit;
974
- }
975
-
976
- /**
977
- * SignalService class for monitoring system signals with WebSocket integration
978
- */
979
-
980
- /**
981
- * Port signal data
982
- */
983
- interface PortSignalEvent {
984
- signal: 'port' | 'server-ready';
985
- port: number;
986
- url: string;
987
- type?: 'open' | 'close';
988
- }
989
- /**
990
- * Error signal data
991
- */
992
- interface ErrorSignalEvent {
993
- signal: 'error';
994
- message: string;
995
- }
996
- /**
997
- * Generic signal event (union type)
998
- */
999
- type SignalEvent = PortSignalEvent | ErrorSignalEvent;
1000
- /**
1001
- * SignalService event handlers
1002
- */
1003
- type SignalServiceEventHandler = {
1004
- port: (event: PortSignalEvent) => void;
1005
- error: (event: ErrorSignalEvent) => void;
1006
- signal: (event: SignalEvent) => void;
1007
- };
1008
- /**
1009
- * SignalService class for monitoring system signals and events
1010
- *
1011
- * @example
1012
- * ```typescript
1013
- * const client = new ComputeClient({ sandboxUrl: '...' });
1014
- * await client.generateToken();
1015
- *
1016
- * const signals = await client.startSignals();
1017
- *
1018
- * signals.on('port', (event) => {
1019
- * console.log(`Port ${event.port} ${event.type}: ${event.url}`);
1020
- * });
1021
- *
1022
- * signals.on('error', (event) => {
1023
- * console.error(`Error: ${event.message}`);
1024
- * });
1025
- *
1026
- * await signals.stop();
1027
- * ```
1028
- */
1029
- declare class SignalService {
1030
- private status;
1031
- private channel;
1032
- private ws;
1033
- private eventHandlers;
1034
- constructor(status: 'active' | 'stopped', channel: string, ws: WebSocketManager);
1035
- /**
1036
- * Set up WebSocket event handlers
1037
- */
1038
- private setupWebSocketHandlers;
1039
- /**
1040
- * Get service status
1041
- */
1042
- getStatus(): 'active' | 'stopped';
1043
- /**
1044
- * Get service channel
1045
- */
1046
- getChannel(): string;
1047
- /**
1048
- * Check if service is active
1049
- */
1050
- isActive(): boolean;
1051
- /**
1052
- * Stop the signal service (uses REST API, not WebSocket)
1053
- */
1054
- private stopService?;
1055
- /**
1056
- * Set stop handler (called by client)
1057
- */
1058
- setStopHandler(handler: () => Promise<void>): void;
1059
- /**
1060
- * Stop the signal service
1061
- */
1062
- stop(): Promise<void>;
1063
- /**
1064
- * Clean up resources
1065
- */
1066
- private cleanup;
1067
- /**
1068
- * Register event handler
1069
- */
1070
- on<K extends keyof SignalServiceEventHandler>(event: K, handler: SignalServiceEventHandler[K]): void;
1071
- /**
1072
- * Unregister event handler
1073
- */
1074
- off<K extends keyof SignalServiceEventHandler>(event: K, handler: SignalServiceEventHandler[K]): void;
1075
- /**
1076
- * Emit event to registered handlers
1077
- */
1078
- private emit;
1079
- }
1080
-
1081
- /**
1082
- * Terminal - Resource namespace for terminal management
1083
- */
1084
-
1085
- /**
1086
- * Terminal resource namespace
1087
- *
1088
- * @example
1089
- * ```typescript
1090
- * // Create a PTY terminal (interactive shell)
1091
- * const pty = await sandbox.terminal.create({ pty: true, shell: '/bin/bash' });
1092
- * pty.on('output', (data) => console.log(data));
1093
- * pty.write('ls -la\n');
1094
- *
1095
- * // Create an exec terminal (command tracking)
1096
- * const exec = await sandbox.terminal.create({ pty: false });
1097
- * const cmd = await exec.command.run('npm test');
1098
- * console.log(cmd.exitCode);
1099
- *
1100
- * // List all terminals
1101
- * const terminals = await sandbox.terminal.list();
1102
- *
1103
- * // Retrieve a specific terminal
1104
- * const terminal = await sandbox.terminal.retrieve(id);
1105
- *
1106
- * // Destroy a terminal
1107
- * await sandbox.terminal.destroy(id);
1108
- * ```
1109
- */
1110
- declare class Terminal {
1111
- private createHandler;
1112
- private listHandler;
1113
- private retrieveHandler;
1114
- private destroyHandler;
1115
- constructor(handlers: {
1116
- create: (options?: {
1117
- shell?: string;
1118
- encoding?: 'raw' | 'base64';
1119
- pty?: boolean;
1120
- }) => Promise<TerminalInstance>;
1121
- list: () => Promise<TerminalResponse[]>;
1122
- retrieve: (id: string) => Promise<TerminalInstance>;
1123
- destroy: (id: string) => Promise<void>;
1124
- });
1125
- /**
1126
- * Create a new terminal session
1127
- *
1128
- * @param options - Terminal creation options
1129
- * @param options.shell - Shell to use (e.g., '/bin/bash') - PTY mode only
1130
- * @param options.encoding - Encoding: 'raw' (default) or 'base64' (binary-safe)
1131
- * @param options.pty - Terminal mode: true = PTY (interactive), false = exec (command tracking)
1132
- * @returns TerminalInstance
1133
- */
1134
- create(options?: {
1135
- shell?: string;
1136
- encoding?: 'raw' | 'base64';
1137
- pty?: boolean;
1138
- }): Promise<TerminalInstance>;
1139
- /**
1140
- * List all active terminals
1141
- * @returns Array of terminal responses
1142
- */
1143
- list(): Promise<TerminalResponse[]>;
1144
- /**
1145
- * Retrieve a specific terminal by ID
1146
- * @param id - The terminal ID
1147
- * @returns Terminal instance
1148
- */
1149
- retrieve(id: string): Promise<TerminalInstance>;
1150
- /**
1151
- * Destroy a terminal by ID
1152
- * @param id - The terminal ID
1153
- */
1154
- destroy(id: string): Promise<void>;
1155
- }
1156
-
1157
- /**
1158
- * Overlay - Resource namespace for filesystem overlay operations
1159
- *
1160
- * Overlays enable instant sandbox setup from template directories by copying
1161
- * files directly for isolation, with heavy directories copied in the background.
1162
- */
1163
- /**
1164
- * Options for waiting for overlay copy completion
1165
- */
1166
- interface WaitForCompletionOptions {
1167
- /** Maximum number of retry attempts (default: 60) */
1168
- maxRetries?: number;
1169
- /** Initial delay between retries in milliseconds (default: 500) */
1170
- initialDelayMs?: number;
1171
- /** Maximum delay between retries in milliseconds (default: 5000) */
1172
- maxDelayMs?: number;
1173
- /** Backoff multiplier for exponential backoff (default: 1.5) */
1174
- backoffFactor?: number;
1175
- }
1176
- /**
1177
- * Strategy for creating an overlay
1178
- * - 'copy': Full copy of all files (standard behavior)
1179
- * - 'smart': Use symlinks for immutable packages (e.g. node_modules) for instant creation
1180
- */
1181
- type OverlayStrategy = 'copy' | 'smart';
1182
- /**
1183
- * Options for creating an overlay
1184
- */
1185
- interface CreateOverlayOptions {
1186
- /** Absolute path to source directory (template) */
1187
- source: string;
1188
- /** Relative path in sandbox where overlay will be mounted */
1189
- target: string;
1190
- /** Glob patterns to ignore (e.g., ["node_modules", "*.log"]) */
1191
- ignore?: string[];
1192
- /** Strategy to use (default: 'smart') */
1193
- strategy?: OverlayStrategy;
1194
- /** If true, wait for background copy to complete before returning (default: false) */
1195
- waitForCompletion?: boolean | WaitForCompletionOptions;
1196
- }
1197
- /**
1198
- * Copy status for overlay background operations
1199
- */
1200
- type OverlayCopyStatus = 'pending' | 'in_progress' | 'complete' | 'failed';
1201
- /**
1202
- * Statistics about an overlay
1203
- */
1204
- interface OverlayStats {
1205
- /** Number of copied files */
1206
- copiedFiles: number;
1207
- /** Number of copied directories (heavy dirs copied in background) */
1208
- copiedDirs: number;
1209
- /** Paths that were skipped (e.g., .git, ignored patterns) */
1210
- skipped: string[];
1211
- }
1212
- /**
1213
- * Overlay information (client-side normalized type)
1214
- */
1215
- interface OverlayInfo {
1216
- /** Unique overlay identifier */
1217
- id: string;
1218
- /** Absolute path to source directory */
1219
- source: string;
1220
- /** Relative path in sandbox */
1221
- target: string;
1222
- /** Strategy used for the overlay */
1223
- strategy: OverlayStrategy;
1224
- /** When the overlay was created */
1225
- createdAt: string;
1226
- /** Statistics about the overlay */
1227
- stats: OverlayStats;
1228
- /** Copy status for background operations */
1229
- copyStatus: OverlayCopyStatus;
1230
- /** Error message if copy failed */
1231
- copyError?: string;
1232
- }
1233
- /**
1234
- * API response for overlay operations (snake_case from server)
1235
- */
1236
- interface OverlayResponse {
1237
- id: string;
1238
- source: string;
1239
- target: string;
1240
- strategy?: string;
1241
- created_at: string;
1242
- stats: {
1243
- copied_files: number;
1244
- copied_dirs: number;
1245
- skipped: string[];
1246
- };
1247
- copy_status: string;
1248
- copy_error?: string;
1249
- }
1250
- /**
1251
- * API response for listing overlays
1252
- */
1253
- interface OverlayListResponse {
1254
- overlays: OverlayResponse[];
1255
- }
1256
- /**
1257
- * Overlay resource namespace
1258
- *
1259
- * @example
1260
- * ```typescript
1261
- * // Create an overlay from a template directory
1262
- * const overlay = await sandbox.filesystem.overlay.create({
1263
- * source: '/templates/nextjs',
1264
- * target: 'project',
1265
- * });
1266
- * console.log(overlay.copyStatus); // 'pending' | 'in_progress' | 'complete' | 'failed'
1267
- *
1268
- * // Create an overlay and wait for background copy to complete
1269
- * const overlay = await sandbox.filesystem.overlay.create({
1270
- * source: '/templates/nextjs',
1271
- * target: 'project',
1272
- * waitForCompletion: true, // blocks until copy is complete
1273
- * });
1274
- *
1275
- * // Wait for an existing overlay's copy to complete
1276
- * const overlay = await sandbox.filesystem.overlay.waitForCompletion('overlay-id');
1277
- *
1278
- * // List all overlays
1279
- * const overlays = await sandbox.filesystem.overlay.list();
1280
- *
1281
- * // Get a specific overlay (useful for polling copy status)
1282
- * const overlay = await sandbox.filesystem.overlay.retrieve('overlay-id');
1283
- * if (overlay.copyStatus === 'complete') {
1284
- * console.log('Background copy finished!');
1285
- * }
1286
- *
1287
- * // Delete an overlay
1288
- * await sandbox.filesystem.overlay.destroy('overlay-id');
1289
- * ```
1290
- */
1291
- declare class Overlay {
1292
- private createHandler;
1293
- private listHandler;
1294
- private retrieveHandler;
1295
- private destroyHandler;
1296
- constructor(handlers: {
1297
- create: (options: CreateOverlayOptions) => Promise<OverlayResponse>;
1298
- list: () => Promise<OverlayListResponse>;
1299
- retrieve: (id: string) => Promise<OverlayResponse>;
1300
- destroy: (id: string) => Promise<void>;
1301
- });
1302
- /**
1303
- * Create a new overlay from a template directory
1304
- *
1305
- * The overlay copies files from the source directory into the target path
1306
- * for better isolation. Heavy directories (node_modules, .venv, etc.) are
1307
- * copied in the background. Use the `ignore` option to exclude files/directories.
1308
- *
1309
- * @param options - Overlay creation options
1310
- * @param options.source - Absolute path to source directory
1311
- * @param options.target - Relative path in sandbox
1312
- * @param options.ignore - Glob patterns to ignore (e.g., ["node_modules", "*.log"])
1313
- * @param options.strategy - Strategy to use ('copy' or 'smart')
1314
- * @param options.waitForCompletion - If true or options object, wait for background copy to complete
1315
- * @returns Overlay info with copy status
1316
- */
1317
- create(options: CreateOverlayOptions): Promise<OverlayInfo>;
1318
- /**
1319
- * List all overlays for the current sandbox
1320
- * @returns Array of overlay info
1321
- */
1322
- list(): Promise<OverlayInfo[]>;
1323
- /**
1324
- * Retrieve a specific overlay by ID
1325
- *
1326
- * Useful for polling the copy status of an overlay.
1327
- *
1328
- * @param id - Overlay ID
1329
- * @returns Overlay info
1330
- */
1331
- retrieve(id: string): Promise<OverlayInfo>;
1332
- /**
1333
- * Destroy (delete) an overlay
1334
- * @param id - Overlay ID
1335
- */
1336
- destroy(id: string): Promise<void>;
1337
- /**
1338
- * Wait for an overlay's background copy to complete
1339
- *
1340
- * Polls the overlay status with exponential backoff until the copy
1341
- * is complete or fails. Throws an error if the copy fails or times out.
1342
- *
1343
- * @param id - Overlay ID
1344
- * @param options - Polling options
1345
- * @returns Overlay info with final copy status
1346
- * @throws Error if copy fails or times out
1347
- */
1348
- waitForCompletion(id: string, options?: WaitForCompletionOptions): Promise<OverlayInfo>;
1349
- /**
1350
- * Convert API response to OverlayInfo
1351
- */
1352
- private toOverlayInfo;
1353
- /**
1354
- * Validate and return strategy, defaulting to 'copy' for unknown/missing values (legacy support)
1355
- */
1356
- private validateStrategy;
1357
- /**
1358
- * Validate and return copy status, defaulting to 'pending' for unknown values
1359
- */
1360
- private validateCopyStatus;
1361
- }
1362
-
1363
- /**
1364
- * Server - Resource namespace for managed server operations
1365
- */
1366
-
1367
- /**
1368
- * Options for starting a managed server
1369
- */
1370
- interface ServerStartOptions {
1371
- /** Unique server identifier (URL-safe) */
1372
- slug: string;
1373
- /** Install command to run before starting (optional, runs blocking, e.g., "npm install") */
1374
- install?: string;
1375
- /** Command to start the server (e.g., "npm run dev") */
1376
- start: string;
1377
- /** Working directory (optional) */
1378
- path?: string;
1379
- /** Path to .env file relative to path (optional) */
1380
- env_file?: string;
1381
- /** Inline environment variables (merged with env_file if both provided) */
1382
- environment?: Record<string, string>;
1383
- /** Requested port number (preallocated before start) */
1384
- port?: number;
1385
- /** If true, fail instead of auto-incrementing when port is taken */
1386
- strict_port?: boolean;
1387
- /** Whether to auto-start the server on daemon boot (default: true) */
1388
- autostart?: boolean;
1389
- /** Inline overlay to create before starting the server */
1390
- overlay?: Omit<CreateOverlayOptions, 'waitForCompletion'>;
1391
- /** Additional overlays to create before starting the server */
1392
- overlays?: Array<Omit<CreateOverlayOptions, 'waitForCompletion'>>;
1393
- /** Overlay IDs this server depends on (waits for copy completion) */
1394
- depends_on?: string[];
1395
- /**
1396
- * When to automatically restart the server:
1397
- * - `never`: No automatic restart (default)
1398
- * - `on-failure`: Restart only on non-zero exit code
1399
- * - `always`: Always restart on exit (including exit code 0)
1400
- */
1401
- restart_policy?: RestartPolicy;
1402
- /** Maximum restart attempts (0 = unlimited, default: 0) */
1403
- max_restarts?: number;
1404
- /** Delay between restart attempts in milliseconds (default: 1000) */
1405
- restart_delay_ms?: number;
1406
- /** Graceful shutdown timeout in milliseconds - SIGTERM → wait → SIGKILL (default: 10000) */
1407
- stop_timeout_ms?: number;
1408
- /**
1409
- * Health check configuration for monitoring server availability
1410
- * When configured, the server will be polled to verify it's responding to requests
1411
- */
1412
- health_check?: HealthCheckConfig;
1413
- }
1414
- /**
1415
- * Server resource namespace
1416
- *
1417
- * @example
1418
- * ```typescript
1419
- * // Start a basic server
1420
- * const server = await sandbox.server.start({
1421
- * slug: 'api',
1422
- * start: 'npm start',
1423
- * path: '/app',
1424
- * });
1425
- *
1426
- * // Start with install command (runs before start)
1427
- * const server = await sandbox.server.start({
1428
- * slug: 'web',
1429
- * install: 'npm install',
1430
- * start: 'npm run dev',
1431
- * path: '/app',
1432
- * });
1433
- *
1434
- * // Start with supervisor settings (auto-restart on failure)
1435
- * const server = await sandbox.server.start({
1436
- * slug: 'web',
1437
- * start: 'node server.js',
1438
- * path: '/app',
1439
- * environment: { NODE_ENV: 'production', PORT: '3000' },
1440
- * restart_policy: 'on-failure',
1441
- * max_restarts: 5,
1442
- * restart_delay_ms: 2000,
1443
- * });
1444
- *
1445
- * // Start with inline overlay dependencies
1446
- * const server = await sandbox.server.start({
1447
- * slug: 'web',
1448
- * start: 'npm run dev',
1449
- * path: '/app',
1450
- * overlay: {
1451
- * source: '/templates/nextjs',
1452
- * target: 'app',
1453
- * strategy: 'smart',
1454
- * },
1455
- * });
1456
- *
1457
- * // List all servers
1458
- * const servers = await sandbox.server.list();
1459
- *
1460
- * // Retrieve a specific server
1461
- * const server = await sandbox.server.retrieve('api');
1462
- *
1463
- * // Stop a server (graceful shutdown with SIGTERM → SIGKILL)
1464
- * await sandbox.server.stop('api');
1465
- *
1466
- * // Delete a server config
1467
- * await sandbox.server.delete('api');
1468
- *
1469
- * // Restart a server
1470
- * await sandbox.server.restart('api');
1471
- * ```
1472
- */
1473
- /**
1474
- * Options for retrieving server logs
1475
- */
1476
- interface ServerLogsOptions {
1477
- /** Which output stream to return: 'stdout', 'stderr', or 'combined' (default) */
1478
- stream?: ServerLogStream;
1479
- }
1480
- /**
1481
- * Server logs info returned from the logs method
1482
- */
1483
- interface ServerLogsInfo {
1484
- /** Server slug identifier */
1485
- slug: string;
1486
- /** Which stream was returned */
1487
- stream: ServerLogStream;
1488
- /** The captured logs */
1489
- logs: string;
1490
- }
1491
- declare class Server {
1492
- private startHandler;
1493
- private listHandler;
1494
- private retrieveHandler;
1495
- private stopHandler;
1496
- private deleteHandler;
1497
- private restartHandler;
1498
- private updateStatusHandler;
1499
- private logsHandler;
1500
- constructor(handlers: {
1501
- start: (options: ServerStartOptions) => Promise<ServerResponse>;
1502
- list: () => Promise<ServersListResponse>;
1503
- retrieve: (slug: string) => Promise<ServerResponse>;
1504
- stop: (slug: string) => Promise<ServerStopResponse | void>;
1505
- delete: (slug: string) => Promise<void>;
1506
- restart: (slug: string) => Promise<ServerResponse>;
1507
- updateStatus: (slug: string, status: ServerStatus) => Promise<void>;
1508
- logs: (slug: string, options?: ServerLogsOptions) => Promise<ServerLogsResponse>;
1509
- });
1510
- /**
1511
- * Start a new managed server with optional supervisor settings
1512
- *
1513
- * **Install Phase:**
1514
- * If `install` is provided, it runs blocking before `start` (e.g., "npm install").
1515
- * The server status will be `installing` during this phase.
1516
- *
1517
- * **Restart Policies:**
1518
- * - `never` (default): No automatic restart on exit
1519
- * - `on-failure`: Restart only on non-zero exit code
1520
- * - `always`: Always restart on exit (including exit code 0)
1521
- *
1522
- * **Graceful Shutdown:**
1523
- * When stopping a server, it first sends SIGTERM and waits for `stop_timeout_ms`
1524
- * before sending SIGKILL if the process hasn't exited.
1525
- *
1526
- * @param options - Server configuration
1527
- * @returns Server info
1528
- *
1529
- * @example
1530
- * ```typescript
1531
- * // Basic server
1532
- * const server = await sandbox.server.start({
1533
- * slug: 'web',
1534
- * start: 'npm run dev',
1535
- * path: '/app',
1536
- * });
1537
- *
1538
- * // With install command
1539
- * const server = await sandbox.server.start({
1540
- * slug: 'api',
1541
- * install: 'npm install',
1542
- * start: 'node server.js',
1543
- * environment: { NODE_ENV: 'production' },
1544
- * restart_policy: 'always',
1545
- * max_restarts: 0, // unlimited
1546
- * });
1547
- * ```
1548
- */
1549
- start(options: ServerStartOptions): Promise<ServerInfo>;
1550
- /**
1551
- * List all managed servers
1552
- * @returns Array of server info
1553
- */
1554
- list(): Promise<ServerInfo[]>;
1555
- /**
1556
- * Retrieve a specific server by slug
1557
- * @param slug - The server slug
1558
- * @returns Server info
1559
- */
1560
- retrieve(slug: string): Promise<ServerInfo>;
1561
- /**
1562
- * Stop a server by slug (non-destructive)
1563
- * @param slug - The server slug
1564
- */
1565
- stop(slug: string): Promise<void>;
1566
- /**
1567
- * Delete a server config by slug (stops + removes persistence)
1568
- * @param slug - The server slug
1569
- */
1570
- delete(slug: string): Promise<void>;
1571
- /**
1572
- * Restart a server by slug
1573
- * @param slug - The server slug
1574
- * @returns Server info
1575
- */
1576
- restart(slug: string): Promise<ServerInfo>;
1577
- /**
1578
- * Update server status (internal use)
1579
- * @param slug - The server slug
1580
- * @param status - New status
1581
- */
1582
- updateStatus(slug: string, status: ServerStatus): Promise<void>;
1583
- /**
1584
- * Retrieve captured output (logs) for a managed server
1585
- * @param slug - The server slug
1586
- * @param options - Options for log retrieval
1587
- * @returns Server logs info
1588
- *
1589
- * @example
1590
- * ```typescript
1591
- * // Get combined logs (default)
1592
- * const logs = await sandbox.server.logs('api');
1593
- * console.log(logs.logs);
1594
- *
1595
- * // Get only stdout
1596
- * const stdout = await sandbox.server.logs('api', { stream: 'stdout' });
1597
- *
1598
- * // Get only stderr
1599
- * const stderr = await sandbox.server.logs('api', { stream: 'stderr' });
1600
- * ```
1601
- */
1602
- logs(slug: string, options?: ServerLogsOptions): Promise<ServerLogsInfo>;
1603
- }
1604
-
1605
- /**
1606
- * Watcher - Resource namespace for file watcher operations
1607
- */
1608
-
1609
- /**
1610
- * Watcher resource namespace
1611
- *
1612
- * @example
1613
- * ```typescript
1614
- * // Create a file watcher
1615
- * const watcher = await sandbox.watcher.create('/project', {
1616
- * ignored: ['node_modules', '.git'],
1617
- * includeContent: true,
1618
- * });
1619
- * watcher.on('change', (event) => {
1620
- * console.log(`${event.event}: ${event.path}`);
1621
- * });
1622
- *
1623
- * // List all watchers
1624
- * const watchers = await sandbox.watcher.list();
1625
- *
1626
- * // Retrieve a specific watcher
1627
- * const watcher = await sandbox.watcher.retrieve(id);
1628
- *
1629
- * // Destroy a watcher
1630
- * await sandbox.watcher.destroy(id);
1631
- * ```
1632
- */
1633
- declare class Watcher {
1634
- private createHandler;
1635
- private listHandler;
1636
- private retrieveHandler;
1637
- private destroyHandler;
1638
- constructor(handlers: {
1639
- create: (path: string, options?: {
1640
- includeContent?: boolean;
1641
- ignored?: string[];
1642
- encoding?: 'raw' | 'base64';
1643
- }) => Promise<FileWatcher>;
1644
- list: () => Promise<WatchersListResponse>;
1645
- retrieve: (id: string) => Promise<WatcherResponse>;
1646
- destroy: (id: string) => Promise<void>;
1647
- });
1648
- /**
1649
- * Create a new file watcher
1650
- * @param path - Path to watch
1651
- * @param options - Watcher options
1652
- * @param options.includeContent - Include file content in change events
1653
- * @param options.ignored - Patterns to ignore
1654
- * @param options.encoding - Encoding: 'raw' (default) or 'base64' (binary-safe)
1655
- * @returns FileWatcher instance
1656
- */
1657
- create(path: string, options?: {
1658
- includeContent?: boolean;
1659
- ignored?: string[];
1660
- encoding?: 'raw' | 'base64';
1661
- }): Promise<FileWatcher>;
1662
- /**
1663
- * List all active file watchers
1664
- * @returns Array of watcher info
1665
- */
1666
- list(): Promise<WatcherInfo[]>;
1667
- /**
1668
- * Retrieve a specific watcher by ID
1669
- * @param id - The watcher ID
1670
- * @returns Watcher info
1671
- */
1672
- retrieve(id: string): Promise<WatcherInfo>;
1673
- /**
1674
- * Destroy a watcher by ID
1675
- * @param id - The watcher ID
1676
- */
1677
- destroy(id: string): Promise<void>;
1678
- }
1679
-
1680
- /**
1681
- * SessionToken - Resource namespace for session token management
1682
- */
1683
-
1684
- /**
1685
- * Session token info
1686
- */
1687
- interface SessionTokenInfo {
1688
- id: string;
1689
- token?: string;
1690
- description?: string;
1691
- createdAt: string;
1692
- expiresAt: string;
1693
- lastUsedAt?: string;
1694
- }
1695
- /**
1696
- * SessionToken resource namespace
1697
- *
1698
- * @example
1699
- * ```typescript
1700
- * // Create a session token (requires access token)
1701
- * const token = await sandbox.sessionToken.create({
1702
- * description: 'My Application',
1703
- * expiresIn: 604800, // 7 days
1704
- * });
1705
- * console.log(token.token);
1706
- *
1707
- * // List all session tokens
1708
- * const tokens = await sandbox.sessionToken.list();
1709
- *
1710
- * // Retrieve a specific token
1711
- * const token = await sandbox.sessionToken.retrieve(id);
1712
- *
1713
- * // Revoke a token
1714
- * await sandbox.sessionToken.revoke(id);
1715
- * ```
1716
- */
1717
- declare class SessionToken {
1718
- private createHandler;
1719
- private listHandler;
1720
- private retrieveHandler;
1721
- private revokeHandler;
1722
- constructor(handlers: {
1723
- create: (options?: {
1724
- description?: string;
1725
- expiresIn?: number;
1726
- }) => Promise<SessionTokenResponse>;
1727
- list: () => Promise<SessionTokenListResponse>;
1728
- retrieve: (id: string) => Promise<SessionTokenResponse>;
1729
- revoke: (id: string) => Promise<void>;
1730
- });
1731
- /**
1732
- * Create a new session token (requires access token)
1733
- * @param options - Token configuration
1734
- * @param options.description - Description for the token
1735
- * @param options.expiresIn - Expiration time in seconds (default: 7 days)
1736
- * @returns Session token info including the token value
1737
- */
1738
- create(options?: {
1739
- description?: string;
1740
- expiresIn?: number;
1741
- }): Promise<SessionTokenInfo>;
1742
- /**
1743
- * List all session tokens
1744
- * @returns Array of session token info
1745
- */
1746
- list(): Promise<SessionTokenInfo[]>;
1747
- /**
1748
- * Retrieve a specific session token by ID
1749
- * @param id - The token ID
1750
- * @returns Session token info
1751
- */
1752
- retrieve(id: string): Promise<SessionTokenInfo>;
1753
- /**
1754
- * Revoke a session token
1755
- * @param id - The token ID to revoke
1756
- */
1757
- revoke(id: string): Promise<void>;
1758
- }
1759
-
1760
- /**
1761
- * MagicLink - Resource namespace for magic link operations
1762
- */
1763
-
1764
- /**
1765
- * Magic link info
1766
- */
1767
- interface MagicLinkInfo {
1768
- url: string;
1769
- expiresAt: string;
1770
- redirectUrl: string;
1771
- }
1772
- /**
1773
- * MagicLink resource namespace
1774
- *
1775
- * @example
1776
- * ```typescript
1777
- * // Create a magic link (requires access token)
1778
- * const link = await sandbox.magicLink.create({
1779
- * redirectUrl: '/dashboard',
1780
- * });
1781
- * console.log(link.url);
1782
- * ```
1783
- */
1784
- declare class MagicLink {
1785
- private createHandler;
1786
- constructor(handlers: {
1787
- create: (options?: {
1788
- redirectUrl?: string;
1789
- }) => Promise<MagicLinkResponse>;
1790
- });
1791
- /**
1792
- * Create a magic link for browser authentication (requires access token)
1793
- *
1794
- * Magic links are one-time URLs that automatically create a session token
1795
- * and set it as a cookie in the user's browser.
1796
- *
1797
- * @param options - Magic link configuration
1798
- * @param options.redirectUrl - URL to redirect to after authentication
1799
- * @returns Magic link info including the URL
1800
- */
1801
- create(options?: {
1802
- redirectUrl?: string;
1803
- }): Promise<MagicLinkInfo>;
1804
- }
1805
-
1806
- /**
1807
- * Signal - Resource namespace for signal service operations
1808
- */
1809
-
1810
- /**
1811
- * Signal service status info
1812
- */
1813
- interface SignalStatusInfo {
1814
- status: 'active' | 'stopped';
1815
- channel: string;
1816
- wsUrl: string;
1817
- }
1818
- /**
1819
- * Signal resource namespace
1820
- *
1821
- * @example
1822
- * ```typescript
1823
- * // Start the signal service
1824
- * const signals = await sandbox.signal.start();
1825
- * signals.on('port', (event) => {
1826
- * console.log(`Port ${event.port} opened: ${event.url}`);
1827
- * });
1828
- *
1829
- * // Get signal service status
1830
- * const status = await sandbox.signal.status();
1831
- *
1832
- * // Emit signals
1833
- * await sandbox.signal.emitPort(3000, 'open', 'http://localhost:3000');
1834
- * await sandbox.signal.emitError('Something went wrong');
1835
- *
1836
- * // Stop the signal service
1837
- * await sandbox.signal.stop();
1838
- * ```
1839
- */
1840
- declare class Signal {
1841
- private startHandler;
1842
- private statusHandler;
1843
- private stopHandler;
1844
- private emitPortHandler;
1845
- private emitErrorHandler;
1846
- private emitServerReadyHandler;
1847
- constructor(handlers: {
1848
- start: () => Promise<SignalService>;
1849
- status: () => Promise<SignalServiceResponse>;
1850
- stop: () => Promise<void>;
1851
- emitPort: (port: number, type: 'open' | 'close', url: string) => Promise<PortSignalResponse>;
1852
- emitError: (message: string) => Promise<GenericSignalResponse>;
1853
- emitServerReady: (port: number, url: string) => Promise<PortSignalResponse>;
1854
- });
1855
- /**
1856
- * Start the signal service
1857
- * @returns SignalService instance with event handling
1858
- */
1859
- start(): Promise<SignalService>;
1860
- /**
1861
- * Get the signal service status
1862
- * @returns Signal service status info
1863
- */
1864
- status(): Promise<SignalStatusInfo>;
1865
- /**
1866
- * Stop the signal service
1867
- */
1868
- stop(): Promise<void>;
1869
- /**
1870
- * Emit a port signal
1871
- * @param port - Port number
1872
- * @param type - Signal type ('open' or 'close')
1873
- * @param url - URL associated with the port
1874
- */
1875
- emitPort(port: number, type: 'open' | 'close', url: string): Promise<void>;
1876
- /**
1877
- * Emit an error signal
1878
- * @param message - Error message
1879
- */
1880
- emitError(message: string): Promise<void>;
1881
- /**
1882
- * Emit a server ready signal
1883
- * @param port - Port number
1884
- * @param url - Server URL
1885
- */
1886
- emitServerReady(port: number, url: string): Promise<void>;
1887
- }
1888
-
1889
- /**
1890
- * File - Resource namespace for file operations
1891
- */
1892
-
1893
- /**
1894
- * File resource namespace
1895
- *
1896
- * @example
1897
- * ```typescript
1898
- * // Create a file
1899
- * const file = await sandbox.file.create('/project/hello.txt', 'Hello, World!');
1900
- *
1901
- * // List files in a directory
1902
- * const files = await sandbox.file.list('/project');
1903
- *
1904
- * // Retrieve file content
1905
- * const content = await sandbox.file.retrieve('/project/hello.txt');
1906
- *
1907
- * // Destroy (delete) a file
1908
- * await sandbox.file.destroy('/project/hello.txt');
1909
- *
1910
- * // Batch write multiple files
1911
- * const results = await sandbox.file.batchWrite([
1912
- * { path: '/project/a.txt', operation: 'write', content: 'A' },
1913
- * { path: '/project/b.txt', operation: 'write', content: 'B' },
1914
- * ]);
1915
- *
1916
- * // Batch delete files
1917
- * const results = await sandbox.file.batchWrite([
1918
- * { path: '/project/old.txt', operation: 'delete' },
1919
- * ]);
1920
- * ```
1921
- */
1922
- declare class File {
1923
- private createHandler;
1924
- private listHandler;
1925
- private retrieveHandler;
1926
- private destroyHandler;
1927
- private batchWriteHandler;
1928
- private existsHandler;
1929
- constructor(handlers: {
1930
- create: (path: string, content?: string) => Promise<FileResponse>;
1931
- list: (path: string) => Promise<FilesListResponse>;
1932
- retrieve: (path: string) => Promise<string>;
1933
- destroy: (path: string) => Promise<void>;
1934
- batchWrite: (files: Array<{
1935
- path: string;
1936
- operation: BatchFileOperation;
1937
- content?: string;
1938
- }>) => Promise<BatchWriteResponse>;
1939
- exists: (path: string) => Promise<boolean>;
1940
- });
1941
- /**
1942
- * Create a new file with optional content
1943
- * @param path - File path
1944
- * @param content - File content (optional)
1945
- * @returns File info
1946
- */
1947
- create(path: string, content?: string): Promise<FileInfo>;
1948
- /**
1949
- * List files at the specified path
1950
- * @param path - Directory path (default: '/')
1951
- * @returns Array of file info
1952
- */
1953
- list(path?: string): Promise<FileInfo[]>;
1954
- /**
1955
- * Retrieve file content
1956
- * @param path - File path
1957
- * @returns File content as string
1958
- */
1959
- retrieve(path: string): Promise<string>;
1960
- /**
1961
- * Destroy (delete) a file or directory
1962
- * @param path - File or directory path
1963
- */
1964
- destroy(path: string): Promise<void>;
1965
- /**
1966
- * Batch file operations (write or delete multiple files)
1967
- *
1968
- * Features:
1969
- * - Deduplication: Last operation wins per path
1970
- * - File locking: Prevents race conditions
1971
- * - Deterministic ordering: Alphabetical path sorting
1972
- * - Partial failure handling: Returns per-file results
1973
- *
1974
- * @param files - Array of file operations
1975
- * @returns Results for each file operation
1976
- */
1977
- batchWrite(files: Array<{
1978
- path: string;
1979
- operation: BatchFileOperation;
1980
- content?: string;
1981
- }>): Promise<BatchWriteResult[]>;
1982
- /**
1983
- * Check if a file exists
1984
- * @param path - File path
1985
- * @returns True if file exists
1986
- */
1987
- exists(path: string): Promise<boolean>;
1988
- }
1989
-
1990
- /**
1991
- * Env - Resource namespace for environment variable operations
1992
- */
1993
-
1994
- /**
1995
- * Env resource namespace
1996
- *
1997
- * @example
1998
- * ```typescript
1999
- * // Retrieve environment variables
2000
- * const vars = await sandbox.env.retrieve('.env');
2001
- * console.log(vars);
2002
- *
2003
- * // Update environment variables (merges with existing)
2004
- * await sandbox.env.update('.env', {
2005
- * API_KEY: 'secret',
2006
- * DEBUG: 'true',
2007
- * });
2008
- *
2009
- * // Remove environment variables
2010
- * await sandbox.env.remove('.env', ['OLD_KEY', 'DEPRECATED']);
2011
- * ```
2012
- */
2013
- declare class Env {
2014
- private retrieveHandler;
2015
- private updateHandler;
2016
- private removeHandler;
2017
- private existsHandler;
2018
- constructor(handlers: {
2019
- retrieve: (file: string) => Promise<EnvGetResponse>;
2020
- update: (file: string, variables: Record<string, string>) => Promise<EnvSetResponse>;
2021
- remove: (file: string, keys: string[]) => Promise<EnvDeleteResponse>;
2022
- exists: (file: string) => Promise<boolean>;
2023
- });
2024
- /**
2025
- * Retrieve environment variables from a file
2026
- * @param file - Path to the .env file (relative to sandbox root)
2027
- * @returns Key-value map of environment variables
2028
- */
2029
- retrieve(file: string): Promise<Record<string, string>>;
2030
- /**
2031
- * Update (merge) environment variables in a file
2032
- * @param file - Path to the .env file (relative to sandbox root)
2033
- * @param variables - Key-value pairs to set
2034
- * @returns Keys that were updated
2035
- */
2036
- update(file: string, variables: Record<string, string>): Promise<string[]>;
2037
- /**
2038
- * Remove environment variables from a file
2039
- * @param file - Path to the .env file (relative to sandbox root)
2040
- * @param keys - Keys to remove
2041
- * @returns Keys that were removed
2042
- */
2043
- remove(file: string, keys: string[]): Promise<string[]>;
2044
- /**
2045
- * Check if an environment file exists
2046
- * @param file - Path to the .env file (relative to sandbox root)
2047
- * @returns True if file exists
2048
- */
2049
- exists(file: string): Promise<boolean>;
2050
- }
2051
-
2052
- /**
2053
- * Auth - Resource namespace for authentication info
2054
- */
2055
-
2056
- /**
2057
- * Authentication status info
2058
- */
2059
- interface AuthStatusInfo {
2060
- authenticated: boolean;
2061
- tokenType?: 'access_token' | 'session_token';
2062
- expiresAt?: string;
2063
- }
2064
- /**
2065
- * Authentication endpoints info
2066
- */
2067
- interface AuthEndpointsInfo {
2068
- createSessionToken: string;
2069
- listSessionTokens: string;
2070
- getSessionToken: string;
2071
- revokeSessionToken: string;
2072
- createMagicLink: string;
2073
- authStatus: string;
2074
- authInfo: string;
2075
- }
2076
- /**
2077
- * Authentication info
2078
- */
2079
- interface AuthInfo {
2080
- message: string;
2081
- instructions: string;
2082
- endpoints: AuthEndpointsInfo;
2083
- }
2084
- /**
2085
- * Auth resource namespace
2086
- *
2087
- * @example
2088
- * ```typescript
2089
- * // Check authentication status
2090
- * const status = await sandbox.auth.status();
2091
- * console.log(status.authenticated);
2092
- * console.log(status.tokenType);
2093
- *
2094
- * // Get authentication info and instructions
2095
- * const info = await sandbox.auth.info();
2096
- * console.log(info.instructions);
2097
- * ```
2098
- */
2099
- declare class Auth {
2100
- private statusHandler;
2101
- private infoHandler;
2102
- constructor(handlers: {
2103
- status: () => Promise<AuthStatusResponse>;
2104
- info: () => Promise<AuthInfoResponse>;
2105
- });
2106
- /**
2107
- * Check authentication status
2108
- * @returns Authentication status info
2109
- */
2110
- status(): Promise<AuthStatusInfo>;
2111
- /**
2112
- * Get authentication information and usage instructions
2113
- * @returns Authentication info
2114
- */
2115
- info(): Promise<AuthInfo>;
2116
- }
2117
-
2118
- /**
2119
- * Run - Resource namespace for code and command execution
2120
- */
2121
- /**
2122
- * Code execution result
2123
- */
2124
- interface CodeResult {
2125
- output: string;
2126
- exitCode: number;
2127
- language: string;
2128
- }
2129
- /**
2130
- * Command execution result
2131
- */
2132
- interface CommandResult {
2133
- stdout: string;
2134
- stderr: string;
2135
- exitCode: number;
2136
- durationMs: number;
2137
- /** Command ID (present for background commands) */
2138
- cmdId?: string;
2139
- /** Terminal ID (present for background commands) */
2140
- terminalId?: string;
2141
- /** Command status (present for background commands) */
2142
- status?: 'running' | 'completed' | 'failed';
2143
- }
2144
- /**
2145
- * Supported languages for code execution
2146
- */
2147
- type CodeLanguage = 'python' | 'python3' | 'node' | 'javascript' | 'js' | 'bash' | 'sh' | 'ruby';
2148
- /**
2149
- * Code execution options
2150
- */
2151
- interface CodeRunOptions {
2152
- /** Programming language (optional - will auto-detect if not specified) */
2153
- language?: CodeLanguage;
2154
- }
2155
- /**
2156
- * Options for waiting for command completion
2157
- */
2158
- interface CommandWaitOptions {
2159
- /** Timeout in seconds to wait for command completion (default: 300, max: 300) */
2160
- timeoutSeconds?: number;
2161
- }
2162
- /**
2163
- * Command execution options
2164
- */
2165
- interface CommandRunOptions {
2166
- /** Shell to use (optional) */
2167
- shell?: string;
2168
- /** Run in background (optional) */
2169
- background?: boolean;
2170
- /** Working directory for the command (optional) */
2171
- cwd?: string;
2172
- /** Environment variables (optional) */
2173
- env?: Record<string, string>;
2174
- /** If true, wait for background command to complete before returning (default: false) */
2175
- waitForCompletion?: boolean | CommandWaitOptions;
2176
- }
2177
- /**
2178
- * Run - Resource namespace for executing code and commands
2179
- *
2180
- * @example
2181
- * ```typescript
2182
- * // Run code with auto-detection
2183
- * const result = await sandbox.run.code('print("Hello from Python")');
2184
- * console.log(result.output); // "Hello from Python\n"
2185
- * console.log(result.language); // "python"
2186
- *
2187
- * // Run code with explicit language
2188
- * const result = await sandbox.run.code('console.log("Hello")', { language: 'node' });
2189
- *
2190
- * // Run a command
2191
- * const result = await sandbox.run.command('ls -la');
2192
- * console.log(result.stdout);
2193
- * console.log(result.exitCode);
2194
- *
2195
- * // Run a command in background and wait for completion
2196
- * const result = await sandbox.run.command('npm install', {
2197
- * background: true,
2198
- * waitForCompletion: true, // blocks until command completes
2199
- * });
2200
- * console.log(result.exitCode);
2201
- *
2202
- * // Run in background without waiting (fire-and-forget)
2203
- * const result = await sandbox.run.command('npm install', { background: true });
2204
- * console.log(result.cmdId); // command ID for manual tracking
2205
- * console.log(result.terminalId); // terminal ID for manual tracking
2206
- * ```
2207
- */
2208
- declare class Run {
2209
- private codeHandler;
2210
- private commandHandler;
2211
- private waitHandler?;
2212
- constructor(handlers: {
2213
- code: (code: string, options?: CodeRunOptions) => Promise<CodeResult>;
2214
- command: (command: string, options?: CommandRunOptions) => Promise<CommandResult>;
2215
- wait?: (terminalId: string, cmdId: string, options?: CommandWaitOptions) => Promise<CommandResult>;
2216
- });
2217
- /**
2218
- * Execute code with automatic language detection
2219
- *
2220
- * Supports: python, python3, node, javascript, js, bash, sh, ruby
2221
- *
2222
- * @param code - The code to execute
2223
- * @param options - Execution options
2224
- * @param options.language - Programming language (auto-detected if not specified)
2225
- * @returns Code execution result with output, exit code, and detected language
2226
- */
2227
- code(code: string, options?: CodeRunOptions): Promise<CodeResult>;
2228
- /**
2229
- * Execute a shell command
2230
- *
2231
- * @param command - The command to execute
2232
- * @param options - Execution options
2233
- * @param options.shell - Shell to use (optional)
2234
- * @param options.background - Run in background (optional)
2235
- * @param options.cwd - Working directory for the command (optional)
2236
- * @param options.env - Environment variables (optional)
2237
- * @param options.waitForCompletion - If true (with background), wait for command to complete
2238
- * @returns Command execution result with stdout, stderr, exit code, and duration
2239
- */
2240
- command(command: string, options?: CommandRunOptions): Promise<CommandResult>;
2241
- /**
2242
- * Wait for a background command to complete
2243
- *
2244
- * Uses the configured wait handler to block until the command
2245
- * is complete or fails (typically via server-side long-polling).
2246
- * Throws an error if the command fails or times out.
2247
- *
2248
- * @param terminalId - Terminal ID from background command result
2249
- * @param cmdId - Command ID from background command result
2250
- * @param options - Wait options passed to the handler
2251
- * @returns Command result with final status
2252
- * @throws Error if command fails or times out
2253
- */
2254
- waitForCompletion(terminalId: string, cmdId: string, options?: CommandWaitOptions): Promise<CommandResult>;
2255
- }
2256
-
2257
- /**
2258
- * Client Types
2259
- *
2260
- * Types specific to the Sandbox client implementation.
2261
- * Core universal types are imported from ../types/universal-sandbox
2262
- */
2263
-
2264
- /**
2265
- * Sandbox status types (client-specific, more limited than universal)
2266
- */
2267
- type SandboxStatus = 'running' | 'stopped' | 'error';
2268
- /**
2269
- * Provider-agnostic sandbox info
2270
- */
2271
- interface ProviderSandboxInfo {
2272
- /** Unique identifier for the sandbox */
2273
- id: string;
2274
- /** Provider hosting the sandbox */
2275
- provider: string;
2276
- /** Runtime environment in the sandbox */
2277
- runtime: Runtime;
2278
- /** Current status of the sandbox */
2279
- status: SandboxStatus;
2280
- /** When the sandbox was created */
2281
- createdAt: Date;
2282
- /** Execution timeout in milliseconds */
2283
- timeout: number;
2284
- /** Additional provider-specific metadata */
2285
- metadata?: Record<string, any>;
2286
- }
2287
- /**
2288
- * Error thrown when a command exits with a non-zero status
2289
- */
2290
- declare class CommandExitError extends Error {
2291
- result: {
2292
- exitCode: number;
2293
- stdout: string;
2294
- stderr: string;
2295
- error: boolean;
2296
- };
2297
- name: string;
2298
- constructor(result: {
2299
- exitCode: number;
2300
- stdout: string;
2301
- stderr: string;
2302
- error: boolean;
2303
- });
2304
- }
2305
- /**
2306
- * Type guard to check if an error is a CommandExitError
2307
- */
2308
- declare function isCommandExitError(error: unknown): error is CommandExitError;
2309
-
2310
- /**
2311
- * Child - Resource namespace for child sandbox operations
2312
- */
2313
-
2314
- /**
2315
- * Child resource namespace for managing child sandboxes
2316
- *
2317
- * Child sandboxes are isolated environments within the parent sandbox,
2318
- * each with their own filesystem. Available only in multi-tenant mode.
2319
- *
2320
- * @example
2321
- * ```typescript
2322
- * // Create a new child sandbox
2323
- * const child = await sandbox.child.create({
2324
- * directory: '/custom/path',
2325
- * overlays: [
2326
- * {
2327
- * source: '/templates/nextjs',
2328
- * target: 'app',
2329
- * strategy: 'smart',
2330
- * },
2331
- * ],
2332
- * servers: [
2333
- * {
2334
- * slug: 'web',
2335
- * start: 'npm run dev',
2336
- * path: '/app',
2337
- * },
2338
- * ],
2339
- * });
2340
- * console.log(child.url); // https://sandbox-12345.sandbox.computesdk.com
2341
- *
2342
- * // List all children
2343
- * const all = await sandbox.child.list();
2344
- *
2345
- * // Get a specific child
2346
- * const info = await sandbox.child.retrieve('sandbox-12345');
2347
- *
2348
- * // Delete a child sandbox
2349
- * await sandbox.child.destroy('sandbox-12345');
2350
- *
2351
- * // Delete child and its files
2352
- * await sandbox.child.destroy('sandbox-12345', { deleteFiles: true });
2353
- * ```
2354
- */
2355
- declare class Child {
2356
- private createHandler;
2357
- private listHandler;
2358
- private retrieveHandler;
2359
- private destroyHandler;
2360
- constructor(handlers: {
2361
- create: (options?: CreateSandboxOptions$1) => Promise<SandboxInfo>;
2362
- list: () => Promise<SandboxesListResponse>;
2363
- retrieve: (subdomain: string) => Promise<SandboxInfo>;
2364
- destroy: (subdomain: string, deleteFiles: boolean) => Promise<void>;
2365
- });
2366
- /**
2367
- * Create a new child sandbox
2368
- * @returns Child sandbox info including URL and subdomain
2369
- */
2370
- create(options?: CreateSandboxOptions$1): Promise<SandboxInfo>;
2371
- /**
2372
- * List all child sandboxes
2373
- * @returns Array of child sandbox info
2374
- */
2375
- list(): Promise<SandboxInfo[]>;
2376
- /**
2377
- * Retrieve a specific child sandbox by subdomain
2378
- * @param subdomain - The child subdomain (e.g., 'sandbox-12345')
2379
- * @returns Child sandbox info
2380
- */
2381
- retrieve(subdomain: string): Promise<SandboxInfo>;
2382
- /**
2383
- * Destroy (delete) a child sandbox
2384
- * @param subdomain - The child subdomain
2385
- * @param options - Destroy options
2386
- * @param options.deleteFiles - Whether to delete the child's files (default: false)
2387
- */
2388
- destroy(subdomain: string, options?: {
2389
- deleteFiles?: boolean;
2390
- }): Promise<void>;
2391
- }
2392
-
2393
- /**
2394
- * Binary WebSocket Protocol Implementation
2395
- *
2396
- * Implements the ComputeSDK binary protocol for WebSocket communication.
2397
- * Provides 50-90% size reduction compared to JSON protocol.
2398
- *
2399
- * Binary Message Format:
2400
- * [1 byte: message type]
2401
- * [2 bytes: channel length (uint16, big-endian)]
2402
- * [N bytes: channel string (UTF-8)]
2403
- * [2 bytes: msg type length (uint16, big-endian)]
2404
- * [N bytes: msg type string (UTF-8)]
2405
- * [4 bytes: data length (uint32, big-endian)]
2406
- * [N bytes: data (key-value encoded for complex objects, raw bytes for binary data)]
2407
- *
2408
- * Key-Value Encoding Format:
2409
- * [2 bytes: num_fields (uint16, big-endian)]
2410
- * For each field:
2411
- * [2 bytes: key_length (uint16, big-endian)]
2412
- * [N bytes: key string (UTF-8)]
2413
- * [1 byte: value_type (0x01=string, 0x02=number, 0x03=boolean, 0x04=bytes)]
2414
- * [4 bytes: value_length (uint32, big-endian)]
2415
- * [N bytes: value data]
2416
- */
2417
- declare enum MessageType {
2418
- Subscribe = 1,
2419
- Unsubscribe = 2,
2420
- Data = 3,
2421
- Error = 4,
2422
- Connected = 5
2423
- }
2424
- /**
2425
- * Encode a WebSocket message to binary format
2426
- * @param message - The message object to encode
2427
- * @returns ArrayBuffer containing the encoded binary message
2428
- */
2429
- declare function encodeBinaryMessage(message: any): ArrayBuffer;
2430
- /**
2431
- * Decode a binary WebSocket message
2432
- * @param buffer - The binary data to decode (ArrayBuffer or Uint8Array)
2433
- * @returns Decoded message object
2434
- */
2435
- declare function decodeBinaryMessage(buffer: ArrayBuffer | Uint8Array): any;
2436
-
2437
- /**
2438
- * ComputeSDK Client - Universal Sandbox Implementation
2439
- *
2440
- * This package provides a Sandbox for interacting with ComputeSDK sandboxes
2441
- * through API endpoints at ${sandboxId}.sandbox.computesdk.com
2442
- *
2443
- * Works in browser, Node.js, and edge runtimes.
2444
- * Browser: Uses native WebSocket and fetch
2445
- * Node.js: Pass WebSocket implementation (e.g., 'ws' library)
2446
- */
2447
-
2448
- /**
2449
- * Extended filesystem interface with overlay support
2450
- */
2451
- interface ExtendedFileSystem extends SandboxFileSystem {
2452
- /** Overlay operations for template directories */
2453
- readonly overlay: Overlay;
2454
- }
2455
-
2456
- /**
2457
- * WebSocket constructor type
2458
- */
2459
- type WebSocketConstructor = new (url: string) => WebSocket;
2460
- /**
2461
- * Configuration options for creating a Sandbox
2462
- */
2463
- interface SandboxConfig {
2464
- /** API endpoint URL (e.g., https://sandbox-123.sandbox.computesdk.com). Optional in browser - can be detected from URL query param or localStorage */
2465
- sandboxUrl?: string;
2466
- /** Sandbox ID */
2467
- sandboxId: string;
2468
- /** Provider name (e.g., 'e2b', 'modal') */
2469
- provider: string;
2470
- /** Access token or session token for authentication. Optional in browser - can be detected from URL query param or localStorage */
2471
- token?: string;
2472
- /** Optional headers to include with all requests */
2473
- headers?: Record<string, string>;
2474
- /** Request timeout in milliseconds (default: 30000) */
2475
- timeout?: number;
2476
- /** WebSocket implementation (optional, uses global WebSocket if not provided) */
2477
- WebSocket?: WebSocketConstructor;
2478
- /** WebSocket protocol: 'binary' (default, recommended) or 'json' (for debugging) */
2479
- protocol?: 'json' | 'binary';
2480
- /** Optional metadata associated with the sandbox */
2481
- metadata?: Record<string, unknown>;
2482
- /**
2483
- * Handler called when destroy() is invoked.
2484
- * If provided, this is called to destroy the sandbox through an external API.
2485
- * If not provided, destroy() only disconnects the WebSocket.
2486
- * @internal
2487
- */
2488
- destroyHandler?: () => Promise<void>;
2489
- }
2490
- /**
2491
- * Health check response
2492
- */
2493
- interface HealthResponse {
2494
- status: string;
2495
- timestamp: string;
2496
- }
2497
- /**
2498
- * Server info response
2499
- */
2500
- interface InfoResponse {
2501
- message: string;
2502
- data: {
2503
- auth_enabled: boolean;
2504
- main_subdomain: string;
2505
- sandbox_count: number;
2506
- sandbox_url: string;
2507
- version: string;
2508
- };
2509
- }
2510
- /**
2511
- * Session token response
2512
- */
2513
- interface SessionTokenResponse {
2514
- id: string;
2515
- token: string;
2516
- description?: string;
2517
- createdAt: string;
2518
- expiresAt: string;
2519
- expiresIn: number;
2520
- }
2521
- /**
2522
- * Session token list response
2523
- */
2524
- interface SessionTokenListResponse {
2525
- message: string;
2526
- data: {
2527
- tokens: Array<{
2528
- id: string;
2529
- description?: string;
2530
- created_at: string;
2531
- expires_at: string;
2532
- last_used_at?: string;
2533
- }>;
2534
- };
2535
- }
2536
- /**
2537
- * Magic link response
2538
- */
2539
- interface MagicLinkResponse {
2540
- message: string;
2541
- data: {
2542
- magic_url: string;
2543
- expires_at: string;
2544
- redirect_url: string;
2545
- };
2546
- }
2547
- /**
2548
- * Authentication status response
2549
- */
2550
- interface AuthStatusResponse {
2551
- message: string;
2552
- data: {
2553
- authenticated: boolean;
2554
- token_type?: 'access_token' | 'session_token';
2555
- expires_at?: string;
2556
- };
2557
- }
2558
- /**
2559
- * Authentication information response
2560
- */
2561
- interface AuthInfoResponse {
2562
- message: string;
2563
- data: {
2564
- message: string;
2565
- instructions: string;
2566
- endpoints: {
2567
- create_session_token: string;
2568
- list_session_tokens: string;
2569
- get_session_token: string;
2570
- revoke_session_token: string;
2571
- create_magic_link: string;
2572
- auth_status: string;
2573
- auth_info: string;
2574
- };
2575
- };
2576
- }
2577
- /**
2578
- * File information
2579
- */
2580
- interface FileInfo {
2581
- name: string;
2582
- path: string;
2583
- size: number;
2584
- is_dir: boolean;
2585
- modified_at: string;
2586
- }
2587
- /**
2588
- * Files list response
2589
- */
2590
- interface FilesListResponse {
2591
- message: string;
2592
- data: {
2593
- files: FileInfo[];
2594
- path: string;
2595
- };
2596
- }
2597
- /**
2598
- * File response
2599
- */
2600
- interface FileResponse {
2601
- message: string;
2602
- data: {
2603
- file: FileInfo;
2604
- content?: string;
2605
- };
2606
- }
2607
- /**
2608
- * Command execution response (used by both /run/command and /terminals/{id}/execute)
2609
- */
2610
- interface CommandExecutionResponse {
2611
- message: string;
2612
- data: {
2613
- terminal_id?: string;
2614
- cmd_id?: string;
2615
- command: string;
2616
- stdout: string;
2617
- stderr: string;
2618
- exit_code?: number;
2619
- duration_ms?: number;
2620
- status?: 'running' | 'completed' | 'failed';
2621
- channel?: string;
2622
- pty?: boolean;
2623
- };
2624
- }
2625
- /**
2626
- * Command details response
2627
- */
2628
- interface CommandDetailsResponse {
2629
- message: string;
2630
- data: {
2631
- cmd_id: string;
2632
- command: string;
2633
- status: 'running' | 'completed' | 'failed';
2634
- stdout: string;
2635
- stderr: string;
2636
- started_at: string;
2637
- finished_at?: string;
2638
- duration_ms?: number;
2639
- exit_code?: number;
2640
- };
2641
- }
2642
- /**
2643
- * Command list item
2644
- */
2645
- interface CommandListItem {
2646
- cmd_id: string;
2647
- command: string;
2648
- status: 'running' | 'completed' | 'failed';
2649
- started_at: string;
2650
- finished_at?: string;
2651
- duration_ms?: number;
2652
- exit_code?: number;
2653
- }
2654
- /**
2655
- * Commands list response
2656
- */
2657
- interface CommandsListResponse {
2658
- message: string;
2659
- data: {
2660
- commands: CommandListItem[];
2661
- count: number;
2662
- };
2663
- }
2664
- /**
2665
- * Code execution response (POST /run/code)
2666
- */
2667
- interface CodeExecutionResponse {
2668
- data: {
2669
- output: string;
2670
- exit_code: number;
2671
- language: string;
2672
- };
2673
- }
2674
- /**
2675
- * File watcher information
2676
- */
2677
- interface WatcherInfo {
2678
- id: string;
2679
- path: string;
2680
- includeContent: boolean;
2681
- ignored: string[];
2682
- status: 'active' | 'stopped';
2683
- channel: string;
2684
- encoding?: 'raw' | 'base64';
2685
- }
2686
- /**
2687
- * File watcher response
2688
- */
2689
- interface WatcherResponse {
2690
- message: string;
2691
- data: WatcherInfo & {
2692
- ws_url: string;
2693
- };
2694
- }
2695
- /**
2696
- * File watchers list response
2697
- */
2698
- interface WatchersListResponse {
2699
- message: string;
2700
- data: {
2701
- watchers: WatcherInfo[];
2702
- };
2703
- }
2704
- /**
2705
- * Signal service response
2706
- */
2707
- interface SignalServiceResponse {
2708
- message: string;
2709
- data: {
2710
- status: 'active' | 'stopped';
2711
- channel: string;
2712
- ws_url: string;
2713
- };
2714
- }
2715
- /**
2716
- * Port signal response
2717
- */
2718
- interface PortSignalResponse {
2719
- message: string;
2720
- data: {
2721
- port: number;
2722
- type: 'open' | 'close';
2723
- url: string;
2724
- };
2725
- }
2726
- /**
2727
- * Generic signal response
2728
- */
2729
- interface GenericSignalResponse {
2730
- message: string;
2731
- data: {
2732
- message: string;
2733
- };
2734
- }
2735
- /**
2736
- * Sandbox information
2737
- */
2738
- interface SandboxInfo {
2739
- subdomain: string;
2740
- directory: string;
2741
- is_main: boolean;
2742
- created_at: string;
2743
- url: string;
2744
- overlays?: SandboxOverlayInfo[];
2745
- servers?: SandboxServerInfo[];
2746
- }
2747
- /**
2748
- * Sandboxes list response
2749
- */
2750
- interface SandboxesListResponse {
2751
- sandboxes: SandboxInfo[];
2752
- }
2753
- /**
2754
- * Terminal response
2755
- */
2756
- interface TerminalResponse {
2757
- message: string;
2758
- data: {
2759
- id: string;
2760
- pty: boolean;
2761
- status: 'running' | 'stopped' | 'ready' | 'active';
2762
- channel?: string;
2763
- ws_url?: string;
2764
- encoding?: 'raw' | 'base64';
2765
- };
2766
- }
2767
- /**
2768
- * Terminal response
2769
- */
2770
- interface TerminalResponse {
2771
- message: string;
2772
- data: {
2773
- id: string;
2774
- pty: boolean;
2775
- status: 'running' | 'stopped' | 'ready' | 'active';
2776
- channel?: string;
2777
- ws_url?: string;
2778
- encoding?: 'raw' | 'base64';
2779
- };
2780
- }
2781
- /**
2782
- * Server status types
2783
- *
2784
- * - `installing`: Running install command (e.g., npm install) before starting
2785
- * - `starting`: Initial startup of the server process
2786
- * - `running`: Server process is running
2787
- * - `ready`: Server is running and ready to accept traffic
2788
- * - `failed`: Server failed to start or encountered a fatal error
2789
- * - `stopped`: Server was intentionally stopped
2790
- * - `restarting`: Server is being automatically restarted by the supervisor
2791
- */
2792
- type ServerStatus = 'installing' | 'starting' | 'running' | 'ready' | 'failed' | 'stopped' | 'restarting';
2793
- /**
2794
- * Server restart policy
2795
- * - `never`: No automatic restart (default)
2796
- * - `on-failure`: Restart only on non-zero exit code
2797
- * - `always`: Always restart on exit (including exit code 0)
2798
- */
2799
- type RestartPolicy = 'never' | 'on-failure' | 'always';
2800
- /**
2801
- * Health check configuration for servers
2802
- * Polls the server to verify it's responding to requests
2803
- */
2804
- interface HealthCheckConfig {
2805
- /** Path to poll for health checks (default: "/") */
2806
- path?: string;
2807
- /** Interval between health checks in milliseconds (default: 2000) */
2808
- interval_ms?: number;
2809
- /** Timeout for each health check request in milliseconds (default: 1500) */
2810
- timeout_ms?: number;
2811
- /** Delay before starting health checks after port detection in milliseconds (default: 5000) */
2812
- delay_ms?: number;
2813
- }
2814
- /**
2815
- * Health check status information returned from server
2816
- */
2817
- interface HealthCheckStatus {
2818
- /** When the last health check was performed (ISO 8601) */
2819
- last_check?: string;
2820
- /** HTTP status code from the last health check */
2821
- last_status?: number;
2822
- /** Number of consecutive failed health checks */
2823
- consecutive_failures: number;
2824
- }
2825
- /**
2826
- * Server information
2827
- */
2828
- interface ServerInfo {
2829
- /** Unique server identifier */
2830
- slug: string;
2831
- /** Install command (optional, runs blocking before start) */
2832
- install?: string;
2833
- /** Command used to start the server */
2834
- start: string;
2835
- /** Working directory path */
2836
- path: string;
2837
- /** Original path before resolution */
2838
- original_path?: string;
2839
- /** Path to .env file */
2840
- env_file?: string;
2841
- /** Inline environment variables */
2842
- environment?: Record<string, string>;
2843
- /** Whether to auto-start the server on daemon boot */
2844
- autostart?: boolean;
2845
- /** If true, port allocation is strict (no auto-increment) */
2846
- strict_port?: boolean;
2847
- /** Overlay IDs this server depends on */
2848
- depends_on?: string[];
2849
- /** Auto-detected port number (populated when port monitor detects listening port) */
2850
- port?: number;
2851
- /** Generated URL from subdomain + port (populated when port is detected) */
2852
- url?: string;
2853
- /** Server lifecycle status */
2854
- status: ServerStatus;
2855
- /** Process ID (direct process, not shell wrapper) */
2856
- pid?: number;
2857
- /** Configured restart policy */
2858
- restart_policy?: RestartPolicy;
2859
- /** Maximum restart attempts (0 = unlimited) */
2860
- max_restarts?: number;
2861
- /** Delay between restarts in nanoseconds (input uses milliseconds via restart_delay_ms) */
2862
- restart_delay?: number;
2863
- /** Graceful shutdown timeout in nanoseconds (input uses milliseconds via stop_timeout_ms) */
2864
- stop_timeout?: number;
2865
- /** Number of times the server has been automatically restarted */
2866
- restart_count?: number;
2867
- /** Last exit code (null if process is still running) */
2868
- exit_code?: number | null;
2869
- /** Health check configuration (if configured) */
2870
- health_check?: HealthCheckConfig;
2871
- /** Whether the server is healthy (only present if health_check is configured) */
2872
- healthy?: boolean;
2873
- /** Health check status details (only present if health_check is configured) */
2874
- health_status?: HealthCheckStatus;
2875
- /** When the server was created */
2876
- created_at: string;
2877
- /** When the server was last updated */
2878
- updated_at: string;
2879
- }
2880
- /**
2881
- * Sandbox server info returned by setup flows
2882
- */
2883
- interface SandboxServerInfo {
2884
- slug: string;
2885
- port?: number;
2886
- url?: string;
2887
- status: ServerStatus;
2888
- /** Whether the server is healthy (only present if health_check is configured) */
2889
- healthy?: boolean;
2890
- /** Health check status details (only present if health_check is configured) */
2891
- health_check?: HealthCheckStatus;
2892
- }
2893
- /**
2894
- * Sandbox overlay info returned by setup flows
2895
- */
2896
- interface SandboxOverlayInfo {
2897
- id: string;
2898
- source: string;
2899
- target: string;
2900
- copy_status: string;
2901
- }
2902
- /**
2903
- * Ready response (public endpoint)
2904
- */
2905
- interface ReadyResponse {
2906
- /** Whether all servers have ports allocated (URLs available) */
2907
- ready: boolean;
2908
- /** Whether all servers with health checks are passing */
2909
- healthy?: boolean;
2910
- servers: SandboxServerInfo[];
2911
- overlays: SandboxOverlayInfo[];
2912
- }
2913
- /**
2914
- * Servers list response
2915
- */
2916
- interface ServersListResponse {
2917
- status: string;
2918
- message: string;
2919
- data: {
2920
- servers: ServerInfo[];
2921
- };
2922
- }
2923
- /**
2924
- * Server response
2925
- */
2926
- interface ServerResponse {
2927
- status: string;
2928
- message: string;
2929
- data: {
2930
- server: ServerInfo;
2931
- };
2932
- }
2933
- /**
2934
- * Server stop response
2935
- */
2936
- interface ServerStopResponse {
2937
- status: string;
2938
- message: string;
2939
- data: {
2940
- slug: string;
2941
- };
2942
- }
2943
- /**
2944
- * Server logs stream type
2945
- */
2946
- type ServerLogStream = 'stdout' | 'stderr' | 'combined';
2947
- /**
2948
- * Server logs response
2949
- */
2950
- interface ServerLogsResponse {
2951
- status: string;
2952
- message: string;
2953
- data: {
2954
- slug: string;
2955
- stream: ServerLogStream;
2956
- logs: string;
2957
- };
2958
- }
2959
- /**
2960
- * Server status update response
2961
- */
2962
- interface ServerStatusUpdateResponse {
2963
- status: string;
2964
- message: string;
2965
- data: {
2966
- slug: string;
2967
- status: ServerStatus;
2968
- };
2969
- }
2970
- /**
2971
- * Environment variables response
2972
- */
2973
- interface EnvGetResponse {
2974
- status: string;
2975
- message: string;
2976
- data: {
2977
- file: string;
2978
- variables: Record<string, string>;
2979
- };
2980
- }
2981
- /**
2982
- * Environment set response
2983
- */
2984
- interface EnvSetResponse {
2985
- status: string;
2986
- message: string;
2987
- data: {
2988
- file: string;
2989
- keys: string[];
2990
- };
2991
- }
2992
- /**
2993
- * Environment delete response
2994
- */
2995
- interface EnvDeleteResponse {
2996
- status: string;
2997
- message: string;
2998
- data: {
2999
- file: string;
3000
- keys: string[];
3001
- };
3002
- }
3003
- /**
3004
- * Batch file operation type
3005
- */
3006
- type BatchFileOperation = 'write' | 'delete';
3007
- /**
3008
- * Batch file operation result
3009
- */
3010
- interface BatchWriteResult {
3011
- path: string;
3012
- success: boolean;
3013
- error?: string;
3014
- file?: FileInfo;
3015
- }
3016
- /**
3017
- * Batch file operation response
3018
- */
3019
- interface BatchWriteResponse {
3020
- message: string;
3021
- data: {
3022
- results: BatchWriteResult[];
3023
- };
3024
- }
3025
- /**
3026
- * Sandbox - Full-featured sandbox client implementation
3027
- *
3028
- * Provides complete feature set including:
3029
- * - Interactive terminals (PTY and exec modes)
3030
- * - Managed servers
3031
- * - File watchers with real-time events
3032
- * - Authentication (session tokens, magic links)
3033
- * - Environment management
3034
- * - Signal service for port/error events
3035
- * - Child sandbox creation
3036
- *
3037
- * This is the most feature-rich implementation available.
3038
- *
3039
- * @example
3040
- * ```typescript
3041
- * import { Sandbox } from 'computesdk'
3042
- *
3043
- * // Pattern 1: Admin operations (requires access token)
3044
- * const sandbox = new Sandbox({
3045
- * sandboxUrl: 'https://sandbox-123.sandbox.computesdk.com',
3046
- * token: accessToken, // From edge service
3047
- * });
3048
- *
3049
- * // Create session token for delegated operations
3050
- * const sessionToken = await sandbox.createSessionToken({
3051
- * description: 'My Application',
3052
- * expiresIn: 604800, // 7 days
3053
- * });
3054
- *
3055
- * // Pattern 2: Delegated operations (binary protocol by default)
3056
- * const sandbox2 = new Sandbox({
3057
- * sandboxUrl: 'https://sandbox-123.sandbox.computesdk.com',
3058
- * token: sessionToken.data.token,
3059
- * // protocol: 'binary' is the default (50-90% size reduction)
3060
- * });
3061
- *
3062
- * // Execute a one-off command
3063
- * const result = await sandbox.execute({ command: 'ls -la' });
3064
- * console.log(result.data.stdout);
3065
- *
3066
- * // Run code
3067
- * const codeResult = await sandbox.runCode('console.log("Hello!")', 'node');
3068
- *
3069
- * // Work with files
3070
- * const files = await sandbox.listFiles('/home/project');
3071
- * await sandbox.writeFile('/home/project/test.txt', 'Hello, World!');
3072
- * const content = await sandbox.readFile('/home/project/test.txt');
3073
- *
3074
- * // Create a PTY terminal with real-time output (interactive shell)
3075
- * const terminal = await sandbox.createTerminal({ pty: true });
3076
- * terminal.on('output', (data) => console.log(data));
3077
- * terminal.write('ls -la\n');
3078
- * await terminal.destroy();
3079
- *
3080
- * // Create an exec terminal for command tracking
3081
- * const execTerminal = await sandbox.createTerminal({ pty: false });
3082
- * const result = await execTerminal.execute('npm install', { background: true });
3083
- * const cmd = await sandbox.getCommand(execTerminal.getId(), result.data.cmd_id);
3084
- * console.log(cmd.data.status); // "running" | "completed" | "failed"
3085
- * await execTerminal.destroy();
3086
- *
3087
- * // Watch for file changes
3088
- * const watcher = await sandbox.createWatcher('/home/project', {
3089
- * ignored: ['node_modules', '.git']
3090
- * });
3091
- * watcher.on('change', (event) => {
3092
- * console.log(`${event.event}: ${event.path}`);
3093
- * });
3094
- * await watcher.destroy();
3095
- *
3096
- * // Monitor system signals
3097
- * const signals = await sandbox.startSignals();
3098
- * signals.on('port', (event) => {
3099
- * console.log(`Port ${event.port} opened: ${event.url}`);
3100
- * });
3101
- * await signals.stop();
3102
- *
3103
- * // Clean up
3104
- * await sandbox.disconnect();
3105
- * ```
3106
- */
3107
- declare class Sandbox {
3108
- readonly sandboxId: string;
3109
- readonly provider: string;
3110
- readonly filesystem: ExtendedFileSystem;
3111
- readonly terminal: Terminal;
3112
- readonly run: Run;
3113
- readonly server: Server;
3114
- readonly watcher: Watcher;
3115
- readonly sessionToken: SessionToken;
3116
- readonly magicLink: MagicLink;
3117
- readonly signal: Signal;
3118
- readonly file: File;
3119
- readonly env: Env;
3120
- readonly auth: Auth;
3121
- readonly child: Child;
3122
- private config;
3123
- private _token;
3124
- private _ws;
3125
- private WebSocketImpl;
3126
- private _terminals;
3127
- constructor(config: SandboxConfig);
3128
- /**
3129
- * Get or create internal WebSocket manager
3130
- */
3131
- private ensureWebSocket;
3132
- /**
3133
- * Create and configure a TerminalInstance from response data
3134
- */
3135
- private hydrateTerminal;
3136
- private request;
3137
- /**
3138
- * Check service health
3139
- */
3140
- health(): Promise<HealthResponse>;
3141
- /**
3142
- * Create a session token (requires access token)
3143
- *
3144
- * Session tokens are delegated credentials that can authenticate API requests
3145
- * without exposing your access token. Only access tokens can create session tokens.
3146
- *
3147
- * @param options - Token configuration
3148
- * @throws {Error} 403 Forbidden if called with a session token
3149
- */
3150
- createSessionToken(options?: {
3151
- description?: string;
3152
- expiresIn?: number;
3153
- }): Promise<SessionTokenResponse>;
3154
- /**
3155
- * List all session tokens (requires access token)
3156
- *
3157
- * @throws {Error} 403 Forbidden if called with a session token
3158
- */
3159
- listSessionTokens(): Promise<SessionTokenListResponse>;
3160
- /**
3161
- * Get details of a specific session token (requires access token)
3162
- *
3163
- * @param tokenId - The token ID
3164
- * @throws {Error} 403 Forbidden if called with a session token
3165
- */
3166
- getSessionToken(tokenId: string): Promise<SessionTokenResponse>;
3167
- /**
3168
- * Revoke a session token (requires access token)
3169
- *
3170
- * @param tokenId - The token ID to revoke
3171
- * @throws {Error} 403 Forbidden if called with a session token
3172
- */
3173
- revokeSessionToken(tokenId: string): Promise<void>;
3174
- /**
3175
- * Generate a magic link for browser authentication (requires access token)
3176
- *
3177
- * Magic links are one-time URLs that automatically create a session token
3178
- * and set it as a cookie in the user's browser. This provides an easy way
3179
- * to authenticate users in browser-based applications.
3180
- *
3181
- * The generated link:
3182
- * - Expires after 5 minutes or first use (whichever comes first)
3183
- * - Automatically creates a new session token (7 day expiry)
3184
- * - Sets the session token as an HttpOnly cookie
3185
- * - Redirects to the specified URL
3186
- *
3187
- * @param options - Magic link configuration
3188
- * @throws {Error} 403 Forbidden if called with a session token
3189
- */
3190
- createMagicLink(options?: {
3191
- redirectUrl?: string;
3192
- }): Promise<MagicLinkResponse>;
3193
- /**
3194
- * Check authentication status
3195
- * Does not require authentication
3196
- */
3197
- getAuthStatus(): Promise<AuthStatusResponse>;
3198
- /**
3199
- * Get authentication information and usage instructions
3200
- * Does not require authentication
3201
- */
3202
- getAuthInfo(): Promise<AuthInfoResponse>;
3203
- /**
3204
- * Set authentication token manually
3205
- * @param token - Access token or session token
3206
- */
3207
- setToken(token: string): void;
3208
- /**
3209
- * Get current authentication token
3210
- */
3211
- getToken(): string | null;
3212
- /**
3213
- * Get current sandbox URL
3214
- */
3215
- getSandboxUrl(): string;
3216
- /**
3217
- * Execute a one-off command without creating a persistent terminal
3218
- *
3219
- * @example
3220
- * ```typescript
3221
- * // Synchronous execution (waits for completion)
3222
- * const result = await sandbox.execute({ command: 'npm test' });
3223
- * console.log(result.data.exit_code);
3224
- *
3225
- * // Background execution (returns immediately)
3226
- * const result = await sandbox.execute({
3227
- * command: 'npm install',
3228
- * background: true
3229
- * });
3230
- * // Use result.data.terminal_id and result.data.cmd_id to track
3231
- * const cmd = await sandbox.getCommand(result.data.terminal_id!, result.data.cmd_id!);
3232
- * ```
3233
- */
3234
- execute(options: {
3235
- command: string;
3236
- shell?: string;
3237
- background?: boolean;
3238
- }): Promise<CommandExecutionResponse>;
3239
- /**
3240
- * Execute code with automatic language detection (POST /run/code)
3241
- *
3242
- * @param code - The code to execute
3243
- * @param language - Programming language (optional - auto-detects if not specified)
3244
- * @returns Code execution result with output, exit code, and detected language
3245
- *
3246
- * @example
3247
- * ```typescript
3248
- * // Auto-detect language
3249
- * const result = await sandbox.runCodeRequest('print("Hello")');
3250
- * console.log(result.data.output); // "Hello\n"
3251
- * console.log(result.data.language); // "python"
3252
- *
3253
- * // Explicit language
3254
- * const result = await sandbox.runCodeRequest('console.log("Hi")', 'node');
3255
- * ```
3256
- */
3257
- runCodeRequest(code: string, language?: string): Promise<CodeExecutionResponse>;
3258
- /**
3259
- * Execute a command and get the result
3260
- * Lower-level method that returns the raw API response
3261
- *
3262
- * @param options.command - Command to execute
3263
- * @param options.shell - Shell to use (optional)
3264
- * @param options.background - Run in background (optional)
3265
- * @param options.cwd - Working directory for the command (optional)
3266
- * @param options.env - Environment variables (optional)
3267
- * @returns Command execution result
3268
- *
3269
- * @example
3270
- * ```typescript
3271
- * const result = await sandbox.runCommandRequest({ command: 'ls -la' });
3272
- * console.log(result.data.stdout);
3273
- * ```
3274
- */
3275
- runCommandRequest(options: {
3276
- command: string;
3277
- shell?: string;
3278
- background?: boolean;
3279
- stream?: boolean;
3280
- cwd?: string;
3281
- env?: Record<string, string>;
3282
- }): Promise<CommandExecutionResponse>;
3283
- /**
3284
- * List files at the specified path
3285
- */
3286
- listFiles(path?: string): Promise<FilesListResponse>;
3287
- /**
3288
- * Create a new file with optional content
3289
- */
3290
- createFile(path: string, content?: string): Promise<FileResponse>;
3291
- /**
3292
- * Get file metadata (without content)
3293
- */
3294
- getFile(path: string): Promise<FileResponse>;
3295
- /**
3296
- * Read file content
3297
- */
3298
- readFile(path: string): Promise<string>;
3299
- /**
3300
- * Write file content (creates or updates)
3301
- */
3302
- writeFile(path: string, content: string): Promise<FileResponse>;
3303
- /**
3304
- * Delete a file or directory
3305
- */
3306
- deleteFile(path: string): Promise<void>;
3307
- /**
3308
- * Check if a file exists (HEAD request)
3309
- * @returns true if file exists, false otherwise
3310
- */
3311
- checkFileExists(path: string): Promise<boolean>;
3312
- /**
3313
- * Batch file operations (write or delete multiple files)
3314
- *
3315
- * Features:
3316
- * - Deduplication: Last operation wins per path
3317
- * - File locking: Prevents race conditions
3318
- * - Deterministic ordering: Alphabetical path sorting
3319
- * - Partial failure handling: Returns 207 Multi-Status with per-file results
3320
- *
3321
- * @param files - Array of file operations
3322
- * @returns Results for each file operation
3323
- *
3324
- * @example
3325
- * ```typescript
3326
- * // Write multiple files
3327
- * const results = await sandbox.batchWriteFiles([
3328
- * { path: '/app/file1.txt', operation: 'write', content: 'Hello' },
3329
- * { path: '/app/file2.txt', operation: 'write', content: 'World' },
3330
- * ]);
3331
- *
3332
- * // Mixed operations (write and delete)
3333
- * const results = await sandbox.batchWriteFiles([
3334
- * { path: '/app/new.txt', operation: 'write', content: 'New file' },
3335
- * { path: '/app/old.txt', operation: 'delete' },
3336
- * ]);
3337
- * ```
3338
- */
3339
- batchWriteFiles(files: Array<{
3340
- path: string;
3341
- operation: 'write' | 'delete';
3342
- content?: string;
3343
- }>): Promise<BatchWriteResponse>;
3344
- /**
3345
- * Create a new filesystem overlay from a template directory
3346
- *
3347
- * Overlays enable instant sandbox setup by symlinking template files first,
3348
- * then copying heavy directories (node_modules, .venv, etc.) in the background.
3349
- *
3350
- * @param options - Overlay creation options
3351
- * @param options.source - Absolute path to source directory (template)
3352
- * @param options.target - Relative path in sandbox where overlay will be mounted
3353
- * @returns Overlay response with copy status
3354
- *
3355
- * @example
3356
- * ```typescript
3357
- * // Prefer using sandbox.filesystem.overlay.create() for camelCase response
3358
- * const overlay = await sandbox.filesystem.overlay.create({
3359
- * source: '/templates/nextjs',
3360
- * target: 'project',
3361
- * });
3362
- * console.log(overlay.copyStatus); // 'pending' | 'in_progress' | 'complete' | 'failed'
3363
- * ```
3364
- */
3365
- createOverlay(options: CreateOverlayOptions): Promise<OverlayResponse>;
3366
- /**
3367
- * List all filesystem overlays for the current sandbox
3368
- * @returns List of overlays with their copy status
3369
- */
3370
- listOverlays(): Promise<OverlayListResponse>;
3371
- /**
3372
- * Get a specific filesystem overlay by ID
3373
- *
3374
- * Useful for polling the copy status of an overlay.
3375
- *
3376
- * @param id - Overlay ID
3377
- * @returns Overlay details with current copy status
3378
- */
3379
- getOverlay(id: string): Promise<OverlayResponse>;
3380
- /**
3381
- * Delete a filesystem overlay
3382
- * @param id - Overlay ID
3383
- */
3384
- deleteOverlay(id: string): Promise<void>;
3385
- /**
3386
- * Create a new persistent terminal session
3387
- *
3388
- * Terminal Modes:
3389
- * - **PTY mode** (pty: true): Interactive shell with real-time WebSocket streaming
3390
- * - Use for: Interactive shells, vim/nano, real-time output
3391
- * - Methods: write(), resize(), on('output')
3392
- *
3393
- * - **Exec mode** (pty: false, default): Command tracking with HTTP polling
3394
- * - Use for: CI/CD, automation, command tracking, exit codes
3395
- * - Methods: execute(), getCommand(), listCommands(), waitForCommand()
3396
- *
3397
- * @example
3398
- * ```typescript
3399
- * // PTY mode - Interactive shell
3400
- * const pty = await sandbox.createTerminal({ pty: true, shell: '/bin/bash' });
3401
- * pty.on('output', (data) => console.log(data));
3402
- * pty.write('npm install\n');
3403
- *
3404
- * // Exec mode - Command tracking
3405
- * const exec = await sandbox.createTerminal({ pty: false });
3406
- * const result = await exec.execute('npm test', { background: true });
3407
- * const cmd = await sandbox.waitForCommand(exec.getId(), result.data.cmd_id);
3408
- * console.log(cmd.data.exit_code);
3409
- *
3410
- * // Backward compatible - creates PTY terminal
3411
- * const terminal = await sandbox.createTerminal('/bin/bash');
3412
- * ```
3413
- *
3414
- * @param options - Terminal creation options
3415
- * @param options.shell - Shell to use (e.g., '/bin/bash', '/bin/sh') - PTY mode only
3416
- * @param options.encoding - Encoding for terminal I/O: 'raw' (default) or 'base64' (binary-safe)
3417
- * @param options.pty - Terminal mode: true = PTY (interactive shell), false = exec (command tracking, default)
3418
- * @returns Terminal instance with event handling
3419
- */
3420
- createTerminal(shellOrOptions?: string | {
3421
- shell?: string;
3422
- encoding?: 'raw' | 'base64';
3423
- pty?: boolean;
3424
- }, encoding?: 'raw' | 'base64'): Promise<TerminalInstance>;
3425
- /**
3426
- * List all active terminals (fetches from API)
3427
- */
3428
- listTerminals(): Promise<TerminalResponse[]>;
3429
- /**
3430
- * Get terminal by ID
3431
- */
3432
- getTerminal(id: string): Promise<TerminalInstance>;
3433
- /**
3434
- * List all commands executed in a terminal (exec mode only)
3435
- * @param terminalId - The terminal ID
3436
- * @returns List of all commands with their status
3437
- * @throws {Error} If terminal is in PTY mode (command tracking not available)
3438
- */
3439
- listCommands(terminalId: string): Promise<CommandsListResponse>;
3440
- /**
3441
- * Get details of a specific command execution (exec mode only)
3442
- * @param terminalId - The terminal ID
3443
- * @param cmdId - The command ID
3444
- * @returns Command execution details including stdout, stderr, and exit code
3445
- * @throws {Error} If terminal is in PTY mode or command not found
3446
- */
3447
- getCommand(terminalId: string, cmdId: string): Promise<CommandDetailsResponse>;
3448
- /**
3449
- * Wait for a command to complete (HTTP long-polling, exec mode only)
3450
- * @param terminalId - The terminal ID
3451
- * @param cmdId - The command ID
3452
- * @param timeout - Optional timeout in seconds (0 = no timeout)
3453
- * @returns Command execution details when completed
3454
- * @throws {Error} If terminal is in PTY mode, command not found, or timeout occurs
3455
- */
3456
- waitForCommand(terminalId: string, cmdId: string, timeout?: number): Promise<CommandDetailsResponse>;
3457
- /**
3458
- * Wait for a background command to complete using long-polling
3459
- *
3460
- * Uses the server's long-polling endpoint with configurable timeout.
3461
- * The tunnel supports up to 5 minutes (300 seconds) via X-Request-Timeout header.
3462
- *
3463
- * @param terminalId - The terminal ID
3464
- * @param cmdId - The command ID
3465
- * @param options - Wait options (timeoutSeconds, default 300)
3466
- * @returns Command result with final status
3467
- * @throws Error if command fails or times out
3468
- * @internal
3469
- */
3470
- private waitForCommandCompletion;
3471
- /**
3472
- * Wait for a command with extended timeout support
3473
- * Uses X-Request-Timeout header for tunnel timeout configuration
3474
- * @internal
3475
- */
3476
- private waitForCommandWithTimeout;
3477
- /**
3478
- * Create a new file watcher with WebSocket integration
3479
- * @param path - Path to watch
3480
- * @param options - Watcher options
3481
- * @param options.includeContent - Include file content in change events
3482
- * @param options.ignored - Patterns to ignore
3483
- * @param options.encoding - Encoding for file content: 'raw' (default) or 'base64' (binary-safe)
3484
- * @returns FileWatcher instance with event handling
3485
- */
3486
- createWatcher(path: string, options?: {
3487
- includeContent?: boolean;
3488
- ignored?: string[];
3489
- encoding?: 'raw' | 'base64';
3490
- }): Promise<FileWatcher>;
3491
- /**
3492
- * List all active file watchers (fetches from API)
3493
- */
3494
- listWatchers(): Promise<WatchersListResponse>;
3495
- /**
3496
- * Get file watcher by ID
3497
- */
3498
- getWatcher(id: string): Promise<WatcherResponse>;
3499
- /**
3500
- * Start the signal service with WebSocket integration
3501
- * @returns SignalService instance with event handling
3502
- */
3503
- startSignals(): Promise<SignalService>;
3504
- /**
3505
- * Get the signal service status (fetches from API)
3506
- */
3507
- getSignalStatus(): Promise<SignalServiceResponse>;
3508
- /**
3509
- * Emit a port signal
3510
- */
3511
- emitPortSignal(port: number, type: 'open' | 'close', url: string): Promise<PortSignalResponse>;
3512
- /**
3513
- * Emit a port signal (alternative endpoint using path parameters)
3514
- */
3515
- emitPortSignalAlt(port: number, type: 'open' | 'close'): Promise<PortSignalResponse>;
3516
- /**
3517
- * Emit an error signal
3518
- */
3519
- emitErrorSignal(message: string): Promise<GenericSignalResponse>;
3520
- /**
3521
- * Emit a server ready signal
3522
- */
3523
- emitServerReadySignal(port: number, url: string): Promise<PortSignalResponse>;
3524
- /**
3525
- * Get environment variables from a .env file
3526
- * @param file - Path to the .env file (relative to sandbox root)
3527
- */
3528
- getEnv(file: string): Promise<EnvGetResponse>;
3529
- /**
3530
- * Set (merge) environment variables in a .env file
3531
- * @param file - Path to the .env file (relative to sandbox root)
3532
- * @param variables - Key-value pairs to set
3533
- */
3534
- setEnv(file: string, variables: Record<string, string>): Promise<EnvSetResponse>;
3535
- /**
3536
- * Delete environment variables from a .env file
3537
- * @param file - Path to the .env file (relative to sandbox root)
3538
- * @param keys - Keys to delete
3539
- */
3540
- deleteEnv(file: string, keys: string[]): Promise<EnvDeleteResponse>;
3541
- /**
3542
- * Check if an environment file exists (HEAD request)
3543
- * @param file - Path to the .env file (relative to sandbox root)
3544
- * @returns true if file exists, false otherwise
3545
- */
3546
- checkEnvFile(file: string): Promise<boolean>;
3547
- /**
3548
- * List all managed servers
3549
- */
3550
- listServers(): Promise<ServersListResponse>;
3551
- /**
3552
- * Start a new managed server with optional supervisor settings
3553
- *
3554
- * @param options - Server configuration
3555
- * @param options.slug - Unique server identifier
3556
- * @param options.install - Install command (optional, runs blocking before start, e.g., "npm install")
3557
- * @param options.start - Command to start the server (e.g., "npm run dev")
3558
- * @param options.path - Working directory (optional)
3559
- * @param options.env_file - Path to .env file relative to path (optional)
3560
- * @param options.environment - Inline environment variables (merged with env_file if both provided)
3561
- * @param options.port - Requested port (preallocated before start)
3562
- * @param options.strict_port - If true, fail instead of auto-incrementing when port is taken
3563
- * @param options.autostart - Auto-start on daemon boot (default: true)
3564
- * @param options.overlay - Inline overlay to create before starting
3565
- * @param options.overlays - Additional overlays to create before starting
3566
- * @param options.depends_on - Overlay IDs this server depends on
3567
- * @param options.restart_policy - When to automatically restart: 'never' (default), 'on-failure', 'always'
3568
- * @param options.max_restarts - Maximum restart attempts, 0 = unlimited (default: 0)
3569
- * @param options.restart_delay_ms - Delay between restart attempts in milliseconds (default: 1000)
3570
- * @param options.stop_timeout_ms - Graceful shutdown timeout in milliseconds (default: 10000)
3571
- *
3572
- * @example
3573
- * ```typescript
3574
- * // Basic server
3575
- * await sandbox.startServer({
3576
- * slug: 'web',
3577
- * start: 'npm run dev',
3578
- * path: '/app',
3579
- * });
3580
- *
3581
- * // With install command and supervisor settings
3582
- * await sandbox.startServer({
3583
- * slug: 'api',
3584
- * install: 'npm install',
3585
- * start: 'node server.js',
3586
- * path: '/app',
3587
- * environment: { NODE_ENV: 'production', PORT: '3000' },
3588
- * restart_policy: 'on-failure',
3589
- * max_restarts: 5,
3590
- * restart_delay_ms: 2000,
3591
- * stop_timeout_ms: 5000,
3592
- * });
3593
- *
3594
- * // With inline overlay dependencies
3595
- * await sandbox.startServer({
3596
- * slug: 'web',
3597
- * start: 'npm run dev',
3598
- * path: '/app',
3599
- * overlay: {
3600
- * source: '/templates/nextjs',
3601
- * target: 'app',
3602
- * strategy: 'smart',
3603
- * },
3604
- * });
3605
- * ```
3606
- */
3607
- startServer(options: {
3608
- slug: string;
3609
- install?: string;
3610
- start: string;
3611
- path?: string;
3612
- env_file?: string;
3613
- environment?: Record<string, string>;
3614
- port?: number;
3615
- strict_port?: boolean;
3616
- autostart?: boolean;
3617
- overlay?: Omit<CreateOverlayOptions, 'waitForCompletion'>;
3618
- overlays?: Array<Omit<CreateOverlayOptions, 'waitForCompletion'>>;
3619
- depends_on?: string[];
3620
- restart_policy?: RestartPolicy;
3621
- max_restarts?: number;
3622
- restart_delay_ms?: number;
3623
- stop_timeout_ms?: number;
3624
- }): Promise<ServerResponse>;
3625
- /**
3626
- * Get information about a specific server
3627
- * @param slug - Server slug
3628
- */
3629
- getServer(slug: string): Promise<ServerResponse>;
3630
- /**
3631
- * Stop a managed server (non-destructive)
3632
- * @param slug - Server slug
3633
- */
3634
- stopServer(slug: string): Promise<ServerStopResponse>;
3635
- /**
3636
- * Delete a managed server configuration
3637
- * @param slug - Server slug
3638
- */
3639
- deleteServer(slug: string): Promise<void>;
3640
- /**
3641
- * Restart a managed server
3642
- * @param slug - Server slug
3643
- */
3644
- restartServer(slug: string): Promise<ServerResponse>;
3645
- /**
3646
- * Get logs for a managed server
3647
- * @param slug - Server slug
3648
- * @param options - Options for log retrieval
3649
- */
3650
- getServerLogs(slug: string, options?: {
3651
- stream?: ServerLogStream;
3652
- }): Promise<ServerLogsResponse>;
3653
- /**
3654
- * Update server status (internal use)
3655
- * @param slug - Server slug
3656
- * @param status - New server status
3657
- */
3658
- updateServerStatus(slug: string, status: ServerStatus): Promise<ServerStatusUpdateResponse>;
3659
- /**
3660
- * Get readiness status for autostarted servers and overlays
3661
- */
3662
- ready(): Promise<ReadyResponse>;
3663
- /**
3664
- * Create a new sandbox environment
3665
- */
3666
- createSandbox(options?: CreateSandboxOptions$1): Promise<SandboxInfo>;
3667
- /**
3668
- * List all sandboxes
3669
- */
3670
- listSandboxes(): Promise<SandboxesListResponse>;
3671
- /**
3672
- * Get sandbox details
3673
- */
3674
- getSandbox(subdomain: string): Promise<SandboxInfo>;
3675
- /**
3676
- * Delete a sandbox
3677
- */
3678
- deleteSandbox(subdomain: string, deleteFiles?: boolean): Promise<void>;
3679
- /**
3680
- * Get WebSocket URL for real-time communication
3681
- * @private
3682
- */
3683
- private getWebSocketUrl;
3684
- /**
3685
- * Execute code in the sandbox (convenience method)
3686
- *
3687
- * Delegates to sandbox.run.code() - prefer using that directly for new code.
3688
- *
3689
- * @param code - The code to execute
3690
- * @param language - Programming language (auto-detected if not specified)
3691
- * @returns Code execution result
3692
- */
3693
- runCode(code: string, language?: 'node' | 'python'): Promise<{
3694
- output: string;
3695
- exitCode: number;
3696
- language: string;
3697
- }>;
3698
- /**
3699
- * Execute shell command in the sandbox
3700
- *
3701
- * Sends clean command string to server - no preprocessing or shell wrapping.
3702
- * The server handles shell invocation, working directory, and backgrounding.
3703
- *
3704
- * @param command - The command to execute (raw string, e.g., "npm install")
3705
- * @param options - Execution options
3706
- * @param options.background - Run in background (server uses goroutines)
3707
- * @param options.cwd - Working directory (server uses cmd.Dir)
3708
- * @param options.env - Environment variables (server uses cmd.Env)
3709
- * @param options.onStdout - Callback for streaming stdout data
3710
- * @param options.onStderr - Callback for streaming stderr data
3711
- * @param options.timeout - Timeout in seconds (max 300 for long-running commands)
3712
- * @returns Command execution result
3713
- *
3714
- * @example
3715
- * ```typescript
3716
- * // Simple command
3717
- * await sandbox.runCommand('ls -la')
3718
- *
3719
- * // With working directory
3720
- * await sandbox.runCommand('npm install', { cwd: '/app' })
3721
- *
3722
- * // Background with env vars
3723
- * await sandbox.runCommand('node server.js', {
3724
- * background: true,
3725
- * env: { PORT: '3000' }
3726
- * })
3727
- *
3728
- * // With streaming output
3729
- * await sandbox.runCommand('npm install', {
3730
- * onStdout: (data) => console.log(data),
3731
- * onStderr: (data) => console.error(data),
3732
- * })
3733
- *
3734
- * // With timeout for long-running commands
3735
- * await sandbox.runCommand('npm install', { timeout: 120 })
3736
- * ```
3737
- */
3738
- runCommand(command: string, options?: {
3739
- background?: boolean;
3740
- cwd?: string;
3741
- env?: Record<string, string>;
3742
- onStdout?: (data: string) => void;
3743
- onStderr?: (data: string) => void;
3744
- /** Timeout in seconds (max 300 for long-running commands) */
3745
- timeout?: number;
3746
- }): Promise<{
3747
- stdout: string;
3748
- stderr: string;
3749
- exitCode: number;
3750
- durationMs: number;
3751
- }>;
3752
- /**
3753
- * Get server information
3754
- * Returns details about the server including auth status, main subdomain, sandbox count, and version
3755
- */
3756
- getServerInfo(): Promise<InfoResponse>;
3757
- /**
3758
- * Get sandbox information
3759
- */
3760
- getInfo(): Promise<{
3761
- id: string;
3762
- provider: string;
3763
- runtime: 'node' | 'python';
3764
- status: 'running' | 'stopped' | 'error';
3765
- createdAt: Date;
3766
- timeout: number;
3767
- metadata?: Record<string, any>;
3768
- }>;
3769
- /**
3770
- * Get URL for accessing sandbox on a specific port (Sandbox interface method)
3771
- */
3772
- getUrl(options: {
3773
- port: number;
3774
- protocol?: string;
3775
- }): Promise<string>;
3776
- /**
3777
- * Get provider instance
3778
- * Note: Not available on direct Sandbox client instances
3779
- */
3780
- getProvider(): never;
3781
- /**
3782
- * Get native provider instance
3783
- * Returns the Sandbox itself since this IS the sandbox implementation
3784
- */
3785
- getInstance(): this;
3786
- /**
3787
- * Destroy the sandbox (Sandbox interface method)
3788
- *
3789
- * If a destroyHandler was provided, calls it to destroy
3790
- * the sandbox on the backend. Otherwise, only disconnects the WebSocket.
3791
- */
3792
- destroy(): Promise<void>;
3793
- /**
3794
- * Disconnect WebSocket
3795
- *
3796
- * Note: This only disconnects the WebSocket. Terminals, watchers, and signals
3797
- * will continue running on the server until explicitly destroyed via their
3798
- * respective destroy() methods or the DELETE endpoints.
3799
- */
3800
- disconnect(): Promise<void>;
3801
- }
3802
-
3803
- /**
3804
- * Helpers for building setup payloads used by COMPUTESDK_SETUP_B64 or POST /sandboxes
3805
- */
3806
-
3807
- type SetupOverlayConfig = Omit<CreateOverlayOptions, 'waitForCompletion'>;
3808
- interface SetupPayload {
3809
- overlays?: SetupOverlayConfig[];
3810
- servers?: ServerStartOptions[];
3811
- }
3812
- interface BuildSetupPayloadOptions {
3813
- overlays?: CreateOverlayOptions[];
3814
- servers?: ServerStartOptions[];
3815
- }
3816
- /**
3817
- * Build a setup payload for COMPUTESDK_SETUP_B64 or POST /sandboxes
3818
- */
3819
- declare const buildSetupPayload: (options: BuildSetupPayloadOptions) => SetupPayload;
3820
- /**
3821
- * Build and base64-encode a setup payload for COMPUTESDK_SETUP_B64
3822
- */
3823
- declare const encodeSetupPayload: (options: BuildSetupPayloadOptions) => string;
3824
-
3825
- /**
3826
- * Compute API - Direct Provider Implementation
3827
- *
3828
- * Gateway/control-plane transport has been removed from this package.
3829
- * `compute` now delegates to one or more configured provider instances directly.
3830
- */
3831
-
3832
- interface CreateSandboxOptions {
3833
- timeout?: number;
3834
- templateId?: string;
3835
- metadata?: Record<string, any>;
3836
- envs?: Record<string, string>;
3837
- name?: string;
3838
- namespace?: string;
3839
- directory?: string;
3840
- overlays?: SetupOverlayConfig[];
3841
- servers?: ServerStartOptions[];
3842
- image?: string;
3843
- snapshotId?: string;
3844
- /** Optional provider name override (must match provider.name) */
3845
- provider?: string;
3846
- }
3847
- interface FindOrCreateSandboxOptions extends CreateSandboxOptions {
3848
- name: string;
3849
- namespace?: string;
3850
- }
3851
- interface FindSandboxOptions {
3852
- name: string;
3853
- namespace?: string;
139
+ interface CreateSandboxOptions extends CreateSandboxOptions$1 {
3854
140
  /** Optional provider name override (must match provider.name) */
3855
141
  provider?: string;
3856
142
  }
3857
- interface ExtendTimeoutOptions {
3858
- duration?: number;
3859
- }
3860
143
  interface CreateSnapshotOptions {
3861
144
  name?: string;
3862
145
  metadata?: Record<string, any>;
@@ -3864,13 +147,10 @@ interface CreateSnapshotOptions {
3864
147
  provider?: string;
3865
148
  }
3866
149
  interface ProviderSandboxManager {
3867
- create(options?: CreateSandboxOptions): Promise<Sandbox$1>;
3868
- getById(sandboxId: string): Promise<Sandbox$1 | null>;
3869
- list?(): Promise<Sandbox$1[]>;
150
+ create(options?: CreateSandboxOptions): Promise<Sandbox>;
151
+ getById(sandboxId: string): Promise<Sandbox | null>;
152
+ list?(): Promise<Sandbox[]>;
3870
153
  destroy(sandboxId: string): Promise<void>;
3871
- findOrCreate?(options: FindOrCreateSandboxOptions): Promise<Sandbox$1>;
3872
- find?(options: FindSandboxOptions): Promise<Sandbox$1 | null>;
3873
- extendTimeout?(sandboxId: string, options?: ExtendTimeoutOptions): Promise<void>;
3874
154
  }
3875
155
  interface ProviderSnapshotManager {
3876
156
  create(sandboxId: string, options?: {
@@ -3907,7 +187,7 @@ interface ExplicitComputeConfig {
3907
187
  providers?: DirectProvider[];
3908
188
  /** Provider selection strategy when no explicit provider is passed */
3909
189
  providerStrategy?: 'priority' | 'round-robin';
3910
- /** Retry the next provider when create/find-or-create fails */
190
+ /** Retry the next provider when create fails */
3911
191
  fallbackOnError?: boolean;
3912
192
  }
3913
193
  declare class ComputeManager {
@@ -3925,16 +205,12 @@ declare class ComputeManager {
3925
205
  private getSnapshotDeleteCandidates;
3926
206
  private getSnapshotCreateCandidates;
3927
207
  private createWithFallback;
3928
- private findOrCreateWithFallback;
3929
208
  setConfig(config: ExplicitComputeConfig): void;
3930
209
  sandbox: {
3931
- create: (options?: CreateSandboxOptions) => Promise<Sandbox$1>;
3932
- getById: (sandboxId: string) => Promise<Sandbox$1 | null>;
3933
- list: () => Promise<Sandbox$1[]>;
210
+ create: (options?: CreateSandboxOptions) => Promise<Sandbox>;
211
+ getById: (sandboxId: string) => Promise<Sandbox | null>;
212
+ list: () => Promise<Sandbox[]>;
3934
213
  destroy: (sandboxId: string) => Promise<void>;
3935
- findOrCreate: (options: FindOrCreateSandboxOptions) => Promise<Sandbox$1>;
3936
- find: (options: FindSandboxOptions) => Promise<Sandbox$1 | null>;
3937
- extendTimeout: (sandboxId: string, options?: ExtendTimeoutOptions) => Promise<void>;
3938
214
  };
3939
215
  snapshot: {
3940
216
  create: (sandboxId: string, options?: CreateSnapshotOptions) => Promise<{
@@ -3958,4 +234,4 @@ interface CallableCompute extends ComputeManager {
3958
234
  }
3959
235
  declare const compute: CallableCompute;
3960
236
 
3961
- export { type CallableCompute, type CodeResult$1 as CodeResult, CommandExitError, type CommandResult$1 as CommandResult, type CreateSandboxOptions$1 as CreateSandboxOptions, type ExplicitComputeConfig, type FileEntry, FileWatcher, MessageType, type ProviderSandboxInfo, type RunCommandOptions, type Runtime, Sandbox, type SandboxFileSystem, type SandboxInfo$1 as SandboxInfo, type Sandbox$1 as SandboxInterface, type SandboxStatus, type SetupOverlayConfig, type SetupPayload, SignalService, type Snapshot, TerminalInstance, type WebSocketConstructor, buildSetupPayload, compute, decodeBinaryMessage, encodeBinaryMessage, encodeSetupPayload, isCommandExitError };
237
+ export { type CallableCompute, type CodeResult, type CommandResult, type CreateSandboxOptions$1 as CreateSandboxOptions, type ExplicitComputeConfig, type FileEntry, type RunCommandOptions, type SandboxFileSystem, type SandboxInfo, type Sandbox as SandboxInterface, type Snapshot, compute };