@cloudflare/sandbox 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,346 +1,7 @@
1
- import { Container } from "@cloudflare/containers";
1
+ import { $ as ProcessCleanupResult, A as HttpClientOptions, B as ExecutionSession, C as WriteFileRequest, D as BaseApiResponse, E as ExecuteResponse, F as BucketCredentials, G as ISandbox, H as FileMetadata, I as BucketProvider, J as MountBucketOptions, K as ListFilesOptions, L as ExecEvent, M as ResponseHandler, N as SessionRequest, O as ContainerStub, P as BaseExecOptions, Q as Process, R as ExecOptions, S as ReadFileRequest, T as ExecuteRequest, U as FileStreamEvent, V as FileChunk, W as GitCheckoutResult, X as PortExposeResult, Y as PortCloseResult, Z as PortListResult, _ as GitCheckoutRequest, _t as RunCodeOptions, a as CreateSessionRequest, at as ProcessStartResult, b as FileOperationRequest, c as DeleteSessionResponse, ct as SessionOptions, d as ProcessClient, dt as isProcess, et as ProcessInfoResult, f as ExposePortRequest, ft as isProcessStatus, g as InterpreterClient, gt as ExecutionResult, h as ExecutionCallbacks, ht as Execution, i as CommandsResponse, it as ProcessOptions, j as RequestConfig, k as ErrorResponse, l as PingResponse, lt as StreamOptions, m as UnexposePortRequest, mt as CreateContextOptions, n as getSandbox, nt as ProcessListResult, o as CreateSessionResponse, ot as ProcessStatus, p as PortClient, pt as CodeContext, q as LogEvent, r as SandboxClient, rt as ProcessLogsResult, s as DeleteSessionRequest, st as SandboxOptions, t as Sandbox, tt as ProcessKillResult, u as UtilityClient, ut as isExecResult, v as GitClient, w as CommandClient, x as MkdirRequest, y as FileClient, z as ExecResult } from "./sandbox-B3vJ541e.js";
2
2
 
3
- //#region ../shared/dist/logger/types.d.ts
4
-
5
- type LogComponent = 'container' | 'sandbox-do' | 'executor';
6
- /**
7
- * Context metadata included in every log entry
8
- */
9
- interface LogContext {
10
- /**
11
- * Unique trace ID for request correlation across distributed components
12
- * Format: "tr_" + 16 hex chars (e.g., "tr_7f3a9b2c4e5d6f1a")
13
- */
14
- traceId: string;
15
- /**
16
- * Component that generated the log
17
- */
18
- component: LogComponent;
19
- /**
20
- * Sandbox identifier (which sandbox instance)
21
- */
22
- sandboxId?: string;
23
- /**
24
- * Session identifier (which session within sandbox)
25
- */
26
- sessionId?: string;
27
- /**
28
- * Process identifier (which background process)
29
- */
30
- processId?: string;
31
- /**
32
- * Command identifier (which command execution)
33
- */
34
- commandId?: string;
35
- /**
36
- * Operation name (e.g., 'exec', 'startProcess', 'writeFile')
37
- */
38
- operation?: string;
39
- /**
40
- * Duration in milliseconds
41
- */
42
- duration?: number;
43
- /**
44
- * Extensible for additional metadata
45
- */
46
- [key: string]: unknown;
47
- }
48
- /**
49
- * Logger interface for structured logging
50
- *
51
- * All methods accept optional context that gets merged with the logger's base context.
52
- */
53
- interface Logger {
54
- /**
55
- * Log debug-level message (most verbose, typically disabled in production)
56
- *
57
- * @param message Human-readable message
58
- * @param context Optional additional context
59
- */
60
- debug(message: string, context?: Partial<LogContext>): void;
61
- /**
62
- * Log info-level message (normal operational events)
63
- *
64
- * @param message Human-readable message
65
- * @param context Optional additional context
66
- */
67
- info(message: string, context?: Partial<LogContext>): void;
68
- /**
69
- * Log warning-level message (recoverable issues, degraded state)
70
- *
71
- * @param message Human-readable message
72
- * @param context Optional additional context
73
- */
74
- warn(message: string, context?: Partial<LogContext>): void;
75
- /**
76
- * Log error-level message (failures, exceptions)
77
- *
78
- * @param message Human-readable message
79
- * @param error Optional Error object to include
80
- * @param context Optional additional context
81
- */
82
- error(message: string, error?: Error, context?: Partial<LogContext>): void;
83
- /**
84
- * Create a child logger with additional context
85
- *
86
- * The child logger inherits all context from the parent and adds new context.
87
- * This is useful for adding operation-specific context without passing through parameters.
88
- *
89
- * @param context Additional context to merge
90
- * @returns New logger instance with merged context
91
- *
92
- * @example
93
- * const logger = createLogger({ component: 'sandbox-do', traceId: 'tr_abc123' });
94
- * const execLogger = logger.child({ operation: 'exec', commandId: 'cmd-456' });
95
- * execLogger.info('Command started'); // Includes all context: component, traceId, operation, commandId
96
- */
97
- child(context: Partial<LogContext>): Logger;
98
- }
99
- //#endregion
100
- //#region ../shared/dist/interpreter-types.d.ts
101
- interface CreateContextOptions {
102
- /**
103
- * Programming language for the context
104
- * @default 'python'
105
- */
106
- language?: 'python' | 'javascript' | 'typescript';
107
- /**
108
- * Working directory for the context
109
- * @default '/workspace'
110
- */
111
- cwd?: string;
112
- /**
113
- * Environment variables for the context
114
- */
115
- envVars?: Record<string, string>;
116
- /**
117
- * Request timeout in milliseconds
118
- * @default 30000
119
- */
120
- timeout?: number;
121
- }
122
- interface CodeContext {
123
- /**
124
- * Unique identifier for the context
125
- */
126
- readonly id: string;
127
- /**
128
- * Programming language of the context
129
- */
130
- readonly language: string;
131
- /**
132
- * Current working directory
133
- */
134
- readonly cwd: string;
135
- /**
136
- * When the context was created
137
- */
138
- readonly createdAt: Date;
139
- /**
140
- * When the context was last used
141
- */
142
- readonly lastUsed: Date;
143
- }
144
- interface RunCodeOptions {
145
- /**
146
- * Context to run the code in. If not provided, uses default context for the language
147
- */
148
- context?: CodeContext;
149
- /**
150
- * Language to use if context is not provided
151
- * @default 'python'
152
- */
153
- language?: 'python' | 'javascript' | 'typescript';
154
- /**
155
- * Environment variables for this execution
156
- */
157
- envVars?: Record<string, string>;
158
- /**
159
- * Execution timeout in milliseconds
160
- * @default 60000
161
- */
162
- timeout?: number;
163
- /**
164
- * AbortSignal for cancelling execution
165
- */
166
- signal?: AbortSignal;
167
- /**
168
- * Callback for stdout output
169
- */
170
- onStdout?: (output: OutputMessage) => void | Promise<void>;
171
- /**
172
- * Callback for stderr output
173
- */
174
- onStderr?: (output: OutputMessage) => void | Promise<void>;
175
- /**
176
- * Callback for execution results (charts, tables, etc)
177
- */
178
- onResult?: (result: Result) => void | Promise<void>;
179
- /**
180
- * Callback for execution errors
181
- */
182
- onError?: (error: ExecutionError) => void | Promise<void>;
183
- }
184
- interface OutputMessage {
185
- /**
186
- * The output text
187
- */
188
- text: string;
189
- /**
190
- * Timestamp of the output
191
- */
192
- timestamp: number;
193
- }
194
- interface Result {
195
- /**
196
- * Plain text representation
197
- */
198
- text?: string;
199
- /**
200
- * HTML representation (tables, formatted output)
201
- */
202
- html?: string;
203
- /**
204
- * PNG image data (base64 encoded)
205
- */
206
- png?: string;
207
- /**
208
- * JPEG image data (base64 encoded)
209
- */
210
- jpeg?: string;
211
- /**
212
- * SVG image data
213
- */
214
- svg?: string;
215
- /**
216
- * LaTeX representation
217
- */
218
- latex?: string;
219
- /**
220
- * Markdown representation
221
- */
222
- markdown?: string;
223
- /**
224
- * JavaScript code to execute
225
- */
226
- javascript?: string;
227
- /**
228
- * JSON data
229
- */
230
- json?: any;
231
- /**
232
- * Chart data if the result is a visualization
233
- */
234
- chart?: ChartData;
235
- /**
236
- * Raw data object
237
- */
238
- data?: any;
239
- /**
240
- * Available output formats
241
- */
242
- formats(): string[];
243
- }
244
- interface ChartData {
245
- /**
246
- * Type of chart
247
- */
248
- type: 'line' | 'bar' | 'scatter' | 'pie' | 'histogram' | 'heatmap' | 'unknown';
249
- /**
250
- * Chart title
251
- */
252
- title?: string;
253
- /**
254
- * Chart data (format depends on library)
255
- */
256
- data: any;
257
- /**
258
- * Chart layout/configuration
259
- */
260
- layout?: any;
261
- /**
262
- * Additional configuration
263
- */
264
- config?: any;
265
- /**
266
- * Library that generated the chart
267
- */
268
- library?: 'matplotlib' | 'plotly' | 'altair' | 'seaborn' | 'unknown';
269
- /**
270
- * Base64 encoded image if available
271
- */
272
- image?: string;
273
- }
274
- interface ExecutionError {
275
- /**
276
- * Error name/type (e.g., 'NameError', 'SyntaxError')
277
- */
278
- name: string;
279
- /**
280
- * Error message
281
- */
282
- message: string;
283
- /**
284
- * Stack trace
285
- */
286
- traceback: string[];
287
- /**
288
- * Line number where error occurred
289
- */
290
- lineNumber?: number;
291
- }
292
- interface ExecutionResult {
293
- code: string;
294
- logs: {
295
- stdout: string[];
296
- stderr: string[];
297
- };
298
- error?: ExecutionError;
299
- executionCount?: number;
300
- results: Array<{
301
- text?: string;
302
- html?: string;
303
- png?: string;
304
- jpeg?: string;
305
- svg?: string;
306
- latex?: string;
307
- markdown?: string;
308
- javascript?: string;
309
- json?: any;
310
- chart?: ChartData;
311
- data?: any;
312
- }>;
313
- }
314
- declare class Execution {
315
- readonly code: string;
316
- readonly context: CodeContext;
317
- /**
318
- * All results from the execution
319
- */
320
- results: Result[];
321
- /**
322
- * Accumulated stdout and stderr
323
- */
324
- logs: {
325
- stdout: string[];
326
- stderr: string[];
327
- };
328
- /**
329
- * Execution error if any
330
- */
331
- error?: ExecutionError;
332
- /**
333
- * Execution count (for interpreter)
334
- */
335
- executionCount?: number;
336
- constructor(code: string, context: CodeContext);
337
- /**
338
- * Convert to a plain object for serialization
339
- */
340
- toJSON(): ExecutionResult;
341
- }
342
- //#endregion
343
3
  //#region ../shared/dist/request-types.d.ts
4
+
344
5
  /**
345
6
  * Request to start a background process
346
7
  * Uses flat structure consistent with other endpoints
@@ -356,1391 +17,6 @@ interface StartProcessRequest {
356
17
  autoCleanup?: boolean;
357
18
  }
358
19
  //#endregion
359
- //#region ../shared/dist/types.d.ts
360
- interface BaseExecOptions {
361
- /**
362
- * Maximum execution time in milliseconds
363
- */
364
- timeout?: number;
365
- /**
366
- * Environment variables for the command
367
- */
368
- env?: Record<string, string>;
369
- /**
370
- * Working directory for command execution
371
- */
372
- cwd?: string;
373
- /**
374
- * Text encoding for output (default: 'utf8')
375
- */
376
- encoding?: string;
377
- }
378
- interface ExecOptions extends BaseExecOptions {
379
- /**
380
- * Enable real-time output streaming via callbacks
381
- */
382
- stream?: boolean;
383
- /**
384
- * Callback for real-time output data
385
- */
386
- onOutput?: (stream: 'stdout' | 'stderr', data: string) => void;
387
- /**
388
- * Callback when command completes (only when stream: true)
389
- */
390
- onComplete?: (result: ExecResult) => void;
391
- /**
392
- * Callback for execution errors
393
- */
394
- onError?: (error: Error) => void;
395
- /**
396
- * AbortSignal for cancelling execution
397
- */
398
- signal?: AbortSignal;
399
- }
400
- interface ExecResult {
401
- /**
402
- * Whether the command succeeded (exitCode === 0)
403
- */
404
- success: boolean;
405
- /**
406
- * Process exit code
407
- */
408
- exitCode: number;
409
- /**
410
- * Standard output content
411
- */
412
- stdout: string;
413
- /**
414
- * Standard error content
415
- */
416
- stderr: string;
417
- /**
418
- * Command that was executed
419
- */
420
- command: string;
421
- /**
422
- * Execution duration in milliseconds
423
- */
424
- duration: number;
425
- /**
426
- * ISO timestamp when command started
427
- */
428
- timestamp: string;
429
- /**
430
- * Session ID if provided
431
- */
432
- sessionId?: string;
433
- }
434
- interface ProcessOptions extends BaseExecOptions {
435
- /**
436
- * Custom process ID for later reference
437
- * If not provided, a UUID will be generated
438
- */
439
- processId?: string;
440
- /**
441
- * Automatically cleanup process record after exit (default: true)
442
- */
443
- autoCleanup?: boolean;
444
- /**
445
- * Callback when process exits
446
- */
447
- onExit?: (code: number | null) => void;
448
- /**
449
- * Callback for real-time output (background processes)
450
- */
451
- onOutput?: (stream: 'stdout' | 'stderr', data: string) => void;
452
- /**
453
- * Callback when process starts successfully
454
- */
455
- onStart?: (process: Process) => void;
456
- /**
457
- * Callback for process errors
458
- */
459
- onError?: (error: Error) => void;
460
- }
461
- type ProcessStatus = 'starting' | 'running' | 'completed' | 'failed' | 'killed' | 'error';
462
- interface Process {
463
- /**
464
- * Unique process identifier
465
- */
466
- readonly id: string;
467
- /**
468
- * System process ID (if available and running)
469
- */
470
- readonly pid?: number;
471
- /**
472
- * Command that was executed
473
- */
474
- readonly command: string;
475
- /**
476
- * Current process status
477
- */
478
- readonly status: ProcessStatus;
479
- /**
480
- * When the process was started
481
- */
482
- readonly startTime: Date;
483
- /**
484
- * When the process ended (if completed)
485
- */
486
- readonly endTime?: Date;
487
- /**
488
- * Process exit code (if completed)
489
- */
490
- readonly exitCode?: number;
491
- /**
492
- * Session ID if provided
493
- */
494
- readonly sessionId?: string;
495
- /**
496
- * Kill the process
497
- */
498
- kill(signal?: string): Promise<void>;
499
- /**
500
- * Get current process status (refreshed)
501
- */
502
- getStatus(): Promise<ProcessStatus>;
503
- /**
504
- * Get accumulated logs
505
- */
506
- getLogs(): Promise<{
507
- stdout: string;
508
- stderr: string;
509
- }>;
510
- }
511
- interface ExecEvent {
512
- type: 'start' | 'stdout' | 'stderr' | 'complete' | 'error';
513
- timestamp: string;
514
- data?: string;
515
- command?: string;
516
- exitCode?: number;
517
- result?: ExecResult;
518
- error?: string;
519
- sessionId?: string;
520
- }
521
- interface LogEvent {
522
- type: 'stdout' | 'stderr' | 'exit' | 'error';
523
- timestamp: string;
524
- data: string;
525
- processId: string;
526
- sessionId?: string;
527
- exitCode?: number;
528
- }
529
- interface StreamOptions extends BaseExecOptions {
530
- /**
531
- * Buffer size for streaming output
532
- */
533
- bufferSize?: number;
534
- /**
535
- * AbortSignal for cancelling stream
536
- */
537
- signal?: AbortSignal;
538
- }
539
- interface SessionOptions {
540
- /**
541
- * Optional session ID (auto-generated if not provided)
542
- */
543
- id?: string;
544
- /**
545
- * Session name for identification
546
- */
547
- name?: string;
548
- /**
549
- * Environment variables for this session
550
- */
551
- env?: Record<string, string>;
552
- /**
553
- * Working directory
554
- */
555
- cwd?: string;
556
- /**
557
- * Enable PID namespace isolation (requires CAP_SYS_ADMIN)
558
- */
559
- isolation?: boolean;
560
- }
561
- interface SandboxOptions {
562
- /**
563
- * Duration after which the sandbox instance will sleep if no requests are received
564
- * Can be:
565
- * - A string like "30s", "3m", "5m", "1h" (seconds, minutes, or hours)
566
- * - A number representing seconds (e.g., 180 for 3 minutes)
567
- * Default: "10m" (10 minutes)
568
- *
569
- * Note: Ignored when keepAlive is true
570
- */
571
- sleepAfter?: string | number;
572
- /**
573
- * Base URL for the sandbox API
574
- */
575
- baseUrl?: string;
576
- /**
577
- * Keep the container alive indefinitely by preventing automatic shutdown
578
- * When true, the container will never auto-timeout and must be explicitly destroyed
579
- * - Any scenario where activity can't be automatically detected
580
- *
581
- * Important: You MUST call sandbox.destroy() when done to avoid resource leaks
582
- *
583
- * Default: false
584
- */
585
- keepAlive?: boolean;
586
- /**
587
- * Normalize sandbox ID to lowercase for preview URL compatibility
588
- *
589
- * Required for preview URLs because hostnames are case-insensitive (RFC 3986), which
590
- * would route requests to a different Durable Object instance with IDs containing uppercase letters.
591
- *
592
- * **Important:** Different normalizeId values create different Durable Object instances:
593
- * - `getSandbox(ns, "MyProject")` → DO key: "MyProject"
594
- * - `getSandbox(ns, "MyProject", {normalizeId: true})` → DO key: "myproject"
595
- *
596
- * **Future change:** In a future version, this will default to `true` (automatically lowercase all IDs).
597
- * IDs with uppercase letters will trigger a warning. To prepare, use lowercase IDs or explicitly
598
- * pass `normalizeId: true`.
599
- *
600
- * @example
601
- * getSandbox(ns, "my-project") // Works with preview URLs (lowercase)
602
- * getSandbox(ns, "MyProject", {normalizeId: true}) // Normalized to "myproject"
603
- *
604
- * @default false
605
- */
606
- normalizeId?: boolean;
607
- /**
608
- * Container startup timeout configuration
609
- *
610
- * Tune timeouts based on your container's characteristics. SDK defaults (30s instance, 90s ports)
611
- * work for most use cases. Adjust for heavy containers or fail-fast applications.
612
- *
613
- * Can also be configured via environment variables:
614
- * - SANDBOX_INSTANCE_TIMEOUT_MS
615
- * - SANDBOX_PORT_TIMEOUT_MS
616
- * - SANDBOX_POLL_INTERVAL_MS
617
- *
618
- * Precedence: options > env vars > SDK defaults
619
- *
620
- * @example
621
- * // Heavy containers (ML models, large apps)
622
- * getSandbox(ns, id, {
623
- * containerTimeouts: { portReadyTimeoutMS: 180_000 }
624
- * })
625
- *
626
- * @example
627
- * // Fail-fast for latency-sensitive apps
628
- * getSandbox(ns, id, {
629
- * containerTimeouts: {
630
- * instanceGetTimeoutMS: 15_000,
631
- * portReadyTimeoutMS: 30_000
632
- * }
633
- * })
634
- */
635
- containerTimeouts?: {
636
- /**
637
- * Time to wait for container instance provisioning
638
- * @default 30000 (30s) - or SANDBOX_INSTANCE_TIMEOUT_MS env var
639
- */
640
- instanceGetTimeoutMS?: number;
641
- /**
642
- * Time to wait for application startup and ports to be ready
643
- * @default 90000 (90s) - or SANDBOX_PORT_TIMEOUT_MS env var
644
- */
645
- portReadyTimeoutMS?: number;
646
- /**
647
- * How often to poll for container readiness
648
- * @default 1000 (1s) - or SANDBOX_POLL_INTERVAL_MS env var
649
- */
650
- waitIntervalMS?: number;
651
- };
652
- }
653
- /**
654
- * Execution session - isolated execution context within a sandbox
655
- * Returned by sandbox.createSession()
656
- * Provides the same API as ISandbox but bound to a specific session
657
- */
658
- interface MkdirResult {
659
- success: boolean;
660
- path: string;
661
- recursive: boolean;
662
- timestamp: string;
663
- exitCode?: number;
664
- }
665
- interface WriteFileResult {
666
- success: boolean;
667
- path: string;
668
- timestamp: string;
669
- exitCode?: number;
670
- }
671
- interface ReadFileResult {
672
- success: boolean;
673
- path: string;
674
- content: string;
675
- timestamp: string;
676
- exitCode?: number;
677
- /**
678
- * Encoding used for content (utf-8 for text, base64 for binary)
679
- */
680
- encoding?: 'utf-8' | 'base64';
681
- /**
682
- * Whether the file is detected as binary
683
- */
684
- isBinary?: boolean;
685
- /**
686
- * MIME type of the file (e.g., 'image/png', 'text/plain')
687
- */
688
- mimeType?: string;
689
- /**
690
- * File size in bytes
691
- */
692
- size?: number;
693
- }
694
- interface DeleteFileResult {
695
- success: boolean;
696
- path: string;
697
- timestamp: string;
698
- exitCode?: number;
699
- }
700
- interface RenameFileResult {
701
- success: boolean;
702
- path: string;
703
- newPath: string;
704
- timestamp: string;
705
- exitCode?: number;
706
- }
707
- interface MoveFileResult {
708
- success: boolean;
709
- path: string;
710
- newPath: string;
711
- timestamp: string;
712
- exitCode?: number;
713
- }
714
- interface FileExistsResult {
715
- success: boolean;
716
- path: string;
717
- exists: boolean;
718
- timestamp: string;
719
- }
720
- interface FileInfo {
721
- name: string;
722
- absolutePath: string;
723
- relativePath: string;
724
- type: 'file' | 'directory' | 'symlink' | 'other';
725
- size: number;
726
- modifiedAt: string;
727
- mode: string;
728
- permissions: {
729
- readable: boolean;
730
- writable: boolean;
731
- executable: boolean;
732
- };
733
- }
734
- interface ListFilesOptions {
735
- recursive?: boolean;
736
- includeHidden?: boolean;
737
- }
738
- interface ListFilesResult {
739
- success: boolean;
740
- path: string;
741
- files: FileInfo[];
742
- count: number;
743
- timestamp: string;
744
- exitCode?: number;
745
- }
746
- interface GitCheckoutResult {
747
- success: boolean;
748
- repoUrl: string;
749
- branch: string;
750
- targetDir: string;
751
- timestamp: string;
752
- exitCode?: number;
753
- }
754
- /**
755
- * SSE events for file streaming
756
- */
757
- type FileStreamEvent = {
758
- type: 'metadata';
759
- mimeType: string;
760
- size: number;
761
- isBinary: boolean;
762
- encoding: 'utf-8' | 'base64';
763
- } | {
764
- type: 'chunk';
765
- data: string;
766
- } | {
767
- type: 'complete';
768
- bytesRead: number;
769
- } | {
770
- type: 'error';
771
- error: string;
772
- };
773
- /**
774
- * File metadata from streaming
775
- */
776
- interface FileMetadata {
777
- mimeType: string;
778
- size: number;
779
- isBinary: boolean;
780
- encoding: 'utf-8' | 'base64';
781
- }
782
- /**
783
- * File stream chunk - either string (text) or Uint8Array (binary, auto-decoded)
784
- */
785
- type FileChunk = string | Uint8Array;
786
- interface ProcessStartResult {
787
- success: boolean;
788
- processId: string;
789
- pid?: number;
790
- command: string;
791
- timestamp: string;
792
- }
793
- interface ProcessListResult {
794
- success: boolean;
795
- processes: Array<{
796
- id: string;
797
- pid?: number;
798
- command: string;
799
- status: ProcessStatus;
800
- startTime: string;
801
- endTime?: string;
802
- exitCode?: number;
803
- }>;
804
- timestamp: string;
805
- }
806
- interface ProcessInfoResult {
807
- success: boolean;
808
- process: {
809
- id: string;
810
- pid?: number;
811
- command: string;
812
- status: ProcessStatus;
813
- startTime: string;
814
- endTime?: string;
815
- exitCode?: number;
816
- };
817
- timestamp: string;
818
- }
819
- interface ProcessKillResult {
820
- success: boolean;
821
- processId: string;
822
- signal?: string;
823
- timestamp: string;
824
- }
825
- interface ProcessLogsResult {
826
- success: boolean;
827
- processId: string;
828
- stdout: string;
829
- stderr: string;
830
- timestamp: string;
831
- }
832
- interface ProcessCleanupResult {
833
- success: boolean;
834
- cleanedCount: number;
835
- timestamp: string;
836
- }
837
- interface SessionDeleteResult {
838
- success: boolean;
839
- sessionId: string;
840
- timestamp: string;
841
- }
842
- interface PortExposeResult {
843
- success: boolean;
844
- port: number;
845
- url: string;
846
- timestamp: string;
847
- }
848
- interface PortListResult {
849
- success: boolean;
850
- ports: Array<{
851
- port: number;
852
- url: string;
853
- status: 'active' | 'inactive';
854
- }>;
855
- timestamp: string;
856
- }
857
- interface PortCloseResult {
858
- success: boolean;
859
- port: number;
860
- timestamp: string;
861
- }
862
- interface ExecutionSession {
863
- /** Unique session identifier */
864
- readonly id: string;
865
- exec(command: string, options?: ExecOptions): Promise<ExecResult>;
866
- execStream(command: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>>;
867
- startProcess(command: string, options?: ProcessOptions): Promise<Process>;
868
- listProcesses(): Promise<Process[]>;
869
- getProcess(id: string): Promise<Process | null>;
870
- killProcess(id: string, signal?: string): Promise<void>;
871
- killAllProcesses(): Promise<number>;
872
- cleanupCompletedProcesses(): Promise<number>;
873
- getProcessLogs(id: string): Promise<{
874
- stdout: string;
875
- stderr: string;
876
- processId: string;
877
- }>;
878
- streamProcessLogs(processId: string, options?: {
879
- signal?: AbortSignal;
880
- }): Promise<ReadableStream<Uint8Array>>;
881
- writeFile(path: string, content: string, options?: {
882
- encoding?: string;
883
- }): Promise<WriteFileResult>;
884
- readFile(path: string, options?: {
885
- encoding?: string;
886
- }): Promise<ReadFileResult>;
887
- readFileStream(path: string): Promise<ReadableStream<Uint8Array>>;
888
- mkdir(path: string, options?: {
889
- recursive?: boolean;
890
- }): Promise<MkdirResult>;
891
- deleteFile(path: string): Promise<DeleteFileResult>;
892
- renameFile(oldPath: string, newPath: string): Promise<RenameFileResult>;
893
- moveFile(sourcePath: string, destinationPath: string): Promise<MoveFileResult>;
894
- listFiles(path: string, options?: ListFilesOptions): Promise<ListFilesResult>;
895
- exists(path: string): Promise<FileExistsResult>;
896
- gitCheckout(repoUrl: string, options?: {
897
- branch?: string;
898
- targetDir?: string;
899
- }): Promise<GitCheckoutResult>;
900
- setEnvVars(envVars: Record<string, string>): Promise<void>;
901
- createCodeContext(options?: CreateContextOptions): Promise<CodeContext>;
902
- runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>;
903
- runCodeStream(code: string, options?: RunCodeOptions): Promise<ReadableStream<Uint8Array>>;
904
- listCodeContexts(): Promise<CodeContext[]>;
905
- deleteCodeContext(contextId: string): Promise<void>;
906
- mountBucket(bucket: string, mountPath: string, options: MountBucketOptions): Promise<void>;
907
- unmountBucket(mountPath: string): Promise<void>;
908
- }
909
- /**
910
- * Supported S3-compatible storage providers
911
- */
912
- type BucketProvider = 'r2' | 's3' | 'gcs';
913
- /**
914
- * Credentials for S3-compatible storage
915
- */
916
- interface BucketCredentials {
917
- accessKeyId: string;
918
- secretAccessKey: string;
919
- }
920
- /**
921
- * Options for mounting an S3-compatible bucket
922
- */
923
- interface MountBucketOptions {
924
- /**
925
- * S3-compatible endpoint URL
926
- *
927
- * Examples:
928
- * - R2: 'https://abc123.r2.cloudflarestorage.com'
929
- * - AWS S3: 'https://s3.us-west-2.amazonaws.com'
930
- * - GCS: 'https://storage.googleapis.com'
931
- *
932
- * Required field
933
- */
934
- endpoint: string;
935
- /**
936
- * Optional provider hint for automatic s3fs flag configuration
937
- * If not specified, will attempt to detect from endpoint URL.
938
- *
939
- * Examples:
940
- * - 'r2' - Cloudflare R2 (adds nomixupload)
941
- * - 's3' - Amazon S3 (standard configuration)
942
- * - 'gcs' - Google Cloud Storage (no special flags needed)
943
- */
944
- provider?: BucketProvider;
945
- /**
946
- * Explicit credentials (overrides env var auto-detection)
947
- */
948
- credentials?: BucketCredentials;
949
- /**
950
- * Mount filesystem as read-only
951
- * Default: false
952
- */
953
- readOnly?: boolean;
954
- /**
955
- * Advanced: Override or extend s3fs options
956
- *
957
- * These will be merged with provider-specific defaults.
958
- * To override defaults completely, specify all options here.
959
- *
960
- * Common options:
961
- * - 'use_path_request_style' - Use path-style URLs (bucket/path vs bucket.host/path)
962
- * - 'nomixupload' - Disable mixed multipart uploads (needed for some providers)
963
- * - 'nomultipart' - Disable all multipart operations
964
- * - 'sigv2' - Use signature version 2 instead of v4
965
- * - 'no_check_certificate' - Skip SSL certificate validation (dev/testing only)
966
- */
967
- s3fsOptions?: string[];
968
- }
969
- interface ISandbox {
970
- exec(command: string, options?: ExecOptions): Promise<ExecResult>;
971
- startProcess(command: string, options?: ProcessOptions): Promise<Process>;
972
- listProcesses(): Promise<Process[]>;
973
- getProcess(id: string): Promise<Process | null>;
974
- killProcess(id: string, signal?: string): Promise<void>;
975
- killAllProcesses(): Promise<number>;
976
- execStream(command: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>>;
977
- streamProcessLogs(processId: string, options?: {
978
- signal?: AbortSignal;
979
- }): Promise<ReadableStream<Uint8Array>>;
980
- cleanupCompletedProcesses(): Promise<number>;
981
- getProcessLogs(id: string): Promise<{
982
- stdout: string;
983
- stderr: string;
984
- processId: string;
985
- }>;
986
- writeFile(path: string, content: string, options?: {
987
- encoding?: string;
988
- }): Promise<WriteFileResult>;
989
- readFile(path: string, options?: {
990
- encoding?: string;
991
- }): Promise<ReadFileResult>;
992
- readFileStream(path: string): Promise<ReadableStream<Uint8Array>>;
993
- mkdir(path: string, options?: {
994
- recursive?: boolean;
995
- }): Promise<MkdirResult>;
996
- deleteFile(path: string): Promise<DeleteFileResult>;
997
- renameFile(oldPath: string, newPath: string): Promise<RenameFileResult>;
998
- moveFile(sourcePath: string, destinationPath: string): Promise<MoveFileResult>;
999
- listFiles(path: string, options?: ListFilesOptions): Promise<ListFilesResult>;
1000
- exists(path: string, sessionId?: string): Promise<FileExistsResult>;
1001
- gitCheckout(repoUrl: string, options?: {
1002
- branch?: string;
1003
- targetDir?: string;
1004
- }): Promise<GitCheckoutResult>;
1005
- mountBucket(bucket: string, mountPath: string, options: MountBucketOptions): Promise<void>;
1006
- unmountBucket(mountPath: string): Promise<void>;
1007
- createSession(options?: SessionOptions): Promise<ExecutionSession>;
1008
- deleteSession(sessionId: string): Promise<SessionDeleteResult>;
1009
- createCodeContext(options?: CreateContextOptions): Promise<CodeContext>;
1010
- runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>;
1011
- runCodeStream(code: string, options?: RunCodeOptions): Promise<ReadableStream>;
1012
- listCodeContexts(): Promise<CodeContext[]>;
1013
- deleteCodeContext(contextId: string): Promise<void>;
1014
- wsConnect(request: Request, port: number): Promise<Response>;
1015
- }
1016
- declare function isExecResult(value: any): value is ExecResult;
1017
- declare function isProcess(value: any): value is Process;
1018
- declare function isProcessStatus(value: string): value is ProcessStatus;
1019
- //#endregion
1020
- //#region src/clients/types.d.ts
1021
- /**
1022
- * Minimal interface for container fetch functionality
1023
- */
1024
- interface ContainerStub {
1025
- containerFetch(url: string, options: RequestInit, port?: number): Promise<Response>;
1026
- }
1027
- /**
1028
- * Shared HTTP client configuration options
1029
- */
1030
- interface HttpClientOptions {
1031
- logger?: Logger;
1032
- baseUrl?: string;
1033
- port?: number;
1034
- stub?: ContainerStub;
1035
- onCommandComplete?: (success: boolean, exitCode: number, stdout: string, stderr: string, command: string) => void;
1036
- onError?: (error: string, command?: string) => void;
1037
- }
1038
- /**
1039
- * Base response interface for all API responses
1040
- */
1041
- interface BaseApiResponse {
1042
- success: boolean;
1043
- timestamp: string;
1044
- }
1045
- /**
1046
- * Legacy error response interface - deprecated, use ApiErrorResponse
1047
- */
1048
- interface ErrorResponse {
1049
- error: string;
1050
- details?: string;
1051
- code?: string;
1052
- }
1053
- /**
1054
- * HTTP request configuration
1055
- */
1056
- interface RequestConfig extends RequestInit {
1057
- endpoint: string;
1058
- data?: Record<string, any>;
1059
- }
1060
- /**
1061
- * Typed response handler
1062
- */
1063
- type ResponseHandler<T> = (response: Response) => Promise<T>;
1064
- /**
1065
- * Common session-aware request interface
1066
- */
1067
- interface SessionRequest {
1068
- sessionId?: string;
1069
- }
1070
- //#endregion
1071
- //#region src/clients/base-client.d.ts
1072
- /**
1073
- * Abstract base class providing common HTTP functionality for all domain clients
1074
- */
1075
- declare abstract class BaseHttpClient {
1076
- protected baseUrl: string;
1077
- protected options: HttpClientOptions;
1078
- protected logger: Logger;
1079
- constructor(options?: HttpClientOptions);
1080
- /**
1081
- * Core HTTP request method with automatic retry for container startup delays
1082
- * Retries both 503 (provisioning) and 500 (startup failure) errors when they're container-related
1083
- */
1084
- protected doFetch(path: string, options?: RequestInit): Promise<Response>;
1085
- /**
1086
- * Make a POST request with JSON body
1087
- */
1088
- protected post<T>(endpoint: string, data: unknown, responseHandler?: ResponseHandler<T>): Promise<T>;
1089
- /**
1090
- * Make a GET request
1091
- */
1092
- protected get<T>(endpoint: string, responseHandler?: ResponseHandler<T>): Promise<T>;
1093
- /**
1094
- * Make a DELETE request
1095
- */
1096
- protected delete<T>(endpoint: string, responseHandler?: ResponseHandler<T>): Promise<T>;
1097
- /**
1098
- * Handle HTTP response with error checking and parsing
1099
- */
1100
- protected handleResponse<T>(response: Response, customHandler?: ResponseHandler<T>): Promise<T>;
1101
- /**
1102
- * Handle error responses with consistent error throwing
1103
- */
1104
- protected handleErrorResponse(response: Response): Promise<never>;
1105
- /**
1106
- * Create a streaming response handler for Server-Sent Events
1107
- */
1108
- protected handleStreamResponse(response: Response): Promise<ReadableStream<Uint8Array>>;
1109
- /**
1110
- * Utility method to log successful operations
1111
- */
1112
- protected logSuccess(operation: string, details?: string): void;
1113
- /**
1114
- * Utility method to log errors intelligently
1115
- * Only logs unexpected errors (5xx), not expected errors (4xx)
1116
- *
1117
- * - 4xx errors (validation, not found, conflicts): Don't log (expected client errors)
1118
- * - 5xx errors (server failures, internal errors): DO log (unexpected server errors)
1119
- */
1120
- protected logError(operation: string, error: unknown): void;
1121
- /**
1122
- * Check if response indicates a retryable container error
1123
- * Uses fail-safe strategy: only retry known transient errors
1124
- *
1125
- * TODO: This relies on string matching error messages, which is brittle.
1126
- * Ideally, the container API should return structured errors with a
1127
- * `retryable: boolean` field to avoid coupling to error message format.
1128
- *
1129
- * @param response - HTTP response to check
1130
- * @returns true if error is retryable container error, false otherwise
1131
- */
1132
- private isRetryableContainerError;
1133
- private executeFetch;
1134
- }
1135
- //#endregion
1136
- //#region src/clients/command-client.d.ts
1137
- /**
1138
- * Request interface for command execution
1139
- */
1140
- interface ExecuteRequest extends SessionRequest {
1141
- command: string;
1142
- timeoutMs?: number;
1143
- }
1144
- /**
1145
- * Response interface for command execution
1146
- */
1147
- interface ExecuteResponse extends BaseApiResponse {
1148
- stdout: string;
1149
- stderr: string;
1150
- exitCode: number;
1151
- command: string;
1152
- }
1153
- /**
1154
- * Client for command execution operations
1155
- */
1156
- declare class CommandClient extends BaseHttpClient {
1157
- /**
1158
- * Execute a command and return the complete result
1159
- * @param command - The command to execute
1160
- * @param sessionId - The session ID for this command execution
1161
- * @param timeoutMs - Optional timeout in milliseconds (unlimited by default)
1162
- */
1163
- execute(command: string, sessionId: string, timeoutMs?: number): Promise<ExecuteResponse>;
1164
- /**
1165
- * Execute a command and return a stream of events
1166
- * @param command - The command to execute
1167
- * @param sessionId - The session ID for this command execution
1168
- */
1169
- executeStream(command: string, sessionId: string): Promise<ReadableStream<Uint8Array>>;
1170
- }
1171
- //#endregion
1172
- //#region src/clients/file-client.d.ts
1173
- /**
1174
- * Request interface for creating directories
1175
- */
1176
- interface MkdirRequest extends SessionRequest {
1177
- path: string;
1178
- recursive?: boolean;
1179
- }
1180
- /**
1181
- * Request interface for writing files
1182
- */
1183
- interface WriteFileRequest extends SessionRequest {
1184
- path: string;
1185
- content: string;
1186
- encoding?: string;
1187
- }
1188
- /**
1189
- * Request interface for reading files
1190
- */
1191
- interface ReadFileRequest extends SessionRequest {
1192
- path: string;
1193
- encoding?: string;
1194
- }
1195
- /**
1196
- * Request interface for file operations (delete, rename, move)
1197
- */
1198
- interface FileOperationRequest extends SessionRequest {
1199
- path: string;
1200
- newPath?: string;
1201
- }
1202
- /**
1203
- * Client for file system operations
1204
- */
1205
- declare class FileClient extends BaseHttpClient {
1206
- /**
1207
- * Create a directory
1208
- * @param path - Directory path to create
1209
- * @param sessionId - The session ID for this operation
1210
- * @param options - Optional settings (recursive)
1211
- */
1212
- mkdir(path: string, sessionId: string, options?: {
1213
- recursive?: boolean;
1214
- }): Promise<MkdirResult>;
1215
- /**
1216
- * Write content to a file
1217
- * @param path - File path to write to
1218
- * @param content - Content to write
1219
- * @param sessionId - The session ID for this operation
1220
- * @param options - Optional settings (encoding)
1221
- */
1222
- writeFile(path: string, content: string, sessionId: string, options?: {
1223
- encoding?: string;
1224
- }): Promise<WriteFileResult>;
1225
- /**
1226
- * Read content from a file
1227
- * @param path - File path to read from
1228
- * @param sessionId - The session ID for this operation
1229
- * @param options - Optional settings (encoding)
1230
- */
1231
- readFile(path: string, sessionId: string, options?: {
1232
- encoding?: string;
1233
- }): Promise<ReadFileResult>;
1234
- /**
1235
- * Stream a file using Server-Sent Events
1236
- * Returns a ReadableStream of SSE events containing metadata, chunks, and completion
1237
- * @param path - File path to stream
1238
- * @param sessionId - The session ID for this operation
1239
- */
1240
- readFileStream(path: string, sessionId: string): Promise<ReadableStream<Uint8Array>>;
1241
- /**
1242
- * Delete a file
1243
- * @param path - File path to delete
1244
- * @param sessionId - The session ID for this operation
1245
- */
1246
- deleteFile(path: string, sessionId: string): Promise<DeleteFileResult>;
1247
- /**
1248
- * Rename a file
1249
- * @param path - Current file path
1250
- * @param newPath - New file path
1251
- * @param sessionId - The session ID for this operation
1252
- */
1253
- renameFile(path: string, newPath: string, sessionId: string): Promise<RenameFileResult>;
1254
- /**
1255
- * Move a file
1256
- * @param path - Current file path
1257
- * @param newPath - Destination file path
1258
- * @param sessionId - The session ID for this operation
1259
- */
1260
- moveFile(path: string, newPath: string, sessionId: string): Promise<MoveFileResult>;
1261
- /**
1262
- * List files in a directory
1263
- * @param path - Directory path to list
1264
- * @param sessionId - The session ID for this operation
1265
- * @param options - Optional settings (recursive, includeHidden)
1266
- */
1267
- listFiles(path: string, sessionId: string, options?: ListFilesOptions): Promise<ListFilesResult>;
1268
- /**
1269
- * Check if a file or directory exists
1270
- * @param path - Path to check
1271
- * @param sessionId - The session ID for this operation
1272
- */
1273
- exists(path: string, sessionId: string): Promise<FileExistsResult>;
1274
- }
1275
- //#endregion
1276
- //#region src/clients/git-client.d.ts
1277
- /**
1278
- * Request interface for Git checkout operations
1279
- */
1280
- interface GitCheckoutRequest extends SessionRequest {
1281
- repoUrl: string;
1282
- branch?: string;
1283
- targetDir?: string;
1284
- }
1285
- /**
1286
- * Client for Git repository operations
1287
- */
1288
- declare class GitClient extends BaseHttpClient {
1289
- constructor(options?: HttpClientOptions);
1290
- /**
1291
- * Clone a Git repository
1292
- * @param repoUrl - URL of the Git repository to clone
1293
- * @param sessionId - The session ID for this operation
1294
- * @param options - Optional settings (branch, targetDir)
1295
- */
1296
- checkout(repoUrl: string, sessionId: string, options?: {
1297
- branch?: string;
1298
- targetDir?: string;
1299
- }): Promise<GitCheckoutResult>;
1300
- /**
1301
- * Extract repository name from URL for default directory name
1302
- */
1303
- private extractRepoName;
1304
- }
1305
- //#endregion
1306
- //#region src/clients/interpreter-client.d.ts
1307
- interface ExecutionCallbacks {
1308
- onStdout?: (output: OutputMessage) => void | Promise<void>;
1309
- onStderr?: (output: OutputMessage) => void | Promise<void>;
1310
- onResult?: (result: Result) => void | Promise<void>;
1311
- onError?: (error: ExecutionError) => void | Promise<void>;
1312
- }
1313
- declare class InterpreterClient extends BaseHttpClient {
1314
- private readonly maxRetries;
1315
- private readonly retryDelayMs;
1316
- createCodeContext(options?: CreateContextOptions): Promise<CodeContext>;
1317
- runCodeStream(contextId: string | undefined, code: string, language: string | undefined, callbacks: ExecutionCallbacks, timeoutMs?: number): Promise<void>;
1318
- listCodeContexts(): Promise<CodeContext[]>;
1319
- deleteCodeContext(contextId: string): Promise<void>;
1320
- /**
1321
- * Execute an operation with automatic retry for transient errors
1322
- */
1323
- private executeWithRetry;
1324
- private isRetryableError;
1325
- private parseErrorResponse;
1326
- private readLines;
1327
- private parseExecutionResult;
1328
- }
1329
- //#endregion
1330
- //#region src/clients/port-client.d.ts
1331
- /**
1332
- * Request interface for exposing ports
1333
- */
1334
- interface ExposePortRequest {
1335
- port: number;
1336
- name?: string;
1337
- }
1338
- /**
1339
- * Request interface for unexposing ports
1340
- */
1341
- interface UnexposePortRequest {
1342
- port: number;
1343
- }
1344
- /**
1345
- * Client for port management and preview URL operations
1346
- */
1347
- declare class PortClient extends BaseHttpClient {
1348
- /**
1349
- * Expose a port and get a preview URL
1350
- * @param port - Port number to expose
1351
- * @param sessionId - The session ID for this operation
1352
- * @param name - Optional name for the port
1353
- */
1354
- exposePort(port: number, sessionId: string, name?: string): Promise<PortExposeResult>;
1355
- /**
1356
- * Unexpose a port and remove its preview URL
1357
- * @param port - Port number to unexpose
1358
- * @param sessionId - The session ID for this operation
1359
- */
1360
- unexposePort(port: number, sessionId: string): Promise<PortCloseResult>;
1361
- /**
1362
- * Get all currently exposed ports
1363
- * @param sessionId - The session ID for this operation
1364
- */
1365
- getExposedPorts(sessionId: string): Promise<PortListResult>;
1366
- }
1367
- //#endregion
1368
- //#region src/clients/process-client.d.ts
1369
- /**
1370
- * Client for background process management
1371
- */
1372
- declare class ProcessClient extends BaseHttpClient {
1373
- /**
1374
- * Start a background process
1375
- * @param command - Command to execute as a background process
1376
- * @param sessionId - The session ID for this operation
1377
- * @param options - Optional settings (processId)
1378
- */
1379
- startProcess(command: string, sessionId: string, options?: {
1380
- processId?: string;
1381
- }): Promise<ProcessStartResult>;
1382
- /**
1383
- * List all processes (sandbox-scoped, not session-scoped)
1384
- */
1385
- listProcesses(): Promise<ProcessListResult>;
1386
- /**
1387
- * Get information about a specific process (sandbox-scoped, not session-scoped)
1388
- * @param processId - ID of the process to retrieve
1389
- */
1390
- getProcess(processId: string): Promise<ProcessInfoResult>;
1391
- /**
1392
- * Kill a specific process (sandbox-scoped, not session-scoped)
1393
- * @param processId - ID of the process to kill
1394
- */
1395
- killProcess(processId: string): Promise<ProcessKillResult>;
1396
- /**
1397
- * Kill all running processes (sandbox-scoped, not session-scoped)
1398
- */
1399
- killAllProcesses(): Promise<ProcessCleanupResult>;
1400
- /**
1401
- * Get logs from a specific process (sandbox-scoped, not session-scoped)
1402
- * @param processId - ID of the process to get logs from
1403
- */
1404
- getProcessLogs(processId: string): Promise<ProcessLogsResult>;
1405
- /**
1406
- * Stream logs from a specific process (sandbox-scoped, not session-scoped)
1407
- * @param processId - ID of the process to stream logs from
1408
- */
1409
- streamProcessLogs(processId: string): Promise<ReadableStream<Uint8Array>>;
1410
- }
1411
- //#endregion
1412
- //#region src/clients/utility-client.d.ts
1413
- /**
1414
- * Response interface for ping operations
1415
- */
1416
- interface PingResponse extends BaseApiResponse {
1417
- message: string;
1418
- uptime?: number;
1419
- }
1420
- /**
1421
- * Response interface for getting available commands
1422
- */
1423
- interface CommandsResponse extends BaseApiResponse {
1424
- availableCommands: string[];
1425
- count: number;
1426
- }
1427
- /**
1428
- * Request interface for creating sessions
1429
- */
1430
- interface CreateSessionRequest {
1431
- id: string;
1432
- env?: Record<string, string>;
1433
- cwd?: string;
1434
- }
1435
- /**
1436
- * Response interface for creating sessions
1437
- */
1438
- interface CreateSessionResponse extends BaseApiResponse {
1439
- id: string;
1440
- message: string;
1441
- }
1442
- /**
1443
- * Request interface for deleting sessions
1444
- */
1445
- interface DeleteSessionRequest {
1446
- sessionId: string;
1447
- }
1448
- /**
1449
- * Response interface for deleting sessions
1450
- */
1451
- interface DeleteSessionResponse extends BaseApiResponse {
1452
- sessionId: string;
1453
- }
1454
- /**
1455
- * Client for health checks and utility operations
1456
- */
1457
- declare class UtilityClient extends BaseHttpClient {
1458
- /**
1459
- * Ping the sandbox to check if it's responsive
1460
- */
1461
- ping(): Promise<string>;
1462
- /**
1463
- * Get list of available commands in the sandbox environment
1464
- */
1465
- getCommands(): Promise<string[]>;
1466
- /**
1467
- * Create a new execution session
1468
- * @param options - Session configuration (id, env, cwd)
1469
- */
1470
- createSession(options: CreateSessionRequest): Promise<CreateSessionResponse>;
1471
- /**
1472
- * Delete an execution session
1473
- * @param sessionId - Session ID to delete
1474
- */
1475
- deleteSession(sessionId: string): Promise<DeleteSessionResponse>;
1476
- /**
1477
- * Get the container version
1478
- * Returns the version embedded in the Docker image during build
1479
- */
1480
- getVersion(): Promise<string>;
1481
- }
1482
- //#endregion
1483
- //#region src/clients/sandbox-client.d.ts
1484
- /**
1485
- * Main sandbox client that composes all domain-specific clients
1486
- * Provides organized access to all sandbox functionality
1487
- */
1488
- declare class SandboxClient {
1489
- readonly commands: CommandClient;
1490
- readonly files: FileClient;
1491
- readonly processes: ProcessClient;
1492
- readonly ports: PortClient;
1493
- readonly git: GitClient;
1494
- readonly interpreter: InterpreterClient;
1495
- readonly utils: UtilityClient;
1496
- constructor(options: HttpClientOptions);
1497
- }
1498
- //#endregion
1499
- //#region src/sandbox.d.ts
1500
- declare function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string, options?: SandboxOptions): Sandbox;
1501
- declare class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
1502
- defaultPort: number;
1503
- sleepAfter: string | number;
1504
- client: SandboxClient;
1505
- private codeInterpreter;
1506
- private sandboxName;
1507
- private normalizeId;
1508
- private baseUrl;
1509
- private portTokens;
1510
- private defaultSession;
1511
- envVars: Record<string, string>;
1512
- private logger;
1513
- private keepAliveEnabled;
1514
- private activeMounts;
1515
- /**
1516
- * Default container startup timeouts (conservative for production)
1517
- * Based on Cloudflare docs: "Containers take several minutes to provision"
1518
- */
1519
- private readonly DEFAULT_CONTAINER_TIMEOUTS;
1520
- /**
1521
- * Active container timeout configuration
1522
- * Can be set via options, env vars, or defaults
1523
- */
1524
- private containerTimeouts;
1525
- constructor(ctx: DurableObjectState<{}>, env: Env);
1526
- setSandboxName(name: string, normalizeId?: boolean): Promise<void>;
1527
- setBaseUrl(baseUrl: string): Promise<void>;
1528
- setSleepAfter(sleepAfter: string | number): Promise<void>;
1529
- setKeepAlive(keepAlive: boolean): Promise<void>;
1530
- setEnvVars(envVars: Record<string, string>): Promise<void>;
1531
- /**
1532
- * RPC method to configure container startup timeouts
1533
- */
1534
- setContainerTimeouts(timeouts: NonNullable<SandboxOptions['containerTimeouts']>): Promise<void>;
1535
- /**
1536
- * Validate a timeout value is within acceptable range
1537
- * Throws error if invalid - used for user-provided values
1538
- */
1539
- private validateTimeout;
1540
- /**
1541
- * Get default timeouts with env var fallbacks and validation
1542
- * Precedence: SDK defaults < Env vars < User config
1543
- */
1544
- private getDefaultTimeouts;
1545
- mountBucket(bucket: string, mountPath: string, options: MountBucketOptions): Promise<void>;
1546
- /**
1547
- * Manually unmount a bucket filesystem
1548
- *
1549
- * @param mountPath - Absolute path where the bucket is mounted
1550
- * @throws InvalidMountConfigError if mount path doesn't exist or isn't mounted
1551
- */
1552
- unmountBucket(mountPath: string): Promise<void>;
1553
- /**
1554
- * Validate mount options
1555
- */
1556
- private validateMountOptions;
1557
- /**
1558
- * Generate unique password file path for s3fs credentials
1559
- */
1560
- private generatePasswordFilePath;
1561
- /**
1562
- * Create password file with s3fs credentials
1563
- * Format: bucket:accessKeyId:secretAccessKey
1564
- */
1565
- private createPasswordFile;
1566
- /**
1567
- * Delete password file
1568
- */
1569
- private deletePasswordFile;
1570
- /**
1571
- * Execute S3FS mount command
1572
- */
1573
- private executeS3FSMount;
1574
- /**
1575
- * Cleanup and destroy the sandbox container
1576
- */
1577
- destroy(): Promise<void>;
1578
- onStart(): void;
1579
- /**
1580
- * Check if the container version matches the SDK version
1581
- * Logs a warning if there's a mismatch
1582
- */
1583
- private checkVersionCompatibility;
1584
- onStop(): void;
1585
- onError(error: unknown): void;
1586
- /**
1587
- * Override Container.containerFetch to use production-friendly timeouts
1588
- * Automatically starts container with longer timeouts if not running
1589
- */
1590
- containerFetch(requestOrUrl: Request | string | URL, portOrInit?: number | RequestInit, portParam?: number): Promise<Response>;
1591
- /**
1592
- * Helper: Check if error is "no container instance available"
1593
- */
1594
- private isNoInstanceError;
1595
- /**
1596
- * Helper: Parse containerFetch arguments (supports multiple signatures)
1597
- */
1598
- private parseContainerFetchArgs;
1599
- /**
1600
- * Override onActivityExpired to prevent automatic shutdown when keepAlive is enabled
1601
- * When keepAlive is disabled, calls parent implementation which stops the container
1602
- */
1603
- onActivityExpired(): Promise<void>;
1604
- fetch(request: Request): Promise<Response>;
1605
- wsConnect(request: Request, port: number): Promise<Response>;
1606
- private determinePort;
1607
- /**
1608
- * Ensure default session exists - lazy initialization
1609
- * This is called automatically by all public methods that need a session
1610
- *
1611
- * The session is persisted to Durable Object storage to survive hot reloads
1612
- * during development. If a session already exists in the container after reload,
1613
- * we reuse it instead of trying to create a new one.
1614
- */
1615
- private ensureDefaultSession;
1616
- exec(command: string, options?: ExecOptions): Promise<ExecResult>;
1617
- /**
1618
- * Internal session-aware exec implementation
1619
- * Used by both public exec() and session wrappers
1620
- */
1621
- private execWithSession;
1622
- private executeWithStreaming;
1623
- private mapExecuteResponseToExecResult;
1624
- /**
1625
- * Create a Process domain object from HTTP client DTO
1626
- * Centralizes process object creation with bound methods
1627
- * This eliminates duplication across startProcess, listProcesses, getProcess, and session wrappers
1628
- */
1629
- private createProcessFromDTO;
1630
- startProcess(command: string, options?: ProcessOptions, sessionId?: string): Promise<Process>;
1631
- listProcesses(sessionId?: string): Promise<Process[]>;
1632
- getProcess(id: string, sessionId?: string): Promise<Process | null>;
1633
- killProcess(id: string, signal?: string, sessionId?: string): Promise<void>;
1634
- killAllProcesses(sessionId?: string): Promise<number>;
1635
- cleanupCompletedProcesses(sessionId?: string): Promise<number>;
1636
- getProcessLogs(id: string, sessionId?: string): Promise<{
1637
- stdout: string;
1638
- stderr: string;
1639
- processId: string;
1640
- }>;
1641
- execStream(command: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>>;
1642
- /**
1643
- * Internal session-aware execStream implementation
1644
- */
1645
- private execStreamWithSession;
1646
- /**
1647
- * Stream logs from a background process as a ReadableStream.
1648
- */
1649
- streamProcessLogs(processId: string, options?: {
1650
- signal?: AbortSignal;
1651
- }): Promise<ReadableStream<Uint8Array>>;
1652
- gitCheckout(repoUrl: string, options: {
1653
- branch?: string;
1654
- targetDir?: string;
1655
- sessionId?: string;
1656
- }): Promise<GitCheckoutResult>;
1657
- mkdir(path: string, options?: {
1658
- recursive?: boolean;
1659
- sessionId?: string;
1660
- }): Promise<MkdirResult>;
1661
- writeFile(path: string, content: string, options?: {
1662
- encoding?: string;
1663
- sessionId?: string;
1664
- }): Promise<WriteFileResult>;
1665
- deleteFile(path: string, sessionId?: string): Promise<DeleteFileResult>;
1666
- renameFile(oldPath: string, newPath: string, sessionId?: string): Promise<RenameFileResult>;
1667
- moveFile(sourcePath: string, destinationPath: string, sessionId?: string): Promise<MoveFileResult>;
1668
- readFile(path: string, options?: {
1669
- encoding?: string;
1670
- sessionId?: string;
1671
- }): Promise<ReadFileResult>;
1672
- /**
1673
- * Stream a file from the sandbox using Server-Sent Events
1674
- * Returns a ReadableStream that can be consumed with streamFile() or collectFile() utilities
1675
- * @param path - Path to the file to stream
1676
- * @param options - Optional session ID
1677
- */
1678
- readFileStream(path: string, options?: {
1679
- sessionId?: string;
1680
- }): Promise<ReadableStream<Uint8Array>>;
1681
- listFiles(path: string, options?: {
1682
- recursive?: boolean;
1683
- includeHidden?: boolean;
1684
- }): Promise<ListFilesResult>;
1685
- exists(path: string, sessionId?: string): Promise<FileExistsResult>;
1686
- exposePort(port: number, options: {
1687
- name?: string;
1688
- hostname: string;
1689
- }): Promise<{
1690
- url: string;
1691
- port: number;
1692
- name: string | undefined;
1693
- }>;
1694
- unexposePort(port: number): Promise<void>;
1695
- getExposedPorts(hostname: string): Promise<{
1696
- url: string;
1697
- port: number;
1698
- status: "active" | "inactive";
1699
- }[]>;
1700
- isPortExposed(port: number): Promise<boolean>;
1701
- validatePortToken(port: number, token: string): Promise<boolean>;
1702
- private generatePortToken;
1703
- private persistPortTokens;
1704
- private constructPreviewUrl;
1705
- /**
1706
- * Create isolated execution session for advanced use cases
1707
- * Returns ExecutionSession with full sandbox API bound to specific session
1708
- */
1709
- createSession(options?: SessionOptions): Promise<ExecutionSession>;
1710
- /**
1711
- * Get an existing session by ID
1712
- * Returns ExecutionSession wrapper bound to the specified session
1713
- *
1714
- * This is useful for retrieving sessions across different requests/contexts
1715
- * without storing the ExecutionSession object (which has RPC lifecycle limitations)
1716
- *
1717
- * @param sessionId - The ID of an existing session
1718
- * @returns ExecutionSession wrapper bound to the session
1719
- */
1720
- getSession(sessionId: string): Promise<ExecutionSession>;
1721
- /**
1722
- * Delete an execution session
1723
- * Cleans up session resources and removes it from the container
1724
- * Note: Cannot delete the default session. To reset the default session,
1725
- * use sandbox.destroy() to terminate the entire sandbox.
1726
- *
1727
- * @param sessionId - The ID of the session to delete
1728
- * @returns Result with success status, sessionId, and timestamp
1729
- * @throws Error if attempting to delete the default session
1730
- */
1731
- deleteSession(sessionId: string): Promise<SessionDeleteResult>;
1732
- /**
1733
- * Internal helper to create ExecutionSession wrapper for a given sessionId
1734
- * Used by both createSession and getSession
1735
- */
1736
- private getSessionWrapper;
1737
- createCodeContext(options?: CreateContextOptions): Promise<CodeContext>;
1738
- runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>;
1739
- runCodeStream(code: string, options?: RunCodeOptions): Promise<ReadableStream>;
1740
- listCodeContexts(): Promise<CodeContext[]>;
1741
- deleteCodeContext(contextId: string): Promise<void>;
1742
- }
1743
- //#endregion
1744
20
  //#region src/file-stream.d.ts
1745
21
  /**
1746
22
  * Stream a file from the sandbox with automatic base64 decoding for binary files