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

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