@cloudflare/sandbox 0.0.0-69b91d1 → 0.0.0-6b08f02

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