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