@cloudflare/sandbox 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/Dockerfile +31 -7
  3. package/README.md +226 -2
  4. package/container_src/bun.lock +122 -0
  5. package/container_src/index.ts +171 -1
  6. package/container_src/jupyter-server.ts +336 -0
  7. package/container_src/mime-processor.ts +255 -0
  8. package/container_src/package.json +9 -0
  9. package/container_src/startup.sh +52 -0
  10. package/dist/{chunk-YVZ3K26G.js → chunk-CUHYLCMT.js} +9 -21
  11. package/dist/chunk-CUHYLCMT.js.map +1 -0
  12. package/dist/chunk-EGC5IYXA.js +108 -0
  13. package/dist/chunk-EGC5IYXA.js.map +1 -0
  14. package/dist/chunk-FKBV7CZS.js +113 -0
  15. package/dist/chunk-FKBV7CZS.js.map +1 -0
  16. package/dist/{chunk-ZJN2PQOS.js → chunk-IATLC32Y.js} +173 -74
  17. package/dist/chunk-IATLC32Y.js.map +1 -0
  18. package/dist/{chunk-6THNBO4S.js → chunk-S5FFBU4Y.js} +1 -1
  19. package/dist/{chunk-6THNBO4S.js.map → chunk-S5FFBU4Y.js.map} +1 -1
  20. package/dist/chunk-SYMWNYWA.js +185 -0
  21. package/dist/chunk-SYMWNYWA.js.map +1 -0
  22. package/dist/{client-BXYlxy-j.d.ts → client-C7rKCYBD.d.ts} +42 -4
  23. package/dist/client.d.ts +2 -1
  24. package/dist/client.js +1 -1
  25. package/dist/index.d.ts +2 -1
  26. package/dist/index.js +10 -4
  27. package/dist/interpreter-types.d.ts +259 -0
  28. package/dist/interpreter-types.js +9 -0
  29. package/dist/interpreter-types.js.map +1 -0
  30. package/dist/interpreter.d.ts +33 -0
  31. package/dist/interpreter.js +8 -0
  32. package/dist/interpreter.js.map +1 -0
  33. package/dist/jupyter-client.d.ts +4 -0
  34. package/dist/jupyter-client.js +8 -0
  35. package/dist/jupyter-client.js.map +1 -0
  36. package/dist/request-handler.d.ts +2 -1
  37. package/dist/request-handler.js +7 -3
  38. package/dist/sandbox.d.ts +2 -1
  39. package/dist/sandbox.js +7 -3
  40. package/dist/types.d.ts +8 -0
  41. package/dist/types.js +1 -1
  42. package/package.json +1 -1
  43. package/src/client.ts +37 -54
  44. package/src/index.ts +13 -4
  45. package/src/interpreter-types.ts +383 -0
  46. package/src/interpreter.ts +150 -0
  47. package/src/jupyter-client.ts +266 -0
  48. package/src/sandbox.ts +281 -153
  49. package/src/types.ts +15 -0
  50. package/dist/chunk-YVZ3K26G.js.map +0 -1
  51. package/dist/chunk-ZJN2PQOS.js.map +0 -1
@@ -0,0 +1,383 @@
1
+ // Context Management
2
+ export interface CreateContextOptions {
3
+ /**
4
+ * Programming language for the context
5
+ * @default 'python'
6
+ */
7
+ language?: 'python' | 'javascript' | 'typescript';
8
+
9
+ /**
10
+ * Working directory for the context
11
+ * @default '/workspace'
12
+ */
13
+ cwd?: string;
14
+
15
+ /**
16
+ * Environment variables for the context
17
+ */
18
+ envVars?: Record<string, string>;
19
+
20
+ /**
21
+ * Request timeout in milliseconds
22
+ * @default 30000
23
+ */
24
+ timeout?: number;
25
+ }
26
+
27
+ export interface CodeContext {
28
+ /**
29
+ * Unique identifier for the context
30
+ */
31
+ readonly id: string;
32
+
33
+ /**
34
+ * Programming language of the context
35
+ */
36
+ readonly language: string;
37
+
38
+ /**
39
+ * Current working directory
40
+ */
41
+ readonly cwd: string;
42
+
43
+ /**
44
+ * When the context was created
45
+ */
46
+ readonly createdAt: Date;
47
+
48
+ /**
49
+ * When the context was last used
50
+ */
51
+ readonly lastUsed: Date;
52
+ }
53
+
54
+ // Execution Options
55
+ export interface RunCodeOptions {
56
+ /**
57
+ * Context to run the code in. If not provided, uses default context for the language
58
+ */
59
+ context?: CodeContext;
60
+
61
+ /**
62
+ * Language to use if context is not provided
63
+ * @default 'python'
64
+ */
65
+ language?: 'python' | 'javascript' | 'typescript';
66
+
67
+ /**
68
+ * Environment variables for this execution
69
+ */
70
+ envVars?: Record<string, string>;
71
+
72
+ /**
73
+ * Execution timeout in milliseconds
74
+ * @default 60000
75
+ */
76
+ timeout?: number;
77
+
78
+ /**
79
+ * AbortSignal for cancelling execution
80
+ */
81
+ signal?: AbortSignal;
82
+
83
+ /**
84
+ * Callback for stdout output
85
+ */
86
+ onStdout?: (output: OutputMessage) => void | Promise<void>;
87
+
88
+ /**
89
+ * Callback for stderr output
90
+ */
91
+ onStderr?: (output: OutputMessage) => void | Promise<void>;
92
+
93
+ /**
94
+ * Callback for execution results (charts, tables, etc)
95
+ */
96
+ onResult?: (result: Result) => void | Promise<void>;
97
+
98
+ /**
99
+ * Callback for execution errors
100
+ */
101
+ onError?: (error: ExecutionError) => void | Promise<void>;
102
+ }
103
+
104
+ // Output Messages
105
+ export interface OutputMessage {
106
+ /**
107
+ * The output text
108
+ */
109
+ text: string;
110
+
111
+ /**
112
+ * Timestamp of the output
113
+ */
114
+ timestamp: number;
115
+ }
116
+
117
+ // Execution Results
118
+ export interface Result {
119
+ /**
120
+ * Plain text representation
121
+ */
122
+ text?: string;
123
+
124
+ /**
125
+ * HTML representation (tables, formatted output)
126
+ */
127
+ html?: string;
128
+
129
+ /**
130
+ * PNG image data (base64 encoded)
131
+ */
132
+ png?: string;
133
+
134
+ /**
135
+ * JPEG image data (base64 encoded)
136
+ */
137
+ jpeg?: string;
138
+
139
+ /**
140
+ * SVG image data
141
+ */
142
+ svg?: string;
143
+
144
+ /**
145
+ * LaTeX representation
146
+ */
147
+ latex?: string;
148
+
149
+ /**
150
+ * Markdown representation
151
+ */
152
+ markdown?: string;
153
+
154
+ /**
155
+ * JavaScript code to execute
156
+ */
157
+ javascript?: string;
158
+
159
+ /**
160
+ * JSON data
161
+ */
162
+ json?: any;
163
+
164
+ /**
165
+ * Chart data if the result is a visualization
166
+ */
167
+ chart?: ChartData;
168
+
169
+ /**
170
+ * Raw data object
171
+ */
172
+ data?: any;
173
+
174
+ /**
175
+ * Available output formats
176
+ */
177
+ formats(): string[];
178
+ }
179
+
180
+ // Chart Data
181
+ export interface ChartData {
182
+ /**
183
+ * Type of chart
184
+ */
185
+ type: 'line' | 'bar' | 'scatter' | 'pie' | 'histogram' | 'heatmap' | 'unknown';
186
+
187
+ /**
188
+ * Chart title
189
+ */
190
+ title?: string;
191
+
192
+ /**
193
+ * Chart data (format depends on library)
194
+ */
195
+ data: any;
196
+
197
+ /**
198
+ * Chart layout/configuration
199
+ */
200
+ layout?: any;
201
+
202
+ /**
203
+ * Additional configuration
204
+ */
205
+ config?: any;
206
+
207
+ /**
208
+ * Library that generated the chart
209
+ */
210
+ library?: 'matplotlib' | 'plotly' | 'altair' | 'seaborn' | 'unknown';
211
+
212
+ /**
213
+ * Base64 encoded image if available
214
+ */
215
+ image?: string;
216
+ }
217
+
218
+ // Execution Error
219
+ export interface ExecutionError {
220
+ /**
221
+ * Error name/type (e.g., 'NameError', 'SyntaxError')
222
+ */
223
+ name: string;
224
+
225
+ /**
226
+ * Error message
227
+ */
228
+ value: string;
229
+
230
+ /**
231
+ * Stack trace
232
+ */
233
+ traceback: string[];
234
+
235
+ /**
236
+ * Line number where error occurred
237
+ */
238
+ lineNumber?: number;
239
+ }
240
+
241
+ // Serializable execution result
242
+ export interface ExecutionResult {
243
+ code: string;
244
+ logs: {
245
+ stdout: string[];
246
+ stderr: string[];
247
+ };
248
+ error?: ExecutionError;
249
+ executionCount?: number;
250
+ results: Array<{
251
+ text?: string;
252
+ html?: string;
253
+ png?: string;
254
+ jpeg?: string;
255
+ svg?: string;
256
+ latex?: string;
257
+ markdown?: string;
258
+ javascript?: string;
259
+ json?: any;
260
+ chart?: ChartData;
261
+ data?: any;
262
+ }>;
263
+ }
264
+
265
+ // Execution Result Container
266
+ export class Execution {
267
+ /**
268
+ * All results from the execution
269
+ */
270
+ public results: Result[] = [];
271
+
272
+ /**
273
+ * Accumulated stdout and stderr
274
+ */
275
+ public logs = {
276
+ stdout: [] as string[],
277
+ stderr: [] as string[]
278
+ };
279
+
280
+ /**
281
+ * Execution error if any
282
+ */
283
+ public error?: ExecutionError;
284
+
285
+ /**
286
+ * Execution count (for Jupyter)
287
+ */
288
+ public executionCount?: number;
289
+
290
+ constructor(
291
+ public readonly code: string,
292
+ public readonly context: CodeContext
293
+ ) {}
294
+
295
+ /**
296
+ * Convert to a plain object for serialization
297
+ */
298
+ toJSON(): ExecutionResult {
299
+ return {
300
+ code: this.code,
301
+ logs: this.logs,
302
+ error: this.error,
303
+ executionCount: this.executionCount,
304
+ results: this.results.map(result => ({
305
+ text: result.text,
306
+ html: result.html,
307
+ png: result.png,
308
+ jpeg: result.jpeg,
309
+ svg: result.svg,
310
+ latex: result.latex,
311
+ markdown: result.markdown,
312
+ javascript: result.javascript,
313
+ json: result.json,
314
+ chart: result.chart,
315
+ data: result.data
316
+ }))
317
+ };
318
+ }
319
+ }
320
+
321
+ // Implementation of Result
322
+ export class ResultImpl implements Result {
323
+ constructor(private raw: any) {}
324
+
325
+ get text(): string | undefined {
326
+ return this.raw.text || this.raw.data?.['text/plain'];
327
+ }
328
+
329
+ get html(): string | undefined {
330
+ return this.raw.html || this.raw.data?.['text/html'];
331
+ }
332
+
333
+ get png(): string | undefined {
334
+ return this.raw.png || this.raw.data?.['image/png'];
335
+ }
336
+
337
+ get jpeg(): string | undefined {
338
+ return this.raw.jpeg || this.raw.data?.['image/jpeg'];
339
+ }
340
+
341
+ get svg(): string | undefined {
342
+ return this.raw.svg || this.raw.data?.['image/svg+xml'];
343
+ }
344
+
345
+ get latex(): string | undefined {
346
+ return this.raw.latex || this.raw.data?.['text/latex'];
347
+ }
348
+
349
+ get markdown(): string | undefined {
350
+ return this.raw.markdown || this.raw.data?.['text/markdown'];
351
+ }
352
+
353
+ get javascript(): string | undefined {
354
+ return this.raw.javascript || this.raw.data?.['application/javascript'];
355
+ }
356
+
357
+ get json(): any {
358
+ return this.raw.json || this.raw.data?.['application/json'];
359
+ }
360
+
361
+ get chart(): ChartData | undefined {
362
+ return this.raw.chart;
363
+ }
364
+
365
+ get data(): any {
366
+ return this.raw.data;
367
+ }
368
+
369
+ formats(): string[] {
370
+ const formats: string[] = [];
371
+ if (this.text) formats.push('text');
372
+ if (this.html) formats.push('html');
373
+ if (this.png) formats.push('png');
374
+ if (this.jpeg) formats.push('jpeg');
375
+ if (this.svg) formats.push('svg');
376
+ if (this.latex) formats.push('latex');
377
+ if (this.markdown) formats.push('markdown');
378
+ if (this.javascript) formats.push('javascript');
379
+ if (this.json) formats.push('json');
380
+ if (this.chart) formats.push('chart');
381
+ return formats;
382
+ }
383
+ }
@@ -0,0 +1,150 @@
1
+ import {
2
+ type CodeContext,
3
+ type CreateContextOptions,
4
+ Execution,
5
+ ResultImpl,
6
+ type RunCodeOptions,
7
+ } from "./interpreter-types.js";
8
+ import type { JupyterClient } from "./jupyter-client.js";
9
+ import type { Sandbox } from "./sandbox.js";
10
+
11
+ export class CodeInterpreter {
12
+ private jupyterClient: JupyterClient;
13
+ private contexts = new Map<string, CodeContext>();
14
+
15
+ constructor(sandbox: Sandbox) {
16
+ this.jupyterClient = sandbox.client as JupyterClient;
17
+ }
18
+
19
+ /**
20
+ * Create a new code execution context
21
+ */
22
+ async createCodeContext(
23
+ options: CreateContextOptions = {}
24
+ ): Promise<CodeContext> {
25
+ const context = await this.jupyterClient.createCodeContext(options);
26
+ this.contexts.set(context.id, context);
27
+ return context;
28
+ }
29
+
30
+ /**
31
+ * Run code with optional context
32
+ */
33
+ async runCode(
34
+ code: string,
35
+ options: RunCodeOptions = {}
36
+ ): Promise<Execution> {
37
+ // Get or create context
38
+ let context = options.context;
39
+ if (!context) {
40
+ // Try to find or create a default context for the language
41
+ const language = options.language || "python";
42
+ context = await this.getOrCreateDefaultContext(language);
43
+ }
44
+
45
+ // Create execution object to collect results
46
+ const execution = new Execution(code, context);
47
+
48
+ // Stream execution
49
+ await this.jupyterClient.runCodeStream(context.id, code, options.language, {
50
+ onStdout: (output) => {
51
+ execution.logs.stdout.push(output.text);
52
+ if (options.onStdout) return options.onStdout(output);
53
+ },
54
+ onStderr: (output) => {
55
+ execution.logs.stderr.push(output.text);
56
+ if (options.onStderr) return options.onStderr(output);
57
+ },
58
+ onResult: async (result) => {
59
+ execution.results.push(new ResultImpl(result) as any);
60
+ if (options.onResult) return options.onResult(result);
61
+ },
62
+ onError: (error) => {
63
+ execution.error = error;
64
+ if (options.onError) return options.onError(error);
65
+ },
66
+ });
67
+
68
+ return execution;
69
+ }
70
+
71
+ /**
72
+ * Run code and return a streaming response
73
+ */
74
+ async runCodeStream(
75
+ code: string,
76
+ options: RunCodeOptions = {}
77
+ ): Promise<ReadableStream> {
78
+ // Get or create context
79
+ let context = options.context;
80
+ if (!context) {
81
+ const language = options.language || "python";
82
+ context = await this.getOrCreateDefaultContext(language);
83
+ }
84
+
85
+ // Create streaming response
86
+ const response = await this.jupyterClient.doFetch("/api/execute/code", {
87
+ method: "POST",
88
+ headers: {
89
+ "Content-Type": "application/json",
90
+ Accept: "text/event-stream",
91
+ },
92
+ body: JSON.stringify({
93
+ context_id: context.id,
94
+ code,
95
+ language: options.language,
96
+ }),
97
+ });
98
+
99
+ if (!response.ok) {
100
+ const errorData = (await response
101
+ .json()
102
+ .catch(() => ({ error: "Unknown error" }))) as { error?: string };
103
+ throw new Error(
104
+ errorData.error || `Failed to execute code: ${response.status}`
105
+ );
106
+ }
107
+
108
+ if (!response.body) {
109
+ throw new Error("No response body for streaming execution");
110
+ }
111
+
112
+ return response.body;
113
+ }
114
+
115
+ /**
116
+ * List all code contexts
117
+ */
118
+ async listCodeContexts(): Promise<CodeContext[]> {
119
+ const contexts = await this.jupyterClient.listCodeContexts();
120
+
121
+ // Update local cache
122
+ for (const context of contexts) {
123
+ this.contexts.set(context.id, context);
124
+ }
125
+
126
+ return contexts;
127
+ }
128
+
129
+ /**
130
+ * Delete a code context
131
+ */
132
+ async deleteCodeContext(contextId: string): Promise<void> {
133
+ await this.jupyterClient.deleteCodeContext(contextId);
134
+ this.contexts.delete(contextId);
135
+ }
136
+
137
+ private async getOrCreateDefaultContext(
138
+ language: "python" | "javascript" | "typescript"
139
+ ): Promise<CodeContext> {
140
+ // Check if we have a cached context for this language
141
+ for (const context of this.contexts.values()) {
142
+ if (context.language === language) {
143
+ return context;
144
+ }
145
+ }
146
+
147
+ // Create new default context
148
+ return this.createCodeContext({ language });
149
+ }
150
+ }