@cloudflare/sandbox 0.13.0-next.651.1 → 0.13.0-next.709.1

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.
Files changed (67) hide show
  1. package/Dockerfile +12 -17
  2. package/README.md +48 -2
  3. package/dist/bridge/index.d.ts.map +1 -1
  4. package/dist/bridge/index.js +1365 -1054
  5. package/dist/bridge/index.js.map +1 -1
  6. package/dist/{contexts-BS0Bs6IU.d.ts → contexts-1EsLHByO.d.ts} +240 -15
  7. package/dist/contexts-1EsLHByO.d.ts.map +1 -0
  8. package/dist/{dist-DF8sudAg.js → dist-Duor5GbS.js} +38 -147
  9. package/dist/dist-Duor5GbS.js.map +1 -0
  10. package/dist/errors/index.d.ts +4 -0
  11. package/dist/errors/index.js +4 -0
  12. package/dist/{errors-BG6NZiPD.js → errors-CXR0xBpw.js} +82 -13
  13. package/dist/errors-CXR0xBpw.js.map +1 -0
  14. package/dist/errors-QYlSkVGz.js +893 -0
  15. package/dist/errors-QYlSkVGz.js.map +1 -0
  16. package/dist/extensions/index.d.ts +4 -74
  17. package/dist/extensions/index.js +5 -152
  18. package/dist/extensions-CFB2xHqY.js +1023 -0
  19. package/dist/extensions-CFB2xHqY.js.map +1 -0
  20. package/dist/filesystem-BWAZCZER.d.ts +732 -0
  21. package/dist/filesystem-BWAZCZER.d.ts.map +1 -0
  22. package/dist/git/index.d.ts +63 -0
  23. package/dist/git/index.d.ts.map +1 -0
  24. package/dist/git/index.js +338 -0
  25. package/dist/git/index.js.map +1 -0
  26. package/dist/index-Bs4bqXDR.d.ts +438 -0
  27. package/dist/index-Bs4bqXDR.d.ts.map +1 -0
  28. package/dist/index-HNYBk-az.d.ts +444 -0
  29. package/dist/index-HNYBk-az.d.ts.map +1 -0
  30. package/dist/index.d.ts +487 -181
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +12 -43
  33. package/dist/index.js.map +1 -1
  34. package/dist/interpreter/index.d.ts +311 -0
  35. package/dist/interpreter/index.d.ts.map +1 -0
  36. package/dist/interpreter/index.js +292 -0
  37. package/dist/interpreter/index.js.map +1 -0
  38. package/dist/openai/index.d.ts +5 -4
  39. package/dist/openai/index.d.ts.map +1 -1
  40. package/dist/openai/index.js +11 -6
  41. package/dist/openai/index.js.map +1 -1
  42. package/dist/opencode/index.d.ts +133 -161
  43. package/dist/opencode/index.d.ts.map +1 -1
  44. package/dist/opencode/index.js +284 -203
  45. package/dist/opencode/index.js.map +1 -1
  46. package/dist/process-types-GStiZ8f8.d.ts +73 -0
  47. package/dist/process-types-GStiZ8f8.d.ts.map +1 -0
  48. package/dist/sandbox-Auuwfnur.js +10010 -0
  49. package/dist/sandbox-Auuwfnur.js.map +1 -0
  50. package/dist/sandbox-BbAabq93.d.ts +42 -0
  51. package/dist/sandbox-BbAabq93.d.ts.map +1 -0
  52. package/dist/xterm/index.d.ts +11 -7
  53. package/dist/xterm/index.d.ts.map +1 -1
  54. package/dist/xterm/index.js +61 -18
  55. package/dist/xterm/index.js.map +1 -1
  56. package/package.json +28 -4
  57. package/dist/contexts-BS0Bs6IU.d.ts.map +0 -1
  58. package/dist/dist-DF8sudAg.js.map +0 -1
  59. package/dist/errors-BG6NZiPD.js.map +0 -1
  60. package/dist/extensions/index.d.ts.map +0 -1
  61. package/dist/extensions/index.js.map +0 -1
  62. package/dist/rpc-types-PBUY-xXM.d.ts +0 -1679
  63. package/dist/rpc-types-PBUY-xXM.d.ts.map +0 -1
  64. package/dist/sandbox-BgwMBQ7S.js +0 -8273
  65. package/dist/sandbox-BgwMBQ7S.js.map +0 -1
  66. package/dist/sandbox-D_MMqExx.d.ts +0 -1077
  67. package/dist/sandbox-D_MMqExx.d.ts.map +0 -1
@@ -1,1679 +0,0 @@
1
- //#region ../shared/dist/interpreter-types.d.ts
2
- interface CreateContextOptions {
3
- /**
4
- * Programming language for the context
5
- * @default 'python'
6
- */
7
- language?: 'python' | 'javascript' | 'typescript';
8
- /**
9
- * Working directory for the context
10
- * @default '/workspace'
11
- */
12
- cwd?: string;
13
- /**
14
- * Environment variables for the context.
15
- * Undefined values are skipped (treated as "not configured").
16
- */
17
- envVars?: Record<string, string | undefined>;
18
- /**
19
- * Request timeout in milliseconds
20
- * @default 30000
21
- */
22
- timeout?: number;
23
- }
24
- interface CodeContext {
25
- /**
26
- * Unique identifier for the context
27
- */
28
- readonly id: string;
29
- /**
30
- * Programming language of the context
31
- */
32
- readonly language: string;
33
- /**
34
- * Current working directory
35
- */
36
- readonly cwd: string;
37
- /**
38
- * When the context was created
39
- */
40
- readonly createdAt: Date;
41
- /**
42
- * When the context was last used
43
- */
44
- readonly lastUsed: Date;
45
- }
46
- interface RunCodeOptions {
47
- /**
48
- * Context to run the code in. If not provided, uses default context for the language
49
- */
50
- context?: CodeContext;
51
- /**
52
- * Language to use if context is not provided
53
- * @default 'python'
54
- */
55
- language?: 'python' | 'javascript' | 'typescript';
56
- /**
57
- * Environment variables for this execution.
58
- * Undefined values are skipped (treated as "not configured").
59
- */
60
- envVars?: Record<string, string | undefined>;
61
- /**
62
- * Execution timeout in milliseconds
63
- * @default 60000
64
- */
65
- timeout?: number;
66
- /**
67
- * AbortSignal for cancelling execution
68
- */
69
- signal?: AbortSignal;
70
- /**
71
- * Callback for stdout output
72
- */
73
- onStdout?: (output: OutputMessage) => void | Promise<void>;
74
- /**
75
- * Callback for stderr output
76
- */
77
- onStderr?: (output: OutputMessage) => void | Promise<void>;
78
- /**
79
- * Callback for execution results (charts, tables, etc)
80
- */
81
- onResult?: (result: Result) => void | Promise<void>;
82
- /**
83
- * Callback for execution errors
84
- */
85
- onError?: (error: ExecutionError) => void | Promise<void>;
86
- }
87
- interface OutputMessage {
88
- /**
89
- * The output text
90
- */
91
- text: string;
92
- /**
93
- * Timestamp of the output
94
- */
95
- timestamp: number;
96
- }
97
- interface Result {
98
- /**
99
- * Plain text representation
100
- */
101
- text?: string;
102
- /**
103
- * HTML representation (tables, formatted output)
104
- */
105
- html?: string;
106
- /**
107
- * PNG image data (base64 encoded)
108
- */
109
- png?: string;
110
- /**
111
- * JPEG image data (base64 encoded)
112
- */
113
- jpeg?: string;
114
- /**
115
- * SVG image data
116
- */
117
- svg?: string;
118
- /**
119
- * LaTeX representation
120
- */
121
- latex?: string;
122
- /**
123
- * Markdown representation
124
- */
125
- markdown?: string;
126
- /**
127
- * JavaScript code to execute
128
- */
129
- javascript?: string;
130
- /**
131
- * JSON data
132
- */
133
- json?: any;
134
- /**
135
- * Chart data if the result is a visualization
136
- */
137
- chart?: ChartData;
138
- /**
139
- * Raw data object
140
- */
141
- data?: any;
142
- /**
143
- * Available output formats
144
- */
145
- formats(): string[];
146
- }
147
- interface ChartData {
148
- /**
149
- * Type of chart
150
- */
151
- type: 'line' | 'bar' | 'scatter' | 'pie' | 'histogram' | 'heatmap' | 'unknown';
152
- /**
153
- * Chart title
154
- */
155
- title?: string;
156
- /**
157
- * Chart data (format depends on library)
158
- */
159
- data: any;
160
- /**
161
- * Chart layout/configuration
162
- */
163
- layout?: any;
164
- /**
165
- * Additional configuration
166
- */
167
- config?: any;
168
- /**
169
- * Library that generated the chart
170
- */
171
- library?: 'matplotlib' | 'plotly' | 'altair' | 'seaborn' | 'unknown';
172
- /**
173
- * Base64 encoded image if available
174
- */
175
- image?: string;
176
- }
177
- interface ExecutionError {
178
- /**
179
- * Error name/type (e.g., 'NameError', 'SyntaxError')
180
- */
181
- name: string;
182
- /**
183
- * Error message
184
- */
185
- message: string;
186
- /**
187
- * Stack trace
188
- */
189
- traceback: string[];
190
- /**
191
- * Line number where error occurred
192
- */
193
- lineNumber?: number;
194
- }
195
- interface ExecutionResult {
196
- code: string;
197
- logs: {
198
- stdout: string[];
199
- stderr: string[];
200
- };
201
- error?: ExecutionError;
202
- executionCount?: number;
203
- results: Array<{
204
- text?: string;
205
- html?: string;
206
- png?: string;
207
- jpeg?: string;
208
- svg?: string;
209
- latex?: string;
210
- markdown?: string;
211
- javascript?: string;
212
- json?: any;
213
- chart?: ChartData;
214
- data?: any;
215
- }>;
216
- }
217
- declare class Execution {
218
- readonly code: string;
219
- readonly context: CodeContext;
220
- /**
221
- * All results from the execution
222
- */
223
- results: Result[];
224
- /**
225
- * Accumulated stdout and stderr
226
- */
227
- logs: {
228
- stdout: string[];
229
- stderr: string[];
230
- };
231
- /**
232
- * Execution error if any
233
- */
234
- error?: ExecutionError;
235
- /**
236
- * Execution count (for interpreter)
237
- */
238
- executionCount?: number;
239
- constructor(code: string, context: CodeContext);
240
- /**
241
- * Convert to a plain object for serialization
242
- */
243
- toJSON(): ExecutionResult;
244
- }
245
- //#endregion
246
- //#region ../shared/dist/pty-types.d.ts
247
- interface PtyOptions {
248
- cols?: number;
249
- rows?: number;
250
- shell?: string;
251
- }
252
- //#endregion
253
- //#region ../shared/dist/types.d.ts
254
- interface BaseExecOptions {
255
- /**
256
- * Maximum execution time in milliseconds
257
- */
258
- timeout?: number;
259
- /**
260
- * Environment variables for this command invocation.
261
- * Values temporarily override session-level/container-level env for the
262
- * duration of the command but do not persist after it completes.
263
- * Undefined values are skipped (treated as "not configured").
264
- */
265
- env?: Record<string, string | undefined>;
266
- /**
267
- * Working directory for command execution
268
- */
269
- cwd?: string;
270
- /**
271
- * Text encoding for output (default: 'utf8')
272
- */
273
- encoding?: string;
274
- }
275
- interface ExecOptions extends BaseExecOptions {
276
- /**
277
- * Enable real-time output streaming via callbacks
278
- */
279
- stream?: boolean;
280
- /**
281
- * Callback for real-time output data
282
- */
283
- onOutput?: (stream: 'stdout' | 'stderr', data: string) => void;
284
- /**
285
- * Callback when command completes (only when stream: true)
286
- */
287
- onComplete?: (result: ExecResult) => void;
288
- /**
289
- * Callback for execution errors
290
- */
291
- onError?: (error: Error) => void;
292
- /**
293
- * AbortSignal for cancelling execution
294
- */
295
- signal?: AbortSignal;
296
- /**
297
- * Whether this command was initiated by the user or by internal
298
- * infrastructure (backup, bucket mount, env setup, etc.).
299
- * Defaults to 'user' when omitted.
300
- */
301
- origin?: 'user' | 'internal';
302
- }
303
- interface ExecResult {
304
- /**
305
- * Whether the command succeeded (exitCode === 0)
306
- */
307
- success: boolean;
308
- /**
309
- * Process exit code
310
- */
311
- exitCode: number;
312
- /**
313
- * Standard output content
314
- */
315
- stdout: string;
316
- /**
317
- * Standard error content
318
- */
319
- stderr: string;
320
- /**
321
- * Command that was executed
322
- */
323
- command: string;
324
- /**
325
- * Execution duration in milliseconds
326
- */
327
- duration: number;
328
- /**
329
- * ISO timestamp when command started
330
- */
331
- timestamp: string;
332
- /**
333
- * Session ID if provided
334
- */
335
- sessionId?: string;
336
- }
337
- /**
338
- * Result from waiting for a log pattern
339
- */
340
- interface WaitForLogResult {
341
- /** The log line that matched */
342
- line: string;
343
- /** Regex capture groups (if condition was a RegExp) */
344
- match?: RegExpMatchArray;
345
- }
346
- /**
347
- * Result from waiting for process exit
348
- */
349
- interface WaitForExitResult {
350
- /** Process exit code */
351
- exitCode: number;
352
- }
353
- /**
354
- * Options for waiting for a port to become ready
355
- */
356
- interface WaitForPortOptions {
357
- /**
358
- * Check mode
359
- * - 'http': Make an HTTP request and check for success status (default)
360
- * - 'tcp': Just check if TCP connection succeeds
361
- * @default 'http'
362
- */
363
- mode?: 'http' | 'tcp';
364
- /**
365
- * HTTP path to check (only used when mode is 'http')
366
- * @default '/'
367
- */
368
- path?: string;
369
- /**
370
- * Expected HTTP status code or range (only used when mode is 'http')
371
- * - Single number: exact match (e.g., 200)
372
- * - Object with min/max: range match (e.g., { min: 200, max: 399 })
373
- * @default { min: 200, max: 399 }
374
- */
375
- status?: number | {
376
- min: number;
377
- max: number;
378
- };
379
- /**
380
- * Maximum time to wait in milliseconds
381
- * @default no timeout
382
- */
383
- timeout?: number;
384
- /**
385
- * Interval between checks in milliseconds
386
- * @default 500
387
- */
388
- interval?: number;
389
- }
390
- /**
391
- * Request body for port readiness check endpoint
392
- */
393
- interface PortCheckRequest {
394
- port: number;
395
- mode: 'http' | 'tcp';
396
- path?: string;
397
- statusMin?: number;
398
- statusMax?: number;
399
- }
400
- /**
401
- * Request body for streaming port watch endpoint
402
- */
403
- interface PortWatchRequest extends PortCheckRequest {
404
- /** Process ID to monitor - stream closes if process exits */
405
- processId?: string;
406
- /** Internal polling interval in ms (default: 500) */
407
- interval?: number;
408
- }
409
- interface ProcessOptions extends BaseExecOptions {
410
- /**
411
- * Optional session ID to run the background process in.
412
- *
413
- * When omitted, the sandbox's default execution policy applies.
414
- */
415
- sessionId?: string;
416
- /**
417
- * Custom process ID for later reference
418
- * If not provided, a UUID will be generated
419
- */
420
- processId?: string;
421
- /**
422
- * Automatically cleanup process record after exit (default: true)
423
- */
424
- autoCleanup?: boolean;
425
- /**
426
- * Callback when process exits
427
- */
428
- onExit?: (code: number | null) => void;
429
- /**
430
- * Callback for real-time output (background processes)
431
- */
432
- onOutput?: (stream: 'stdout' | 'stderr', data: string) => void;
433
- /**
434
- * Callback when process starts successfully
435
- */
436
- onStart?: (process: Process) => void;
437
- /**
438
- * Callback for process errors
439
- */
440
- onError?: (error: Error) => void;
441
- }
442
- type ProcessStatus = 'starting' | 'running' | 'completed' | 'failed' | 'killed' | 'error';
443
- interface Process {
444
- /**
445
- * Unique process identifier
446
- */
447
- readonly id: string;
448
- /**
449
- * System process ID (if available and running)
450
- */
451
- readonly pid?: number;
452
- /**
453
- * Command that was executed
454
- */
455
- readonly command: string;
456
- /**
457
- * Current process status
458
- */
459
- readonly status: ProcessStatus;
460
- /**
461
- * When the process was started
462
- */
463
- readonly startTime: Date;
464
- /**
465
- * When the process ended (if completed)
466
- */
467
- readonly endTime?: Date;
468
- /**
469
- * Process exit code (if completed)
470
- */
471
- readonly exitCode?: number;
472
- /**
473
- * Session ID if provided
474
- */
475
- readonly sessionId?: string;
476
- /**
477
- * Kill the process
478
- */
479
- kill(signal?: string): Promise<void>;
480
- /**
481
- * Get current process status (refreshed)
482
- */
483
- getStatus(): Promise<ProcessStatus>;
484
- /**
485
- * Get accumulated logs
486
- */
487
- getLogs(): Promise<{
488
- stdout: string;
489
- stderr: string;
490
- }>;
491
- /**
492
- * Wait for a log pattern to appear in process output
493
- *
494
- * @example
495
- * const proc = await sandbox.startProcess("python train.py");
496
- * await proc.waitForLog("Epoch 1 complete");
497
- * await proc.waitForLog(/Epoch (\d+) complete/);
498
- */
499
- waitForLog(pattern: string | RegExp, timeout?: number): Promise<WaitForLogResult>;
500
- /**
501
- * Wait for a port to become ready
502
- *
503
- * @example
504
- * // Wait for HTTP endpoint to return 200-399
505
- * const proc = await sandbox.startProcess("npm run dev");
506
- * await proc.waitForPort(3000);
507
- *
508
- * @example
509
- * // Wait for specific health endpoint
510
- * await proc.waitForPort(3000, { path: '/health', status: 200 });
511
- *
512
- * @example
513
- * // TCP-only check (just verify port is accepting connections)
514
- * await proc.waitForPort(5432, { mode: 'tcp' });
515
- */
516
- waitForPort(port: number, options?: WaitForPortOptions): Promise<void>;
517
- /**
518
- * Wait for the process to exit
519
- *
520
- * Returns the exit code. Use getProcessLogs() or streamProcessLogs()
521
- * to retrieve output after the process exits.
522
- */
523
- waitForExit(timeout?: number): Promise<WaitForExitResult>;
524
- }
525
- interface ExecEvent {
526
- type: 'start' | 'stdout' | 'stderr' | 'complete' | 'error';
527
- timestamp: string;
528
- data?: string;
529
- command?: string;
530
- exitCode?: number;
531
- result?: ExecResult;
532
- error?: string;
533
- sessionId?: string;
534
- pid?: number;
535
- }
536
- interface LogEvent {
537
- type: 'stdout' | 'stderr' | 'exit' | 'error';
538
- timestamp: string;
539
- data: string;
540
- processId: string;
541
- sessionId?: string;
542
- exitCode?: number;
543
- }
544
- interface StreamOptions extends BaseExecOptions {
545
- /**
546
- * Optional session ID to run the streaming command in.
547
- *
548
- * When omitted, the sandbox's default execution policy applies.
549
- */
550
- sessionId?: string;
551
- /**
552
- * Buffer size for streaming output
553
- */
554
- bufferSize?: number;
555
- /**
556
- * AbortSignal for cancelling stream
557
- */
558
- signal?: AbortSignal;
559
- }
560
- interface SessionOptions {
561
- /**
562
- * Optional session ID (auto-generated if not provided)
563
- */
564
- id?: string;
565
- /**
566
- * Session name for identification
567
- */
568
- name?: string;
569
- /**
570
- * Environment variables for this session.
571
- * Undefined values are skipped (treated as "not configured").
572
- */
573
- env?: Record<string, string | undefined>;
574
- /**
575
- * Working directory
576
- */
577
- cwd?: string;
578
- /**
579
- * Enable PID namespace isolation (requires CAP_SYS_ADMIN)
580
- */
581
- isolation?: boolean;
582
- /**
583
- * Maximum amount of time a command can run in milliseconds
584
- */
585
- commandTimeoutMs?: number;
586
- }
587
- interface SandboxOptions {
588
- /**
589
- * Duration after which the sandbox instance will sleep if no requests are received
590
- * Can be:
591
- * - A string like "30s", "3m", "5m", "1h" (seconds, minutes, or hours)
592
- * - A number representing seconds (e.g., 180 for 3 minutes)
593
- * Default: "10m" (10 minutes)
594
- *
595
- * Note: Ignored when keepAlive is true
596
- */
597
- sleepAfter?: string | number;
598
- /**
599
- * Keep the container alive indefinitely by preventing automatic shutdown
600
- * When true, the container will never auto-timeout and must be explicitly destroyed
601
- * - Any scenario where activity can't be automatically detected
602
- *
603
- * Important: You MUST call sandbox.destroy() when done to avoid resource leaks
604
- *
605
- * Default: false
606
- */
607
- keepAlive?: boolean;
608
- /**
609
- * When true (the default), implicit operations automatically create and reuse
610
- * a persistent default shell session. Set to false to run implicit top-level
611
- * operations sessionlessly, where each command spawns a fresh process with no
612
- * shared shell state. Explicit per-call session IDs continue to work normally
613
- * when this is false.
614
- *
615
- * Default: true
616
- */
617
- enableDefaultSession?: boolean;
618
- /**
619
- * Normalize sandbox ID to lowercase for preview URL compatibility
620
- *
621
- * Required for preview URLs because hostnames are case-insensitive (RFC 3986), which
622
- * would route requests to a different Durable Object instance with IDs containing uppercase letters.
623
- *
624
- * **Important:** Different normalizeId values create different Durable Object instances:
625
- * - `getSandbox(ns, "MyProject")` → DO key: "MyProject"
626
- * - `getSandbox(ns, "MyProject", {normalizeId: true})` → DO key: "myproject"
627
- *
628
- * **Future change:** In a future version, this will default to `true` (automatically lowercase all IDs).
629
- * IDs with uppercase letters will trigger a warning. To prepare, use lowercase IDs or explicitly
630
- * pass `normalizeId: true`.
631
- *
632
- * @example
633
- * getSandbox(ns, "my-project") // Works with preview URLs (lowercase)
634
- * getSandbox(ns, "MyProject", {normalizeId: true}) // Normalized to "myproject"
635
- *
636
- * @default false
637
- */
638
- normalizeId?: boolean;
639
- /**
640
- * Container startup timeout configuration
641
- *
642
- * Tune timeouts based on your container's characteristics. SDK defaults (30s instance, 90s ports)
643
- * work for most use cases. Adjust for heavy containers or fail-fast applications.
644
- *
645
- * Can also be configured via environment variables:
646
- * - SANDBOX_INSTANCE_TIMEOUT_MS
647
- * - SANDBOX_PORT_TIMEOUT_MS
648
- * - SANDBOX_POLL_INTERVAL_MS
649
- *
650
- * Precedence: options > env vars > SDK defaults
651
- *
652
- * @example
653
- * // Heavy containers (ML models, large apps)
654
- * getSandbox(ns, id, {
655
- * containerTimeouts: { portReadyTimeoutMS: 180_000 }
656
- * })
657
- *
658
- * @example
659
- * // Fail-fast for latency-sensitive apps
660
- * getSandbox(ns, id, {
661
- * containerTimeouts: {
662
- * instanceGetTimeoutMS: 15_000,
663
- * portReadyTimeoutMS: 30_000
664
- * }
665
- * })
666
- */
667
- containerTimeouts?: {
668
- /**
669
- * Time to wait for container instance provisioning
670
- * @default 30000 (30s) - or SANDBOX_INSTANCE_TIMEOUT_MS env var
671
- */
672
- instanceGetTimeoutMS?: number;
673
- /**
674
- * Time to wait for application startup and ports to be ready
675
- * @default 90000 (90s) - or SANDBOX_PORT_TIMEOUT_MS env var
676
- */
677
- portReadyTimeoutMS?: number;
678
- /**
679
- * How often to poll for container readiness
680
- * @default 300 (300ms) - or SANDBOX_POLL_INTERVAL_MS env var
681
- */
682
- waitIntervalMS?: number;
683
- };
684
- }
685
- /**
686
- * Execution session - isolated execution context within a sandbox
687
- * Returned by sandbox.createSession()
688
- * Provides the same API as ISandbox but bound to a specific session
689
- */
690
- interface MkdirResult {
691
- success: boolean;
692
- path: string;
693
- recursive: boolean;
694
- timestamp: string;
695
- exitCode?: number;
696
- }
697
- interface WriteFileResult {
698
- success: boolean;
699
- path: string;
700
- timestamp: string;
701
- exitCode?: number;
702
- }
703
- /**
704
- * Valid `encoding` values accepted by `readFile` / `writeFile` options.
705
- *
706
- * - `'utf-8'` / `'utf8'` — treat content as text.
707
- * - `'base64'` — treat content as base64-encoded binary.
708
- * - `'none'` — streaming variant of `readFile`, returns a
709
- * `ReadableStream<Uint8Array>` of raw bytes (see `ReadFileStreamResult`).
710
- */
711
- type FileEncoding = 'utf-8' | 'utf8' | 'base64' | 'none';
712
- interface ReadFileResult {
713
- success: boolean;
714
- path: string;
715
- content: string;
716
- timestamp: string;
717
- exitCode?: number;
718
- /**
719
- * Encoding used for content (utf-8 for text, base64 for binary)
720
- */
721
- encoding?: 'utf-8' | 'base64';
722
- /**
723
- * Whether the file is detected as binary
724
- */
725
- isBinary?: boolean;
726
- /**
727
- * MIME type of the file (e.g., 'image/png', 'text/plain')
728
- */
729
- mimeType?: string;
730
- /**
731
- * File size in bytes
732
- */
733
- size?: number;
734
- }
735
- /**
736
- * Result of `readFile()` with `encoding: 'none'`.
737
- *
738
- * `content` is a raw binary `ReadableStream<Uint8Array>` delivered directly
739
- * over the capnp channel — no base64 encoding, no SSE framing, no buffering.
740
- */
741
- interface ReadFileStreamResult {
742
- success: true;
743
- path: string;
744
- content: ReadableStream<Uint8Array>;
745
- size: number;
746
- mimeType: string;
747
- timestamp: string;
748
- }
749
- interface DeleteFileResult {
750
- success: boolean;
751
- path: string;
752
- timestamp: string;
753
- exitCode?: number;
754
- }
755
- interface RenameFileResult {
756
- success: boolean;
757
- path: string;
758
- newPath: string;
759
- timestamp: string;
760
- exitCode?: number;
761
- }
762
- interface MoveFileResult {
763
- success: boolean;
764
- path: string;
765
- newPath: string;
766
- timestamp: string;
767
- exitCode?: number;
768
- }
769
- interface FileExistsResult {
770
- success: boolean;
771
- path: string;
772
- exists: boolean;
773
- timestamp: string;
774
- }
775
- interface FileInfo {
776
- name: string;
777
- absolutePath: string;
778
- relativePath: string;
779
- type: 'file' | 'directory' | 'symlink' | 'other';
780
- size: number;
781
- modifiedAt: string;
782
- mode: string;
783
- permissions: {
784
- readable: boolean;
785
- writable: boolean;
786
- executable: boolean;
787
- };
788
- }
789
- interface ListFilesOptions {
790
- recursive?: boolean;
791
- includeHidden?: boolean;
792
- /**
793
- * Optional session ID used to resolve relative paths and execution context.
794
- *
795
- * When omitted, the sandbox's default execution policy applies.
796
- */
797
- sessionId?: string;
798
- }
799
- interface ListFilesResult {
800
- success: boolean;
801
- path: string;
802
- files: FileInfo[];
803
- count: number;
804
- timestamp: string;
805
- exitCode?: number;
806
- }
807
- interface GitCheckoutResult {
808
- success: boolean;
809
- repoUrl: string;
810
- branch: string;
811
- targetDir: string;
812
- timestamp: string;
813
- exitCode?: number;
814
- }
815
- /**
816
- * SSE events for file streaming
817
- */
818
- type FileStreamEvent = {
819
- type: 'metadata';
820
- mimeType: string;
821
- size: number;
822
- isBinary: boolean;
823
- encoding: 'utf-8' | 'base64';
824
- } | {
825
- type: 'chunk';
826
- data: string;
827
- } | {
828
- type: 'complete';
829
- bytesRead: number;
830
- } | {
831
- type: 'error';
832
- error: string;
833
- };
834
- /**
835
- * File metadata from streaming
836
- */
837
- interface FileMetadata {
838
- mimeType: string;
839
- size: number;
840
- isBinary: boolean;
841
- encoding: 'utf-8' | 'base64';
842
- }
843
- /**
844
- * File stream chunk - either string (text) or Uint8Array (binary, auto-decoded)
845
- */
846
- type FileChunk = string | Uint8Array;
847
- /**
848
- * Options for watching a directory.
849
- *
850
- * `watch()` resolves only after the watcher is established on the filesystem.
851
- * The returned SSE stream can be consumed with `parseSSEStream()`.
852
- */
853
- interface WatchOptions {
854
- /**
855
- * Watch subdirectories recursively
856
- * @default true
857
- */
858
- recursive?: boolean;
859
- /**
860
- * Glob patterns to include (e.g., '*.ts', '*.js').
861
- * If not specified, all files are included.
862
- * Cannot be used together with `exclude`.
863
- */
864
- include?: string[];
865
- /**
866
- * Glob patterns to exclude (e.g., 'node_modules', '.git').
867
- * Cannot be used together with `include`.
868
- * @default ['.git', 'node_modules', '.DS_Store']
869
- */
870
- exclude?: string[];
871
- /**
872
- * Session to run the watch in.
873
- * If omitted, the default session is used.
874
- */
875
- sessionId?: string;
876
- }
877
- /**
878
- * Options for checking whether a path changed while disconnected.
879
- *
880
- * Pass the `version` returned from a previous `checkChanges()` call to learn
881
- * whether the path is unchanged, changed, or needs a full resync because the
882
- * retained change state was reset. Change state lives only for the current
883
- * container lifetime and may expire while idle.
884
- */
885
- interface CheckChangesOptions extends WatchOptions {
886
- /**
887
- * Version returned by a previous `checkChanges()` call.
888
- */
889
- since?: string;
890
- }
891
- /**
892
- * @internal SSE event types for container communication
893
- */
894
- type FileWatchEventType = 'create' | 'modify' | 'delete' | 'move_from' | 'move_to' | 'attrib';
895
- /**
896
- * @internal Request body for starting a file watch
897
- */
898
- interface WatchRequest {
899
- path: string;
900
- recursive?: boolean;
901
- events?: FileWatchEventType[];
902
- include?: string[];
903
- exclude?: string[];
904
- sessionId?: string;
905
- }
906
- /**
907
- * @internal Request body for checking retained change state.
908
- */
909
- interface CheckChangesRequest extends WatchRequest {
910
- since?: string;
911
- }
912
- /**
913
- * SSE events emitted by `sandbox.watch()`.
914
- */
915
- type FileWatchSSEEvent = {
916
- type: 'watching';
917
- path: string;
918
- watchId: string;
919
- } | {
920
- type: 'event';
921
- eventType: FileWatchEventType;
922
- path: string;
923
- isDirectory: boolean;
924
- timestamp: string;
925
- } | {
926
- type: 'error';
927
- error: string;
928
- } | {
929
- type: 'stopped';
930
- reason: string;
931
- };
932
- /**
933
- * Result returned by `checkChanges()`.
934
- */
935
- type CheckChangesResult = {
936
- success: true;
937
- status: 'unchanged' | 'changed';
938
- version: string;
939
- timestamp: string;
940
- } | {
941
- success: true;
942
- status: 'resync';
943
- reason: 'expired' | 'restarted';
944
- version: string;
945
- timestamp: string;
946
- };
947
- interface ProcessStartResult {
948
- success: boolean;
949
- processId: string;
950
- pid?: number;
951
- command: string;
952
- timestamp: string;
953
- }
954
- interface ProcessListResult {
955
- success: boolean;
956
- processes: Array<{
957
- id: string;
958
- pid?: number;
959
- command: string;
960
- status: ProcessStatus;
961
- startTime: string;
962
- endTime?: string;
963
- exitCode?: number;
964
- }>;
965
- timestamp: string;
966
- }
967
- interface ProcessInfoResult {
968
- success: boolean;
969
- process: {
970
- id: string;
971
- pid?: number;
972
- command: string;
973
- status: ProcessStatus;
974
- startTime: string;
975
- endTime?: string;
976
- exitCode?: number;
977
- };
978
- timestamp: string;
979
- }
980
- interface ProcessKillResult {
981
- success: boolean;
982
- processId: string;
983
- signal?: string;
984
- timestamp: string;
985
- }
986
- interface ProcessLogsResult {
987
- success: boolean;
988
- processId: string;
989
- stdout: string;
990
- stderr: string;
991
- timestamp: string;
992
- }
993
- interface ProcessCleanupResult {
994
- success: boolean;
995
- message?: string;
996
- killedCount?: number;
997
- cleanedCount: number;
998
- timestamp: string;
999
- }
1000
- interface SessionDeleteResult {
1001
- success: boolean;
1002
- sessionId: string;
1003
- timestamp: string;
1004
- }
1005
- interface ExecutionSession {
1006
- /** Unique session identifier */
1007
- readonly id: string;
1008
- exec(command: string, options?: ExecOptions): Promise<ExecResult>;
1009
- execStream(command: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>>;
1010
- startProcess(command: string, options?: ProcessOptions): Promise<Process>;
1011
- listProcesses(sessionId?: string): Promise<Process[]>;
1012
- getProcess(id: string, sessionId?: string): Promise<Process | null>;
1013
- killProcess(id: string, signal?: string): Promise<void>;
1014
- killAllProcesses(): Promise<number>;
1015
- cleanupCompletedProcesses(): Promise<number>;
1016
- getProcessLogs(id: string): Promise<{
1017
- stdout: string;
1018
- stderr: string;
1019
- processId: string;
1020
- }>;
1021
- streamProcessLogs(processId: string, options?: {
1022
- signal?: AbortSignal;
1023
- }): Promise<ReadableStream<Uint8Array>>;
1024
- writeFile(path: string, content: string | ReadableStream<Uint8Array>, options?: {
1025
- encoding?: string;
1026
- }): Promise<WriteFileResult>;
1027
- readFile(path: string, options: {
1028
- encoding: 'none';
1029
- }): Promise<ReadFileStreamResult>;
1030
- readFile(path: string, options?: {
1031
- encoding?: Exclude<FileEncoding, 'none'>;
1032
- }): Promise<ReadFileResult>;
1033
- readFileStream(path: string): Promise<ReadableStream<Uint8Array>>;
1034
- watch(path: string, options?: Omit<WatchOptions, 'sessionId'>): Promise<ReadableStream<Uint8Array>>;
1035
- checkChanges(path: string, options?: Omit<CheckChangesOptions, 'sessionId'>): Promise<CheckChangesResult>;
1036
- mkdir(path: string, options?: {
1037
- recursive?: boolean;
1038
- }): Promise<MkdirResult>;
1039
- deleteFile(path: string): Promise<DeleteFileResult>;
1040
- renameFile(oldPath: string, newPath: string): Promise<RenameFileResult>;
1041
- moveFile(sourcePath: string, destinationPath: string): Promise<MoveFileResult>;
1042
- listFiles(path: string, options?: ListFilesOptions): Promise<ListFilesResult>;
1043
- exists(path: string): Promise<FileExistsResult>;
1044
- gitCheckout(repoUrl: string, options?: {
1045
- branch?: string;
1046
- targetDir?: string;
1047
- /** Clone depth for shallow clones (e.g., 1 for latest commit only) */
1048
- depth?: number;
1049
- /** Maximum wall-clock time for the git clone subprocess in milliseconds */
1050
- cloneTimeoutMs?: number;
1051
- }): Promise<GitCheckoutResult>;
1052
- setEnvVars(envVars: Record<string, string | undefined>): Promise<void>;
1053
- createCodeContext(options?: CreateContextOptions): Promise<CodeContext>;
1054
- runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>;
1055
- runCodeStream(code: string, options?: RunCodeOptions): Promise<ReadableStream<Uint8Array>>;
1056
- listCodeContexts(): Promise<CodeContext[]>;
1057
- deleteCodeContext(contextId: string): Promise<void>;
1058
- mountBucket(bucket: string, mountPath: string, options: MountBucketOptions): Promise<void>;
1059
- unmountBucket(mountPath: string): Promise<void>;
1060
- createBackup(options: BackupOptions): Promise<DirectoryBackup>;
1061
- restoreBackup(backup: DirectoryBackup): Promise<RestoreBackupResult>;
1062
- terminal(request: Request, options?: PtyOptions): Promise<Response>;
1063
- }
1064
- /**
1065
- * Options for creating a directory backup
1066
- */
1067
- interface BackupCompressionOptions {
1068
- format?: 'gzip' | 'lz4' | 'zstd';
1069
- threads?: number;
1070
- }
1071
- interface BackupOptions {
1072
- /** Directory to back up. Must be absolute and under `/workspace`, `/home`, `/tmp`, `/var/tmp`, or `/app`. */
1073
- dir: string;
1074
- /** Human-readable name for this backup. Optional. */
1075
- name?: string;
1076
- /** Seconds until automatic garbage collection. Default: 259200 (3 days). No upper limit. */
1077
- ttl?: number;
1078
- /**
1079
- * Respect git ignore rules for the backup directory when it is inside a git repository.
1080
- *
1081
- * Default: false.
1082
- * If the directory is not inside a git repository, no git-based exclusions are applied.
1083
- * If git is not installed in the container, a warning is logged and gitignore rules are skipped.
1084
- */
1085
- gitignore?: boolean;
1086
- /**
1087
- * Glob patterns to exclude from the backup.
1088
- * These are passed directly to mksquashfs as wildcard exclude patterns.
1089
- *
1090
- * @example ['node_modules', '*.log', '.cache']
1091
- */
1092
- excludes?: string[];
1093
- /**
1094
- * Use local R2 binding for backup storage instead of presigned URLs.
1095
- * Required for local development where presigned URLs and FUSE are unavailable.
1096
- * When true, the DO resolves BACKUP_BUCKET from its own env as an R2 binding.
1097
- */
1098
- localBucket?: boolean;
1099
- compression?: BackupCompressionOptions;
1100
- /**
1101
- * Use parallel multipart upload to R2 for large archives.
1102
- * Significantly speeds up uploads for archives over 10 MiB.
1103
- * Default: true.
1104
- */
1105
- multipart?: boolean;
1106
- }
1107
- /**
1108
- * Handle representing a stored directory backup.
1109
- * Serializable metadata returned by createBackup().
1110
- * Store it anywhere and later pass it to restoreBackup().
1111
- */
1112
- interface DirectoryBackup {
1113
- /** Unique backup identifier */
1114
- readonly id: string;
1115
- /** Directory to restore into. Must be under `/workspace`, `/home`, `/tmp`, `/var/tmp`, or `/app`. */
1116
- readonly dir: string;
1117
- /** Whether this backup was created with local R2 binding mode. */
1118
- readonly localBucket?: boolean;
1119
- }
1120
- /**
1121
- * Result returned from a successful restoreBackup() call
1122
- */
1123
- interface RestoreBackupResult {
1124
- success: boolean;
1125
- /** The directory that was restored */
1126
- dir: string;
1127
- /** Backup ID that was restored */
1128
- id: string;
1129
- }
1130
- /**
1131
- * Supported S3-compatible storage providers
1132
- */
1133
- type BucketProvider = 'r2' | 's3' | 'gcs';
1134
- /**
1135
- * Credentials for S3-compatible storage
1136
- */
1137
- interface BucketCredentials {
1138
- accessKeyId: string;
1139
- secretAccessKey: string;
1140
- }
1141
- /**
1142
- * Options for mounting an S3-compatible bucket via s3fs-FUSE (production)
1143
- */
1144
- interface RemoteMountBucketOptions {
1145
- /**
1146
- * S3-compatible endpoint URL
1147
- *
1148
- * Examples:
1149
- * - R2: 'https://abc123.r2.cloudflarestorage.com'
1150
- * - AWS S3: 'https://s3.us-west-2.amazonaws.com'
1151
- * - GCS: 'https://storage.googleapis.com'
1152
- */
1153
- endpoint: string;
1154
- /**
1155
- * Optional provider hint for automatic s3fs flag configuration
1156
- * If not specified, will attempt to detect from endpoint URL.
1157
- *
1158
- * Examples:
1159
- * - 'r2' - Cloudflare R2 (adds nomixupload)
1160
- * - 's3' - Amazon S3 (standard configuration)
1161
- * - 'gcs' - Google Cloud Storage (no special flags needed)
1162
- */
1163
- provider?: BucketProvider;
1164
- /**
1165
- * Explicit credentials (overrides env var auto-detection)
1166
- */
1167
- credentials?: BucketCredentials;
1168
- /**
1169
- * Mount filesystem as read-only
1170
- * Default: false
1171
- */
1172
- readOnly?: boolean;
1173
- /**
1174
- * Advanced: Override or extend s3fs options
1175
- *
1176
- * These will be merged with provider-specific defaults.
1177
- * To override defaults completely, specify all options here.
1178
- *
1179
- * Common options:
1180
- * - 'use_path_request_style' - Use path-style URLs (bucket/path vs bucket.host/path)
1181
- * - 'nomixupload' - Disable mixed multipart uploads (needed for some providers)
1182
- * - 'nomultipart' - Disable all multipart operations
1183
- * - 'sigv2' - Use signature version 2 instead of v4
1184
- * - 'no_check_certificate' - Skip SSL certificate validation (dev/testing only)
1185
- */
1186
- s3fsOptions?: string[];
1187
- /**
1188
- * Optional prefix/subdirectory within the bucket to mount.
1189
- *
1190
- * When specified, only the contents under this prefix are visible at the
1191
- * mount point, scoping the mount to a subdirectory of the bucket.
1192
- *
1193
- * Must start with '/' (e.g., '/workspaces/project123' or '/data/uploads/')
1194
- */
1195
- prefix?: string;
1196
- /**
1197
- * Keep real credentials in the Durable Object; write dummy credentials into
1198
- * the container-side s3fs password file. Outbound s3fs requests are
1199
- * intercepted by the DO, signed with real credentials, and forwarded to the
1200
- * configured endpoint.
1201
- *
1202
- * Default: false (real credentials are written into the container)
1203
- */
1204
- credentialProxy?: boolean;
1205
- }
1206
- /**
1207
- * Options for mounting a local R2 binding via bidirectional sync (local dev)
1208
- *
1209
- * Used during local development with `wrangler dev`. The Durable Object
1210
- * resolves the R2 binding from its own env using the `bucket` parameter
1211
- * and syncs files via polling instead of s3fs-FUSE.
1212
- */
1213
- interface LocalMountBucketOptions {
1214
- /**
1215
- * Must be true to indicate local R2 binding mode.
1216
- */
1217
- localBucket: true;
1218
- /**
1219
- * Optional prefix/subdirectory within the bucket to sync.
1220
- *
1221
- * When specified, only the contents under this prefix will be visible
1222
- * at the mount point.
1223
- */
1224
- prefix?: string;
1225
- /**
1226
- * Mount filesystem as read-only
1227
- * Default: false
1228
- */
1229
- readOnly?: boolean;
1230
- }
1231
- /**
1232
- * Options for mounting an R2 binding via credential-less egress interception.
1233
- */
1234
- interface R2BindingMountBucketOptions {
1235
- /**
1236
- * Must not be set — distinguishes this variant from RemoteMountBucketOptions.
1237
- */
1238
- endpoint?: never;
1239
- /**
1240
- * Optional prefix/subdirectory within the bucket to mount.
1241
- *
1242
- * When specified, only the contents under this prefix will be visible
1243
- * at the mount point.
1244
- */
1245
- prefix?: string;
1246
- /**
1247
- * Mount filesystem as read-only
1248
- * Default: false
1249
- */
1250
- readOnly?: boolean;
1251
- /**
1252
- * Advanced: Override or extend s3fs options.
1253
- * Provider defaults for R2 are still applied automatically.
1254
- */
1255
- s3fsOptions?: string[];
1256
- }
1257
- /**
1258
- * Options for mounting a bucket — remote (s3fs-FUSE), local (R2 binding sync),
1259
- * or R2 egress (credential-less s3fs via egress interception).
1260
- */
1261
- type MountBucketOptions = RemoteMountBucketOptions | LocalMountBucketOptions | R2BindingMountBucketOptions;
1262
- interface ISandbox {
1263
- exec(command: string, options?: ExecOptions): Promise<ExecResult>;
1264
- startProcess(command: string, options?: ProcessOptions): Promise<Process>;
1265
- listProcesses(sessionId?: string): Promise<Process[]>;
1266
- getProcess(id: string, sessionId?: string): Promise<Process | null>;
1267
- killProcess(id: string, signal?: string): Promise<void>;
1268
- killAllProcesses(): Promise<number>;
1269
- execStream(command: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>>;
1270
- streamProcessLogs(processId: string, options?: {
1271
- signal?: AbortSignal;
1272
- }): Promise<ReadableStream<Uint8Array>>;
1273
- cleanupCompletedProcesses(): Promise<number>;
1274
- getProcessLogs(id: string): Promise<{
1275
- stdout: string;
1276
- stderr: string;
1277
- processId: string;
1278
- }>;
1279
- writeFile(path: string, content: string | ReadableStream<Uint8Array>, options?: {
1280
- encoding?: string;
1281
- }): Promise<WriteFileResult>;
1282
- readFile(path: string, options: {
1283
- encoding: 'none';
1284
- }): Promise<ReadFileStreamResult>;
1285
- readFile(path: string, options?: {
1286
- encoding?: Exclude<FileEncoding, 'none'>;
1287
- }): Promise<ReadFileResult>;
1288
- readFileStream(path: string): Promise<ReadableStream<Uint8Array>>;
1289
- watch(path: string, options?: WatchOptions): Promise<ReadableStream<Uint8Array>>;
1290
- checkChanges(path: string, options?: CheckChangesOptions): Promise<CheckChangesResult>;
1291
- mkdir(path: string, options?: {
1292
- recursive?: boolean;
1293
- }): Promise<MkdirResult>;
1294
- deleteFile(path: string): Promise<DeleteFileResult>;
1295
- renameFile(oldPath: string, newPath: string): Promise<RenameFileResult>;
1296
- moveFile(sourcePath: string, destinationPath: string): Promise<MoveFileResult>;
1297
- listFiles(path: string, options?: ListFilesOptions): Promise<ListFilesResult>;
1298
- exists(path: string, sessionId?: string): Promise<FileExistsResult>;
1299
- gitCheckout(repoUrl: string, options?: {
1300
- branch?: string;
1301
- targetDir?: string;
1302
- sessionId?: string;
1303
- /** Clone depth for shallow clones (e.g., 1 for latest commit only) */
1304
- depth?: number;
1305
- /** Maximum wall-clock time for the git clone subprocess in milliseconds */
1306
- cloneTimeoutMs?: number;
1307
- }): Promise<GitCheckoutResult>;
1308
- setEnvVars(envVars: Record<string, string | undefined>): Promise<void>;
1309
- mountBucket(bucket: string, mountPath: string, options: MountBucketOptions): Promise<void>;
1310
- unmountBucket(mountPath: string): Promise<void>;
1311
- createSession(options?: SessionOptions): Promise<ExecutionSession>;
1312
- deleteSession(sessionId: string): Promise<SessionDeleteResult>;
1313
- /**
1314
- * Returns the Cloudflare placement ID observed during the most recent
1315
- * session-create handshake with the container. `null` when the container
1316
- * does not expose `CLOUDFLARE_PLACEMENT_ID` (local development). `undefined`
1317
- * when no handshake has been observed yet on this sandbox.
1318
- */
1319
- getContainerPlacementId(): Promise<string | null | undefined>;
1320
- createCodeContext(options?: CreateContextOptions): Promise<CodeContext>;
1321
- runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>;
1322
- runCodeStream(code: string, options?: RunCodeOptions): Promise<ReadableStream>;
1323
- listCodeContexts(): Promise<CodeContext[]>;
1324
- deleteCodeContext(contextId: string): Promise<void>;
1325
- createBackup(options: BackupOptions): Promise<DirectoryBackup>;
1326
- restoreBackup(backup: DirectoryBackup): Promise<RestoreBackupResult>;
1327
- wsConnect(request: Request, port: number): Promise<Response>;
1328
- }
1329
- declare function isExecResult(value: any): value is ExecResult;
1330
- declare function isProcess(value: any): value is Process;
1331
- declare function isProcessStatus(value: string): value is ProcessStatus;
1332
- //#endregion
1333
- //#region ../shared/dist/request-types.d.ts
1334
- /**
1335
- * Result for a single uploaded part (ETag returned by R2).
1336
- */
1337
- interface UploadedPart {
1338
- partNumber: number;
1339
- etag: string;
1340
- }
1341
- /**
1342
- * Response after the container has uploaded all parts.
1343
- */
1344
- interface UploadPartsResponse {
1345
- success: boolean;
1346
- parts: UploadedPart[];
1347
- }
1348
- /**
1349
- * Response from the container after creating a backup archive
1350
- */
1351
- interface CreateBackupResponse {
1352
- success: boolean;
1353
- /** Size of the archive in bytes */
1354
- sizeBytes: number;
1355
- /** Path to the archive file in the container */
1356
- archivePath: string;
1357
- }
1358
- /**
1359
- * Response from the container after restoring a backup
1360
- */
1361
- interface RestoreBackupResponse {
1362
- success: boolean;
1363
- /** Directory that was restored */
1364
- dir: string;
1365
- }
1366
- //#endregion
1367
- //#region ../shared/dist/rpc-types.d.ts
1368
- interface SandboxAPI {
1369
- commands: SandboxCommandsAPI;
1370
- files: SandboxFilesAPI;
1371
- processes: SandboxProcessesAPI;
1372
- ports: SandboxPortsAPI;
1373
- git: SandboxGitAPI;
1374
- interpreter: SandboxInterpreterAPI;
1375
- utils: SandboxUtilsAPI;
1376
- backup: SandboxBackupAPI;
1377
- watch: SandboxWatchAPI;
1378
- tunnels: SandboxTunnelsAPI;
1379
- extensions: SandboxExtensionsAPI;
1380
- }
1381
- interface SandboxCommandsAPI {
1382
- execute(command: string, sessionId: string, options?: {
1383
- timeoutMs?: number;
1384
- env?: Record<string, string | undefined>;
1385
- cwd?: string;
1386
- origin?: 'user' | 'internal';
1387
- }): Promise<{
1388
- success: boolean;
1389
- exitCode: number;
1390
- stdout: string;
1391
- stderr: string;
1392
- command: string;
1393
- timestamp: string;
1394
- }>;
1395
- executeStream(command: string, sessionId: string, options?: {
1396
- timeoutMs?: number;
1397
- env?: Record<string, string | undefined>;
1398
- cwd?: string;
1399
- origin?: 'user' | 'internal';
1400
- }): Promise<ReadableStream<Uint8Array>>;
1401
- }
1402
- interface SandboxFilesAPI {
1403
- readFile(path: string, sessionId: string, options: {
1404
- encoding: 'none';
1405
- }): Promise<ReadFileStreamResult>;
1406
- readFile(path: string, sessionId: string, options?: {
1407
- encoding?: Exclude<FileEncoding, 'none'>;
1408
- }): Promise<ReadFileResult>;
1409
- readFileStream(path: string, sessionId: string): Promise<ReadableStream<Uint8Array>>;
1410
- writeFile(path: string, content: string, sessionId: string, options?: {
1411
- encoding?: string;
1412
- permissions?: string;
1413
- }): Promise<WriteFileResult>;
1414
- writeFileStream(path: string, stream: ReadableStream<Uint8Array>, sessionId: string): Promise<{
1415
- success: boolean;
1416
- path: string;
1417
- bytesWritten: number;
1418
- timestamp: string;
1419
- }>;
1420
- deleteFile(path: string, sessionId: string): Promise<DeleteFileResult>;
1421
- renameFile(oldPath: string, newPath: string, sessionId: string): Promise<RenameFileResult>;
1422
- moveFile(sourcePath: string, destinationPath: string, sessionId: string): Promise<MoveFileResult>;
1423
- mkdir(path: string, sessionId: string, options?: {
1424
- recursive?: boolean;
1425
- }): Promise<MkdirResult>;
1426
- listFiles(path: string, sessionId: string, options?: ListFilesOptions): Promise<ListFilesResult>;
1427
- exists(path: string, sessionId: string): Promise<FileExistsResult>;
1428
- }
1429
- interface SandboxProcessesAPI {
1430
- startProcess(command: string, sessionId: string, options?: {
1431
- processId?: string;
1432
- timeoutMs?: number;
1433
- }): Promise<ProcessStartResult>;
1434
- listProcesses(): Promise<ProcessListResult>;
1435
- getProcess(id: string): Promise<ProcessInfoResult>;
1436
- killProcess(id: string): Promise<ProcessKillResult>;
1437
- killAllProcesses(): Promise<ProcessCleanupResult>;
1438
- getProcessLogs(id: string): Promise<ProcessLogsResult>;
1439
- streamProcessLogs(id: string): Promise<ReadableStream<Uint8Array>>;
1440
- }
1441
- interface SandboxPortsAPI {
1442
- watchPort(request: PortWatchRequest): Promise<ReadableStream<Uint8Array>>;
1443
- }
1444
- interface SandboxGitAPI {
1445
- checkout(repoUrl: string, sessionId: string, options?: {
1446
- branch?: string;
1447
- targetDir?: string;
1448
- depth?: number;
1449
- timeoutMs?: number;
1450
- }): Promise<GitCheckoutResult>;
1451
- }
1452
- interface SandboxInterpreterAPI {
1453
- createCodeContext(options?: CreateContextOptions): Promise<CodeContext>;
1454
- streamCode(contextId: string, code: string, language?: string): Promise<ReadableStream<Uint8Array>>;
1455
- runCodeStream(contextId: string | undefined, code: string, language: string | undefined, callbacks: {
1456
- onStdout?: (output: OutputMessage) => void | Promise<void>;
1457
- onStderr?: (output: OutputMessage) => void | Promise<void>;
1458
- onResult?: (result: Result) => void | Promise<void>;
1459
- onError?: (error: ExecutionError) => void | Promise<void>;
1460
- }, timeoutMs?: number): Promise<void>;
1461
- listCodeContexts(): Promise<CodeContext[]>;
1462
- deleteCodeContext(contextId: string): Promise<void>;
1463
- }
1464
- interface SandboxUtilsAPI {
1465
- ping(): Promise<string>;
1466
- getVersion(): Promise<string>;
1467
- getCommands(): Promise<string[]>;
1468
- createSession(options: {
1469
- id: string;
1470
- env?: Record<string, string | undefined>;
1471
- cwd?: string;
1472
- }): Promise<{
1473
- success: boolean;
1474
- id: string;
1475
- message: string;
1476
- timestamp: string;
1477
- containerPlacementId?: string | null;
1478
- }>;
1479
- deleteSession(sessionId: string): Promise<{
1480
- success: boolean;
1481
- sessionId: string;
1482
- timestamp: string;
1483
- }>;
1484
- listSessions(): Promise<{
1485
- sessions: string[];
1486
- }>;
1487
- }
1488
- interface SandboxBackupAPI {
1489
- createArchive(dir: string, archivePath: string, sessionId: string, options?: {
1490
- excludes?: string[];
1491
- gitignore?: boolean;
1492
- compression?: BackupCompressionOptions;
1493
- }): Promise<CreateBackupResponse>;
1494
- restoreArchive(dir: string, archivePath: string, sessionId: string): Promise<RestoreBackupResponse>;
1495
- uploadParts(request: {
1496
- archivePath: string;
1497
- parts: Array<{
1498
- partNumber: number;
1499
- url: string;
1500
- offset: number;
1501
- size: number;
1502
- }>;
1503
- sessionId?: string;
1504
- }): Promise<UploadPartsResponse>;
1505
- }
1506
- interface SandboxWatchAPI {
1507
- watch(request: WatchRequest): Promise<ReadableStream<Uint8Array>>;
1508
- checkChanges(request: CheckChangesRequest): Promise<CheckChangesResult>;
1509
- }
1510
- /**
1511
- * Public-facing tunnel record. Discriminated on the presence of `name`:
1512
- * quick tunnels (`*.trycloudflare.com`) omit it, named tunnels carry the
1513
- * label that was passed to `get(port, { name })`.
1514
- */
1515
- type TunnelInfo = QuickTunnelInfo | NamedTunnelInfo;
1516
- interface QuickTunnelInfo {
1517
- id: string;
1518
- port: number;
1519
- /** `https://<random>.trycloudflare.com`. */
1520
- url: string;
1521
- /** Hostname portion of `url`. */
1522
- hostname: string;
1523
- createdAt: string;
1524
- /** Absent on quick tunnels; narrows the union. */
1525
- name?: never;
1526
- }
1527
- interface NamedTunnelInfo {
1528
- /** Cloudflare tunnel UUID (8-4-4-4-12). */
1529
- id: string;
1530
- port: number;
1531
- /** `https://<hostname>`. */
1532
- url: string;
1533
- /** Full hostname bound to the tunnel (without scheme). */
1534
- hostname: string;
1535
- createdAt: string;
1536
- /** Label originally passed via `TunnelOptions.name`. */
1537
- name: string;
1538
- }
1539
- /**
1540
- * Options accepted by `sandbox.tunnels.get(port, options)`. Omitting
1541
- * `name` (or omitting the options object) selects the zero-config quick
1542
- * tunnel; setting `name` selects the named-tunnel flow.
1543
- */
1544
- interface TunnelOptions {
1545
- /**
1546
- * Single DNS label under the configured zone. The full hostname is
1547
- * `<name>.<zone-name>`. See `validateTunnelName` for the format rules.
1548
- */
1549
- name?: string;
1550
- }
1551
- interface SandboxTunnelsAPI {
1552
- /** Spawn `cloudflared tunnel --url`. No credentials required. */
1553
- runQuickTunnel(id: string, port: number): Promise<TunnelInfo>;
1554
- /**
1555
- * Spawn `cloudflared tunnel run --token <token> --url http://localhost:<port>`.
1556
- *
1557
- * The SDK is the source of truth for the hostname this tunnel binds to;
1558
- * the container only sees the opaque token and the local port. The
1559
- * returned `TunnelInfo` carries empty `url`/`hostname` fields — the SDK
1560
- * enriches them with the values from the Cloudflare API before handing
1561
- * the record to user code.
1562
- *
1563
- * The token must never be logged, persisted, or echoed back to callers.
1564
- */
1565
- runNamedTunnel(id: string, token: string, port: number): Promise<TunnelInfo>;
1566
- /** Stop the cloudflared process for the given tunnel id. */
1567
- destroyTunnel(id: string): Promise<{
1568
- success: true;
1569
- id: string;
1570
- }>;
1571
- /** List tunnels currently running inside the container. */
1572
- listTunnels(): Promise<TunnelInfo[]>;
1573
- }
1574
- /**
1575
- * Author-facing description of a sidecar extension. An extension is an
1576
- * npm-style package: an `.tgz` whose embedded `package.json` declares the
1577
- * sidecar entrypoint (via `bin`) and any extension metadata (under the
1578
- * `sandboxExtension` key).
1579
- *
1580
- * The SDK ships the tarball bytes; the container hashes them, provisions a
1581
- * dedicated directory keyed by content hash, derives identity from the
1582
- * embedded `package.json`, installs the package with `bun add`, and spawns
1583
- * the declared bin under Bun.
1584
- *
1585
- * `ExtensionPackage` carries tarball bytes produced by an extension build.
1586
- * The SDK sends those bytes only when the container has not provisioned the
1587
- * package hash yet.
1588
- */
1589
- interface ExtensionPackage {
1590
- /** Raw `.tgz` bytes. */
1591
- tarball: Uint8Array;
1592
- /**
1593
- * Bin entry to run when the embedded `package.json` declares more than one.
1594
- * Defaults to the value of `sandboxExtension.bin` in `package.json`, then
1595
- * to the single bin entry if there is exactly one.
1596
- */
1597
- bin?: string;
1598
- /**
1599
- * Max time to wait for the sidecar to accept a capnweb connection on its
1600
- * unix socket. Falls back to `sandboxExtension.readinessTimeoutMs` in
1601
- * `package.json`, then to a host default.
1602
- */
1603
- readinessTimeoutMs?: number;
1604
- /**
1605
- * Run lifecycle scripts during `bun add`. Defaults to false — provisioning
1606
- * happens before the sidecar is supervised, so install-time side effects
1607
- * are deliberately opt-in.
1608
- */
1609
- allowInstallScripts?: boolean;
1610
- }
1611
- /** Health snapshot for a provisioned extension. */
1612
- interface ExtensionHealth {
1613
- packageHash: string;
1614
- id: string;
1615
- version: string;
1616
- /** Tarball is on disk and the package.json has been read. */
1617
- provisioned: boolean;
1618
- /** Sidecar process is currently running. */
1619
- running: boolean;
1620
- pid: number | null;
1621
- /** Whether a `__ping__` round-tripped over capnweb. */
1622
- responsive: boolean;
1623
- }
1624
- /**
1625
- * Connect request payload. The SDK hashes the tarball locally and first sends
1626
- * only the hash. If the current host process has not provisioned that hash,
1627
- * it responds with an `ExtensionTarballRequired` error and the SDK retries
1628
- * with `tarball` populated.
1629
- */
1630
- interface ExtensionConnectRequest {
1631
- packageHash: string;
1632
- /** Only sent when the host has not seen this hash yet. */
1633
- tarball?: Uint8Array;
1634
- bin?: string;
1635
- readinessTimeoutMs?: number;
1636
- allowInstallScripts?: boolean;
1637
- }
1638
- /**
1639
- * Control surface for container sidecar extensions.
1640
- *
1641
- * `connect` is the only entry point: it provisions on first use, supervises
1642
- * lazily, and returns the sidecar's capnweb remote main as a stub. Calls on
1643
- * the stub are proxied through the container's capnweb session to the
1644
- * sidecar's capnweb session — callback parameters (including streaming
1645
- * handlers) round-trip across both hops.
1646
- */
1647
- interface SandboxExtensionsAPI {
1648
- /**
1649
- * Provision the package (if new) and return the sidecar's typed remote
1650
- * main. The result is a capnweb stub whose methods correspond to the
1651
- * sidecar's `RpcTarget` surface.
1652
- */
1653
- connect(req: ExtensionConnectRequest): Promise<unknown>;
1654
- /** Health snapshot, probing the sidecar with a `__ping__` when running. */
1655
- health(packageHash: string): Promise<ExtensionHealth>;
1656
- /** Stop a sidecar and release its capnweb session. */
1657
- stop(packageHash: string): Promise<void>;
1658
- }
1659
- /**
1660
- * RPC surface the Sandbox DO exposes to the container over the existing
1661
- * capnweb session. The container reaches it via
1662
- * `session.getRemoteMain<SandboxControlCallback>()` and invokes methods
1663
- * to push control-plane events (today: tunnel exits) back to the DO.
1664
- *
1665
- * One stable target per sandbox; not per-tunnel. Reusable seam for
1666
- * future container→DO events.
1667
- */
1668
- interface SandboxControlCallback {
1669
- /**
1670
- * Called by the container when a `cloudflared` process exits for any
1671
- * reason — SIGTERM from `destroyTunnel`, container-initiated SIGKILL,
1672
- * network failure, segfault. `exitCode` is `null` if the process was
1673
- * signalled rather than exited cleanly.
1674
- */
1675
- onTunnelExit(id: string, port: number, exitCode: number | null): Promise<void>;
1676
- }
1677
- //#endregion
1678
- export { RenameFileResult as $, ExecResult as A, ListFilesOptions as B, BucketProvider as C, DirectoryBackup as D, DeleteFileResult as E, FileMetadata as F, MountBucketOptions as G, LocalMountBucketOptions as H, FileStreamEvent as I, ProcessOptions as J, MoveFileResult as K, FileWatchSSEEvent as L, FileChunk as M, FileEncoding as N, ExecEvent as O, FileExistsResult as P, RemoteMountBucketOptions as Q, GitCheckoutResult as R, BucketCredentials as S, CheckChangesResult as T, LogEvent as U, ListFilesResult as V, MkdirResult as W, ReadFileResult as X, ProcessStatus as Y, ReadFileStreamResult as Z, SandboxWatchAPI as _, RunCodeOptions as _t, SandboxAPI as a, WaitForLogResult as at, BackupOptions as b, SandboxControlCallback as c, WriteFileResult as ct, SandboxGitAPI as d, isProcessStatus as dt, RestoreBackupResult as et, SandboxInterpreterAPI as f, PtyOptions as ft, SandboxUtilsAPI as g, ExecutionResult as gt, SandboxTunnelsAPI as h, Execution as ht, QuickTunnelInfo as i, StreamOptions as it, ExecutionSession as j, ExecOptions as k, SandboxExtensionsAPI as l, isExecResult as lt, SandboxProcessesAPI as m, CreateContextOptions as mt, ExtensionPackage as n, SessionDeleteResult as nt, SandboxBackupAPI as o, WaitForPortOptions as ot, SandboxPortsAPI as p, CodeContext as pt, Process as q, NamedTunnelInfo as r, SessionOptions as rt, SandboxCommandsAPI as s, WatchOptions as st, ExtensionHealth as t, SandboxOptions as tt, SandboxFilesAPI as u, isProcess as ut, TunnelInfo as v, CheckChangesOptions as w, BaseExecOptions as x, TunnelOptions as y, ISandbox as z };
1679
- //# sourceMappingURL=rpc-types-PBUY-xXM.d.ts.map