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