@cloudflare/sandbox 0.0.0-0ac3cfa → 0.0.0-12bbd12

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/src/sandbox.ts ADDED
@@ -0,0 +1,788 @@
1
+ import { Container, getContainer } from "@cloudflare/containers";
2
+ import { CodeInterpreter } from "./interpreter";
3
+ import type {
4
+ CodeContext,
5
+ CreateContextOptions,
6
+ ExecutionResult,
7
+ RunCodeOptions,
8
+ } from "./interpreter-types";
9
+ import { JupyterClient } from "./jupyter-client";
10
+ import { isLocalhostPattern } from "./request-handler";
11
+ import {
12
+ logSecurityEvent,
13
+ SecurityError,
14
+ sanitizeSandboxId,
15
+ validatePort,
16
+ } from "./security";
17
+ import { parseSSEStream } from "./sse-parser";
18
+ import type {
19
+ ExecEvent,
20
+ ExecOptions,
21
+ ExecResult,
22
+ ExecuteResponse,
23
+ ISandbox,
24
+ Process,
25
+ ProcessOptions,
26
+ ProcessStatus,
27
+ StreamOptions,
28
+ } from "./types";
29
+ import { ProcessNotFoundError, SandboxError } from "./types";
30
+
31
+ export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string) {
32
+ const stub = getContainer(ns, id);
33
+
34
+ // Store the name on first access
35
+ stub.setSandboxName?.(id);
36
+
37
+ return stub;
38
+ }
39
+
40
+ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
41
+ defaultPort = 3000; // Default port for the container's Bun server
42
+ sleepAfter = "20m"; // Keep container warm for 20 minutes to avoid cold starts
43
+ client: JupyterClient;
44
+ private sandboxName: string | null = null;
45
+ private codeInterpreter: CodeInterpreter;
46
+
47
+ constructor(ctx: DurableObjectState, env: Env) {
48
+ super(ctx, env);
49
+ this.client = new JupyterClient({
50
+ onCommandComplete: (success, exitCode, _stdout, _stderr, command) => {
51
+ console.log(
52
+ `[Container] Command completed: ${command}, Success: ${success}, Exit code: ${exitCode}`
53
+ );
54
+ },
55
+ onCommandStart: (command) => {
56
+ console.log(`[Container] Command started: ${command}`);
57
+ },
58
+ onError: (error, _command) => {
59
+ console.error(`[Container] Command error: ${error}`);
60
+ },
61
+ onOutput: (stream, data, _command) => {
62
+ console.log(`[Container] [${stream}] ${data}`);
63
+ },
64
+ port: 3000, // Control plane port
65
+ stub: this,
66
+ });
67
+
68
+ // Initialize code interpreter
69
+ this.codeInterpreter = new CodeInterpreter(this);
70
+
71
+ // Load the sandbox name from storage on initialization
72
+ this.ctx.blockConcurrencyWhile(async () => {
73
+ this.sandboxName =
74
+ (await this.ctx.storage.get<string>("sandboxName")) || null;
75
+ });
76
+ }
77
+
78
+ // RPC method to set the sandbox name
79
+ async setSandboxName(name: string): Promise<void> {
80
+ if (!this.sandboxName) {
81
+ this.sandboxName = name;
82
+ await this.ctx.storage.put("sandboxName", name);
83
+ console.log(`[Sandbox] Stored sandbox name via RPC: ${name}`);
84
+ }
85
+ }
86
+
87
+ // RPC method to set environment variables
88
+ async setEnvVars(envVars: Record<string, string>): Promise<void> {
89
+ this.envVars = { ...this.envVars, ...envVars };
90
+ console.log(`[Sandbox] Updated environment variables`);
91
+ }
92
+
93
+ override onStart() {
94
+ console.log("Sandbox successfully started");
95
+ }
96
+
97
+ override onStop() {
98
+ console.log("Sandbox successfully shut down");
99
+ if (this.client) {
100
+ this.client.clearSession();
101
+ }
102
+ }
103
+
104
+ override onError(error: unknown) {
105
+ console.log("Sandbox error:", error);
106
+ }
107
+
108
+ // Override fetch to route internal container requests to appropriate ports
109
+ override async fetch(request: Request): Promise<Response> {
110
+ const url = new URL(request.url);
111
+
112
+ // Capture and store the sandbox name from the header if present
113
+ if (!this.sandboxName && request.headers.has("X-Sandbox-Name")) {
114
+ const name = request.headers.get("X-Sandbox-Name")!;
115
+ this.sandboxName = name;
116
+ await this.ctx.storage.put("sandboxName", name);
117
+ console.log(`[Sandbox] Stored sandbox name: ${this.sandboxName}`);
118
+ }
119
+
120
+ // Determine which port to route to
121
+ const port = this.determinePort(url);
122
+
123
+ // Route to the appropriate port
124
+ return await this.containerFetch(request, port);
125
+ }
126
+
127
+ private determinePort(url: URL): number {
128
+ // Extract port from proxy requests (e.g., /proxy/8080/*)
129
+ const proxyMatch = url.pathname.match(/^\/proxy\/(\d+)/);
130
+ if (proxyMatch) {
131
+ return parseInt(proxyMatch[1]);
132
+ }
133
+
134
+ // All other requests go to control plane on port 3000
135
+ // This includes /api/* endpoints and any other control requests
136
+ return 3000;
137
+ }
138
+
139
+ // Enhanced exec method - always returns ExecResult with optional streaming
140
+ // This replaces the old exec method to match ISandbox interface
141
+ async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
142
+ const startTime = Date.now();
143
+ const timestamp = new Date().toISOString();
144
+
145
+ // Handle timeout
146
+ let timeoutId: NodeJS.Timeout | undefined;
147
+
148
+ try {
149
+ // Handle cancellation
150
+ if (options?.signal?.aborted) {
151
+ throw new Error("Operation was aborted");
152
+ }
153
+
154
+ let result: ExecResult;
155
+
156
+ if (options?.stream && options?.onOutput) {
157
+ // Streaming with callbacks - we need to collect the final result
158
+ result = await this.executeWithStreaming(
159
+ command,
160
+ options,
161
+ startTime,
162
+ timestamp
163
+ );
164
+ } else {
165
+ // Regular execution
166
+ const response = await this.client.execute(command, {
167
+ sessionId: options?.sessionId,
168
+ cwd: options?.cwd,
169
+ env: options?.env,
170
+ });
171
+
172
+ const duration = Date.now() - startTime;
173
+ result = this.mapExecuteResponseToExecResult(
174
+ response,
175
+ duration,
176
+ options?.sessionId
177
+ );
178
+ }
179
+
180
+ // Call completion callback if provided
181
+ if (options?.onComplete) {
182
+ options.onComplete(result);
183
+ }
184
+
185
+ return result;
186
+ } catch (error) {
187
+ if (options?.onError && error instanceof Error) {
188
+ options.onError(error);
189
+ }
190
+ throw error;
191
+ } finally {
192
+ if (timeoutId) {
193
+ clearTimeout(timeoutId);
194
+ }
195
+ }
196
+ }
197
+
198
+ private async executeWithStreaming(
199
+ command: string,
200
+ options: ExecOptions,
201
+ startTime: number,
202
+ timestamp: string
203
+ ): Promise<ExecResult> {
204
+ let stdout = "";
205
+ let stderr = "";
206
+
207
+ try {
208
+ const stream = await this.client.executeCommandStream(
209
+ command,
210
+ options.sessionId
211
+ );
212
+
213
+ for await (const event of parseSSEStream<ExecEvent>(stream)) {
214
+ // Check for cancellation
215
+ if (options.signal?.aborted) {
216
+ throw new Error("Operation was aborted");
217
+ }
218
+
219
+ switch (event.type) {
220
+ case "stdout":
221
+ case "stderr":
222
+ if (event.data) {
223
+ // Update accumulated output
224
+ if (event.type === "stdout") stdout += event.data;
225
+ if (event.type === "stderr") stderr += event.data;
226
+
227
+ // Call user's callback
228
+ if (options.onOutput) {
229
+ options.onOutput(event.type, event.data);
230
+ }
231
+ }
232
+ break;
233
+
234
+ case "complete": {
235
+ // Use result from complete event if available
236
+ const duration = Date.now() - startTime;
237
+ return (
238
+ event.result || {
239
+ success: event.exitCode === 0,
240
+ exitCode: event.exitCode || 0,
241
+ stdout,
242
+ stderr,
243
+ command,
244
+ duration,
245
+ timestamp,
246
+ sessionId: options.sessionId,
247
+ }
248
+ );
249
+ }
250
+
251
+ case "error":
252
+ throw new Error(event.error || "Command execution failed");
253
+ }
254
+ }
255
+
256
+ // If we get here without a complete event, something went wrong
257
+ throw new Error("Stream ended without completion event");
258
+ } catch (error) {
259
+ if (options.signal?.aborted) {
260
+ throw new Error("Operation was aborted");
261
+ }
262
+ throw error;
263
+ }
264
+ }
265
+
266
+ private mapExecuteResponseToExecResult(
267
+ response: ExecuteResponse,
268
+ duration: number,
269
+ sessionId?: string
270
+ ): ExecResult {
271
+ return {
272
+ success: response.success,
273
+ exitCode: response.exitCode,
274
+ stdout: response.stdout,
275
+ stderr: response.stderr,
276
+ command: response.command,
277
+ duration,
278
+ timestamp: response.timestamp,
279
+ sessionId,
280
+ };
281
+ }
282
+
283
+ // Background process management
284
+ async startProcess(
285
+ command: string,
286
+ options?: ProcessOptions
287
+ ): Promise<Process> {
288
+ // Use the new HttpClient method to start the process
289
+ try {
290
+ const response = await this.client.startProcess(command, {
291
+ processId: options?.processId,
292
+ sessionId: options?.sessionId,
293
+ timeout: options?.timeout,
294
+ env: options?.env,
295
+ cwd: options?.cwd,
296
+ encoding: options?.encoding,
297
+ autoCleanup: options?.autoCleanup,
298
+ });
299
+
300
+ const process = response.process;
301
+ const processObj: Process = {
302
+ id: process.id,
303
+ pid: process.pid,
304
+ command: process.command,
305
+ status: process.status as ProcessStatus,
306
+ startTime: new Date(process.startTime),
307
+ endTime: undefined,
308
+ exitCode: undefined,
309
+ sessionId: process.sessionId,
310
+
311
+ async kill(): Promise<void> {
312
+ throw new Error("Method will be replaced");
313
+ },
314
+ async getStatus(): Promise<ProcessStatus> {
315
+ throw new Error("Method will be replaced");
316
+ },
317
+ async getLogs(): Promise<{ stdout: string; stderr: string }> {
318
+ throw new Error("Method will be replaced");
319
+ },
320
+ };
321
+
322
+ // Bind context properly
323
+ processObj.kill = async (signal?: string) => {
324
+ await this.killProcess(process.id, signal);
325
+ };
326
+
327
+ processObj.getStatus = async () => {
328
+ const current = await this.getProcess(process.id);
329
+ return current?.status || "error";
330
+ };
331
+
332
+ processObj.getLogs = async () => {
333
+ const logs = await this.getProcessLogs(process.id);
334
+ return { stdout: logs.stdout, stderr: logs.stderr };
335
+ };
336
+
337
+ // Call onStart callback if provided
338
+ if (options?.onStart) {
339
+ options.onStart(processObj);
340
+ }
341
+
342
+ return processObj;
343
+ } catch (error) {
344
+ if (options?.onError && error instanceof Error) {
345
+ options.onError(error);
346
+ }
347
+
348
+ throw error;
349
+ }
350
+ }
351
+
352
+ async listProcesses(): Promise<Process[]> {
353
+ const response = await this.client.listProcesses();
354
+
355
+ return response.processes.map((processData) => ({
356
+ id: processData.id,
357
+ pid: processData.pid,
358
+ command: processData.command,
359
+ status: processData.status,
360
+ startTime: new Date(processData.startTime),
361
+ endTime: processData.endTime ? new Date(processData.endTime) : undefined,
362
+ exitCode: processData.exitCode,
363
+ sessionId: processData.sessionId,
364
+
365
+ kill: async (signal?: string) => {
366
+ await this.killProcess(processData.id, signal);
367
+ },
368
+
369
+ getStatus: async () => {
370
+ const current = await this.getProcess(processData.id);
371
+ return current?.status || "error";
372
+ },
373
+
374
+ getLogs: async () => {
375
+ const logs = await this.getProcessLogs(processData.id);
376
+ return { stdout: logs.stdout, stderr: logs.stderr };
377
+ },
378
+ }));
379
+ }
380
+
381
+ async getProcess(id: string): Promise<Process | null> {
382
+ const response = await this.client.getProcess(id);
383
+ if (!response.process) {
384
+ return null;
385
+ }
386
+
387
+ const processData = response.process;
388
+ return {
389
+ id: processData.id,
390
+ pid: processData.pid,
391
+ command: processData.command,
392
+ status: processData.status,
393
+ startTime: new Date(processData.startTime),
394
+ endTime: processData.endTime ? new Date(processData.endTime) : undefined,
395
+ exitCode: processData.exitCode,
396
+ sessionId: processData.sessionId,
397
+
398
+ kill: async (signal?: string) => {
399
+ await this.killProcess(processData.id, signal);
400
+ },
401
+
402
+ getStatus: async () => {
403
+ const current = await this.getProcess(processData.id);
404
+ return current?.status || "error";
405
+ },
406
+
407
+ getLogs: async () => {
408
+ const logs = await this.getProcessLogs(processData.id);
409
+ return { stdout: logs.stdout, stderr: logs.stderr };
410
+ },
411
+ };
412
+ }
413
+
414
+ async killProcess(id: string, _signal?: string): Promise<void> {
415
+ try {
416
+ // Note: signal parameter is not currently supported by the HttpClient implementation
417
+ await this.client.killProcess(id);
418
+ } catch (error) {
419
+ if (
420
+ error instanceof Error &&
421
+ error.message.includes("Process not found")
422
+ ) {
423
+ throw new ProcessNotFoundError(id);
424
+ }
425
+ throw new SandboxError(
426
+ `Failed to kill process ${id}: ${
427
+ error instanceof Error ? error.message : "Unknown error"
428
+ }`,
429
+ "KILL_PROCESS_FAILED"
430
+ );
431
+ }
432
+ }
433
+
434
+ async killAllProcesses(): Promise<number> {
435
+ const response = await this.client.killAllProcesses();
436
+ return response.killedCount;
437
+ }
438
+
439
+ async cleanupCompletedProcesses(): Promise<number> {
440
+ // For now, this would need to be implemented as a container endpoint
441
+ // as we no longer maintain local process storage
442
+ // We'll return 0 as a placeholder until the container endpoint is added
443
+ return 0;
444
+ }
445
+
446
+ async getProcessLogs(
447
+ id: string
448
+ ): Promise<{ stdout: string; stderr: string }> {
449
+ try {
450
+ const response = await this.client.getProcessLogs(id);
451
+ return {
452
+ stdout: response.stdout,
453
+ stderr: response.stderr,
454
+ };
455
+ } catch (error) {
456
+ if (
457
+ error instanceof Error &&
458
+ error.message.includes("Process not found")
459
+ ) {
460
+ throw new ProcessNotFoundError(id);
461
+ }
462
+ throw error;
463
+ }
464
+ }
465
+
466
+ // Streaming methods - return ReadableStream for RPC compatibility
467
+ async execStream(
468
+ command: string,
469
+ options?: StreamOptions
470
+ ): Promise<ReadableStream<Uint8Array>> {
471
+ // Check for cancellation
472
+ if (options?.signal?.aborted) {
473
+ throw new Error("Operation was aborted");
474
+ }
475
+
476
+ // Get the stream from HttpClient (need to add this method)
477
+ const stream = await this.client.executeCommandStream(
478
+ command,
479
+ options?.sessionId
480
+ );
481
+
482
+ // Return the ReadableStream directly - can be converted to AsyncIterable by consumers
483
+ return stream;
484
+ }
485
+
486
+ async streamProcessLogs(
487
+ processId: string,
488
+ options?: { signal?: AbortSignal }
489
+ ): Promise<ReadableStream<Uint8Array>> {
490
+ // Check for cancellation
491
+ if (options?.signal?.aborted) {
492
+ throw new Error("Operation was aborted");
493
+ }
494
+
495
+ // Get the stream from HttpClient
496
+ const stream = await this.client.streamProcessLogs(processId);
497
+
498
+ // Return the ReadableStream directly - can be converted to AsyncIterable by consumers
499
+ return stream;
500
+ }
501
+
502
+ async gitCheckout(
503
+ repoUrl: string,
504
+ options: { branch?: string; targetDir?: string }
505
+ ) {
506
+ return this.client.gitCheckout(repoUrl, options.branch, options.targetDir);
507
+ }
508
+
509
+ async mkdir(path: string, options: { recursive?: boolean } = {}) {
510
+ return this.client.mkdir(path, options.recursive);
511
+ }
512
+
513
+ async writeFile(
514
+ path: string,
515
+ content: string,
516
+ options: { encoding?: string } = {}
517
+ ) {
518
+ return this.client.writeFile(path, content, options.encoding);
519
+ }
520
+
521
+ async deleteFile(path: string) {
522
+ return this.client.deleteFile(path);
523
+ }
524
+
525
+ async renameFile(oldPath: string, newPath: string) {
526
+ return this.client.renameFile(oldPath, newPath);
527
+ }
528
+
529
+ async moveFile(sourcePath: string, destinationPath: string) {
530
+ return this.client.moveFile(sourcePath, destinationPath);
531
+ }
532
+
533
+ async readFile(path: string, options: { encoding?: string } = {}) {
534
+ return this.client.readFile(path, options.encoding);
535
+ }
536
+
537
+ async listFiles(
538
+ path: string,
539
+ options: {
540
+ recursive?: boolean;
541
+ includeHidden?: boolean;
542
+ } = {}
543
+ ) {
544
+ return this.client.listFiles(path, options);
545
+ }
546
+
547
+ async exposePort(port: number, options: { name?: string; hostname: string }) {
548
+ await this.client.exposePort(port, options?.name);
549
+
550
+ // We need the sandbox name to construct preview URLs
551
+ if (!this.sandboxName) {
552
+ throw new Error(
553
+ "Sandbox name not available. Ensure sandbox is accessed through getSandbox()"
554
+ );
555
+ }
556
+
557
+ const url = this.constructPreviewUrl(
558
+ port,
559
+ this.sandboxName,
560
+ options.hostname
561
+ );
562
+
563
+ return {
564
+ url,
565
+ port,
566
+ name: options?.name,
567
+ };
568
+ }
569
+
570
+ async unexposePort(port: number) {
571
+ if (!validatePort(port)) {
572
+ logSecurityEvent(
573
+ "INVALID_PORT_UNEXPOSE",
574
+ {
575
+ port,
576
+ },
577
+ "high"
578
+ );
579
+ throw new SecurityError(
580
+ `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
581
+ );
582
+ }
583
+
584
+ await this.client.unexposePort(port);
585
+
586
+ logSecurityEvent(
587
+ "PORT_UNEXPOSED",
588
+ {
589
+ port,
590
+ },
591
+ "low"
592
+ );
593
+ }
594
+
595
+ async getExposedPorts(hostname: string) {
596
+ const response = await this.client.getExposedPorts();
597
+
598
+ // We need the sandbox name to construct preview URLs
599
+ if (!this.sandboxName) {
600
+ throw new Error(
601
+ "Sandbox name not available. Ensure sandbox is accessed through getSandbox()"
602
+ );
603
+ }
604
+
605
+ return response.ports.map((port) => ({
606
+ url: this.constructPreviewUrl(port.port, this.sandboxName!, hostname),
607
+ port: port.port,
608
+ name: port.name,
609
+ exposedAt: port.exposedAt,
610
+ }));
611
+ }
612
+
613
+ private constructPreviewUrl(
614
+ port: number,
615
+ sandboxId: string,
616
+ hostname: string
617
+ ): string {
618
+ if (!validatePort(port)) {
619
+ logSecurityEvent(
620
+ "INVALID_PORT_REJECTED",
621
+ {
622
+ port,
623
+ sandboxId,
624
+ hostname,
625
+ },
626
+ "high"
627
+ );
628
+ throw new SecurityError(
629
+ `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
630
+ );
631
+ }
632
+
633
+ let sanitizedSandboxId: string;
634
+ try {
635
+ sanitizedSandboxId = sanitizeSandboxId(sandboxId);
636
+ } catch (error) {
637
+ logSecurityEvent(
638
+ "INVALID_SANDBOX_ID_REJECTED",
639
+ {
640
+ sandboxId,
641
+ port,
642
+ hostname,
643
+ error: error instanceof Error ? error.message : "Unknown error",
644
+ },
645
+ "high"
646
+ );
647
+ throw error;
648
+ }
649
+
650
+ const isLocalhost = isLocalhostPattern(hostname);
651
+
652
+ if (isLocalhost) {
653
+ // Unified subdomain approach for localhost (RFC 6761)
654
+ const [host, portStr] = hostname.split(":");
655
+ const mainPort = portStr || "80";
656
+
657
+ // Use URL constructor for safe URL building
658
+ try {
659
+ const baseUrl = new URL(`http://${host}:${mainPort}`);
660
+ // Construct subdomain safely
661
+ const subdomainHost = `${port}-${sanitizedSandboxId}.${host}`;
662
+ baseUrl.hostname = subdomainHost;
663
+
664
+ const finalUrl = baseUrl.toString();
665
+
666
+ logSecurityEvent(
667
+ "PREVIEW_URL_CONSTRUCTED",
668
+ {
669
+ port,
670
+ sandboxId: sanitizedSandboxId,
671
+ hostname,
672
+ resultUrl: finalUrl,
673
+ environment: "localhost",
674
+ },
675
+ "low"
676
+ );
677
+
678
+ return finalUrl;
679
+ } catch (error) {
680
+ logSecurityEvent(
681
+ "URL_CONSTRUCTION_FAILED",
682
+ {
683
+ port,
684
+ sandboxId: sanitizedSandboxId,
685
+ hostname,
686
+ error: error instanceof Error ? error.message : "Unknown error",
687
+ },
688
+ "high"
689
+ );
690
+ throw new SecurityError(
691
+ `Failed to construct preview URL: ${
692
+ error instanceof Error ? error.message : "Unknown error"
693
+ }`
694
+ );
695
+ }
696
+ }
697
+
698
+ // Production subdomain logic - enforce HTTPS
699
+ try {
700
+ // Always use HTTPS for production (non-localhost)
701
+ const protocol = "https";
702
+ const baseUrl = new URL(`${protocol}://${hostname}`);
703
+
704
+ // Construct subdomain safely
705
+ const subdomainHost = `${port}-${sanitizedSandboxId}.${hostname}`;
706
+ baseUrl.hostname = subdomainHost;
707
+
708
+ const finalUrl = baseUrl.toString();
709
+
710
+ logSecurityEvent(
711
+ "PREVIEW_URL_CONSTRUCTED",
712
+ {
713
+ port,
714
+ sandboxId: sanitizedSandboxId,
715
+ hostname,
716
+ resultUrl: finalUrl,
717
+ environment: "production",
718
+ },
719
+ "low"
720
+ );
721
+
722
+ return finalUrl;
723
+ } catch (error) {
724
+ logSecurityEvent(
725
+ "URL_CONSTRUCTION_FAILED",
726
+ {
727
+ port,
728
+ sandboxId: sanitizedSandboxId,
729
+ hostname,
730
+ error: error instanceof Error ? error.message : "Unknown error",
731
+ },
732
+ "high"
733
+ );
734
+ throw new SecurityError(
735
+ `Failed to construct preview URL: ${
736
+ error instanceof Error ? error.message : "Unknown error"
737
+ }`
738
+ );
739
+ }
740
+ }
741
+
742
+ // Code Interpreter Methods
743
+
744
+ /**
745
+ * Create a new code execution context
746
+ */
747
+ async createCodeContext(
748
+ options?: CreateContextOptions
749
+ ): Promise<CodeContext> {
750
+ return this.codeInterpreter.createCodeContext(options);
751
+ }
752
+
753
+ /**
754
+ * Run code with streaming callbacks
755
+ */
756
+ async runCode(
757
+ code: string,
758
+ options?: RunCodeOptions
759
+ ): Promise<ExecutionResult> {
760
+ const execution = await this.codeInterpreter.runCode(code, options);
761
+ // Convert to plain object for RPC serialization
762
+ return execution.toJSON();
763
+ }
764
+
765
+ /**
766
+ * Run code and return a streaming response
767
+ */
768
+ async runCodeStream(
769
+ code: string,
770
+ options?: RunCodeOptions
771
+ ): Promise<ReadableStream> {
772
+ return this.codeInterpreter.runCodeStream(code, options);
773
+ }
774
+
775
+ /**
776
+ * List all code contexts
777
+ */
778
+ async listCodeContexts(): Promise<CodeContext[]> {
779
+ return this.codeInterpreter.listCodeContexts();
780
+ }
781
+
782
+ /**
783
+ * Delete a code context
784
+ */
785
+ async deleteCodeContext(contextId: string): Promise<void> {
786
+ return this.codeInterpreter.deleteCodeContext(contextId);
787
+ }
788
+ }