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