@cloudflare/sandbox 0.0.0-215ab49 → 0.0.0-2450ebd

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 (81) hide show
  1. package/CHANGELOG.md +157 -0
  2. package/Dockerfile +112 -54
  3. package/README.md +91 -489
  4. package/dist/chunk-BFVUNTP4.js +104 -0
  5. package/dist/chunk-BFVUNTP4.js.map +1 -0
  6. package/dist/chunk-EKSWCBCA.js +86 -0
  7. package/dist/chunk-EKSWCBCA.js.map +1 -0
  8. package/dist/chunk-EXQOIRZI.js +2351 -0
  9. package/dist/chunk-EXQOIRZI.js.map +1 -0
  10. package/dist/chunk-JXZMAU2C.js +559 -0
  11. package/dist/chunk-JXZMAU2C.js.map +1 -0
  12. package/dist/chunk-Z532A7QC.js +78 -0
  13. package/dist/chunk-Z532A7QC.js.map +1 -0
  14. package/dist/file-stream.d.ts +43 -0
  15. package/dist/file-stream.js +9 -0
  16. package/dist/file-stream.js.map +1 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +66 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/interpreter.d.ts +33 -0
  21. package/dist/interpreter.js +8 -0
  22. package/dist/interpreter.js.map +1 -0
  23. package/dist/request-handler.d.ts +18 -0
  24. package/dist/request-handler.js +12 -0
  25. package/dist/request-handler.js.map +1 -0
  26. package/dist/sandbox-D9K2ypln.d.ts +583 -0
  27. package/dist/sandbox.d.ts +4 -0
  28. package/dist/sandbox.js +12 -0
  29. package/dist/sandbox.js.map +1 -0
  30. package/dist/security.d.ts +31 -0
  31. package/dist/security.js +13 -0
  32. package/dist/security.js.map +1 -0
  33. package/dist/sse-parser.d.ts +28 -0
  34. package/dist/sse-parser.js +11 -0
  35. package/dist/sse-parser.js.map +1 -0
  36. package/package.json +13 -5
  37. package/src/clients/base-client.ts +280 -0
  38. package/src/clients/command-client.ts +115 -0
  39. package/src/clients/file-client.ts +269 -0
  40. package/src/clients/git-client.ts +92 -0
  41. package/src/clients/index.ts +63 -0
  42. package/src/clients/interpreter-client.ts +329 -0
  43. package/src/clients/port-client.ts +105 -0
  44. package/src/clients/process-client.ts +177 -0
  45. package/src/clients/sandbox-client.ts +41 -0
  46. package/src/clients/types.ts +84 -0
  47. package/src/clients/utility-client.ts +94 -0
  48. package/src/errors/adapter.ts +180 -0
  49. package/src/errors/classes.ts +469 -0
  50. package/src/errors/index.ts +105 -0
  51. package/src/file-stream.ts +164 -0
  52. package/src/index.ts +85 -12
  53. package/src/interpreter.ts +159 -0
  54. package/src/request-handler.ts +69 -43
  55. package/src/sandbox.ts +558 -292
  56. package/src/security.ts +14 -23
  57. package/src/sse-parser.ts +4 -8
  58. package/startup.sh +3 -0
  59. package/tests/base-client.test.ts +328 -0
  60. package/tests/command-client.test.ts +407 -0
  61. package/tests/file-client.test.ts +643 -0
  62. package/tests/file-stream.test.ts +306 -0
  63. package/tests/git-client.test.ts +328 -0
  64. package/tests/port-client.test.ts +301 -0
  65. package/tests/process-client.test.ts +658 -0
  66. package/tests/sandbox.test.ts +465 -0
  67. package/tests/sse-parser.test.ts +290 -0
  68. package/tests/utility-client.test.ts +266 -0
  69. package/tests/wrangler.jsonc +35 -0
  70. package/tsconfig.json +9 -1
  71. package/vitest.config.ts +31 -0
  72. package/container_src/handler/exec.ts +0 -338
  73. package/container_src/handler/file.ts +0 -844
  74. package/container_src/handler/git.ts +0 -182
  75. package/container_src/handler/ports.ts +0 -314
  76. package/container_src/handler/process.ts +0 -640
  77. package/container_src/index.ts +0 -361
  78. package/container_src/package.json +0 -9
  79. package/container_src/types.ts +0 -108
  80. package/src/client.ts +0 -1038
  81. package/src/types.ts +0 -386
package/src/sandbox.ts CHANGED
@@ -1,67 +1,99 @@
1
+ import type { DurableObject } from 'cloudflare:workers';
1
2
  import { Container, getContainer } from "@cloudflare/containers";
2
- import { HttpClient } from "./client";
3
- import { isLocalhostPattern } from "./request-handler";
4
- import {
5
- logSecurityEvent,
6
- SecurityError,
7
- sanitizeSandboxId,
8
- validatePort
9
- } from "./security";
10
3
  import type {
4
+ CodeContext,
5
+ CreateContextOptions,
6
+ ExecEvent,
11
7
  ExecOptions,
12
8
  ExecResult,
9
+ ExecutionResult,
10
+ ExecutionSession,
13
11
  ISandbox,
14
12
  Process,
15
13
  ProcessOptions,
16
14
  ProcessStatus,
15
+ RunCodeOptions,
16
+ SessionOptions,
17
17
  StreamOptions
18
- } from "./types";
18
+ } from "@repo/shared";
19
+ import { createLogger, runWithLogger, TraceContext } from "@repo/shared";
20
+ import { type ExecuteResponse, SandboxClient } from "./clients";
21
+ import type { ErrorResponse } from './errors';
22
+ import { CustomDomainRequiredError, ErrorCode } from './errors';
23
+ import { CodeInterpreter } from "./interpreter";
24
+ import { isLocalhostPattern } from "./request-handler";
19
25
  import {
20
- ProcessNotFoundError,
21
- SandboxError
22
- } from "./types";
26
+ SecurityError,
27
+ sanitizeSandboxId,
28
+ validatePort
29
+ } from "./security";
30
+ import { parseSSEStream } from "./sse-parser";
23
31
 
24
- export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string) {
32
+ export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string, options?: {
33
+ baseUrl: string
34
+ }) {
25
35
  const stub = getContainer(ns, id);
26
36
 
27
37
  // Store the name on first access
28
38
  stub.setSandboxName?.(id);
29
39
 
40
+ if(options?.baseUrl) {
41
+ stub.setBaseUrl(options.baseUrl);
42
+ }
43
+
30
44
  return stub;
31
45
  }
32
46
 
33
47
  export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
34
48
  defaultPort = 3000; // Default port for the container's Bun server
35
49
  sleepAfter = "3m"; // Sleep the sandbox if no requests are made in this timeframe
36
- client: HttpClient;
50
+
51
+ client: SandboxClient;
52
+ private codeInterpreter: CodeInterpreter;
37
53
  private sandboxName: string | null = null;
54
+ private baseUrl: string | null = null;
55
+ private portTokens: Map<number, string> = new Map();
56
+ private defaultSession: string | null = null;
57
+ envVars: Record<string, string> = {};
58
+ private logger: ReturnType<typeof createLogger>;
38
59
 
39
- constructor(ctx: DurableObjectState, env: Env) {
60
+ constructor(ctx: DurableObject['ctx'], env: Env) {
40
61
  super(ctx, env);
41
- this.client = new HttpClient({
42
- onCommandComplete: (success, exitCode, _stdout, _stderr, command) => {
43
- console.log(
44
- `[Container] Command completed: ${command}, Success: ${success}, Exit code: ${exitCode}`
45
- );
46
- },
47
- onCommandStart: (command) => {
48
- console.log(
49
- `[Container] Command started: ${command}`
50
- );
51
- },
52
- onError: (error, _command) => {
53
- console.error(`[Container] Command error: ${error}`);
54
- },
55
- onOutput: (stream, data, _command) => {
56
- console.log(`[Container] [${stream}] ${data}`);
57
- },
62
+
63
+ const envObj = env as any;
64
+ // Set sandbox environment variables from env object
65
+ const sandboxEnvKeys = ['SANDBOX_LOG_LEVEL', 'SANDBOX_LOG_FORMAT'] as const;
66
+ sandboxEnvKeys.forEach(key => {
67
+ if (envObj?.[key]) {
68
+ this.envVars[key] = envObj[key];
69
+ }
70
+ });
71
+
72
+ this.logger = createLogger({
73
+ component: 'sandbox-do',
74
+ sandboxId: this.ctx.id.toString()
75
+ });
76
+
77
+ this.client = new SandboxClient({
78
+ logger: this.logger,
58
79
  port: 3000, // Control plane port
59
80
  stub: this,
60
81
  });
61
82
 
62
- // Load the sandbox name from storage on initialization
83
+ // Initialize code interpreter - pass 'this' after client is ready
84
+ // The CodeInterpreter extracts client.interpreter from the sandbox
85
+ this.codeInterpreter = new CodeInterpreter(this);
86
+
87
+ // Load the sandbox name and port tokens from storage on initialization
63
88
  this.ctx.blockConcurrencyWhile(async () => {
64
89
  this.sandboxName = await this.ctx.storage.get<string>('sandboxName') || null;
90
+ const storedTokens = await this.ctx.storage.get<Record<string, string>>('portTokens') || {};
91
+
92
+ // Convert stored tokens back to Map
93
+ this.portTokens = new Map();
94
+ for (const [portStr, token] of Object.entries(storedTokens)) {
95
+ this.portTokens.set(parseInt(portStr, 10), token);
96
+ }
65
97
  });
66
98
  }
67
99
 
@@ -70,55 +102,93 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
70
102
  if (!this.sandboxName) {
71
103
  this.sandboxName = name;
72
104
  await this.ctx.storage.put('sandboxName', name);
73
- console.log(`[Sandbox] Stored sandbox name via RPC: ${name}`);
105
+ }
106
+ }
107
+
108
+ // RPC method to set the base URL
109
+ async setBaseUrl(baseUrl: string): Promise<void> {
110
+ if (!this.baseUrl) {
111
+ this.baseUrl = baseUrl;
112
+ await this.ctx.storage.put('baseUrl', baseUrl);
113
+ } else {
114
+ if(this.baseUrl !== baseUrl) {
115
+ throw new Error('Base URL already set and different from one previously provided');
116
+ }
74
117
  }
75
118
  }
76
119
 
77
120
  // RPC method to set environment variables
78
121
  async setEnvVars(envVars: Record<string, string>): Promise<void> {
122
+ // Update local state for new sessions
79
123
  this.envVars = { ...this.envVars, ...envVars };
80
- console.log(`[Sandbox] Updated environment variables`);
124
+
125
+ // If default session already exists, update it directly
126
+ if (this.defaultSession) {
127
+ // Set environment variables by executing export commands in the existing session
128
+ for (const [key, value] of Object.entries(envVars)) {
129
+ const escapedValue = value.replace(/'/g, "'\\''");
130
+ const exportCommand = `export ${key}='${escapedValue}'`;
131
+
132
+ const result = await this.client.commands.execute(exportCommand, this.defaultSession);
133
+
134
+ if (result.exitCode !== 0) {
135
+ throw new Error(`Failed to set ${key}: ${result.stderr || 'Unknown error'}`);
136
+ }
137
+ }
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Cleanup and destroy the sandbox container
143
+ */
144
+ override async destroy(): Promise<void> {
145
+ this.logger.info('Destroying sandbox container');
146
+ await super.destroy();
81
147
  }
82
148
 
83
149
  override onStart() {
84
- console.log("Sandbox successfully started");
150
+ this.logger.debug('Sandbox started');
85
151
  }
86
152
 
87
153
  override onStop() {
88
- console.log("Sandbox successfully shut down");
89
- if (this.client) {
90
- this.client.clearSession();
91
- }
154
+ this.logger.debug('Sandbox stopped');
92
155
  }
93
156
 
94
157
  override onError(error: unknown) {
95
- console.log("Sandbox error:", error);
158
+ this.logger.error('Sandbox error', error instanceof Error ? error : new Error(String(error)));
96
159
  }
97
160
 
98
161
  // Override fetch to route internal container requests to appropriate ports
99
162
  override async fetch(request: Request): Promise<Response> {
100
- const url = new URL(request.url);
163
+ // Extract or generate trace ID from request
164
+ const traceId = TraceContext.fromHeaders(request.headers) || TraceContext.generate();
101
165
 
102
- // Capture and store the sandbox name from the header if present
103
- if (!this.sandboxName && request.headers.has('X-Sandbox-Name')) {
104
- const name = request.headers.get('X-Sandbox-Name')!;
105
- this.sandboxName = name;
106
- await this.ctx.storage.put('sandboxName', name);
107
- console.log(`[Sandbox] Stored sandbox name: ${this.sandboxName}`);
108
- }
166
+ // Create request-specific logger with trace ID
167
+ const requestLogger = this.logger.child({ traceId, operation: 'fetch' });
168
+
169
+ return await runWithLogger(requestLogger, async () => {
170
+ const url = new URL(request.url);
171
+
172
+ // Capture and store the sandbox name from the header if present
173
+ if (!this.sandboxName && request.headers.has('X-Sandbox-Name')) {
174
+ const name = request.headers.get('X-Sandbox-Name')!;
175
+ this.sandboxName = name;
176
+ await this.ctx.storage.put('sandboxName', name);
177
+ }
109
178
 
110
- // Determine which port to route to
111
- const port = this.determinePort(url);
179
+ // Determine which port to route to
180
+ const port = this.determinePort(url);
112
181
 
113
- // Route to the appropriate port
114
- return await this.containerFetch(request, port);
182
+ // Route to the appropriate port
183
+ return await this.containerFetch(request, port);
184
+ });
115
185
  }
116
186
 
117
187
  private determinePort(url: URL): number {
118
188
  // Extract port from proxy requests (e.g., /proxy/8080/*)
119
189
  const proxyMatch = url.pathname.match(/^\/proxy\/(\d+)/);
120
190
  if (proxyMatch) {
121
- return parseInt(proxyMatch[1]);
191
+ return parseInt(proxyMatch[1], 10);
122
192
  }
123
193
 
124
194
  // All other requests go to control plane on port 3000
@@ -126,9 +196,43 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
126
196
  return 3000;
127
197
  }
128
198
 
199
+ /**
200
+ * Ensure default session exists - lazy initialization
201
+ * This is called automatically by all public methods that need a session
202
+ */
203
+ private async ensureDefaultSession(): Promise<string> {
204
+ if (!this.defaultSession) {
205
+ const sessionId = `sandbox-${this.sandboxName || 'default'}`;
206
+
207
+ // Create session in container
208
+ await this.client.utils.createSession({
209
+ id: sessionId,
210
+ env: this.envVars || {},
211
+ cwd: '/workspace',
212
+ });
213
+
214
+ this.defaultSession = sessionId;
215
+ this.logger.debug('Default session initialized', { sessionId });
216
+ }
217
+ return this.defaultSession;
218
+ }
219
+
129
220
  // Enhanced exec method - always returns ExecResult with optional streaming
130
221
  // This replaces the old exec method to match ISandbox interface
131
222
  async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
223
+ const session = await this.ensureDefaultSession();
224
+ return this.execWithSession(command, session, options);
225
+ }
226
+
227
+ /**
228
+ * Internal session-aware exec implementation
229
+ * Used by both public exec() and session wrappers
230
+ */
231
+ private async execWithSession(
232
+ command: string,
233
+ sessionId: string,
234
+ options?: ExecOptions
235
+ ): Promise<ExecResult> {
132
236
  const startTime = Date.now();
133
237
  const timestamp = new Date().toISOString();
134
238
 
@@ -145,20 +249,13 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
145
249
 
146
250
  if (options?.stream && options?.onOutput) {
147
251
  // Streaming with callbacks - we need to collect the final result
148
- result = await this.executeWithStreaming(command, options, startTime, timestamp);
252
+ result = await this.executeWithStreaming(command, sessionId, options, startTime, timestamp);
149
253
  } else {
150
- // Regular execution
151
- const response = await this.client.execute(
152
- command,
153
- {
154
- sessionId: options?.sessionId,
155
- cwd: options?.cwd,
156
- env: options?.env,
157
- }
158
- );
254
+ // Regular execution with session
255
+ const response = await this.client.commands.execute(command, sessionId);
159
256
 
160
257
  const duration = Date.now() - startTime;
161
- result = this.mapExecuteResponseToExecResult(response, duration, options?.sessionId);
258
+ result = this.mapExecuteResponseToExecResult(response, duration, sessionId);
162
259
  }
163
260
 
164
261
  // Call completion callback if provided
@@ -181,6 +278,7 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
181
278
 
182
279
  private async executeWithStreaming(
183
280
  command: string,
281
+ sessionId: string,
184
282
  options: ExecOptions,
185
283
  startTime: number,
186
284
  timestamp: string
@@ -189,10 +287,9 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
189
287
  let stderr = '';
190
288
 
191
289
  try {
192
- const stream = await this.client.executeCommandStream(command, options.sessionId);
193
- const { parseSSEStream } = await import('./sse-parser');
290
+ const stream = await this.client.commands.executeStream(command, sessionId);
194
291
 
195
- for await (const event of parseSSEStream<import('./types').ExecEvent>(stream)) {
292
+ for await (const event of parseSSEStream<ExecEvent>(stream)) {
196
293
  // Check for cancellation
197
294
  if (options.signal?.aborted) {
198
295
  throw new Error('Operation was aborted');
@@ -216,20 +313,20 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
216
313
  case 'complete': {
217
314
  // Use result from complete event if available
218
315
  const duration = Date.now() - startTime;
219
- return event.result || {
220
- success: event.exitCode === 0,
221
- exitCode: event.exitCode || 0,
316
+ return {
317
+ success: (event.exitCode ?? 0) === 0,
318
+ exitCode: event.exitCode ?? 0,
222
319
  stdout,
223
320
  stderr,
224
321
  command,
225
322
  duration,
226
323
  timestamp,
227
- sessionId: options.sessionId
324
+ sessionId
228
325
  };
229
326
  }
230
327
 
231
328
  case 'error':
232
- throw new Error(event.error || 'Command execution failed');
329
+ throw new Error(event.data || 'Command execution failed');
233
330
  }
234
331
  }
235
332
 
@@ -245,7 +342,7 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
245
342
  }
246
343
 
247
344
  private mapExecuteResponseToExecResult(
248
- response: import('./client').ExecuteResponse,
345
+ response: ExecuteResponse,
249
346
  duration: number,
250
347
  sessionId?: string
251
348
  ): ExecResult {
@@ -261,57 +358,68 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
261
358
  };
262
359
  }
263
360
 
361
+ /**
362
+ * Create a Process domain object from HTTP client DTO
363
+ * Centralizes process object creation with bound methods
364
+ * This eliminates duplication across startProcess, listProcesses, getProcess, and session wrappers
365
+ */
366
+ private createProcessFromDTO(
367
+ data: {
368
+ id: string;
369
+ pid?: number;
370
+ command: string;
371
+ status: ProcessStatus;
372
+ startTime: string | Date;
373
+ endTime?: string | Date;
374
+ exitCode?: number;
375
+ },
376
+ sessionId: string
377
+ ): Process {
378
+ return {
379
+ id: data.id,
380
+ pid: data.pid,
381
+ command: data.command,
382
+ status: data.status,
383
+ startTime: typeof data.startTime === 'string' ? new Date(data.startTime) : data.startTime,
384
+ endTime: data.endTime ? (typeof data.endTime === 'string' ? new Date(data.endTime) : data.endTime) : undefined,
385
+ exitCode: data.exitCode,
386
+ sessionId,
387
+
388
+ kill: async (signal?: string) => {
389
+ await this.killProcess(data.id, signal);
390
+ },
391
+
392
+ getStatus: async () => {
393
+ const current = await this.getProcess(data.id);
394
+ return current?.status || 'error';
395
+ },
396
+
397
+ getLogs: async () => {
398
+ const logs = await this.getProcessLogs(data.id);
399
+ return { stdout: logs.stdout, stderr: logs.stderr };
400
+ }
401
+ };
402
+ }
403
+
264
404
 
265
405
  // Background process management
266
- async startProcess(command: string, options?: ProcessOptions): Promise<Process> {
406
+ async startProcess(command: string, options?: ProcessOptions, sessionId?: string): Promise<Process> {
267
407
  // Use the new HttpClient method to start the process
268
408
  try {
269
- const response = await this.client.startProcess(command, {
270
- processId: options?.processId,
271
- sessionId: options?.sessionId,
272
- timeout: options?.timeout,
273
- env: options?.env,
274
- cwd: options?.cwd,
275
- encoding: options?.encoding,
276
- autoCleanup: options?.autoCleanup
409
+ const session = sessionId ?? await this.ensureDefaultSession();
410
+ const response = await this.client.processes.startProcess(command, session, {
411
+ processId: options?.processId
277
412
  });
278
413
 
279
- const process = response.process;
280
- const processObj: Process = {
281
- id: process.id,
282
- pid: process.pid,
283
- command: process.command,
284
- status: process.status as ProcessStatus,
285
- startTime: new Date(process.startTime),
414
+ const processObj = this.createProcessFromDTO({
415
+ id: response.processId,
416
+ pid: response.pid,
417
+ command: response.command,
418
+ status: 'running' as ProcessStatus,
419
+ startTime: new Date(),
286
420
  endTime: undefined,
287
- exitCode: undefined,
288
- sessionId: process.sessionId,
289
-
290
- async kill(): Promise<void> {
291
- throw new Error('Method will be replaced');
292
- },
293
- async getStatus(): Promise<ProcessStatus> {
294
- throw new Error('Method will be replaced');
295
- },
296
- async getLogs(): Promise<{ stdout: string; stderr: string }> {
297
- throw new Error('Method will be replaced');
298
- }
299
- };
300
-
301
- // Bind context properly
302
- processObj.kill = async (signal?: string) => {
303
- await this.killProcess(process.id, signal);
304
- };
305
-
306
- processObj.getStatus = async () => {
307
- const current = await this.getProcess(process.id);
308
- return current?.status || 'error';
309
- };
310
-
311
- processObj.getLogs = async () => {
312
- const logs = await this.getProcessLogs(process.id);
313
- return { stdout: logs.stdout, stderr: logs.stderr };
314
- };
421
+ exitCode: undefined
422
+ }, session);
315
423
 
316
424
  // Call onStart callback if provided
317
425
  if (options?.onStart) {
@@ -329,108 +437,68 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
329
437
  }
330
438
  }
331
439
 
332
- async listProcesses(): Promise<Process[]> {
333
- const response = await this.client.listProcesses();
334
-
335
- return response.processes.map(processData => ({
336
- id: processData.id,
337
- pid: processData.pid,
338
- command: processData.command,
339
- status: processData.status,
340
- startTime: new Date(processData.startTime),
341
- endTime: processData.endTime ? new Date(processData.endTime) : undefined,
342
- exitCode: processData.exitCode,
343
- sessionId: processData.sessionId,
344
-
345
- kill: async (signal?: string) => {
346
- await this.killProcess(processData.id, signal);
347
- },
348
-
349
- getStatus: async () => {
350
- const current = await this.getProcess(processData.id);
351
- return current?.status || 'error';
352
- },
353
-
354
- getLogs: async () => {
355
- const logs = await this.getProcessLogs(processData.id);
356
- return { stdout: logs.stdout, stderr: logs.stderr };
357
- }
358
- }));
440
+ async listProcesses(sessionId?: string): Promise<Process[]> {
441
+ const session = sessionId ?? await this.ensureDefaultSession();
442
+ const response = await this.client.processes.listProcesses();
443
+
444
+ return response.processes.map(processData =>
445
+ this.createProcessFromDTO({
446
+ id: processData.id,
447
+ pid: processData.pid,
448
+ command: processData.command,
449
+ status: processData.status,
450
+ startTime: processData.startTime,
451
+ endTime: processData.endTime,
452
+ exitCode: processData.exitCode
453
+ }, session)
454
+ );
359
455
  }
360
456
 
361
- async getProcess(id: string): Promise<Process | null> {
362
- const response = await this.client.getProcess(id);
457
+ async getProcess(id: string, sessionId?: string): Promise<Process | null> {
458
+ const session = sessionId ?? await this.ensureDefaultSession();
459
+ const response = await this.client.processes.getProcess(id);
363
460
  if (!response.process) {
364
461
  return null;
365
462
  }
366
463
 
367
464
  const processData = response.process;
368
- return {
465
+ return this.createProcessFromDTO({
369
466
  id: processData.id,
370
467
  pid: processData.pid,
371
468
  command: processData.command,
372
469
  status: processData.status,
373
- startTime: new Date(processData.startTime),
374
- endTime: processData.endTime ? new Date(processData.endTime) : undefined,
375
- exitCode: processData.exitCode,
376
- sessionId: processData.sessionId,
377
-
378
- kill: async (signal?: string) => {
379
- await this.killProcess(processData.id, signal);
380
- },
381
-
382
- getStatus: async () => {
383
- const current = await this.getProcess(processData.id);
384
- return current?.status || 'error';
385
- },
386
-
387
- getLogs: async () => {
388
- const logs = await this.getProcessLogs(processData.id);
389
- return { stdout: logs.stdout, stderr: logs.stderr };
390
- }
391
- };
470
+ startTime: processData.startTime,
471
+ endTime: processData.endTime,
472
+ exitCode: processData.exitCode
473
+ }, session);
392
474
  }
393
475
 
394
- async killProcess(id: string, _signal?: string): Promise<void> {
395
- try {
396
- // Note: signal parameter is not currently supported by the HttpClient implementation
397
- await this.client.killProcess(id);
398
- } catch (error) {
399
- if (error instanceof Error && error.message.includes('Process not found')) {
400
- throw new ProcessNotFoundError(id);
401
- }
402
- throw new SandboxError(
403
- `Failed to kill process ${id}: ${error instanceof Error ? error.message : 'Unknown error'}`,
404
- 'KILL_PROCESS_FAILED'
405
- );
406
- }
476
+ async killProcess(id: string, signal?: string, sessionId?: string): Promise<void> {
477
+ // Note: signal parameter is not currently supported by the HttpClient implementation
478
+ // The HTTP client already throws properly typed errors, so we just let them propagate
479
+ await this.client.processes.killProcess(id);
407
480
  }
408
481
 
409
- async killAllProcesses(): Promise<number> {
410
- const response = await this.client.killAllProcesses();
411
- return response.killedCount;
482
+ async killAllProcesses(sessionId?: string): Promise<number> {
483
+ const response = await this.client.processes.killAllProcesses();
484
+ return response.cleanedCount;
412
485
  }
413
486
 
414
- async cleanupCompletedProcesses(): Promise<number> {
487
+ async cleanupCompletedProcesses(sessionId?: string): Promise<number> {
415
488
  // For now, this would need to be implemented as a container endpoint
416
489
  // as we no longer maintain local process storage
417
490
  // We'll return 0 as a placeholder until the container endpoint is added
418
491
  return 0;
419
492
  }
420
493
 
421
- async getProcessLogs(id: string): Promise<{ stdout: string; stderr: string }> {
422
- try {
423
- const response = await this.client.getProcessLogs(id);
424
- return {
425
- stdout: response.stdout,
426
- stderr: response.stderr
427
- };
428
- } catch (error) {
429
- if (error instanceof Error && error.message.includes('Process not found')) {
430
- throw new ProcessNotFoundError(id);
431
- }
432
- throw error;
433
- }
494
+ async getProcessLogs(id: string, sessionId?: string): Promise<{ stdout: string; stderr: string; processId: string }> {
495
+ // The HTTP client already throws properly typed errors, so we just let them propagate
496
+ const response = await this.client.processes.getProcessLogs(id);
497
+ return {
498
+ stdout: response.stdout,
499
+ stderr: response.stderr,
500
+ processId: response.processId
501
+ };
434
502
  }
435
503
 
436
504
 
@@ -441,11 +509,21 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
441
509
  throw new Error('Operation was aborted');
442
510
  }
443
511
 
444
- // Get the stream from HttpClient (need to add this method)
445
- const stream = await this.client.executeCommandStream(command, options?.sessionId);
512
+ const session = await this.ensureDefaultSession();
513
+ // Get the stream from CommandClient
514
+ return this.client.commands.executeStream(command, session);
515
+ }
446
516
 
447
- // Return the ReadableStream directly - can be converted to AsyncIterable by consumers
448
- return stream;
517
+ /**
518
+ * Internal session-aware execStream implementation
519
+ */
520
+ private async execStreamWithSession(command: string, sessionId: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>> {
521
+ // Check for cancellation
522
+ if (options?.signal?.aborted) {
523
+ throw new Error('Operation was aborted');
524
+ }
525
+
526
+ return this.client.commands.executeStream(command, sessionId);
449
527
  }
450
528
 
451
529
  async streamProcessLogs(processId: string, options?: { signal?: AbortSignal }): Promise<ReadableStream<Uint8Array>> {
@@ -454,69 +532,117 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
454
532
  throw new Error('Operation was aborted');
455
533
  }
456
534
 
457
- // Get the stream from HttpClient
458
- const stream = await this.client.streamProcessLogs(processId);
459
-
460
- // Return the ReadableStream directly - can be converted to AsyncIterable by consumers
461
- return stream;
535
+ return this.client.processes.streamProcessLogs(processId);
462
536
  }
463
537
 
464
538
  async gitCheckout(
465
539
  repoUrl: string,
466
- options: { branch?: string; targetDir?: string }
540
+ options: { branch?: string; targetDir?: string; sessionId?: string }
467
541
  ) {
468
- return this.client.gitCheckout(repoUrl, options.branch, options.targetDir);
542
+ const session = options.sessionId ?? await this.ensureDefaultSession();
543
+ return this.client.git.checkout(repoUrl, session, {
544
+ branch: options.branch,
545
+ targetDir: options.targetDir
546
+ });
469
547
  }
470
548
 
471
549
  async mkdir(
472
550
  path: string,
473
- options: { recursive?: boolean } = {}
551
+ options: { recursive?: boolean; sessionId?: string } = {}
474
552
  ) {
475
- return this.client.mkdir(path, options.recursive);
553
+ const session = options.sessionId ?? await this.ensureDefaultSession();
554
+ return this.client.files.mkdir(path, session, { recursive: options.recursive });
476
555
  }
477
556
 
478
557
  async writeFile(
479
558
  path: string,
480
559
  content: string,
481
- options: { encoding?: string } = {}
560
+ options: { encoding?: string; sessionId?: string } = {}
482
561
  ) {
483
- return this.client.writeFile(path, content, options.encoding);
562
+ const session = options.sessionId ?? await this.ensureDefaultSession();
563
+ return this.client.files.writeFile(path, content, session, { encoding: options.encoding });
484
564
  }
485
565
 
486
- async deleteFile(path: string) {
487
- return this.client.deleteFile(path);
566
+ async deleteFile(path: string, sessionId?: string) {
567
+ const session = sessionId ?? await this.ensureDefaultSession();
568
+ return this.client.files.deleteFile(path, session);
488
569
  }
489
570
 
490
571
  async renameFile(
491
572
  oldPath: string,
492
- newPath: string
573
+ newPath: string,
574
+ sessionId?: string
493
575
  ) {
494
- return this.client.renameFile(oldPath, newPath);
576
+ const session = sessionId ?? await this.ensureDefaultSession();
577
+ return this.client.files.renameFile(oldPath, newPath, session);
495
578
  }
496
579
 
497
580
  async moveFile(
498
581
  sourcePath: string,
499
- destinationPath: string
582
+ destinationPath: string,
583
+ sessionId?: string
500
584
  ) {
501
- return this.client.moveFile(sourcePath, destinationPath);
585
+ const session = sessionId ?? await this.ensureDefaultSession();
586
+ return this.client.files.moveFile(sourcePath, destinationPath, session);
502
587
  }
503
588
 
504
589
  async readFile(
505
590
  path: string,
506
- options: { encoding?: string } = {}
591
+ options: { encoding?: string; sessionId?: string } = {}
507
592
  ) {
508
- return this.client.readFile(path, options.encoding);
593
+ const session = options.sessionId ?? await this.ensureDefaultSession();
594
+ return this.client.files.readFile(path, session, { encoding: options.encoding });
595
+ }
596
+
597
+ /**
598
+ * Stream a file from the sandbox using Server-Sent Events
599
+ * Returns a ReadableStream that can be consumed with streamFile() or collectFile() utilities
600
+ * @param path - Path to the file to stream
601
+ * @param options - Optional session ID
602
+ */
603
+ async readFileStream(
604
+ path: string,
605
+ options: { sessionId?: string } = {}
606
+ ): Promise<ReadableStream<Uint8Array>> {
607
+ const session = options.sessionId ?? await this.ensureDefaultSession();
608
+ return this.client.files.readFileStream(path, session);
609
+ }
610
+
611
+ async listFiles(
612
+ path: string,
613
+ options?: { recursive?: boolean; includeHidden?: boolean }
614
+ ) {
615
+ const session = await this.ensureDefaultSession();
616
+ return this.client.files.listFiles(path, session, options);
509
617
  }
510
618
 
511
619
  async exposePort(port: number, options: { name?: string; hostname: string }) {
512
- await this.client.exposePort(port, options?.name);
620
+ // Check if hostname is workers.dev domain (doesn't support wildcard subdomains)
621
+ if (options.hostname.endsWith('.workers.dev')) {
622
+ const errorResponse: ErrorResponse = {
623
+ code: ErrorCode.CUSTOM_DOMAIN_REQUIRED,
624
+ message: `Port exposure requires a custom domain. .workers.dev domains do not support wildcard subdomains required for port proxying.`,
625
+ context: { originalError: options.hostname },
626
+ httpStatus: 400,
627
+ timestamp: new Date().toISOString()
628
+ };
629
+ throw new CustomDomainRequiredError(errorResponse);
630
+ }
631
+
632
+ const sessionId = await this.ensureDefaultSession();
633
+ await this.client.ports.exposePort(port, sessionId, options?.name);
513
634
 
514
635
  // We need the sandbox name to construct preview URLs
515
636
  if (!this.sandboxName) {
516
637
  throw new Error('Sandbox name not available. Ensure sandbox is accessed through getSandbox()');
517
638
  }
518
639
 
519
- const url = this.constructPreviewUrl(port, this.sandboxName, options.hostname);
640
+ // Generate and store token for this port
641
+ const token = this.generatePortToken();
642
+ this.portTokens.set(port, token);
643
+ await this.persistPortTokens();
644
+
645
+ const url = this.constructPreviewUrl(port, this.sandboxName, options.hostname, token);
520
646
 
521
647
  return {
522
648
  url,
@@ -527,58 +653,101 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
527
653
 
528
654
  async unexposePort(port: number) {
529
655
  if (!validatePort(port)) {
530
- logSecurityEvent('INVALID_PORT_UNEXPOSE', {
531
- port
532
- }, 'high');
533
656
  throw new SecurityError(`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`);
534
657
  }
535
658
 
536
- await this.client.unexposePort(port);
659
+ const sessionId = await this.ensureDefaultSession();
660
+ await this.client.ports.unexposePort(port, sessionId);
537
661
 
538
- logSecurityEvent('PORT_UNEXPOSED', {
539
- port
540
- }, 'low');
662
+ // Clean up token for this port
663
+ if (this.portTokens.has(port)) {
664
+ this.portTokens.delete(port);
665
+ await this.persistPortTokens();
666
+ }
541
667
  }
542
668
 
543
669
  async getExposedPorts(hostname: string) {
544
- const response = await this.client.getExposedPorts();
670
+ const sessionId = await this.ensureDefaultSession();
671
+ const response = await this.client.ports.getExposedPorts(sessionId);
545
672
 
546
673
  // We need the sandbox name to construct preview URLs
547
674
  if (!this.sandboxName) {
548
675
  throw new Error('Sandbox name not available. Ensure sandbox is accessed through getSandbox()');
549
676
  }
550
677
 
551
- return response.ports.map(port => ({
552
- url: this.constructPreviewUrl(port.port, this.sandboxName!, hostname),
553
- port: port.port,
554
- name: port.name,
555
- exposedAt: port.exposedAt,
556
- }));
678
+ return response.ports.map(port => {
679
+ // Get token for this port - must exist for all exposed ports
680
+ const token = this.portTokens.get(port.port);
681
+ if (!token) {
682
+ throw new Error(`Port ${port.port} is exposed but has no token. This should not happen.`);
683
+ }
684
+
685
+ return {
686
+ url: this.constructPreviewUrl(port.port, this.sandboxName!, hostname, token),
687
+ port: port.port,
688
+ status: port.status,
689
+ };
690
+ });
691
+ }
692
+
693
+
694
+ async isPortExposed(port: number): Promise<boolean> {
695
+ try {
696
+ const sessionId = await this.ensureDefaultSession();
697
+ const response = await this.client.ports.getExposedPorts(sessionId);
698
+ return response.ports.some(exposedPort => exposedPort.port === port);
699
+ } catch (error) {
700
+ this.logger.error('Error checking if port is exposed', error instanceof Error ? error : new Error(String(error)), { port });
701
+ return false;
702
+ }
703
+ }
704
+
705
+ async validatePortToken(port: number, token: string): Promise<boolean> {
706
+ // First check if port is exposed
707
+ const isExposed = await this.isPortExposed(port);
708
+ if (!isExposed) {
709
+ return false;
710
+ }
711
+
712
+ // Get stored token for this port - must exist for all exposed ports
713
+ const storedToken = this.portTokens.get(port);
714
+ if (!storedToken) {
715
+ // This should not happen - all exposed ports must have tokens
716
+ this.logger.error('Port is exposed but has no token - bug detected', undefined, { port });
717
+ return false;
718
+ }
719
+
720
+ // Constant-time comparison to prevent timing attacks
721
+ return storedToken === token;
722
+ }
723
+
724
+ private generatePortToken(): string {
725
+ // Generate cryptographically secure 16-character token using Web Crypto API
726
+ // Available in Cloudflare Workers runtime
727
+ const array = new Uint8Array(12); // 12 bytes = 16 base64url chars (after padding removal)
728
+ crypto.getRandomValues(array);
729
+
730
+ // Convert to base64url format (URL-safe, no padding, lowercase)
731
+ const base64 = btoa(String.fromCharCode(...array));
732
+ return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '').toLowerCase();
557
733
  }
558
734
 
735
+ private async persistPortTokens(): Promise<void> {
736
+ // Convert Map to plain object for storage
737
+ const tokensObj: Record<string, string> = {};
738
+ for (const [port, token] of this.portTokens.entries()) {
739
+ tokensObj[port.toString()] = token;
740
+ }
741
+ await this.ctx.storage.put('portTokens', tokensObj);
742
+ }
559
743
 
560
- private constructPreviewUrl(port: number, sandboxId: string, hostname: string): string {
744
+ private constructPreviewUrl(port: number, sandboxId: string, hostname: string, token: string): string {
561
745
  if (!validatePort(port)) {
562
- logSecurityEvent('INVALID_PORT_REJECTED', {
563
- port,
564
- sandboxId,
565
- hostname
566
- }, 'high');
567
746
  throw new SecurityError(`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`);
568
747
  }
569
748
 
570
- let sanitizedSandboxId: string;
571
- try {
572
- sanitizedSandboxId = sanitizeSandboxId(sandboxId);
573
- } catch (error) {
574
- logSecurityEvent('INVALID_SANDBOX_ID_REJECTED', {
575
- sandboxId,
576
- port,
577
- hostname,
578
- error: error instanceof Error ? error.message : 'Unknown error'
579
- }, 'high');
580
- throw error;
581
- }
749
+ // Validate sandbox ID (will throw SecurityError if invalid)
750
+ const sanitizedSandboxId = sanitizeSandboxId(sandboxId);
582
751
 
583
752
  const isLocalhost = isLocalhostPattern(hostname);
584
753
 
@@ -590,28 +759,12 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
590
759
  // Use URL constructor for safe URL building
591
760
  try {
592
761
  const baseUrl = new URL(`http://${host}:${mainPort}`);
593
- // Construct subdomain safely
594
- const subdomainHost = `${port}-${sanitizedSandboxId}.${host}`;
762
+ // Construct subdomain safely with mandatory token
763
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${host}`;
595
764
  baseUrl.hostname = subdomainHost;
596
765
 
597
- const finalUrl = baseUrl.toString();
598
-
599
- logSecurityEvent('PREVIEW_URL_CONSTRUCTED', {
600
- port,
601
- sandboxId: sanitizedSandboxId,
602
- hostname,
603
- resultUrl: finalUrl,
604
- environment: 'localhost'
605
- }, 'low');
606
-
607
- return finalUrl;
766
+ return baseUrl.toString();
608
767
  } catch (error) {
609
- logSecurityEvent('URL_CONSTRUCTION_FAILED', {
610
- port,
611
- sandboxId: sanitizedSandboxId,
612
- hostname,
613
- error: error instanceof Error ? error.message : 'Unknown error'
614
- }, 'high');
615
768
  throw new SecurityError(`Failed to construct preview URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
616
769
  }
617
770
  }
@@ -622,29 +775,142 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
622
775
  const protocol = "https";
623
776
  const baseUrl = new URL(`${protocol}://${hostname}`);
624
777
 
625
- // Construct subdomain safely
626
- const subdomainHost = `${port}-${sanitizedSandboxId}.${hostname}`;
778
+ // Construct subdomain safely with mandatory token
779
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${hostname}`;
627
780
  baseUrl.hostname = subdomainHost;
628
781
 
629
- const finalUrl = baseUrl.toString();
630
-
631
- logSecurityEvent('PREVIEW_URL_CONSTRUCTED', {
632
- port,
633
- sandboxId: sanitizedSandboxId,
634
- hostname,
635
- resultUrl: finalUrl,
636
- environment: 'production'
637
- }, 'low');
638
-
639
- return finalUrl;
782
+ return baseUrl.toString();
640
783
  } catch (error) {
641
- logSecurityEvent('URL_CONSTRUCTION_FAILED', {
642
- port,
643
- sandboxId: sanitizedSandboxId,
644
- hostname,
645
- error: error instanceof Error ? error.message : 'Unknown error'
646
- }, 'high');
647
784
  throw new SecurityError(`Failed to construct preview URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
648
785
  }
649
786
  }
787
+
788
+ // ============================================================================
789
+ // Session Management - Advanced Use Cases
790
+ // ============================================================================
791
+
792
+ /**
793
+ * Create isolated execution session for advanced use cases
794
+ * Returns ExecutionSession with full sandbox API bound to specific session
795
+ */
796
+ async createSession(options?: SessionOptions): Promise<ExecutionSession> {
797
+ const sessionId = options?.id || `session-${Date.now()}`;
798
+
799
+ // Create session in container
800
+ await this.client.utils.createSession({
801
+ id: sessionId,
802
+ env: options?.env,
803
+ cwd: options?.cwd,
804
+ });
805
+
806
+ // Return wrapper that binds sessionId to all operations
807
+ return this.getSessionWrapper(sessionId);
808
+ }
809
+
810
+ /**
811
+ * Get an existing session by ID
812
+ * Returns ExecutionSession wrapper bound to the specified session
813
+ *
814
+ * This is useful for retrieving sessions across different requests/contexts
815
+ * without storing the ExecutionSession object (which has RPC lifecycle limitations)
816
+ *
817
+ * @param sessionId - The ID of an existing session
818
+ * @returns ExecutionSession wrapper bound to the session
819
+ */
820
+ async getSession(sessionId: string): Promise<ExecutionSession> {
821
+ // No need to verify session exists in container - operations will fail naturally if it doesn't
822
+ return this.getSessionWrapper(sessionId);
823
+ }
824
+
825
+ /**
826
+ * Internal helper to create ExecutionSession wrapper for a given sessionId
827
+ * Used by both createSession and getSession
828
+ */
829
+ private getSessionWrapper(sessionId: string): ExecutionSession {
830
+ return {
831
+ id: sessionId,
832
+
833
+ // Command execution - delegate to internal session-aware methods
834
+ exec: (command, options) => this.execWithSession(command, sessionId, options),
835
+ execStream: (command, options) => this.execStreamWithSession(command, sessionId, options),
836
+
837
+ // Process management
838
+ startProcess: (command, options) => this.startProcess(command, options, sessionId),
839
+ listProcesses: () => this.listProcesses(sessionId),
840
+ getProcess: (id) => this.getProcess(id, sessionId),
841
+ killProcess: (id, signal) => this.killProcess(id, signal),
842
+ killAllProcesses: () => this.killAllProcesses(),
843
+ cleanupCompletedProcesses: () => this.cleanupCompletedProcesses(),
844
+ getProcessLogs: (id) => this.getProcessLogs(id),
845
+ streamProcessLogs: (processId, options) => this.streamProcessLogs(processId, options),
846
+
847
+ // File operations - pass sessionId via options or parameter
848
+ writeFile: (path, content, options) => this.writeFile(path, content, { ...options, sessionId }),
849
+ readFile: (path, options) => this.readFile(path, { ...options, sessionId }),
850
+ readFileStream: (path) => this.readFileStream(path, { sessionId }),
851
+ mkdir: (path, options) => this.mkdir(path, { ...options, sessionId }),
852
+ deleteFile: (path) => this.deleteFile(path, sessionId),
853
+ renameFile: (oldPath, newPath) => this.renameFile(oldPath, newPath, sessionId),
854
+ moveFile: (sourcePath, destPath) => this.moveFile(sourcePath, destPath, sessionId),
855
+ listFiles: (path, options) => this.client.files.listFiles(path, sessionId, options),
856
+
857
+ // Git operations
858
+ gitCheckout: (repoUrl, options) => this.gitCheckout(repoUrl, { ...options, sessionId }),
859
+
860
+ // Environment management - needs special handling
861
+ setEnvVars: async (envVars: Record<string, string>) => {
862
+ try {
863
+ // Set environment variables by executing export commands
864
+ for (const [key, value] of Object.entries(envVars)) {
865
+ const escapedValue = value.replace(/'/g, "'\\''");
866
+ const exportCommand = `export ${key}='${escapedValue}'`;
867
+
868
+ const result = await this.client.commands.execute(exportCommand, sessionId);
869
+
870
+ if (result.exitCode !== 0) {
871
+ throw new Error(`Failed to set ${key}: ${result.stderr || 'Unknown error'}`);
872
+ }
873
+ }
874
+ } catch (error) {
875
+ this.logger.error('Failed to set environment variables', error instanceof Error ? error : new Error(String(error)), { sessionId });
876
+ throw error;
877
+ }
878
+ },
879
+
880
+ // Code interpreter methods - delegate to sandbox's code interpreter
881
+ createCodeContext: (options) => this.codeInterpreter.createCodeContext(options),
882
+ runCode: async (code, options) => {
883
+ const execution = await this.codeInterpreter.runCode(code, options);
884
+ return execution.toJSON();
885
+ },
886
+ runCodeStream: (code, options) => this.codeInterpreter.runCodeStream(code, options),
887
+ listCodeContexts: () => this.codeInterpreter.listCodeContexts(),
888
+ deleteCodeContext: (contextId) => this.codeInterpreter.deleteCodeContext(contextId),
889
+ };
890
+ }
891
+
892
+ // ============================================================================
893
+ // Code interpreter methods - delegate to CodeInterpreter wrapper
894
+ // ============================================================================
895
+
896
+ async createCodeContext(options?: CreateContextOptions): Promise<CodeContext> {
897
+ return this.codeInterpreter.createCodeContext(options);
898
+ }
899
+
900
+ async runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult> {
901
+ const execution = await this.codeInterpreter.runCode(code, options);
902
+ return execution.toJSON();
903
+ }
904
+
905
+ async runCodeStream(code: string, options?: RunCodeOptions): Promise<ReadableStream> {
906
+ return this.codeInterpreter.runCodeStream(code, options);
907
+ }
908
+
909
+ async listCodeContexts(): Promise<CodeContext[]> {
910
+ return this.codeInterpreter.listCodeContexts();
911
+ }
912
+
913
+ async deleteCodeContext(contextId: string): Promise<void> {
914
+ return this.codeInterpreter.deleteCodeContext(contextId);
915
+ }
650
916
  }