@cloudflare/sandbox 0.2.0 → 0.2.2

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 (59) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/Dockerfile +31 -7
  3. package/README.md +226 -2
  4. package/container_src/bun.lock +122 -0
  5. package/container_src/circuit-breaker.ts +121 -0
  6. package/container_src/index.ts +305 -10
  7. package/container_src/jupyter-server.ts +579 -0
  8. package/container_src/jupyter-service.ts +448 -0
  9. package/container_src/mime-processor.ts +255 -0
  10. package/container_src/package.json +9 -0
  11. package/container_src/startup.sh +83 -0
  12. package/dist/{chunk-YVZ3K26G.js → chunk-CUHYLCMT.js} +9 -21
  13. package/dist/chunk-CUHYLCMT.js.map +1 -0
  14. package/dist/chunk-EGC5IYXA.js +108 -0
  15. package/dist/chunk-EGC5IYXA.js.map +1 -0
  16. package/dist/chunk-FKBV7CZS.js +113 -0
  17. package/dist/chunk-FKBV7CZS.js.map +1 -0
  18. package/dist/chunk-LALY4SFU.js +129 -0
  19. package/dist/chunk-LALY4SFU.js.map +1 -0
  20. package/dist/{chunk-6THNBO4S.js → chunk-S5FFBU4Y.js} +1 -1
  21. package/dist/{chunk-6THNBO4S.js.map → chunk-S5FFBU4Y.js.map} +1 -1
  22. package/dist/chunk-VTKZL632.js +237 -0
  23. package/dist/chunk-VTKZL632.js.map +1 -0
  24. package/dist/{chunk-ZJN2PQOS.js → chunk-ZMPO44U4.js} +171 -72
  25. package/dist/chunk-ZMPO44U4.js.map +1 -0
  26. package/dist/{client-BXYlxy-j.d.ts → client-bzEV222a.d.ts} +52 -4
  27. package/dist/client.d.ts +2 -1
  28. package/dist/client.js +1 -1
  29. package/dist/errors.d.ts +95 -0
  30. package/dist/errors.js +27 -0
  31. package/dist/errors.js.map +1 -0
  32. package/dist/index.d.ts +3 -1
  33. package/dist/index.js +33 -3
  34. package/dist/interpreter-types.d.ts +259 -0
  35. package/dist/interpreter-types.js +9 -0
  36. package/dist/interpreter-types.js.map +1 -0
  37. package/dist/interpreter.d.ts +33 -0
  38. package/dist/interpreter.js +8 -0
  39. package/dist/interpreter.js.map +1 -0
  40. package/dist/jupyter-client.d.ts +4 -0
  41. package/dist/jupyter-client.js +9 -0
  42. package/dist/jupyter-client.js.map +1 -0
  43. package/dist/request-handler.d.ts +2 -1
  44. package/dist/request-handler.js +8 -3
  45. package/dist/sandbox.d.ts +2 -1
  46. package/dist/sandbox.js +8 -3
  47. package/dist/types.d.ts +8 -0
  48. package/dist/types.js +1 -1
  49. package/package.json +1 -1
  50. package/src/client.ts +37 -54
  51. package/src/errors.ts +218 -0
  52. package/src/index.ts +44 -10
  53. package/src/interpreter-types.ts +383 -0
  54. package/src/interpreter.ts +150 -0
  55. package/src/jupyter-client.ts +349 -0
  56. package/src/sandbox.ts +281 -153
  57. package/src/types.ts +15 -0
  58. package/dist/chunk-YVZ3K26G.js.map +0 -1
  59. package/dist/chunk-ZJN2PQOS.js.map +0 -1
@@ -0,0 +1,448 @@
1
+ import { existsSync } from "node:fs";
2
+ import { CircuitBreaker } from "./circuit-breaker";
3
+ import { type CreateContextRequest, JupyterServer } from "./jupyter-server";
4
+
5
+ interface PoolStats {
6
+ available: number;
7
+ inUse: number;
8
+ total: number;
9
+ minSize: number;
10
+ maxSize: number;
11
+ warming: boolean;
12
+ }
13
+
14
+ interface CircuitBreakerState {
15
+ state: string;
16
+ failures: number;
17
+ lastFailure: number;
18
+ isOpen: boolean;
19
+ }
20
+
21
+ export interface JupyterHealthStatus {
22
+ ready: boolean;
23
+ initializing: boolean;
24
+ error?: string;
25
+ checks?: {
26
+ httpApi: boolean;
27
+ kernelManager: boolean;
28
+ markerFile: boolean;
29
+ kernelSpawn?: boolean;
30
+ websocket?: boolean;
31
+ };
32
+ timestamp: number;
33
+ performance?: {
34
+ poolStats?: Record<string, PoolStats>;
35
+ activeContexts?: number;
36
+ uptime?: number;
37
+ circuitBreakers?: {
38
+ contextCreation: CircuitBreakerState;
39
+ codeExecution: CircuitBreakerState;
40
+ kernelCommunication: CircuitBreakerState;
41
+ };
42
+ };
43
+ }
44
+
45
+ /**
46
+ * Wrapper service that provides graceful degradation for Jupyter functionality
47
+ */
48
+ export class JupyterService {
49
+ private jupyterServer: JupyterServer;
50
+ private initPromise: Promise<void> | null = null;
51
+ private initialized = false;
52
+ private initError: Error | null = null;
53
+ private startTime = Date.now();
54
+ private circuitBreakers: {
55
+ contextCreation: CircuitBreaker;
56
+ codeExecution: CircuitBreaker;
57
+ kernelCommunication: CircuitBreaker;
58
+ };
59
+
60
+ constructor() {
61
+ this.jupyterServer = new JupyterServer();
62
+
63
+ // Initialize circuit breakers for different operations
64
+ this.circuitBreakers = {
65
+ contextCreation: new CircuitBreaker({
66
+ name: "context-creation",
67
+ threshold: 3,
68
+ timeout: 60000, // 1 minute
69
+ }),
70
+ codeExecution: new CircuitBreaker({
71
+ name: "code-execution",
72
+ threshold: 5,
73
+ timeout: 30000, // 30 seconds
74
+ }),
75
+ kernelCommunication: new CircuitBreaker({
76
+ name: "kernel-communication",
77
+ threshold: 10,
78
+ timeout: 20000, // 20 seconds
79
+ }),
80
+ };
81
+ }
82
+
83
+ /**
84
+ * Initialize Jupyter server with retry logic
85
+ */
86
+ async initialize(): Promise<void> {
87
+ if (this.initialized) return;
88
+
89
+ if (!this.initPromise) {
90
+ this.initPromise = this.doInitialize()
91
+ .then(() => {
92
+ this.initialized = true;
93
+ console.log("[JupyterService] Initialization complete");
94
+ })
95
+ .catch((err) => {
96
+ this.initError = err;
97
+ // Don't null out initPromise on error - keep it so we can return the same error
98
+ console.error("[JupyterService] Initialization failed:", err);
99
+ throw err;
100
+ });
101
+ }
102
+
103
+ return this.initPromise;
104
+ }
105
+
106
+ private async doInitialize(): Promise<void> {
107
+ // Wait for Jupyter marker file or timeout
108
+ const markerCheckPromise = this.waitForMarkerFile();
109
+ const timeoutPromise = new Promise<void>((_, reject) => {
110
+ setTimeout(
111
+ () => reject(new Error("Jupyter initialization timeout")),
112
+ 60000
113
+ );
114
+ });
115
+
116
+ try {
117
+ await Promise.race([markerCheckPromise, timeoutPromise]);
118
+ console.log("[JupyterService] Jupyter process detected via marker file");
119
+ } catch (error) {
120
+ console.log(
121
+ "[JupyterService] Marker file not found yet - proceeding with initialization"
122
+ );
123
+ }
124
+
125
+ // Initialize Jupyter server
126
+ await this.jupyterServer.initialize();
127
+
128
+ // Pre-warm context pools in background after Jupyter is ready
129
+ this.warmContextPools();
130
+ }
131
+
132
+ /**
133
+ * Pre-warm context pools for better performance
134
+ */
135
+ private async warmContextPools() {
136
+ try {
137
+ console.log(
138
+ "[JupyterService] Pre-warming context pools for better performance"
139
+ );
140
+
141
+ // Enable pool warming with min sizes
142
+ await this.jupyterServer.enablePoolWarming("python", 1);
143
+ await this.jupyterServer.enablePoolWarming("javascript", 1);
144
+ } catch (error) {
145
+ console.error("[JupyterService] Error pre-warming context pools:", error);
146
+ }
147
+ }
148
+
149
+ private async waitForMarkerFile(): Promise<void> {
150
+ const markerPath = "/tmp/jupyter-ready";
151
+ let attempts = 0;
152
+ const maxAttempts = 120; // 2 minutes with 1s intervals
153
+
154
+ while (attempts < maxAttempts) {
155
+ if (existsSync(markerPath)) {
156
+ return;
157
+ }
158
+ attempts++;
159
+ await new Promise((resolve) => setTimeout(resolve, 1000));
160
+ }
161
+
162
+ throw new Error("Marker file not found within timeout");
163
+ }
164
+
165
+ /**
166
+ * Get current health status
167
+ */
168
+ async getHealthStatus(): Promise<JupyterHealthStatus> {
169
+ const status: JupyterHealthStatus = {
170
+ ready: this.initialized,
171
+ initializing: this.initPromise !== null && !this.initialized,
172
+ timestamp: Date.now(),
173
+ };
174
+
175
+ if (this.initError) {
176
+ status.error = this.initError.message;
177
+ }
178
+
179
+ // Detailed health checks
180
+ if (this.initialized || this.initPromise) {
181
+ status.checks = {
182
+ httpApi: await this.checkHttpApi(),
183
+ kernelManager: this.initialized,
184
+ markerFile: existsSync("/tmp/jupyter-ready"),
185
+ };
186
+
187
+ // Advanced health checks only if fully initialized
188
+ if (this.initialized) {
189
+ const advancedChecks = await this.performAdvancedHealthChecks();
190
+ status.checks.kernelSpawn = advancedChecks.kernelSpawn;
191
+ status.checks.websocket = advancedChecks.websocket;
192
+
193
+ // Performance metrics
194
+ status.performance = {
195
+ poolStats: await this.jupyterServer.getPoolStats(),
196
+ activeContexts: (await this.jupyterServer.listContexts()).length,
197
+ uptime: Date.now() - this.startTime,
198
+ };
199
+ }
200
+ }
201
+
202
+ // Add circuit breaker status
203
+ if (status.performance) {
204
+ status.performance.circuitBreakers = {
205
+ contextCreation: this.circuitBreakers.contextCreation.getState(),
206
+ codeExecution: this.circuitBreakers.codeExecution.getState(),
207
+ kernelCommunication:
208
+ this.circuitBreakers.kernelCommunication.getState(),
209
+ };
210
+ }
211
+
212
+ return status;
213
+ }
214
+
215
+ private async checkHttpApi(): Promise<boolean> {
216
+ try {
217
+ const response = await fetch("http://localhost:8888/api", {
218
+ signal: AbortSignal.timeout(2000),
219
+ });
220
+ return response.ok;
221
+ } catch {
222
+ return false;
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Perform advanced health checks including kernel spawn and WebSocket
228
+ */
229
+ private async performAdvancedHealthChecks(): Promise<{
230
+ kernelSpawn: boolean;
231
+ websocket: boolean;
232
+ }> {
233
+ const checks = {
234
+ kernelSpawn: false,
235
+ websocket: false,
236
+ };
237
+
238
+ try {
239
+ // Test kernel spawn with timeout
240
+ const testContext = await Promise.race([
241
+ this.jupyterServer.createContext({ language: "python" }),
242
+ new Promise<null>((_, reject) =>
243
+ setTimeout(() => reject(new Error("Kernel spawn timeout")), 5000)
244
+ ),
245
+ ]);
246
+
247
+ if (testContext) {
248
+ checks.kernelSpawn = true;
249
+
250
+ // Test WebSocket by executing simple code
251
+ try {
252
+ const result = await Promise.race([
253
+ this.jupyterServer.executeCode(
254
+ testContext.id,
255
+ "print('health_check')"
256
+ ),
257
+ new Promise<null>((_, reject) =>
258
+ setTimeout(() => reject(new Error("WebSocket timeout")), 3000)
259
+ ),
260
+ ]);
261
+
262
+ checks.websocket = result !== null;
263
+ } catch {
264
+ // WebSocket test failed
265
+ }
266
+
267
+ // Clean up test context
268
+ try {
269
+ await this.jupyterServer.deleteContext(testContext.id);
270
+ } catch {
271
+ // Ignore cleanup errors
272
+ }
273
+ }
274
+ } catch (error) {
275
+ console.log("[JupyterService] Advanced health check failed:", error);
276
+ }
277
+
278
+ return checks;
279
+ }
280
+
281
+ /**
282
+ * Ensure Jupyter is initialized before proceeding
283
+ * This will wait for initialization to complete or fail
284
+ */
285
+ private async ensureInitialized(timeoutMs: number = 30000): Promise<void> {
286
+ if (this.initialized) return;
287
+
288
+ // Start initialization if not already started
289
+ if (!this.initPromise) {
290
+ this.initPromise = this.initialize();
291
+ }
292
+
293
+ // Wait for initialization with timeout
294
+ try {
295
+ await Promise.race([
296
+ this.initPromise,
297
+ new Promise<never>((_, reject) =>
298
+ setTimeout(
299
+ () =>
300
+ reject(new Error("Timeout waiting for Jupyter initialization")),
301
+ timeoutMs
302
+ )
303
+ ),
304
+ ]);
305
+ } catch (error) {
306
+ // If it's a timeout and Jupyter is still initializing, throw a retryable error
307
+ if (
308
+ error instanceof Error &&
309
+ error.message.includes("Timeout") &&
310
+ !this.initError
311
+ ) {
312
+ throw new JupyterNotReadyError(
313
+ "Jupyter is taking longer than expected to initialize. Please try again.",
314
+ {
315
+ retryAfter: 10,
316
+ progress: this.getInitializationProgress(),
317
+ }
318
+ );
319
+ }
320
+ // If initialization actually failed, throw the real error
321
+ throw new Error(
322
+ `Jupyter initialization failed: ${
323
+ error instanceof Error ? error.message : "Unknown error"
324
+ }`
325
+ );
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Create context - will wait for Jupyter if still initializing
331
+ */
332
+ async createContext(req: CreateContextRequest): Promise<any> {
333
+ if (!this.initialized) {
334
+ console.log(
335
+ "[JupyterService] Context creation requested while Jupyter is initializing - waiting..."
336
+ );
337
+ const startWait = Date.now();
338
+ await this.ensureInitialized();
339
+ const waitTime = Date.now() - startWait;
340
+ console.log(
341
+ `[JupyterService] Jupyter ready after ${waitTime}ms wait - proceeding with context creation`
342
+ );
343
+ }
344
+
345
+ // Use circuit breaker for context creation
346
+ return await this.circuitBreakers.contextCreation.execute(async () => {
347
+ return await this.jupyterServer.createContext(req);
348
+ });
349
+ }
350
+
351
+ /**
352
+ * Execute code - will wait for Jupyter if still initializing
353
+ */
354
+ async executeCode(
355
+ contextId: string | undefined,
356
+ code: string,
357
+ language?: string
358
+ ): Promise<Response> {
359
+ if (!this.initialized) {
360
+ console.log(
361
+ "[JupyterService] Code execution requested while Jupyter is initializing - waiting..."
362
+ );
363
+ const startWait = Date.now();
364
+ await this.ensureInitialized();
365
+ const waitTime = Date.now() - startWait;
366
+ console.log(
367
+ `[JupyterService] Jupyter ready after ${waitTime}ms wait - proceeding with code execution`
368
+ );
369
+ }
370
+
371
+ // Use circuit breaker for code execution
372
+ return await this.circuitBreakers.codeExecution.execute(async () => {
373
+ return await this.jupyterServer.executeCode(contextId, code, language);
374
+ });
375
+ }
376
+
377
+ /**
378
+ * List contexts with graceful degradation
379
+ */
380
+ async listContexts(): Promise<any[]> {
381
+ if (!this.initialized) {
382
+ return [];
383
+ }
384
+ return await this.jupyterServer.listContexts();
385
+ }
386
+
387
+ /**
388
+ * Delete context - will wait for Jupyter if still initializing
389
+ */
390
+ async deleteContext(contextId: string): Promise<void> {
391
+ if (!this.initialized) {
392
+ console.log(
393
+ "[JupyterService] Context deletion requested while Jupyter is initializing - waiting..."
394
+ );
395
+ const startWait = Date.now();
396
+ await this.ensureInitialized();
397
+ const waitTime = Date.now() - startWait;
398
+ console.log(
399
+ `[JupyterService] Jupyter ready after ${waitTime}ms wait - proceeding with context deletion`
400
+ );
401
+ }
402
+
403
+ // Use circuit breaker for kernel communication
404
+ return await this.circuitBreakers.kernelCommunication.execute(async () => {
405
+ return await this.jupyterServer.deleteContext(contextId);
406
+ });
407
+ }
408
+
409
+ /**
410
+ * Shutdown the service
411
+ */
412
+ async shutdown(): Promise<void> {
413
+ if (this.initialized) {
414
+ await this.jupyterServer.shutdown();
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Get initialization progress
420
+ */
421
+ private getInitializationProgress(): number {
422
+ if (this.initialized) return 100;
423
+ if (!this.initPromise) return 0;
424
+
425
+ const elapsed = Date.now() - this.startTime;
426
+ const estimatedTotal = 20000; // 20 seconds estimated
427
+ return Math.min(95, Math.round((elapsed / estimatedTotal) * 100));
428
+ }
429
+ }
430
+
431
+ /**
432
+ * Error thrown when Jupyter is not ready yet
433
+ * This matches the interface of the SDK's JupyterNotReadyError
434
+ */
435
+ export class JupyterNotReadyError extends Error {
436
+ public readonly retryAfter: number;
437
+ public readonly progress?: number;
438
+
439
+ constructor(
440
+ message: string,
441
+ options?: { retryAfter?: number; progress?: number }
442
+ ) {
443
+ super(message);
444
+ this.name = "JupyterNotReadyError";
445
+ this.retryAfter = options?.retryAfter || 5;
446
+ this.progress = options?.progress;
447
+ }
448
+ }
@@ -0,0 +1,255 @@
1
+ export interface ExecutionResult {
2
+ type: 'result' | 'stdout' | 'stderr' | 'error' | 'execution_complete';
3
+ text?: string;
4
+ html?: string;
5
+ png?: string; // base64
6
+ jpeg?: string; // base64
7
+ svg?: string;
8
+ latex?: string;
9
+ markdown?: string;
10
+ javascript?: string;
11
+ json?: any;
12
+ chart?: ChartData;
13
+ data?: any;
14
+ metadata?: any;
15
+ execution_count?: number;
16
+ ename?: string;
17
+ evalue?: string;
18
+ traceback?: string[];
19
+ timestamp: number;
20
+ }
21
+
22
+ export interface ChartData {
23
+ type: 'line' | 'bar' | 'scatter' | 'pie' | 'histogram' | 'heatmap' | 'unknown';
24
+ title?: string;
25
+ data: any;
26
+ layout?: any;
27
+ config?: any;
28
+ library?: 'matplotlib' | 'plotly' | 'altair' | 'seaborn' | 'unknown';
29
+ }
30
+
31
+ export function processJupyterMessage(msg: any): ExecutionResult | null {
32
+ const msgType = msg.header?.msg_type || msg.msg_type;
33
+
34
+ switch (msgType) {
35
+ case 'execute_result':
36
+ case 'display_data':
37
+ return processDisplayData(msg.content.data, msg.content.metadata);
38
+
39
+ case 'stream':
40
+ return {
41
+ type: msg.content.name === 'stdout' ? 'stdout' : 'stderr',
42
+ text: msg.content.text,
43
+ timestamp: Date.now()
44
+ };
45
+
46
+ case 'error':
47
+ return {
48
+ type: 'error',
49
+ ename: msg.content.ename,
50
+ evalue: msg.content.evalue,
51
+ traceback: msg.content.traceback,
52
+ timestamp: Date.now()
53
+ };
54
+
55
+ default:
56
+ return null;
57
+ }
58
+ }
59
+
60
+ function processDisplayData(data: any, metadata?: any): ExecutionResult {
61
+ const result: ExecutionResult = {
62
+ type: 'result',
63
+ timestamp: Date.now(),
64
+ metadata
65
+ };
66
+
67
+ // Process different MIME types in order of preference
68
+
69
+ // Interactive/Rich formats
70
+ if (data['application/vnd.plotly.v1+json']) {
71
+ result.chart = extractPlotlyChart(data['application/vnd.plotly.v1+json']);
72
+ result.json = data['application/vnd.plotly.v1+json'];
73
+ }
74
+
75
+ if (data['application/vnd.vega.v5+json']) {
76
+ result.chart = extractVegaChart(data['application/vnd.vega.v5+json'], 'vega');
77
+ result.json = data['application/vnd.vega.v5+json'];
78
+ }
79
+
80
+ if (data['application/vnd.vegalite.v4+json'] || data['application/vnd.vegalite.v5+json']) {
81
+ const vegaData = data['application/vnd.vegalite.v4+json'] || data['application/vnd.vegalite.v5+json'];
82
+ result.chart = extractVegaChart(vegaData, 'vega-lite');
83
+ result.json = vegaData;
84
+ }
85
+
86
+ // HTML content (tables, formatted output)
87
+ if (data['text/html']) {
88
+ result.html = data['text/html'];
89
+
90
+ // Check if it's a pandas DataFrame
91
+ if (isPandasDataFrame(data['text/html'])) {
92
+ result.data = { type: 'dataframe', html: data['text/html'] };
93
+ }
94
+ }
95
+
96
+ // Images
97
+ if (data['image/png']) {
98
+ result.png = data['image/png'];
99
+
100
+ // Try to detect if it's a chart
101
+ if (isLikelyChart(data, metadata)) {
102
+ result.chart = {
103
+ type: 'unknown',
104
+ library: 'matplotlib',
105
+ data: { image: data['image/png'] }
106
+ };
107
+ }
108
+ }
109
+
110
+ if (data['image/jpeg']) {
111
+ result.jpeg = data['image/jpeg'];
112
+ }
113
+
114
+ if (data['image/svg+xml']) {
115
+ result.svg = data['image/svg+xml'];
116
+ }
117
+
118
+ // Mathematical content
119
+ if (data['text/latex']) {
120
+ result.latex = data['text/latex'];
121
+ }
122
+
123
+ // Code
124
+ if (data['application/javascript']) {
125
+ result.javascript = data['application/javascript'];
126
+ }
127
+
128
+ // Structured data
129
+ if (data['application/json']) {
130
+ result.json = data['application/json'];
131
+ }
132
+
133
+ // Markdown
134
+ if (data['text/markdown']) {
135
+ result.markdown = data['text/markdown'];
136
+ }
137
+
138
+ // Plain text (fallback)
139
+ if (data['text/plain']) {
140
+ result.text = data['text/plain'];
141
+ }
142
+
143
+ return result;
144
+ }
145
+
146
+ function extractPlotlyChart(plotlyData: any): ChartData {
147
+ const data = plotlyData.data || plotlyData;
148
+ const layout = plotlyData.layout || {};
149
+
150
+ // Try to detect chart type from traces
151
+ let chartType: ChartData['type'] = 'unknown';
152
+ if (data && data.length > 0) {
153
+ const firstTrace = data[0];
154
+ if (firstTrace.type === 'scatter') {
155
+ chartType = firstTrace.mode?.includes('lines') ? 'line' : 'scatter';
156
+ } else if (firstTrace.type === 'bar') {
157
+ chartType = 'bar';
158
+ } else if (firstTrace.type === 'pie') {
159
+ chartType = 'pie';
160
+ } else if (firstTrace.type === 'histogram') {
161
+ chartType = 'histogram';
162
+ } else if (firstTrace.type === 'heatmap') {
163
+ chartType = 'heatmap';
164
+ }
165
+ }
166
+
167
+ return {
168
+ type: chartType,
169
+ title: layout.title?.text || layout.title,
170
+ data: data,
171
+ layout: layout,
172
+ config: plotlyData.config,
173
+ library: 'plotly'
174
+ };
175
+ }
176
+
177
+ function extractVegaChart(vegaData: any, format: 'vega' | 'vega-lite'): ChartData {
178
+ // Try to detect chart type from mark or encoding
179
+ let chartType: ChartData['type'] = 'unknown';
180
+
181
+ if (format === 'vega-lite' && vegaData.mark) {
182
+ const mark = typeof vegaData.mark === 'string' ? vegaData.mark : vegaData.mark.type;
183
+ switch (mark) {
184
+ case 'line':
185
+ chartType = 'line';
186
+ break;
187
+ case 'bar':
188
+ chartType = 'bar';
189
+ break;
190
+ case 'point':
191
+ case 'circle':
192
+ chartType = 'scatter';
193
+ break;
194
+ case 'arc':
195
+ chartType = 'pie';
196
+ break;
197
+ case 'rect':
198
+ if (vegaData.encoding?.color) {
199
+ chartType = 'heatmap';
200
+ }
201
+ break;
202
+ }
203
+ }
204
+
205
+ return {
206
+ type: chartType,
207
+ title: vegaData.title,
208
+ data: vegaData,
209
+ library: 'altair' // Altair outputs Vega-Lite
210
+ };
211
+ }
212
+
213
+ function isPandasDataFrame(html: string): boolean {
214
+ // Simple heuristic to detect pandas DataFrame HTML
215
+ return html.includes('dataframe') ||
216
+ (html.includes('<table') && html.includes('<thead') && html.includes('<tbody'));
217
+ }
218
+
219
+ function isLikelyChart(data: any, metadata?: any): boolean {
220
+ // Check metadata for hints
221
+ if (metadata?.needs?.includes('matplotlib')) {
222
+ return true;
223
+ }
224
+
225
+ // Check if other chart formats are present
226
+ if (data['application/vnd.plotly.v1+json'] ||
227
+ data['application/vnd.vega.v5+json'] ||
228
+ data['application/vnd.vegalite.v4+json']) {
229
+ return true;
230
+ }
231
+
232
+ // If only image output without text, likely a chart
233
+ if ((data['image/png'] || data['image/svg+xml']) && !data['text/plain']) {
234
+ return true;
235
+ }
236
+
237
+ return false;
238
+ }
239
+
240
+ export function extractFormats(result: ExecutionResult): string[] {
241
+ const formats: string[] = [];
242
+
243
+ if (result.text) formats.push('text');
244
+ if (result.html) formats.push('html');
245
+ if (result.png) formats.push('png');
246
+ if (result.jpeg) formats.push('jpeg');
247
+ if (result.svg) formats.push('svg');
248
+ if (result.latex) formats.push('latex');
249
+ if (result.markdown) formats.push('markdown');
250
+ if (result.javascript) formats.push('javascript');
251
+ if (result.json) formats.push('json');
252
+ if (result.chart) formats.push('chart');
253
+
254
+ return formats;
255
+ }
@@ -5,5 +5,14 @@
5
5
  "main": "index.ts",
6
6
  "scripts": {
7
7
  "start": "bun run index.ts"
8
+ },
9
+ "dependencies": {
10
+ "@jupyterlab/services": "^7.0.0",
11
+ "ws": "^8.16.0",
12
+ "uuid": "^9.0.1"
13
+ },
14
+ "devDependencies": {
15
+ "@types/ws": "^8.5.10",
16
+ "@types/uuid": "^9.0.7"
8
17
  }
9
18
  }