@cloudflare/sandbox 0.0.0-9fa3058 → 0.0.0-aa00a75

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