@cloudflare/sandbox 0.0.0-c87db11 → 0.0.0-cdb8197

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 (35) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/Dockerfile +32 -29
  3. package/README.md +127 -12
  4. package/container_src/bun.lock +31 -77
  5. package/container_src/control-process.ts +784 -0
  6. package/container_src/handler/exec.ts +99 -254
  7. package/container_src/handler/file.ts +253 -640
  8. package/container_src/handler/git.ts +28 -80
  9. package/container_src/handler/process.ts +443 -515
  10. package/container_src/handler/session.ts +92 -0
  11. package/container_src/index.ts +108 -163
  12. package/container_src/interpreter-service.ts +276 -0
  13. package/container_src/isolation.ts +1213 -0
  14. package/container_src/mime-processor.ts +1 -1
  15. package/container_src/package.json +4 -4
  16. package/container_src/runtime/executors/javascript/node_executor.ts +123 -0
  17. package/container_src/runtime/executors/python/ipython_executor.py +338 -0
  18. package/container_src/runtime/executors/typescript/ts_executor.ts +138 -0
  19. package/container_src/runtime/process-pool.ts +464 -0
  20. package/container_src/shell-escape.ts +42 -0
  21. package/container_src/startup.sh +6 -79
  22. package/container_src/types.ts +35 -12
  23. package/package.json +2 -2
  24. package/src/client.ts +214 -187
  25. package/src/errors.ts +15 -14
  26. package/src/file-stream.ts +162 -0
  27. package/src/index.ts +43 -16
  28. package/src/{jupyter-client.ts → interpreter-client.ts} +6 -3
  29. package/src/interpreter-types.ts +102 -95
  30. package/src/interpreter.ts +8 -8
  31. package/src/sandbox.ts +314 -336
  32. package/src/types.ts +194 -24
  33. package/container_src/jupyter-server.ts +0 -579
  34. package/container_src/jupyter-service.ts +0 -458
  35. package/container_src/jupyter_config.py +0 -48
package/src/sandbox.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { Container, getContainer } from "@cloudflare/containers";
2
2
  import { CodeInterpreter } from "./interpreter";
3
+ import { InterpreterClient } from "./interpreter-client";
3
4
  import type {
4
5
  CodeContext,
5
6
  CreateContextOptions,
6
7
  ExecutionResult,
7
8
  RunCodeOptions,
8
9
  } from "./interpreter-types";
9
- import { JupyterClient } from "./jupyter-client";
10
10
  import { isLocalhostPattern } from "./request-handler";
11
11
  import {
12
12
  logSecurityEvent,
@@ -16,8 +16,11 @@ import {
16
16
  } from "./security";
17
17
  import { parseSSEStream } from "./sse-parser";
18
18
  import type {
19
+ ExecEvent,
19
20
  ExecOptions,
20
21
  ExecResult,
22
+ ExecuteResponse,
23
+ ExecutionSession,
21
24
  ISandbox,
22
25
  Process,
23
26
  ProcessOptions,
@@ -38,13 +41,14 @@ export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string) {
38
41
  export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
39
42
  defaultPort = 3000; // Default port for the container's Bun server
40
43
  sleepAfter = "20m"; // Keep container warm for 20 minutes to avoid cold starts
41
- client: JupyterClient;
44
+ client: InterpreterClient;
42
45
  private sandboxName: string | null = null;
43
46
  private codeInterpreter: CodeInterpreter;
47
+ private defaultSession: ExecutionSession | null = null;
44
48
 
45
- constructor(ctx: DurableObjectState, env: Env) {
49
+ constructor(ctx: DurableObjectState<{}>, env: Env) {
46
50
  super(ctx, env);
47
- this.client = new JupyterClient({
51
+ this.client = new InterpreterClient({
48
52
  onCommandComplete: (success, exitCode, _stdout, _stderr, command) => {
49
53
  console.log(
50
54
  `[Container] Command completed: ${command}, Success: ${success}, Exit code: ${exitCode}`
@@ -86,6 +90,11 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
86
90
  async setEnvVars(envVars: Record<string, string>): Promise<void> {
87
91
  this.envVars = { ...this.envVars, ...envVars };
88
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
+ }
89
98
  }
90
99
 
91
100
  override onStart() {
@@ -94,9 +103,6 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
94
103
 
95
104
  override onStop() {
96
105
  console.log("Sandbox successfully shut down");
97
- if (this.client) {
98
- this.client.clearSession();
99
- }
100
106
  }
101
107
 
102
108
  override onError(error: unknown) {
@@ -129,385 +135,104 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
129
135
  return parseInt(proxyMatch[1]);
130
136
  }
131
137
 
138
+ if (url.port) {
139
+ return parseInt(url.port);
140
+ }
141
+
132
142
  // All other requests go to control plane on port 3000
133
143
  // This includes /api/* endpoints and any other control requests
134
144
  return 3000;
135
145
  }
136
146
 
137
- // Enhanced exec method - always returns ExecResult with optional streaming
138
- // This replaces the old exec method to match ISandbox interface
139
- async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
140
- const startTime = Date.now();
141
- const timestamp = new Date().toISOString();
142
-
143
- // Handle timeout
144
- let timeoutId: NodeJS.Timeout | undefined;
145
-
146
- try {
147
- // Handle cancellation
148
- if (options?.signal?.aborted) {
149
- throw new Error("Operation was aborted");
150
- }
151
-
152
- let result: ExecResult;
153
-
154
- if (options?.stream && options?.onOutput) {
155
- // Streaming with callbacks - we need to collect the final result
156
- result = await this.executeWithStreaming(
157
- command,
158
- options,
159
- startTime,
160
- timestamp
161
- );
162
- } else {
163
- // Regular execution
164
- const response = await this.client.execute(command, {
165
- sessionId: options?.sessionId,
166
- cwd: options?.cwd,
167
- env: options?.env,
168
- });
169
-
170
- const duration = Date.now() - startTime;
171
- result = this.mapExecuteResponseToExecResult(
172
- response,
173
- duration,
174
- options?.sessionId
175
- );
176
- }
177
-
178
- // Call completion callback if provided
179
- if (options?.onComplete) {
180
- options.onComplete(result);
181
- }
182
-
183
- return result;
184
- } catch (error) {
185
- if (options?.onError && error instanceof Error) {
186
- options.onError(error);
187
- }
188
- throw error;
189
- } finally {
190
- if (timeoutId) {
191
- clearTimeout(timeoutId);
192
- }
147
+ // Helper to ensure default session is initialized
148
+ private async ensureDefaultSession(): Promise<ExecutionSession> {
149
+ if (!this.defaultSession) {
150
+ 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}`);
193
158
  }
159
+ return this.defaultSession;
194
160
  }
195
161
 
196
- private async executeWithStreaming(
197
- command: string,
198
- options: ExecOptions,
199
- startTime: number,
200
- timestamp: string
201
- ): Promise<ExecResult> {
202
- let stdout = "";
203
- let stderr = "";
204
162
 
205
- try {
206
- const stream = await this.client.executeCommandStream(
207
- command,
208
- options.sessionId
209
- );
210
-
211
- for await (const event of parseSSEStream<import("./types").ExecEvent>(
212
- stream
213
- )) {
214
- // Check for cancellation
215
- if (options.signal?.aborted) {
216
- throw new Error("Operation was aborted");
217
- }
218
-
219
- switch (event.type) {
220
- case "stdout":
221
- case "stderr":
222
- if (event.data) {
223
- // Update accumulated output
224
- if (event.type === "stdout") stdout += event.data;
225
- if (event.type === "stderr") stderr += event.data;
226
-
227
- // Call user's callback
228
- if (options.onOutput) {
229
- options.onOutput(event.type, event.data);
230
- }
231
- }
232
- break;
233
-
234
- case "complete": {
235
- // Use result from complete event if available
236
- const duration = Date.now() - startTime;
237
- return (
238
- event.result || {
239
- success: event.exitCode === 0,
240
- exitCode: event.exitCode || 0,
241
- stdout,
242
- stderr,
243
- command,
244
- duration,
245
- timestamp,
246
- sessionId: options.sessionId,
247
- }
248
- );
249
- }
250
-
251
- case "error":
252
- throw new Error(event.error || "Command execution failed");
253
- }
254
- }
255
-
256
- // If we get here without a complete event, something went wrong
257
- throw new Error("Stream ended without completion event");
258
- } catch (error) {
259
- if (options.signal?.aborted) {
260
- throw new Error("Operation was aborted");
261
- }
262
- throw error;
263
- }
264
- }
265
-
266
- private mapExecuteResponseToExecResult(
267
- response: import("./client").ExecuteResponse,
268
- duration: number,
269
- sessionId?: string
270
- ): ExecResult {
271
- return {
272
- success: response.success,
273
- exitCode: response.exitCode,
274
- stdout: response.stdout,
275
- stderr: response.stderr,
276
- command: response.command,
277
- duration,
278
- timestamp: response.timestamp,
279
- sessionId,
280
- };
163
+ async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
164
+ const session = await this.ensureDefaultSession();
165
+ return session.exec(command, options);
281
166
  }
282
167
 
283
- // Background process management
284
168
  async startProcess(
285
169
  command: string,
286
170
  options?: ProcessOptions
287
171
  ): Promise<Process> {
288
- // Use the new HttpClient method to start the process
289
- try {
290
- const response = await this.client.startProcess(command, {
291
- processId: options?.processId,
292
- sessionId: options?.sessionId,
293
- timeout: options?.timeout,
294
- env: options?.env,
295
- cwd: options?.cwd,
296
- encoding: options?.encoding,
297
- autoCleanup: options?.autoCleanup,
298
- });
299
-
300
- const process = response.process;
301
- const processObj: Process = {
302
- id: process.id,
303
- pid: process.pid,
304
- command: process.command,
305
- status: process.status as ProcessStatus,
306
- startTime: new Date(process.startTime),
307
- endTime: undefined,
308
- exitCode: undefined,
309
- sessionId: process.sessionId,
310
-
311
- async kill(): Promise<void> {
312
- throw new Error("Method will be replaced");
313
- },
314
- async getStatus(): Promise<ProcessStatus> {
315
- throw new Error("Method will be replaced");
316
- },
317
- async getLogs(): Promise<{ stdout: string; stderr: string }> {
318
- throw new Error("Method will be replaced");
319
- },
320
- };
321
-
322
- // Bind context properly
323
- processObj.kill = async (signal?: string) => {
324
- await this.killProcess(process.id, signal);
325
- };
326
-
327
- processObj.getStatus = async () => {
328
- const current = await this.getProcess(process.id);
329
- return current?.status || "error";
330
- };
331
-
332
- processObj.getLogs = async () => {
333
- const logs = await this.getProcessLogs(process.id);
334
- return { stdout: logs.stdout, stderr: logs.stderr };
335
- };
336
-
337
- // Call onStart callback if provided
338
- if (options?.onStart) {
339
- options.onStart(processObj);
340
- }
341
-
342
- return processObj;
343
- } catch (error) {
344
- if (options?.onError && error instanceof Error) {
345
- options.onError(error);
346
- }
347
-
348
- throw error;
349
- }
172
+ const session = await this.ensureDefaultSession();
173
+ return session.startProcess(command, options);
350
174
  }
351
175
 
352
176
  async listProcesses(): Promise<Process[]> {
353
- const response = await this.client.listProcesses();
354
-
355
- return response.processes.map((processData) => ({
356
- id: processData.id,
357
- pid: processData.pid,
358
- command: processData.command,
359
- status: processData.status,
360
- startTime: new Date(processData.startTime),
361
- endTime: processData.endTime ? new Date(processData.endTime) : undefined,
362
- exitCode: processData.exitCode,
363
- sessionId: processData.sessionId,
364
-
365
- kill: async (signal?: string) => {
366
- await this.killProcess(processData.id, signal);
367
- },
368
-
369
- getStatus: async () => {
370
- const current = await this.getProcess(processData.id);
371
- return current?.status || "error";
372
- },
373
-
374
- getLogs: async () => {
375
- const logs = await this.getProcessLogs(processData.id);
376
- return { stdout: logs.stdout, stderr: logs.stderr };
377
- },
378
- }));
177
+ const session = await this.ensureDefaultSession();
178
+ return session.listProcesses();
379
179
  }
380
180
 
381
181
  async getProcess(id: string): Promise<Process | null> {
382
- const response = await this.client.getProcess(id);
383
- if (!response.process) {
384
- return null;
385
- }
386
-
387
- const processData = response.process;
388
- return {
389
- id: processData.id,
390
- pid: processData.pid,
391
- command: processData.command,
392
- status: processData.status,
393
- startTime: new Date(processData.startTime),
394
- endTime: processData.endTime ? new Date(processData.endTime) : undefined,
395
- exitCode: processData.exitCode,
396
- sessionId: processData.sessionId,
397
-
398
- kill: async (signal?: string) => {
399
- await this.killProcess(processData.id, signal);
400
- },
401
-
402
- getStatus: async () => {
403
- const current = await this.getProcess(processData.id);
404
- return current?.status || "error";
405
- },
406
-
407
- getLogs: async () => {
408
- const logs = await this.getProcessLogs(processData.id);
409
- return { stdout: logs.stdout, stderr: logs.stderr };
410
- },
411
- };
182
+ const session = await this.ensureDefaultSession();
183
+ return session.getProcess(id);
412
184
  }
413
185
 
414
- async killProcess(id: string, _signal?: string): Promise<void> {
415
- try {
416
- // Note: signal parameter is not currently supported by the HttpClient implementation
417
- await this.client.killProcess(id);
418
- } catch (error) {
419
- if (
420
- error instanceof Error &&
421
- error.message.includes("Process not found")
422
- ) {
423
- throw new ProcessNotFoundError(id);
424
- }
425
- throw new SandboxError(
426
- `Failed to kill process ${id}: ${
427
- error instanceof Error ? error.message : "Unknown error"
428
- }`,
429
- "KILL_PROCESS_FAILED"
430
- );
431
- }
186
+ async killProcess(id: string, signal?: string): Promise<void> {
187
+ const session = await this.ensureDefaultSession();
188
+ return session.killProcess(id, signal);
432
189
  }
433
190
 
434
191
  async killAllProcesses(): Promise<number> {
435
- const response = await this.client.killAllProcesses();
436
- return response.killedCount;
192
+ const session = await this.ensureDefaultSession();
193
+ return session.killAllProcesses();
437
194
  }
438
195
 
439
196
  async cleanupCompletedProcesses(): Promise<number> {
440
- // For now, this would need to be implemented as a container endpoint
441
- // as we no longer maintain local process storage
442
- // We'll return 0 as a placeholder until the container endpoint is added
443
- return 0;
197
+ const session = await this.ensureDefaultSession();
198
+ return session.cleanupCompletedProcesses();
444
199
  }
445
200
 
446
201
  async getProcessLogs(
447
202
  id: string
448
203
  ): Promise<{ stdout: string; stderr: string }> {
449
- try {
450
- const response = await this.client.getProcessLogs(id);
451
- return {
452
- stdout: response.stdout,
453
- stderr: response.stderr,
454
- };
455
- } catch (error) {
456
- if (
457
- error instanceof Error &&
458
- error.message.includes("Process not found")
459
- ) {
460
- throw new ProcessNotFoundError(id);
461
- }
462
- throw error;
463
- }
204
+ const session = await this.ensureDefaultSession();
205
+ return session.getProcessLogs(id);
464
206
  }
465
207
 
466
- // Streaming methods - return ReadableStream for RPC compatibility
208
+ // Streaming methods - delegates to default session
467
209
  async execStream(
468
210
  command: string,
469
211
  options?: StreamOptions
470
212
  ): Promise<ReadableStream<Uint8Array>> {
471
- // Check for cancellation
472
- if (options?.signal?.aborted) {
473
- throw new Error("Operation was aborted");
474
- }
475
-
476
- // Get the stream from HttpClient (need to add this method)
477
- const stream = await this.client.executeCommandStream(
478
- command,
479
- options?.sessionId
480
- );
481
-
482
- // Return the ReadableStream directly - can be converted to AsyncIterable by consumers
483
- return stream;
213
+ const session = await this.ensureDefaultSession();
214
+ return session.execStream(command, options);
484
215
  }
485
216
 
486
217
  async streamProcessLogs(
487
218
  processId: string,
488
219
  options?: { signal?: AbortSignal }
489
220
  ): Promise<ReadableStream<Uint8Array>> {
490
- // Check for cancellation
491
- if (options?.signal?.aborted) {
492
- throw new Error("Operation was aborted");
493
- }
494
-
495
- // Get the stream from HttpClient
496
- const stream = await this.client.streamProcessLogs(processId);
497
-
498
- // Return the ReadableStream directly - can be converted to AsyncIterable by consumers
499
- return stream;
221
+ const session = await this.ensureDefaultSession();
222
+ return session.streamProcessLogs(processId, options);
500
223
  }
501
224
 
502
225
  async gitCheckout(
503
226
  repoUrl: string,
504
227
  options: { branch?: string; targetDir?: string }
505
228
  ) {
506
- return this.client.gitCheckout(repoUrl, options.branch, options.targetDir);
229
+ const session = await this.ensureDefaultSession();
230
+ return session.gitCheckout(repoUrl, options);
507
231
  }
508
232
 
509
233
  async mkdir(path: string, options: { recursive?: boolean } = {}) {
510
- return this.client.mkdir(path, options.recursive);
234
+ const session = await this.ensureDefaultSession();
235
+ return session.mkdir(path, options);
511
236
  }
512
237
 
513
238
  async writeFile(
@@ -515,23 +240,44 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
515
240
  content: string,
516
241
  options: { encoding?: string } = {}
517
242
  ) {
518
- return this.client.writeFile(path, content, options.encoding);
243
+ const session = await this.ensureDefaultSession();
244
+ return session.writeFile(path, content, options);
519
245
  }
520
246
 
521
247
  async deleteFile(path: string) {
522
- return this.client.deleteFile(path);
248
+ const session = await this.ensureDefaultSession();
249
+ return session.deleteFile(path);
523
250
  }
524
251
 
525
252
  async renameFile(oldPath: string, newPath: string) {
526
- return this.client.renameFile(oldPath, newPath);
253
+ const session = await this.ensureDefaultSession();
254
+ return session.renameFile(oldPath, newPath);
527
255
  }
528
256
 
529
257
  async moveFile(sourcePath: string, destinationPath: string) {
530
- return this.client.moveFile(sourcePath, destinationPath);
258
+ const session = await this.ensureDefaultSession();
259
+ return session.moveFile(sourcePath, destinationPath);
531
260
  }
532
261
 
533
262
  async readFile(path: string, options: { encoding?: string } = {}) {
534
- return this.client.readFile(path, options.encoding);
263
+ const session = await this.ensureDefaultSession();
264
+ return session.readFile(path, options);
265
+ }
266
+
267
+ async readFileStream(path: string): Promise<ReadableStream<Uint8Array>> {
268
+ const session = await this.ensureDefaultSession();
269
+ return session.readFileStream(path);
270
+ }
271
+
272
+ async listFiles(
273
+ path: string,
274
+ options: {
275
+ recursive?: boolean;
276
+ includeHidden?: boolean;
277
+ } = {}
278
+ ) {
279
+ const session = await this.ensureDefaultSession();
280
+ return session.listFiles(path, options);
535
281
  }
536
282
 
537
283
  async exposePort(port: number, options: { name?: string; hostname: string }) {
@@ -775,4 +521,236 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
775
521
  async deleteCodeContext(contextId: string): Promise<void> {
776
522
  return this.codeInterpreter.deleteCodeContext(contextId);
777
523
  }
524
+
525
+ // ============================================================================
526
+ // Session Management (Simple Isolation)
527
+ // ============================================================================
528
+
529
+ /**
530
+ * Create a new execution session with isolation
531
+ * Returns a session object with exec() method
532
+ */
533
+
534
+ async createSession(options: {
535
+ id?: string;
536
+ env?: Record<string, string>;
537
+ cwd?: string;
538
+ isolation?: boolean;
539
+ }): Promise<ExecutionSession> {
540
+ const sessionId = options.id || `session-${Date.now()}`;
541
+
542
+ await this.client.createSession({
543
+ id: sessionId,
544
+ env: options.env,
545
+ cwd: options.cwd,
546
+ isolation: options.isolation
547
+ });
548
+ // Return comprehensive ExecutionSession object that implements all ISandbox methods
549
+ return {
550
+ id: sessionId,
551
+
552
+ // Command execution - clean method names
553
+ exec: async (command: string, options?: ExecOptions) => {
554
+ const result = await this.client.exec(sessionId, command);
555
+ return {
556
+ ...result,
557
+ command,
558
+ duration: 0,
559
+ timestamp: new Date().toISOString()
560
+ };
561
+ },
562
+
563
+ execStream: async (command: string, options?: StreamOptions) => {
564
+ return await this.client.execStream(sessionId, command);
565
+ },
566
+
567
+ // Process management - route to session-aware methods
568
+ startProcess: async (command: string, options?: ProcessOptions) => {
569
+ // Use session-specific process management
570
+ const response = await this.client.startProcess(command, sessionId, {
571
+ processId: options?.processId,
572
+ timeout: options?.timeout,
573
+ env: options?.env,
574
+ cwd: options?.cwd,
575
+ encoding: options?.encoding,
576
+ autoCleanup: options?.autoCleanup,
577
+ });
578
+
579
+ // Convert response to Process object with bound methods
580
+ const process = response.process;
581
+ return {
582
+ id: process.id,
583
+ pid: process.pid,
584
+ command: process.command,
585
+ status: process.status as ProcessStatus,
586
+ startTime: new Date(process.startTime),
587
+ endTime: process.endTime ? new Date(process.endTime) : undefined,
588
+ exitCode: process.exitCode ?? undefined,
589
+ kill: async (signal?: string) => {
590
+ await this.client.killProcess(process.id);
591
+ },
592
+ getStatus: async () => {
593
+ const resp = await this.client.getProcess(process.id);
594
+ return resp.process?.status as ProcessStatus || "error";
595
+ },
596
+ getLogs: async () => {
597
+ return await this.client.getProcessLogs(process.id);
598
+ },
599
+ };
600
+ },
601
+
602
+ listProcesses: async () => {
603
+ // Get processes for this specific session
604
+ const response = await this.client.listProcesses(sessionId);
605
+
606
+ // Convert to Process objects with bound methods
607
+ return response.processes.map(p => ({
608
+ id: p.id,
609
+ pid: p.pid,
610
+ command: p.command,
611
+ status: p.status as ProcessStatus,
612
+ startTime: new Date(p.startTime),
613
+ endTime: p.endTime ? new Date(p.endTime) : undefined,
614
+ exitCode: p.exitCode ?? undefined,
615
+ kill: async (signal?: string) => {
616
+ await this.client.killProcess(p.id);
617
+ },
618
+ getStatus: async () => {
619
+ const processResp = await this.client.getProcess(p.id);
620
+ return processResp.process?.status as ProcessStatus || "error";
621
+ },
622
+ getLogs: async () => {
623
+ return this.client.getProcessLogs(p.id);
624
+ },
625
+ }));
626
+ },
627
+
628
+ getProcess: async (id: string) => {
629
+ const response = await this.client.getProcess(id);
630
+ if (!response.process) return null;
631
+
632
+ const p = response.process;
633
+ return {
634
+ id: p.id,
635
+ pid: p.pid,
636
+ command: p.command,
637
+ status: p.status as ProcessStatus,
638
+ startTime: new Date(p.startTime),
639
+ endTime: p.endTime ? new Date(p.endTime) : undefined,
640
+ exitCode: p.exitCode ?? undefined,
641
+ kill: async (signal?: string) => {
642
+ await this.client.killProcess(p.id);
643
+ },
644
+ getStatus: async () => {
645
+ const processResp = await this.client.getProcess(p.id);
646
+ return processResp.process?.status as ProcessStatus || "error";
647
+ },
648
+ getLogs: async () => {
649
+ return this.client.getProcessLogs(p.id);
650
+ },
651
+ };
652
+ },
653
+
654
+ killProcess: async (id: string, signal?: string) => {
655
+ await this.client.killProcess(id);
656
+ },
657
+
658
+ killAllProcesses: async () => {
659
+ // Kill all processes for this specific session
660
+ const response = await this.client.killAllProcesses(sessionId);
661
+ return response.killedCount;
662
+ },
663
+
664
+ streamProcessLogs: async (processId: string, options?: { signal?: AbortSignal }) => {
665
+ return await this.client.streamProcessLogs(processId, options);
666
+ },
667
+
668
+ getProcessLogs: async (id: string) => {
669
+ return await this.client.getProcessLogs(id);
670
+ },
671
+
672
+ cleanupCompletedProcesses: async () => {
673
+ // This would need a new endpoint to cleanup processes for a specific session
674
+ // For now, return 0 as no cleanup is performed
675
+ return 0;
676
+ },
677
+
678
+ // File operations - clean method names (no "InSession" suffix)
679
+ writeFile: async (path: string, content: string, options?: { encoding?: string }) => {
680
+ return await this.client.writeFile(path, content, options?.encoding, sessionId);
681
+ },
682
+
683
+ readFile: async (path: string, options?: { encoding?: string }) => {
684
+ return await this.client.readFile(path, options?.encoding, sessionId);
685
+ },
686
+
687
+ readFileStream: async (path: string) => {
688
+ return await this.client.readFileStream(path, sessionId);
689
+ },
690
+
691
+ mkdir: async (path: string, options?: { recursive?: boolean }) => {
692
+ return await this.client.mkdir(path, options?.recursive, sessionId);
693
+ },
694
+
695
+ deleteFile: async (path: string) => {
696
+ return await this.client.deleteFile(path, sessionId);
697
+ },
698
+
699
+ renameFile: async (oldPath: string, newPath: string) => {
700
+ return await this.client.renameFile(oldPath, newPath, sessionId);
701
+ },
702
+
703
+ moveFile: async (sourcePath: string, destinationPath: string) => {
704
+ return await this.client.moveFile(sourcePath, destinationPath, sessionId);
705
+ },
706
+
707
+ listFiles: async (path: string, options?: { recursive?: boolean; includeHidden?: boolean }) => {
708
+ return await this.client.listFiles(path, sessionId, options);
709
+ },
710
+
711
+ gitCheckout: async (repoUrl: string, options?: { branch?: string; targetDir?: string }) => {
712
+ return await this.client.gitCheckout(repoUrl, sessionId, options?.branch, options?.targetDir);
713
+ },
714
+
715
+ // Port management
716
+ exposePort: async (port: number, options: { name?: string; hostname: string }) => {
717
+ return await this.exposePort(port, options);
718
+ },
719
+
720
+ unexposePort: async (port: number) => {
721
+ return await this.unexposePort(port);
722
+ },
723
+
724
+ getExposedPorts: async (hostname: string) => {
725
+ return await this.getExposedPorts(hostname);
726
+ },
727
+
728
+ // Environment management
729
+ setEnvVars: async (envVars: Record<string, string>) => {
730
+ // TODO: Implement session-specific environment updates
731
+ console.log(`[Session ${sessionId}] Environment variables update not yet implemented`);
732
+ },
733
+
734
+ // Code Interpreter API
735
+ createCodeContext: async (options?: any) => {
736
+ return await this.createCodeContext(options);
737
+ },
738
+
739
+ runCode: async (code: string, options?: any) => {
740
+ return await this.runCode(code, options);
741
+ },
742
+
743
+ runCodeStream: async (code: string, options?: any) => {
744
+ return await this.runCodeStream(code, options);
745
+ },
746
+
747
+ listCodeContexts: async () => {
748
+ return await this.listCodeContexts();
749
+ },
750
+
751
+ deleteCodeContext: async (contextId: string) => {
752
+ return await this.deleteCodeContext(contextId);
753
+ }
754
+ };
755
+ }
778
756
  }