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