@cloudflare/sandbox 0.0.0-fb3c9c2 → 0.0.0-fddccfd

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