@cloudflare/sandbox 0.0.0-d86b60e → 0.0.0-da2cfb8

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