@cloudflare/sandbox 0.0.0-44e584c → 0.0.0-4bedc3a

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 (40) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/Dockerfile +99 -11
  3. package/README.md +805 -24
  4. package/container_src/bun.lock +122 -0
  5. package/container_src/circuit-breaker.ts +121 -0
  6. package/container_src/control-process.ts +784 -0
  7. package/container_src/handler/exec.ts +185 -0
  8. package/container_src/handler/file.ts +406 -0
  9. package/container_src/handler/git.ts +130 -0
  10. package/container_src/handler/ports.ts +314 -0
  11. package/container_src/handler/process.ts +568 -0
  12. package/container_src/handler/session.ts +92 -0
  13. package/container_src/index.ts +434 -2739
  14. package/container_src/isolation.ts +1039 -0
  15. package/container_src/jupyter-server.ts +579 -0
  16. package/container_src/jupyter-service.ts +461 -0
  17. package/container_src/jupyter_config.py +48 -0
  18. package/container_src/mime-processor.ts +255 -0
  19. package/container_src/package.json +9 -0
  20. package/container_src/shell-escape.ts +42 -0
  21. package/container_src/startup.sh +84 -0
  22. package/container_src/types.ts +131 -0
  23. package/package.json +5 -9
  24. package/src/client.ts +431 -1372
  25. package/src/errors.ts +218 -0
  26. package/src/index.ts +63 -128
  27. package/src/interpreter-types.ts +383 -0
  28. package/src/interpreter.ts +150 -0
  29. package/src/jupyter-client.ts +349 -0
  30. package/src/request-handler.ts +144 -0
  31. package/src/sandbox.ts +743 -0
  32. package/src/security.ts +113 -0
  33. package/src/sse-parser.ts +147 -0
  34. package/src/types.ts +502 -0
  35. package/tsconfig.json +1 -1
  36. package/tests/client.example.ts +0 -308
  37. package/tests/connection-test.ts +0 -81
  38. package/tests/simple-test.ts +0 -81
  39. package/tests/test1.ts +0 -281
  40. package/tests/test2.ts +0 -929
package/src/sandbox.ts ADDED
@@ -0,0 +1,743 @@
1
+ import { Container, getContainer } from "@cloudflare/containers";
2
+ import { CodeInterpreter } from "./interpreter";
3
+ import type {
4
+ CodeContext,
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
+ ExecEvent,
20
+ ExecOptions,
21
+ ExecResult,
22
+ ExecuteResponse,
23
+ ExecutionSession,
24
+ ISandbox,
25
+ Process,
26
+ ProcessOptions,
27
+ ProcessStatus,
28
+ StreamOptions,
29
+ } from "./types";
30
+ import { ProcessNotFoundError, SandboxError } from "./types";
31
+
32
+ export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string) {
33
+ const stub = getContainer(ns, id);
34
+
35
+ // Store the name on first access
36
+ stub.setSandboxName?.(id);
37
+
38
+ return stub;
39
+ }
40
+
41
+ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
42
+ 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;
48
+
49
+ constructor(ctx: DurableObjectState, env: Env) {
50
+ 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
+ },
66
+ port: 3000, // Control plane port
67
+ stub: this,
68
+ });
69
+
70
+ // Initialize code interpreter
71
+ this.codeInterpreter = new CodeInterpreter(this);
72
+
73
+ // Load the sandbox name from storage on initialization
74
+ this.ctx.blockConcurrencyWhile(async () => {
75
+ this.sandboxName =
76
+ (await this.ctx.storage.get<string>("sandboxName")) || null;
77
+ });
78
+ }
79
+
80
+ // RPC method to set the sandbox name
81
+ async setSandboxName(name: string): Promise<void> {
82
+ if (!this.sandboxName) {
83
+ this.sandboxName = name;
84
+ await this.ctx.storage.put("sandboxName", name);
85
+ console.log(`[Sandbox] Stored sandbox name via RPC: ${name}`);
86
+ }
87
+ }
88
+
89
+ // RPC method to set environment variables
90
+ async setEnvVars(envVars: Record<string, string>): Promise<void> {
91
+ this.envVars = { ...this.envVars, ...envVars };
92
+ console.log(`[Sandbox] Updated environment variables`);
93
+
94
+ // If we have a default session, update its environment too
95
+ if (this.defaultSession) {
96
+ await this.defaultSession.setEnvVars(envVars);
97
+ }
98
+ }
99
+
100
+ override onStart() {
101
+ console.log("Sandbox successfully started");
102
+ }
103
+
104
+ override onStop() {
105
+ console.log("Sandbox successfully shut down");
106
+ }
107
+
108
+ override onError(error: unknown) {
109
+ console.log("Sandbox error:", error);
110
+ }
111
+
112
+ // Override fetch to route internal container requests to appropriate ports
113
+ override async fetch(request: Request): Promise<Response> {
114
+ const url = new URL(request.url);
115
+
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
+ }
123
+
124
+ // Determine which port to route to
125
+ const port = this.determinePort(url);
126
+
127
+ // Route to the appropriate port
128
+ return await this.containerFetch(request, port);
129
+ }
130
+
131
+ private determinePort(url: URL): number {
132
+ // Extract port from proxy requests (e.g., /proxy/8080/*)
133
+ const proxyMatch = url.pathname.match(/^\/proxy\/(\d+)/);
134
+ if (proxyMatch) {
135
+ return parseInt(proxyMatch[1]);
136
+ }
137
+
138
+ // All other requests go to control plane on port 3000
139
+ // This includes /api/* endpoints and any other control requests
140
+ return 3000;
141
+ }
142
+
143
+ // Helper to ensure default session is initialized
144
+ private async ensureDefaultSession(): Promise<ExecutionSession> {
145
+ if (!this.defaultSession) {
146
+ const sessionId = `sandbox-${this.sandboxName || 'default'}`;
147
+ this.defaultSession = await this.createSession({
148
+ id: sessionId,
149
+ env: this.envVars || {},
150
+ cwd: '/workspace',
151
+ isolation: true
152
+ });
153
+ console.log(`[Sandbox] Default session initialized: ${sessionId}`);
154
+ }
155
+ return this.defaultSession;
156
+ }
157
+
158
+
159
+ async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
160
+ const session = await this.ensureDefaultSession();
161
+ return session.exec(command, options);
162
+ }
163
+
164
+ async startProcess(
165
+ command: string,
166
+ options?: ProcessOptions
167
+ ): Promise<Process> {
168
+ const session = await this.ensureDefaultSession();
169
+ return session.startProcess(command, options);
170
+ }
171
+
172
+ async listProcesses(): Promise<Process[]> {
173
+ const session = await this.ensureDefaultSession();
174
+ return session.listProcesses();
175
+ }
176
+
177
+ async getProcess(id: string): Promise<Process | null> {
178
+ const session = await this.ensureDefaultSession();
179
+ return session.getProcess(id);
180
+ }
181
+
182
+ async killProcess(id: string, signal?: string): Promise<void> {
183
+ const session = await this.ensureDefaultSession();
184
+ return session.killProcess(id, signal);
185
+ }
186
+
187
+ async killAllProcesses(): Promise<number> {
188
+ const session = await this.ensureDefaultSession();
189
+ return session.killAllProcesses();
190
+ }
191
+
192
+ async cleanupCompletedProcesses(): Promise<number> {
193
+ const session = await this.ensureDefaultSession();
194
+ return session.cleanupCompletedProcesses();
195
+ }
196
+
197
+ async getProcessLogs(
198
+ id: string
199
+ ): Promise<{ stdout: string; stderr: string }> {
200
+ const session = await this.ensureDefaultSession();
201
+ return session.getProcessLogs(id);
202
+ }
203
+
204
+ // Streaming methods - delegates to default session
205
+ async execStream(
206
+ command: string,
207
+ options?: StreamOptions
208
+ ): Promise<ReadableStream<Uint8Array>> {
209
+ const session = await this.ensureDefaultSession();
210
+ return session.execStream(command, options);
211
+ }
212
+
213
+ async streamProcessLogs(
214
+ processId: string,
215
+ options?: { signal?: AbortSignal }
216
+ ): Promise<ReadableStream<Uint8Array>> {
217
+ const session = await this.ensureDefaultSession();
218
+ return session.streamProcessLogs(processId, options);
219
+ }
220
+
221
+ async gitCheckout(
222
+ repoUrl: string,
223
+ options: { branch?: string; targetDir?: string }
224
+ ) {
225
+ const session = await this.ensureDefaultSession();
226
+ return session.gitCheckout(repoUrl, options);
227
+ }
228
+
229
+ async mkdir(path: string, options: { recursive?: boolean } = {}) {
230
+ const session = await this.ensureDefaultSession();
231
+ return session.mkdir(path, options);
232
+ }
233
+
234
+ async writeFile(
235
+ path: string,
236
+ content: string,
237
+ options: { encoding?: string } = {}
238
+ ) {
239
+ const session = await this.ensureDefaultSession();
240
+ return session.writeFile(path, content, options);
241
+ }
242
+
243
+ async deleteFile(path: string) {
244
+ const session = await this.ensureDefaultSession();
245
+ return session.deleteFile(path);
246
+ }
247
+
248
+ async renameFile(oldPath: string, newPath: string) {
249
+ const session = await this.ensureDefaultSession();
250
+ return session.renameFile(oldPath, newPath);
251
+ }
252
+
253
+ async moveFile(sourcePath: string, destinationPath: string) {
254
+ const session = await this.ensureDefaultSession();
255
+ return session.moveFile(sourcePath, destinationPath);
256
+ }
257
+
258
+ async readFile(path: string, options: { encoding?: string } = {}) {
259
+ const session = await this.ensureDefaultSession();
260
+ return session.readFile(path, options);
261
+ }
262
+
263
+ async listFiles(
264
+ path: string,
265
+ options: {
266
+ recursive?: boolean;
267
+ includeHidden?: boolean;
268
+ } = {}
269
+ ) {
270
+ const session = await this.ensureDefaultSession();
271
+ return session.listFiles(path, options);
272
+ }
273
+
274
+ async exposePort(port: number, options: { name?: string; hostname: string }) {
275
+ await this.client.exposePort(port, options?.name);
276
+
277
+ // We need the sandbox name to construct preview URLs
278
+ if (!this.sandboxName) {
279
+ throw new Error(
280
+ "Sandbox name not available. Ensure sandbox is accessed through getSandbox()"
281
+ );
282
+ }
283
+
284
+ const url = this.constructPreviewUrl(
285
+ port,
286
+ this.sandboxName,
287
+ options.hostname
288
+ );
289
+
290
+ return {
291
+ url,
292
+ port,
293
+ name: options?.name,
294
+ };
295
+ }
296
+
297
+ async unexposePort(port: number) {
298
+ if (!validatePort(port)) {
299
+ logSecurityEvent(
300
+ "INVALID_PORT_UNEXPOSE",
301
+ {
302
+ port,
303
+ },
304
+ "high"
305
+ );
306
+ throw new SecurityError(
307
+ `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
308
+ );
309
+ }
310
+
311
+ await this.client.unexposePort(port);
312
+
313
+ logSecurityEvent(
314
+ "PORT_UNEXPOSED",
315
+ {
316
+ port,
317
+ },
318
+ "low"
319
+ );
320
+ }
321
+
322
+ async getExposedPorts(hostname: string) {
323
+ const response = await this.client.getExposedPorts();
324
+
325
+ // We need the sandbox name to construct preview URLs
326
+ if (!this.sandboxName) {
327
+ throw new Error(
328
+ "Sandbox name not available. Ensure sandbox is accessed through getSandbox()"
329
+ );
330
+ }
331
+
332
+ return response.ports.map((port) => ({
333
+ url: this.constructPreviewUrl(port.port, this.sandboxName!, hostname),
334
+ port: port.port,
335
+ name: port.name,
336
+ exposedAt: port.exposedAt,
337
+ }));
338
+ }
339
+
340
+ private constructPreviewUrl(
341
+ port: number,
342
+ sandboxId: string,
343
+ hostname: string
344
+ ): string {
345
+ if (!validatePort(port)) {
346
+ logSecurityEvent(
347
+ "INVALID_PORT_REJECTED",
348
+ {
349
+ port,
350
+ sandboxId,
351
+ hostname,
352
+ },
353
+ "high"
354
+ );
355
+ throw new SecurityError(
356
+ `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
357
+ );
358
+ }
359
+
360
+ let sanitizedSandboxId: string;
361
+ try {
362
+ sanitizedSandboxId = sanitizeSandboxId(sandboxId);
363
+ } catch (error) {
364
+ logSecurityEvent(
365
+ "INVALID_SANDBOX_ID_REJECTED",
366
+ {
367
+ sandboxId,
368
+ port,
369
+ hostname,
370
+ error: error instanceof Error ? error.message : "Unknown error",
371
+ },
372
+ "high"
373
+ );
374
+ throw error;
375
+ }
376
+
377
+ const isLocalhost = isLocalhostPattern(hostname);
378
+
379
+ if (isLocalhost) {
380
+ // Unified subdomain approach for localhost (RFC 6761)
381
+ const [host, portStr] = hostname.split(":");
382
+ const mainPort = portStr || "80";
383
+
384
+ // Use URL constructor for safe URL building
385
+ try {
386
+ const baseUrl = new URL(`http://${host}:${mainPort}`);
387
+ // Construct subdomain safely
388
+ const subdomainHost = `${port}-${sanitizedSandboxId}.${host}`;
389
+ baseUrl.hostname = subdomainHost;
390
+
391
+ const finalUrl = baseUrl.toString();
392
+
393
+ logSecurityEvent(
394
+ "PREVIEW_URL_CONSTRUCTED",
395
+ {
396
+ port,
397
+ sandboxId: sanitizedSandboxId,
398
+ hostname,
399
+ resultUrl: finalUrl,
400
+ environment: "localhost",
401
+ },
402
+ "low"
403
+ );
404
+
405
+ return finalUrl;
406
+ } catch (error) {
407
+ logSecurityEvent(
408
+ "URL_CONSTRUCTION_FAILED",
409
+ {
410
+ port,
411
+ sandboxId: sanitizedSandboxId,
412
+ hostname,
413
+ error: error instanceof Error ? error.message : "Unknown error",
414
+ },
415
+ "high"
416
+ );
417
+ throw new SecurityError(
418
+ `Failed to construct preview URL: ${
419
+ error instanceof Error ? error.message : "Unknown error"
420
+ }`
421
+ );
422
+ }
423
+ }
424
+
425
+ // Production subdomain logic - enforce HTTPS
426
+ try {
427
+ // Always use HTTPS for production (non-localhost)
428
+ const protocol = "https";
429
+ const baseUrl = new URL(`${protocol}://${hostname}`);
430
+
431
+ // Construct subdomain safely
432
+ const subdomainHost = `${port}-${sanitizedSandboxId}.${hostname}`;
433
+ baseUrl.hostname = subdomainHost;
434
+
435
+ const finalUrl = baseUrl.toString();
436
+
437
+ logSecurityEvent(
438
+ "PREVIEW_URL_CONSTRUCTED",
439
+ {
440
+ port,
441
+ sandboxId: sanitizedSandboxId,
442
+ hostname,
443
+ resultUrl: finalUrl,
444
+ environment: "production",
445
+ },
446
+ "low"
447
+ );
448
+
449
+ return finalUrl;
450
+ } catch (error) {
451
+ logSecurityEvent(
452
+ "URL_CONSTRUCTION_FAILED",
453
+ {
454
+ port,
455
+ sandboxId: sanitizedSandboxId,
456
+ hostname,
457
+ error: error instanceof Error ? error.message : "Unknown error",
458
+ },
459
+ "high"
460
+ );
461
+ throw new SecurityError(
462
+ `Failed to construct preview URL: ${
463
+ error instanceof Error ? error.message : "Unknown error"
464
+ }`
465
+ );
466
+ }
467
+ }
468
+
469
+ // Code Interpreter Methods
470
+
471
+ /**
472
+ * Create a new code execution context
473
+ */
474
+ async createCodeContext(
475
+ options?: CreateContextOptions
476
+ ): Promise<CodeContext> {
477
+ return this.codeInterpreter.createCodeContext(options);
478
+ }
479
+
480
+ /**
481
+ * Run code with streaming callbacks
482
+ */
483
+ async runCode(
484
+ code: string,
485
+ options?: RunCodeOptions
486
+ ): Promise<ExecutionResult> {
487
+ const execution = await this.codeInterpreter.runCode(code, options);
488
+ // Convert to plain object for RPC serialization
489
+ return execution.toJSON();
490
+ }
491
+
492
+ /**
493
+ * Run code and return a streaming response
494
+ */
495
+ async runCodeStream(
496
+ code: string,
497
+ options?: RunCodeOptions
498
+ ): Promise<ReadableStream> {
499
+ return this.codeInterpreter.runCodeStream(code, options);
500
+ }
501
+
502
+ /**
503
+ * List all code contexts
504
+ */
505
+ async listCodeContexts(): Promise<CodeContext[]> {
506
+ return this.codeInterpreter.listCodeContexts();
507
+ }
508
+
509
+ /**
510
+ * Delete a code context
511
+ */
512
+ async deleteCodeContext(contextId: string): Promise<void> {
513
+ return this.codeInterpreter.deleteCodeContext(contextId);
514
+ }
515
+
516
+ // ============================================================================
517
+ // Session Management (Simple Isolation)
518
+ // ============================================================================
519
+
520
+ /**
521
+ * Create a new execution session with isolation
522
+ * Returns a session object with exec() method
523
+ */
524
+
525
+ async createSession(options: {
526
+ id?: string;
527
+ env?: Record<string, string>;
528
+ cwd?: string;
529
+ isolation?: boolean;
530
+ }): Promise<ExecutionSession> {
531
+ const sessionId = options.id || `session-${Date.now()}`;
532
+
533
+ await this.client.createSession({
534
+ id: sessionId,
535
+ env: options.env,
536
+ cwd: options.cwd,
537
+ isolation: options.isolation
538
+ });
539
+ // Return comprehensive ExecutionSession object that implements all ISandbox methods
540
+ return {
541
+ id: sessionId,
542
+
543
+ // Command execution - clean method names
544
+ exec: async (command: string, options?: ExecOptions) => {
545
+ const result = await this.client.exec(sessionId, command);
546
+ return {
547
+ ...result,
548
+ command,
549
+ duration: 0,
550
+ timestamp: new Date().toISOString()
551
+ };
552
+ },
553
+
554
+ execStream: async (command: string, options?: StreamOptions) => {
555
+ return await this.client.execStream(sessionId, command);
556
+ },
557
+
558
+ // Process management - route to session-aware methods
559
+ startProcess: async (command: string, options?: ProcessOptions) => {
560
+ // Use session-specific process management
561
+ const response = await this.client.startProcess(command, sessionId, {
562
+ processId: options?.processId,
563
+ timeout: options?.timeout,
564
+ env: options?.env,
565
+ cwd: options?.cwd,
566
+ encoding: options?.encoding,
567
+ autoCleanup: options?.autoCleanup,
568
+ });
569
+
570
+ // Convert response to Process object with bound methods
571
+ const process = response.process;
572
+ return {
573
+ id: process.id,
574
+ pid: process.pid,
575
+ command: process.command,
576
+ status: process.status as ProcessStatus,
577
+ startTime: new Date(process.startTime),
578
+ endTime: process.endTime ? new Date(process.endTime) : undefined,
579
+ exitCode: process.exitCode ?? undefined,
580
+ kill: async (signal?: string) => {
581
+ await this.client.killProcess(process.id);
582
+ },
583
+ getStatus: async () => {
584
+ const resp = await this.client.getProcess(process.id);
585
+ return resp.process?.status as ProcessStatus || "error";
586
+ },
587
+ getLogs: async () => {
588
+ return await this.client.getProcessLogs(process.id);
589
+ },
590
+ };
591
+ },
592
+
593
+ listProcesses: async () => {
594
+ // Get processes for this specific session
595
+ const response = await this.client.listProcesses(sessionId);
596
+
597
+ // Convert to Process objects with bound methods
598
+ return response.processes.map(p => ({
599
+ id: p.id,
600
+ pid: p.pid,
601
+ command: p.command,
602
+ status: p.status as ProcessStatus,
603
+ startTime: new Date(p.startTime),
604
+ endTime: p.endTime ? new Date(p.endTime) : undefined,
605
+ exitCode: p.exitCode ?? undefined,
606
+ kill: async (signal?: string) => {
607
+ await this.client.killProcess(p.id);
608
+ },
609
+ getStatus: async () => {
610
+ const processResp = await this.client.getProcess(p.id);
611
+ return processResp.process?.status as ProcessStatus || "error";
612
+ },
613
+ getLogs: async () => {
614
+ return this.client.getProcessLogs(p.id);
615
+ },
616
+ }));
617
+ },
618
+
619
+ getProcess: async (id: string) => {
620
+ const response = await this.client.getProcess(id);
621
+ if (!response.process) return null;
622
+
623
+ const p = response.process;
624
+ return {
625
+ id: p.id,
626
+ pid: p.pid,
627
+ command: p.command,
628
+ status: p.status as ProcessStatus,
629
+ startTime: new Date(p.startTime),
630
+ endTime: p.endTime ? new Date(p.endTime) : undefined,
631
+ exitCode: p.exitCode ?? undefined,
632
+ kill: async (signal?: string) => {
633
+ await this.client.killProcess(p.id);
634
+ },
635
+ getStatus: async () => {
636
+ const processResp = await this.client.getProcess(p.id);
637
+ return processResp.process?.status as ProcessStatus || "error";
638
+ },
639
+ getLogs: async () => {
640
+ return this.client.getProcessLogs(p.id);
641
+ },
642
+ };
643
+ },
644
+
645
+ killProcess: async (id: string, signal?: string) => {
646
+ await this.client.killProcess(id);
647
+ },
648
+
649
+ killAllProcesses: async () => {
650
+ // Kill all processes for this specific session
651
+ const response = await this.client.killAllProcesses(sessionId);
652
+ return response.killedCount;
653
+ },
654
+
655
+ streamProcessLogs: async (processId: string, options?: { signal?: AbortSignal }) => {
656
+ return await this.client.streamProcessLogs(processId, options);
657
+ },
658
+
659
+ getProcessLogs: async (id: string) => {
660
+ return await this.client.getProcessLogs(id);
661
+ },
662
+
663
+ cleanupCompletedProcesses: async () => {
664
+ // This would need a new endpoint to cleanup processes for a specific session
665
+ // For now, return 0 as no cleanup is performed
666
+ return 0;
667
+ },
668
+
669
+ // File operations - clean method names (no "InSession" suffix)
670
+ writeFile: async (path: string, content: string, options?: { encoding?: string }) => {
671
+ return await this.client.writeFile(path, content, options?.encoding, sessionId);
672
+ },
673
+
674
+ readFile: async (path: string, options?: { encoding?: string }) => {
675
+ return await this.client.readFile(path, options?.encoding, sessionId);
676
+ },
677
+
678
+ mkdir: async (path: string, options?: { recursive?: boolean }) => {
679
+ return await this.client.mkdir(path, options?.recursive, sessionId);
680
+ },
681
+
682
+ deleteFile: async (path: string) => {
683
+ return await this.client.deleteFile(path, sessionId);
684
+ },
685
+
686
+ renameFile: async (oldPath: string, newPath: string) => {
687
+ return await this.client.renameFile(oldPath, newPath, sessionId);
688
+ },
689
+
690
+ moveFile: async (sourcePath: string, destinationPath: string) => {
691
+ return await this.client.moveFile(sourcePath, destinationPath, sessionId);
692
+ },
693
+
694
+ listFiles: async (path: string, options?: { recursive?: boolean; includeHidden?: boolean }) => {
695
+ return await this.client.listFiles(path, sessionId, options);
696
+ },
697
+
698
+ gitCheckout: async (repoUrl: string, options?: { branch?: string; targetDir?: string }) => {
699
+ return await this.client.gitCheckout(repoUrl, sessionId, options?.branch, options?.targetDir);
700
+ },
701
+
702
+ // Port management
703
+ exposePort: async (port: number, options: { name?: string; hostname: string }) => {
704
+ return await this.exposePort(port, options);
705
+ },
706
+
707
+ unexposePort: async (port: number) => {
708
+ return await this.unexposePort(port);
709
+ },
710
+
711
+ getExposedPorts: async (hostname: string) => {
712
+ return await this.getExposedPorts(hostname);
713
+ },
714
+
715
+ // Environment management
716
+ setEnvVars: async (envVars: Record<string, string>) => {
717
+ // TODO: Implement session-specific environment updates
718
+ console.log(`[Session ${sessionId}] Environment variables update not yet implemented`);
719
+ },
720
+
721
+ // Code Interpreter API
722
+ createCodeContext: async (options?: any) => {
723
+ return await this.createCodeContext(options);
724
+ },
725
+
726
+ runCode: async (code: string, options?: any) => {
727
+ return await this.runCode(code, options);
728
+ },
729
+
730
+ runCodeStream: async (code: string, options?: any) => {
731
+ return await this.runCodeStream(code, options);
732
+ },
733
+
734
+ listCodeContexts: async () => {
735
+ return await this.listCodeContexts();
736
+ },
737
+
738
+ deleteCodeContext: async (contextId: string) => {
739
+ return await this.deleteCodeContext(contextId);
740
+ }
741
+ };
742
+ }
743
+ }