@e2b/code-interpreter 0.0.9-beta.70 → 0.0.9-beta.72

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/README.md CHANGED
@@ -18,23 +18,23 @@ npm install @e2b/code-interpreter
18
18
  ### Minimal example with the sharing context
19
19
 
20
20
  ```js
21
- import { CodeInterpreter } from '@e2b/code-interpreter'
21
+ import { Sandbox } from '@e2b/code-interpreter'
22
22
 
23
- const sandbox = await CodeInterpreter.create()
24
- await sandbox.notebook.execCell('x = 1')
23
+ const sandbox = await Sandbox.create()
24
+ await sandbox.runCode('x = 1')
25
25
 
26
- const execution = await sandbox.notebook.execCell('x+=1; x')
26
+ const execution = await sandbox.runCode('x+=1; x')
27
27
  console.log(execution.text) // outputs 2
28
28
 
29
- await sandbox.close()
29
+ await sandbox.kill()
30
30
  ```
31
31
 
32
32
  ### Get charts and any display-able data
33
33
 
34
34
  ```js
35
- import { CodeInterpreter } from '@e2b/code-interpreter'
35
+ import { Sandbox } from '@e2b/code-interpreter'
36
36
 
37
- const sandbox = await CodeInterpreter.create()
37
+ const sandbox = await Sandbox.create()
38
38
 
39
39
  const code = `
40
40
  import matplotlib.pyplot as plt
@@ -48,20 +48,20 @@ plt.show()
48
48
  `
49
49
 
50
50
  // you can install dependencies in "jupyter notebook style"
51
- await sandbox.notebook.execCell('!pip install matplotlib')
51
+ await sandbox.runCode('!pip install matplotlib')
52
52
 
53
- const execution = await sandbox.notebook.execCell(code)
53
+ const execution = await sandbox.runCode(code)
54
54
 
55
55
  // this contains the image data, you can e.g. save it to file or send to frontend
56
56
  execution.results[0].png
57
57
 
58
- await sandbox.close()
58
+ await sandbox.kill()
59
59
  ```
60
60
 
61
61
  ### Streaming code output
62
62
 
63
63
  ```js
64
- import { CodeInterpreter } from '@e2b/code-interpreter'
64
+ import { Sandbox } from '@e2b/code-interpreter'
65
65
 
66
66
  const code = `
67
67
  import time
@@ -75,13 +75,13 @@ time.sleep(3)
75
75
  print("world")
76
76
  `
77
77
 
78
- const sandbox = await CodeInterpreter.create()
78
+ const sandbox = await Sandbox.create()
79
79
 
80
- await sandbox.notebook.execCell(code, {
80
+ await sandbox.runCode(code, {
81
81
  onStdout: (out) => console.log(out),
82
82
  onStderr: (outErr) => console.error(outErr),
83
83
  onResult: (result) => console.log(result.text),
84
84
  })
85
85
 
86
- await sandbox.close()
86
+ await sandbox.kill()
87
87
  ```
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { ConnectionConfig, Sandbox } from 'e2b';
1
+ import { Sandbox as Sandbox$1 } from 'e2b';
2
2
  export * from 'e2b';
3
3
 
4
4
  /**
@@ -304,22 +304,23 @@ declare class Execution {
304
304
  };
305
305
  }
306
306
 
307
+ type Context = {
308
+ id: string;
309
+ language: string;
310
+ cwd: string;
311
+ };
307
312
  /**
308
313
  * Code interpreter module for executing code in a stateful context.
309
314
  */
310
- declare class JupyterExtension {
311
- private readonly url;
312
- private readonly connectionConfig;
313
- private static readonly execTimeoutMs;
314
- private static readonly defaultKernelID;
315
- constructor(url: string, connectionConfig: ConnectionConfig);
316
- /**
317
- * Runs the code in the specified context, if not specified, the default context is used.
315
+ declare class Sandbox extends Sandbox$1 {
316
+ protected static readonly defaultTemplate: string;
317
+ /**
318
+ * Run the code for the specified language. If no language is specified, Python is used.
318
319
  * You can reference previously defined variables, imports, and functions in the code.
319
320
  *
320
321
  * @param code The code to execute
321
322
  * @param opts Options for executing the code
322
- * @param opts.kernelID The context ID to run the code in
323
+ * @param opts.language Based on the value, a default context for the language is used. If not defined, the default Python context is used.
323
324
  * @param opts.onStdout Callback for handling stdout messages
324
325
  * @param opts.onStderr Callback for handling stderr messages
325
326
  * @param opts.onResult Callback for handling the final result
@@ -328,8 +329,32 @@ declare class JupyterExtension {
328
329
  * @param opts.requestTimeoutMs Max time to wait for the request to finish
329
330
  * @returns Execution object
330
331
  */
331
- execCell(code: string, opts?: {
332
- kernelID?: string;
332
+ runCode(code: string, opts?: {
333
+ language?: string;
334
+ onStdout?: (output: OutputMessage) => (Promise<any> | any);
335
+ onStderr?: (output: OutputMessage) => (Promise<any> | any);
336
+ onResult?: (data: Result) => (Promise<any> | any);
337
+ envs?: Record<string, string>;
338
+ timeoutMs?: number;
339
+ requestTimeoutMs?: number;
340
+ }): Promise<Execution>;
341
+ /**
342
+ * Runs the code in the specified context, if not specified, the default context is used.
343
+ * You can reference previously defined variables, imports, and functions in the code.
344
+ *
345
+ * @param code The code to execute
346
+ * @param opts Options for executing the code
347
+ * @param opts.context Concrete context to run the code in. If not specified, the default Python context is used.
348
+ * @param opts.onStdout Callback for handling stdout messages
349
+ * @param opts.onStderr Callback for handling stderr messages
350
+ * @param opts.onResult Callback for handling the final result
351
+ * @param opts.envs Environment variables to set for the execution
352
+ * @param opts.timeoutMs Max time to wait for the execution to finish
353
+ * @param opts.requestTimeoutMs Max time to wait for the request to finish
354
+ * @returns Execution object
355
+ */
356
+ runCode(code: string, opts?: {
357
+ context?: Context;
333
358
  onStdout?: (output: OutputMessage) => (Promise<any> | any);
334
359
  onStderr?: (output: OutputMessage) => (Promise<any> | any);
335
360
  onResult?: (data: Result) => (Promise<any> | any);
@@ -341,56 +366,16 @@ declare class JupyterExtension {
341
366
  * Creates a new context to run code in.
342
367
  *
343
368
  * @param cwd The working directory for the context
344
- * @param kernelName The name of the context
369
+ * @param language The name of the context
345
370
  * @param requestTimeoutMs Max time to wait for the request to finish
346
371
  * @returns The context ID
347
372
  */
348
- createKernel({ cwd, kernelName, requestTimeoutMs, }?: {
373
+ createCodeContext({ cwd, language, requestTimeoutMs, }?: {
349
374
  cwd?: string;
350
- kernelName?: string;
351
- requestTimeoutMs?: number;
352
- }): Promise<string>;
353
- /**
354
- * Restarts the context.
355
- * Restarting will clear all variables, imports, and other settings set during previous executions.
356
- *
357
- * @param kernelID The context ID to restart
358
- * @param requestTimeoutMs Max time to wait for the request to finish
359
- */
360
- restartKernel({ kernelID, requestTimeoutMs, }?: {
361
- kernelID?: string;
375
+ language?: string;
362
376
  requestTimeoutMs?: number;
363
- }): Promise<void>;
364
- /**
365
- * Shuts down the context.
366
- *
367
- * @param kernelID The context ID to shut down
368
- * @param requestTimeoutMs Max time to wait for the request to finish
369
- */
370
- shutdownKernel({ kernelID, requestTimeoutMs, }?: {
371
- kernelID?: string;
372
- requestTimeoutMs?: number;
373
- }): Promise<void>;
374
- /**
375
- * Lists all available contexts.
376
- *
377
- * @param requestTimeoutMs Max time to wait for the request to finish
378
- * @returns List of context IDs and names
379
- */
380
- listKernels({ requestTimeoutMs, }?: {
381
- requestTimeoutMs?: number;
382
- }): Promise<{
383
- kernelID: string;
384
- name: string;
385
- }[]>;
386
- }
387
- /**
388
- * Code interpreter module for executing code in a stateful context.
389
- */
390
- declare class CodeInterpreter extends Sandbox {
391
- protected static readonly defaultTemplate: string;
392
- protected static readonly jupyterPort = 49999;
393
- readonly notebook: JupyterExtension;
377
+ }): Promise<Context>;
378
+ protected get jupyterUrl(): string;
394
379
  }
395
380
 
396
- export { type BarData, type BarGraph, type BoxAndWhiskerData, type BoxAndWhiskerGraph, CodeInterpreter, Execution, ExecutionError, type Graph, GraphType, type GraphTypes, JupyterExtension, type LineGraph, type Logs, type MIMEType, OutputMessage, type PieData, type PieGraph, type PointData, type RawData, Result, ScaleType, type ScatterGraph, type SuperGraph, CodeInterpreter as default };
381
+ export { type BarData, type BarGraph, type BoxAndWhiskerData, type BoxAndWhiskerGraph, type Context, Execution, ExecutionError, type Graph, GraphType, type GraphTypes, type LineGraph, type Logs, type MIMEType, OutputMessage, type PieData, type PieGraph, type PointData, type RawData, Result, Sandbox, ScaleType, type ScatterGraph, type SuperGraph, Sandbox as default };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ConnectionConfig, Sandbox } from 'e2b';
1
+ import { Sandbox as Sandbox$1 } from 'e2b';
2
2
  export * from 'e2b';
3
3
 
4
4
  /**
@@ -304,22 +304,23 @@ declare class Execution {
304
304
  };
305
305
  }
306
306
 
307
+ type Context = {
308
+ id: string;
309
+ language: string;
310
+ cwd: string;
311
+ };
307
312
  /**
308
313
  * Code interpreter module for executing code in a stateful context.
309
314
  */
310
- declare class JupyterExtension {
311
- private readonly url;
312
- private readonly connectionConfig;
313
- private static readonly execTimeoutMs;
314
- private static readonly defaultKernelID;
315
- constructor(url: string, connectionConfig: ConnectionConfig);
316
- /**
317
- * Runs the code in the specified context, if not specified, the default context is used.
315
+ declare class Sandbox extends Sandbox$1 {
316
+ protected static readonly defaultTemplate: string;
317
+ /**
318
+ * Run the code for the specified language. If no language is specified, Python is used.
318
319
  * You can reference previously defined variables, imports, and functions in the code.
319
320
  *
320
321
  * @param code The code to execute
321
322
  * @param opts Options for executing the code
322
- * @param opts.kernelID The context ID to run the code in
323
+ * @param opts.language Based on the value, a default context for the language is used. If not defined, the default Python context is used.
323
324
  * @param opts.onStdout Callback for handling stdout messages
324
325
  * @param opts.onStderr Callback for handling stderr messages
325
326
  * @param opts.onResult Callback for handling the final result
@@ -328,8 +329,32 @@ declare class JupyterExtension {
328
329
  * @param opts.requestTimeoutMs Max time to wait for the request to finish
329
330
  * @returns Execution object
330
331
  */
331
- execCell(code: string, opts?: {
332
- kernelID?: string;
332
+ runCode(code: string, opts?: {
333
+ language?: string;
334
+ onStdout?: (output: OutputMessage) => (Promise<any> | any);
335
+ onStderr?: (output: OutputMessage) => (Promise<any> | any);
336
+ onResult?: (data: Result) => (Promise<any> | any);
337
+ envs?: Record<string, string>;
338
+ timeoutMs?: number;
339
+ requestTimeoutMs?: number;
340
+ }): Promise<Execution>;
341
+ /**
342
+ * Runs the code in the specified context, if not specified, the default context is used.
343
+ * You can reference previously defined variables, imports, and functions in the code.
344
+ *
345
+ * @param code The code to execute
346
+ * @param opts Options for executing the code
347
+ * @param opts.context Concrete context to run the code in. If not specified, the default Python context is used.
348
+ * @param opts.onStdout Callback for handling stdout messages
349
+ * @param opts.onStderr Callback for handling stderr messages
350
+ * @param opts.onResult Callback for handling the final result
351
+ * @param opts.envs Environment variables to set for the execution
352
+ * @param opts.timeoutMs Max time to wait for the execution to finish
353
+ * @param opts.requestTimeoutMs Max time to wait for the request to finish
354
+ * @returns Execution object
355
+ */
356
+ runCode(code: string, opts?: {
357
+ context?: Context;
333
358
  onStdout?: (output: OutputMessage) => (Promise<any> | any);
334
359
  onStderr?: (output: OutputMessage) => (Promise<any> | any);
335
360
  onResult?: (data: Result) => (Promise<any> | any);
@@ -341,56 +366,16 @@ declare class JupyterExtension {
341
366
  * Creates a new context to run code in.
342
367
  *
343
368
  * @param cwd The working directory for the context
344
- * @param kernelName The name of the context
369
+ * @param language The name of the context
345
370
  * @param requestTimeoutMs Max time to wait for the request to finish
346
371
  * @returns The context ID
347
372
  */
348
- createKernel({ cwd, kernelName, requestTimeoutMs, }?: {
373
+ createCodeContext({ cwd, language, requestTimeoutMs, }?: {
349
374
  cwd?: string;
350
- kernelName?: string;
351
- requestTimeoutMs?: number;
352
- }): Promise<string>;
353
- /**
354
- * Restarts the context.
355
- * Restarting will clear all variables, imports, and other settings set during previous executions.
356
- *
357
- * @param kernelID The context ID to restart
358
- * @param requestTimeoutMs Max time to wait for the request to finish
359
- */
360
- restartKernel({ kernelID, requestTimeoutMs, }?: {
361
- kernelID?: string;
375
+ language?: string;
362
376
  requestTimeoutMs?: number;
363
- }): Promise<void>;
364
- /**
365
- * Shuts down the context.
366
- *
367
- * @param kernelID The context ID to shut down
368
- * @param requestTimeoutMs Max time to wait for the request to finish
369
- */
370
- shutdownKernel({ kernelID, requestTimeoutMs, }?: {
371
- kernelID?: string;
372
- requestTimeoutMs?: number;
373
- }): Promise<void>;
374
- /**
375
- * Lists all available contexts.
376
- *
377
- * @param requestTimeoutMs Max time to wait for the request to finish
378
- * @returns List of context IDs and names
379
- */
380
- listKernels({ requestTimeoutMs, }?: {
381
- requestTimeoutMs?: number;
382
- }): Promise<{
383
- kernelID: string;
384
- name: string;
385
- }[]>;
386
- }
387
- /**
388
- * Code interpreter module for executing code in a stateful context.
389
- */
390
- declare class CodeInterpreter extends Sandbox {
391
- protected static readonly defaultTemplate: string;
392
- protected static readonly jupyterPort = 49999;
393
- readonly notebook: JupyterExtension;
377
+ }): Promise<Context>;
378
+ protected get jupyterUrl(): string;
394
379
  }
395
380
 
396
- export { type BarData, type BarGraph, type BoxAndWhiskerData, type BoxAndWhiskerGraph, CodeInterpreter, Execution, ExecutionError, type Graph, GraphType, type GraphTypes, JupyterExtension, type LineGraph, type Logs, type MIMEType, OutputMessage, type PieData, type PieGraph, type PointData, type RawData, Result, ScaleType, type ScatterGraph, type SuperGraph, CodeInterpreter as default };
381
+ export { type BarData, type BarGraph, type BoxAndWhiskerData, type BoxAndWhiskerGraph, type Context, Execution, ExecutionError, type Graph, GraphType, type GraphTypes, type LineGraph, type Logs, type MIMEType, OutputMessage, type PieData, type PieGraph, type PointData, type RawData, Result, Sandbox, ScaleType, type ScatterGraph, type SuperGraph, Sandbox as default };
package/dist/index.js CHANGED
@@ -75,15 +75,14 @@ var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")])
75
75
  // src/index.ts
76
76
  var src_exports = {};
77
77
  __export(src_exports, {
78
- CodeInterpreter: () => CodeInterpreter,
79
- JupyterExtension: () => JupyterExtension,
78
+ Sandbox: () => Sandbox,
80
79
  default: () => src_default
81
80
  });
82
81
  module.exports = __toCommonJS(src_exports);
83
82
  __reExport(src_exports, require("e2b"), module.exports);
84
83
 
85
- // src/codeInterpreter.ts
86
- var import_e2b2 = require("e2b");
84
+ // src/sandbox.ts
85
+ var import_e2b3 = require("e2b");
87
86
 
88
87
  // src/messaging.ts
89
88
  var import_e2b = require("e2b");
@@ -283,7 +282,8 @@ function parseOutput(execution, line, onStdout, onStderr, onResult) {
283
282
  });
284
283
  }
285
284
 
286
- // src/codeInterpreter.ts
285
+ // src/utils.ts
286
+ var import_e2b2 = require("e2b");
287
287
  function formatRequestTimeoutError(error) {
288
288
  if (error instanceof Error && error.name === "AbortError") {
289
289
  return new import_e2b2.TimeoutError("Request timed out \u2014 the 'requestTimeoutMs' option can be used to increase this timeout");
@@ -326,43 +326,34 @@ function readLines(stream) {
326
326
  }
327
327
  });
328
328
  }
329
- var _JupyterExtension = class _JupyterExtension {
330
- constructor(url, connectionConfig) {
331
- this.url = url;
332
- this.connectionConfig = connectionConfig;
333
- }
334
- /**
335
- * Runs the code in the specified context, if not specified, the default context is used.
336
- * You can reference previously defined variables, imports, and functions in the code.
337
- *
338
- * @param code The code to execute
339
- * @param opts Options for executing the code
340
- * @param opts.kernelID The context ID to run the code in
341
- * @param opts.onStdout Callback for handling stdout messages
342
- * @param opts.onStderr Callback for handling stderr messages
343
- * @param opts.onResult Callback for handling the final result
344
- * @param opts.envs Environment variables to set for the execution
345
- * @param opts.timeoutMs Max time to wait for the execution to finish
346
- * @param opts.requestTimeoutMs Max time to wait for the request to finish
347
- * @returns Execution object
348
- */
349
- execCell(code, opts) {
329
+
330
+ // src/consts.ts
331
+ var DEFAULT_TIMEOUT_MS = 6e4;
332
+ var JUPYTER_PORT = 49999;
333
+
334
+ // src/sandbox.ts
335
+ var Sandbox = class extends import_e2b3.Sandbox {
336
+ runCode(code, opts) {
350
337
  return __async(this, null, function* () {
351
- var _a, _b;
338
+ var _a, _b, _c;
339
+ if ((opts == null ? void 0 : opts.context) && (opts == null ? void 0 : opts.language)) {
340
+ throw new import_e2b3.InvalidArgumentError("You can provide context or language, but not both at the same time.");
341
+ }
352
342
  const controller = new AbortController();
353
343
  const requestTimeout = (_a = opts == null ? void 0 : opts.requestTimeoutMs) != null ? _a : this.connectionConfig.requestTimeoutMs;
354
344
  const reqTimer = requestTimeout ? setTimeout(() => {
355
345
  controller.abort();
356
346
  }, requestTimeout) : void 0;
357
347
  try {
358
- const res = yield fetch(`${this.url}/execute`, {
348
+ const res = yield fetch(`${this.jupyterUrl}/execute`, {
359
349
  method: "POST",
360
350
  headers: {
361
351
  "Content-Type": "application/json"
362
352
  },
363
353
  body: JSON.stringify({
364
354
  code,
365
- context_id: opts == null ? void 0 : opts.kernelID,
355
+ context_id: (_b = opts == null ? void 0 : opts.context) == null ? void 0 : _b.id,
356
+ language: opts == null ? void 0 : opts.language,
366
357
  env_vars: opts == null ? void 0 : opts.envs
367
358
  }),
368
359
  signal: controller.signal,
@@ -376,7 +367,7 @@ var _JupyterExtension = class _JupyterExtension {
376
367
  throw new Error(`Not response body: ${res.statusText} ${yield res == null ? void 0 : res.text()}`);
377
368
  }
378
369
  clearTimeout(reqTimer);
379
- const bodyTimeout = (_b = opts == null ? void 0 : opts.timeoutMs) != null ? _b : _JupyterExtension.execTimeoutMs;
370
+ const bodyTimeout = (_c = opts == null ? void 0 : opts.timeoutMs) != null ? _c : DEFAULT_TIMEOUT_MS;
380
371
  const bodyTimer = bodyTimeout ? setTimeout(() => {
381
372
  controller.abort();
382
373
  }, bodyTimeout) : void 0;
@@ -412,24 +403,24 @@ var _JupyterExtension = class _JupyterExtension {
412
403
  * Creates a new context to run code in.
413
404
  *
414
405
  * @param cwd The working directory for the context
415
- * @param kernelName The name of the context
406
+ * @param language The name of the context
416
407
  * @param requestTimeoutMs Max time to wait for the request to finish
417
408
  * @returns The context ID
418
409
  */
419
- createKernel() {
410
+ createCodeContext() {
420
411
  return __async(this, arguments, function* ({
421
412
  cwd,
422
- kernelName,
413
+ language,
423
414
  requestTimeoutMs
424
415
  } = {}) {
425
416
  try {
426
- const res = yield fetch(`${this.url}/contexts`, {
417
+ const res = yield fetch(`${this.jupyterUrl}/contexts`, {
427
418
  method: "POST",
428
419
  headers: {
429
420
  "Content-Type": "application/json"
430
421
  },
431
422
  body: JSON.stringify({
432
- name: kernelName,
423
+ language,
433
424
  cwd
434
425
  }),
435
426
  keepalive: true,
@@ -439,119 +430,23 @@ var _JupyterExtension = class _JupyterExtension {
439
430
  if (error) {
440
431
  throw error;
441
432
  }
442
- const data = yield res.json();
443
- return data.id;
444
- } catch (error) {
445
- throw formatRequestTimeoutError(error);
446
- }
447
- });
448
- }
449
- /**
450
- * Restarts the context.
451
- * Restarting will clear all variables, imports, and other settings set during previous executions.
452
- *
453
- * @param kernelID The context ID to restart
454
- * @param requestTimeoutMs Max time to wait for the request to finish
455
- */
456
- restartKernel() {
457
- return __async(this, arguments, function* ({
458
- kernelID,
459
- requestTimeoutMs
460
- } = {}) {
461
- try {
462
- kernelID = kernelID || _JupyterExtension.defaultKernelID;
463
- const res = yield fetch(`${this.url}/contexts/${kernelID}/restart`, {
464
- method: "POST",
465
- headers: {
466
- "Content-Type": "application/json"
467
- },
468
- keepalive: true,
469
- signal: this.connectionConfig.getSignal(requestTimeoutMs)
470
- });
471
- const error = yield extractError(res);
472
- if (error) {
473
- throw error;
474
- }
475
- } catch (error) {
476
- throw formatRequestTimeoutError(error);
477
- }
478
- });
479
- }
480
- /**
481
- * Shuts down the context.
482
- *
483
- * @param kernelID The context ID to shut down
484
- * @param requestTimeoutMs Max time to wait for the request to finish
485
- */
486
- shutdownKernel() {
487
- return __async(this, arguments, function* ({
488
- kernelID,
489
- requestTimeoutMs
490
- } = {}) {
491
- try {
492
- kernelID = kernelID || _JupyterExtension.defaultKernelID;
493
- const res = yield fetch(`${this.url}/contexts/${kernelID}`, {
494
- method: "DELETE",
495
- keepalive: true,
496
- signal: this.connectionConfig.getSignal(requestTimeoutMs)
497
- });
498
- const error = yield extractError(res);
499
- if (error) {
500
- throw error;
501
- }
433
+ return yield res.json();
502
434
  } catch (error) {
503
435
  throw formatRequestTimeoutError(error);
504
436
  }
505
437
  });
506
438
  }
507
- /**
508
- * Lists all available contexts.
509
- *
510
- * @param requestTimeoutMs Max time to wait for the request to finish
511
- * @returns List of context IDs and names
512
- */
513
- listKernels() {
514
- return __async(this, arguments, function* ({
515
- requestTimeoutMs
516
- } = {}) {
517
- try {
518
- const res = yield fetch(`${this.url}/contexts`, {
519
- keepalive: true,
520
- signal: this.connectionConfig.getSignal(requestTimeoutMs)
521
- });
522
- const error = yield extractError(res);
523
- if (error) {
524
- throw error;
525
- }
526
- return (yield res.json()).map((kernel) => ({ kernelID: kernel.id, name: kernel.name }));
527
- } catch (error) {
528
- throw formatRequestTimeoutError(error);
529
- }
530
- });
531
- }
532
- };
533
- _JupyterExtension.execTimeoutMs = 3e5;
534
- _JupyterExtension.defaultKernelID = "default";
535
- var JupyterExtension = _JupyterExtension;
536
- var _CodeInterpreter = class _CodeInterpreter extends import_e2b2.Sandbox {
537
- constructor() {
538
- super(...arguments);
539
- this.notebook = new JupyterExtension(
540
- `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(_CodeInterpreter.jupyterPort)}`,
541
- this.connectionConfig
542
- );
439
+ get jupyterUrl() {
440
+ return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(JUPYTER_PORT)}`;
543
441
  }
544
442
  };
545
- _CodeInterpreter.defaultTemplate = "code-interpreter-beta";
546
- _CodeInterpreter.jupyterPort = 49999;
547
- var CodeInterpreter = _CodeInterpreter;
443
+ Sandbox.defaultTemplate = "code-interpreter-beta";
548
444
 
549
445
  // src/index.ts
550
- var src_default = CodeInterpreter;
446
+ var src_default = Sandbox;
551
447
  // Annotate the CommonJS export names for ESM import in node:
552
448
  0 && (module.exports = {
553
- CodeInterpreter,
554
- JupyterExtension,
449
+ Sandbox,
555
450
  ...require("e2b")
556
451
  });
557
452
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/codeInterpreter.ts","../src/messaging.ts"],"sourcesContent":["export * from 'e2b'\n\nexport { CodeInterpreter, JupyterExtension } from './codeInterpreter'\n\nexport type {\n Logs,\n ExecutionError,\n Result,\n Execution,\n MIMEType,\n RawData,\n OutputMessage,\n} from './messaging'\nexport type {\n ScaleType,\n GraphType,\n GraphTypes,\n Graph,\n BarGraph,\n BarData,\n LineGraph,\n ScatterGraph,\n BoxAndWhiskerGraph,\n BoxAndWhiskerData,\n PieGraph,\n PieData,\n SuperGraph,\n PointData,\n} from './graphs'\nimport { CodeInterpreter } from './codeInterpreter'\n\nexport default CodeInterpreter\n","import { ConnectionConfig, Sandbox, TimeoutError } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError } from './messaging'\n\nfunction formatRequestTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Request timed out — the \\'requestTimeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nfunction formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Execution timed out — the \\'timeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nasync function* readLines(stream: ReadableStream<Uint8Array>) {\n const reader = stream.getReader();\n let buffer = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (value !== undefined) {\n buffer += new TextDecoder().decode(value)\n }\n\n if (done) {\n if (buffer.length > 0) {\n yield buffer\n }\n break\n }\n\n let newlineIdx = -1\n\n do {\n newlineIdx = buffer.indexOf('\\n')\n if (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx)\n buffer = buffer.slice(newlineIdx + 1)\n }\n } while (newlineIdx !== -1)\n }\n } finally {\n reader.releaseLock()\n }\n}\n\n/**\n * Code interpreter module for executing code in a stateful context.\n */\nexport class JupyterExtension {\n private static readonly execTimeoutMs = 300_000\n private static readonly defaultKernelID = 'default'\n\n constructor(private readonly url: string, private readonly connectionConfig: ConnectionConfig) { }\n\n /**\n * Runs the code in the specified context, if not specified, the default context is used.\n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code The code to execute\n * @param opts Options for executing the code\n * @param opts.kernelID The context ID to run the code in\n * @param opts.onStdout Callback for handling stdout messages\n * @param opts.onStderr Callback for handling stderr messages\n * @param opts.onResult Callback for handling the final result\n * @param opts.envs Environment variables to set for the execution\n * @param opts.timeoutMs Max time to wait for the execution to finish\n * @param opts.requestTimeoutMs Max time to wait for the request to finish\n * @returns Execution object\n */\n async execCell(\n code: string,\n opts?: {\n kernelID?: string,\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n onResult?: (data: Result) => (Promise<any> | any),\n envs?: Record<string, string>,\n timeoutMs?: number,\n requestTimeoutMs?: number,\n },\n ): Promise<Execution> {\n const controller = new AbortController()\n\n const requestTimeout = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n try {\n const res = await fetch(`${this.url}/execute`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n code,\n context_id: opts?.kernelID,\n env_vars: opts?.envs,\n }),\n signal: controller.signal,\n keepalive: true,\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n if (!res.body) {\n throw new Error(`Not response body: ${res.statusText} ${await res?.text()}`)\n }\n\n clearTimeout(reqTimer)\n\n const bodyTimeout = opts?.timeoutMs ?? JupyterExtension.execTimeoutMs\n\n const bodyTimer = bodyTimeout\n ? setTimeout(() => {\n controller.abort()\n }, bodyTimeout)\n : undefined\n\n const execution = new Execution()\n\n\n try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult)\n }\n } catch (error) {\n throw formatExecutionTimeoutError(error)\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Creates a new context to run code in.\n *\n * @param cwd The working directory for the context\n * @param kernelName The name of the context\n * @param requestTimeoutMs Max time to wait for the request to finish\n * @returns The context ID\n */\n async createKernel({\n cwd,\n kernelName,\n requestTimeoutMs,\n }: {\n cwd?: string,\n kernelName?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<string> {\n try {\n\n const res = await fetch(`${this.url}/contexts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n name: kernelName,\n cwd,\n }),\n keepalive: true,\n signal: this.connectionConfig.getSignal(requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n const data = await res.json()\n return data.id\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Restarts the context.\n * Restarting will clear all variables, imports, and other settings set during previous executions.\n *\n * @param kernelID The context ID to restart\n * @param requestTimeoutMs Max time to wait for the request to finish\n */\n async restartKernel({\n kernelID,\n requestTimeoutMs,\n }: {\n kernelID?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<void> {\n try {\n kernelID = kernelID || JupyterExtension.defaultKernelID\n const res = await fetch(`${this.url}/contexts/${kernelID}/restart`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n keepalive: true,\n signal: this.connectionConfig.getSignal(requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Shuts down the context.\n *\n * @param kernelID The context ID to shut down\n * @param requestTimeoutMs Max time to wait for the request to finish\n */\n async shutdownKernel({\n kernelID,\n requestTimeoutMs,\n }: {\n kernelID?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<void> {\n try {\n\n kernelID = kernelID || JupyterExtension.defaultKernelID\n\n const res = await fetch(`${this.url}/contexts/${kernelID}`, {\n method: 'DELETE',\n keepalive: true,\n signal: this.connectionConfig.getSignal(requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Lists all available contexts.\n *\n * @param requestTimeoutMs Max time to wait for the request to finish\n * @returns List of context IDs and names\n */\n async listKernels({\n requestTimeoutMs,\n }: {\n requestTimeoutMs?: number,\n } = {}): Promise<{ kernelID: string, name: string }[]> {\n try {\n const res = await fetch(`${this.url}/contexts`, {\n keepalive: true,\n signal: this.connectionConfig.getSignal(requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n return (await res.json()).map((kernel: any) => ({ kernelID: kernel.id, name: kernel.name }))\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n}\n\n/**\n * Code interpreter module for executing code in a stateful context.\n */\nexport class CodeInterpreter extends Sandbox {\n protected static override readonly defaultTemplate: string = 'code-interpreter-beta'\n protected static readonly jupyterPort = 49999\n\n readonly notebook = new JupyterExtension(\n `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(CodeInterpreter.jupyterPort)}`,\n this.connectionConfig,\n )\n}\n","import { NotFoundError, SandboxError, TimeoutError } from 'e2b'\nimport { GraphTypes } from './graphs'\n\nexport async function extractError(res: Response) {\n if (res.ok) {\n return\n }\n\n switch (res.status) {\n case 502:\n return new TimeoutError(\n `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n )\n case 404:\n return new NotFoundError(await res.text())\n default:\n return new SandboxError(`${res.status} ${res.statusText}`)\n }\n}\n\nexport class OutputMessage {\n constructor(\n public readonly line: string,\n /**\n * Unix epoch in nanoseconds\n */\n public readonly timestamp: number,\n public readonly error: boolean\n ) {}\n\n public toString() {\n return this.line\n }\n}\n\n/**\n * Represents an error that occurred during the execution of a cell.\n * The error contains the name of the error, the value of the error, and the traceback.\n */\nexport class ExecutionError {\n constructor(\n /**\n * Name of the error.\n **/\n public name: string,\n /**\n * Value of the error.\n **/\n public value: string,\n /**\n * The raw traceback of the error.\n **/\n public traceback: string\n ) {}\n}\n\n/**\n * Represents a MIME type.\n */\nexport type MIMEType = string\n\ntype E2BData = {\n data: Record<string, unknown>\n graph: GraphTypes\n}\n\n/**\n * Dictionary that maps MIME types to their corresponding representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n} & E2BData\n\n/**\n * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.\n * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics\n *\n *\n * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented\n * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,\n * for the actual result the representation is always present for the result, the other representations are always optional.\n */\nexport class Result {\n /**\n * Text representation of the result.\n */\n readonly text?: string\n /**\n * HTML representation of the data.\n */\n readonly html?: string\n /**\n * Markdown representation of the data.\n */\n readonly markdown?: string\n /**\n * SVG representation of the data.\n */\n readonly svg?: string\n /**\n * PNG representation of the data.\n */\n readonly png?: string\n /**\n * JPEG representation of the data.\n */\n readonly jpeg?: string\n /**\n * PDF representation of the data.\n */\n readonly pdf?: string\n /**\n * LaTeX representation of the data.\n */\n readonly latex?: string\n /**\n * JSON representation of the data.\n */\n readonly json?: string\n /**\n * JavaScript representation of the data.\n */\n readonly javascript?: string\n /**\n * Contains the data from DataFrame.\n */\n readonly data?: Record<string, unknown>\n /**\n * Contains the graph data.\n */\n readonly graph?: GraphTypes\n /**\n * Extra data that can be included. Not part of the standard types.\n */\n readonly extra?: any\n\n readonly raw: RawData\n\n constructor(rawData: RawData, public readonly isMainResult: boolean) {\n const data = { ...rawData }\n delete data['type']\n delete data['is_main_result']\n\n this.text = data['text']\n this.html = data['html']\n this.markdown = data['markdown']\n this.svg = data['svg']\n this.png = data['png']\n this.jpeg = data['jpeg']\n this.pdf = data['pdf']\n this.latex = data['latex']\n this.json = data['json']\n this.javascript = data['javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.data = data['data']\n this.graph = data['graph']\n\n this.extra = {}\n\n for (const key of Object.keys(data)) {\n if (\n ![\n 'plain',\n 'html',\n 'markdown',\n 'svg',\n 'png',\n 'jpeg',\n 'pdf',\n 'latex',\n 'json',\n 'javascript',\n 'data',\n 'extra',\n ].includes(key)\n ) {\n this.extra[key] = data[key]\n }\n }\n }\n\n /**\n * Returns all the formats available for the result.\n *\n * @returns Array of strings representing the formats available for the result.\n */\n formats(): string[] {\n const formats = []\n if (this.html) {\n formats.push('html')\n }\n if (this.markdown) {\n formats.push('markdown')\n }\n if (this.svg) {\n formats.push('svg')\n }\n if (this.png) {\n formats.push('png')\n }\n if (this.jpeg) {\n formats.push('jpeg')\n }\n if (this.pdf) {\n formats.push('pdf')\n }\n if (this.latex) {\n formats.push('latex')\n }\n if (this.json) {\n formats.push('json')\n }\n if (this.javascript) {\n formats.push('javascript')\n }\n if (this.data) {\n formats.push('data')\n }\n\n for (const key of Object.keys(this.extra)) {\n formats.push(key)\n }\n\n return formats\n }\n\n /**\n * Returns the serializable representation of the result.\n */\n toJSON() {\n return {\n text: this.text,\n html: this.html,\n markdown: this.markdown,\n svg: this.svg,\n png: this.png,\n jpeg: this.jpeg,\n pdf: this.pdf,\n latex: this.latex,\n json: this.json,\n javascript: this.javascript,\n ...(Object.keys(this.extra).length > 0 ? { extra: this.extra } : {}),\n }\n }\n}\n\n/**\n * Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc.\n */\nexport type Logs = {\n /**\n * List of strings printed to stdout by prints, subprocesses, etc.\n */\n stdout: string[]\n /**\n * List of strings printed to stderr by prints, subprocesses, etc.\n */\n stderr: string[]\n}\n\n/**\n * Represents the result of a cell execution.\n */\nexport class Execution {\n constructor(\n /**\n * List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).\n */\n public results: Result[] = [],\n /**\n * Logs printed to stdout and stderr during execution.\n */\n public logs: Logs = { stdout: [], stderr: [] },\n /**\n * An Error object if an error occurred, null otherwise.\n */\n public error?: ExecutionError,\n /**\n * Execution count of the cell.\n */\n public executionCount?: number\n ) {}\n\n /**\n * Returns the text representation of the main result of the cell.\n */\n get text(): string | undefined {\n for (const data of this.results) {\n if (data.isMainResult) {\n return data.text\n }\n }\n }\n\n /**\n * Returns the serializable representation of the execution result.\n */\n toJSON() {\n return {\n results: this.results,\n logs: this.logs,\n error: this.error,\n }\n }\n}\n\nexport async function parseOutput(\n execution: Execution,\n line: string,\n onStdout?: (output: OutputMessage) => Promise<any> | any,\n onStderr?: (output: OutputMessage) => Promise<any> | any,\n onResult?: (data: Result) => Promise<any> | any\n) {\n const msg = JSON.parse(line)\n\n switch (msg.type) {\n case 'result':\n const result = new Result(\n { ...msg, type: undefined, is_main_result: undefined },\n msg.is_main_result\n )\n execution.results.push(result)\n if (onResult) {\n await onResult(result)\n }\n break\n case 'stdout':\n execution.logs.stdout.push(msg.text)\n if (onStdout) {\n await onStdout({\n error: false,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'stderr':\n execution.logs.stderr.push(msg.text)\n if (onStderr) {\n await onStderr({\n error: true,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'error':\n execution.error = new ExecutionError(msg.name, msg.value, msg.traceback)\n break\n case 'number_of_executions':\n execution.executionCount = msg.execution_count\n break\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAc,gBAAd;;;ACAA,IAAAA,cAAwD;;;ACAxD,iBAA0D;AAG1D,SAAsB,aAAa,KAAe;AAAA;AAChD,QAAI,IAAI,IAAI;AACV;AAAA,IACF;AAEA,YAAQ,IAAI,QAAQ;AAAA,MAClB,KAAK;AACH,eAAO,IAAI;AAAA,UACT,GAAG,MAAM,IAAI,KAAK,CAAC;AAAA,QACrB;AAAA,MACF,KAAK;AACH,eAAO,IAAI,yBAAc,MAAM,IAAI,KAAK,CAAC;AAAA,MAC3C;AACE,eAAO,IAAI,wBAAa,GAAG,IAAI,MAAM,IAAI,IAAI,UAAU,EAAE;AAAA,IAC7D;AAAA,EACF;AAAA;AAqBO,IAAM,iBAAN,MAAqB;AAAA,EAC1B,YAIS,MAIA,OAIA,WACP;AATO;AAIA;AAIA;AAAA,EACN;AACL;AA4BO,IAAM,SAAN,MAAa;AAAA,EAwDlB,YAAY,SAAkC,cAAuB;AAAvB;AAC5C,UAAM,OAAO,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,KAAK;AAAA,MACvC;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQM,cAIiD;AAAA,+CAJrC;AAAA,MAChB;AAAA,IACF,IAEI,CAAC,GAAkD;AACrD,UAAI;AACF,cAAM,MAAM,MAAM,MAAM,GAAG,KAAK,GAAG,aAAa;AAAA,UAC9C,WAAW;AAAA,UACX,QAAQ,KAAK,iBAAiB,UAAU,gBAAgB;AAAA,QAC1D,CAAC;AAED,cAAM,QAAQ,MAAM,aAAa,GAAG;AACpC,YAAI,OAAO;AACT,gBAAM;AAAA,QACR;AAEA,gBAAQ,MAAM,IAAI,KAAK,GAAG,IAAI,CAAC,YAAiB,EAAE,UAAU,OAAO,IAAI,MAAM,OAAO,KAAK,EAAE;AAAA,MAC7F,SAAS,OAAO;AACd,cAAM,0BAA0B,KAAK;AAAA,MACvC;AAAA,IACF;AAAA;AACF;AAxOa,kBACa,gBAAgB;AAD7B,kBAEa,kBAAkB;AAFrC,IAAM,mBAAN;AA6OA,IAAM,mBAAN,MAAM,yBAAwB,oBAAQ;AAAA,EAAtC;AAAA;AAIL,SAAS,WAAW,IAAI;AAAA,MACtB,GAAG,KAAK,iBAAiB,QAAQ,SAAS,OAAO,MAAM,KAAK,QAAQ,iBAAgB,WAAW,CAAC;AAAA,MAChG,KAAK;AAAA,IACP;AAAA;AACF;AARa,iBACwB,kBAA0B;AADlD,iBAEe,cAAc;AAFnC,IAAM,kBAAN;;;ADvQP,IAAO,cAAQ;","names":["import_e2b","error"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/sandbox.ts","../src/messaging.ts","../src/utils.ts","../src/consts.ts"],"sourcesContent":["export * from 'e2b'\n\nexport { Sandbox } from './sandbox'\nexport type { Context } from './sandbox'\nexport type {\n Logs,\n ExecutionError,\n Result,\n Execution,\n MIMEType,\n RawData,\n OutputMessage,\n} from './messaging'\nexport type {\n ScaleType,\n GraphType,\n GraphTypes,\n Graph,\n BarGraph,\n BarData,\n LineGraph,\n ScatterGraph,\n BoxAndWhiskerGraph,\n BoxAndWhiskerData,\n PieGraph,\n PieData,\n SuperGraph,\n PointData,\n} from './graphs'\nimport { Sandbox } from './sandbox'\n\nexport default Sandbox\n","import { Sandbox as BaseSandbox, InvalidArgumentError } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError } from './messaging'\nimport { formatExecutionTimeoutError, formatRequestTimeoutError, readLines } from \"./utils\";\nimport { JUPYTER_PORT, DEFAULT_TIMEOUT_MS } from './consts'\nexport type Context = {\n id: string\n language: string\n cwd: string\n}\n\n/**\n * Code interpreter module for executing code in a stateful context.\n */\nexport class Sandbox extends BaseSandbox {\n protected static override readonly defaultTemplate: string = 'code-interpreter-beta'\n\n /**\n * Run the code for the specified language. If no language is specified, Python is used.\n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code The code to execute\n * @param opts Options for executing the code\n * @param opts.language Based on the value, a default context for the language is used. If not defined, the default Python context is used.\n * @param opts.onStdout Callback for handling stdout messages\n * @param opts.onStderr Callback for handling stderr messages\n * @param opts.onResult Callback for handling the final result\n * @param opts.envs Environment variables to set for the execution\n * @param opts.timeoutMs Max time to wait for the execution to finish\n * @param opts.requestTimeoutMs Max time to wait for the request to finish\n * @returns Execution object\n */\nasync runCode(\n code: string,\n opts?: {\n language?: string,\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n onResult?: (data: Result) => (Promise<any> | any),\n envs?: Record<string, string>,\n timeoutMs?: number,\n requestTimeoutMs?: number,\n },\n ): Promise<Execution>\n /**\n * Runs the code in the specified context, if not specified, the default context is used.\n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code The code to execute\n * @param opts Options for executing the code\n * @param opts.context Concrete context to run the code in. If not specified, the default Python context is used.\n * @param opts.onStdout Callback for handling stdout messages\n * @param opts.onStderr Callback for handling stderr messages\n * @param opts.onResult Callback for handling the final result\n * @param opts.envs Environment variables to set for the execution\n * @param opts.timeoutMs Max time to wait for the execution to finish\n * @param opts.requestTimeoutMs Max time to wait for the request to finish\n * @returns Execution object\n */\n async runCode(\n code: string,\n opts?: {\n context?: Context,\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n onResult?: (data: Result) => (Promise<any> | any),\n envs?: Record<string, string>,\n timeoutMs?: number,\n requestTimeoutMs?: number,\n },\n ): Promise<Execution>\n async runCode(\n code: string,\n opts?: {\n language?: string,\n context?: Context,\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n onResult?: (data: Result) => (Promise<any> | any),\n envs?: Record<string, string>,\n timeoutMs?: number,\n requestTimeoutMs?: number,\n },\n ): Promise<Execution> {\n if (opts?.context && opts?.language) {\n throw new InvalidArgumentError(\"You can provide context or language, but not both at the same time.\")\n }\n\n const controller = new AbortController()\n\n const requestTimeout = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n code,\n context_id: opts?.context?.id,\n language: opts?.language,\n env_vars: opts?.envs,\n }),\n signal: controller.signal,\n keepalive: true,\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n if (!res.body) {\n throw new Error(`Not response body: ${res.statusText} ${await res?.text()}`)\n }\n\n clearTimeout(reqTimer)\n\n const bodyTimeout = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n const bodyTimer = bodyTimeout\n ? setTimeout(() => {\n controller.abort()\n }, bodyTimeout)\n : undefined\n\n const execution = new Execution()\n\n\n try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult)\n }\n } catch (error) {\n throw formatExecutionTimeoutError(error)\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Creates a new context to run code in.\n *\n * @param cwd The working directory for the context\n * @param language The name of the context\n * @param requestTimeoutMs Max time to wait for the request to finish\n * @returns The context ID\n */\n async createCodeContext({\n cwd,\n language,\n requestTimeoutMs,\n }: {\n cwd?: string,\n language?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<Context> {\n try {\n\n const res = await fetch(`${this.jupyterUrl}/contexts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n language: language,\n cwd,\n }),\n keepalive: true,\n signal: this.connectionConfig.getSignal(requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n return await res.json()\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n protected get jupyterUrl(): string {\n return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(JUPYTER_PORT)}`\n }\n}\n","import { NotFoundError, SandboxError, TimeoutError } from 'e2b'\nimport { GraphTypes } from './graphs'\n\nexport async function extractError(res: Response) {\n if (res.ok) {\n return\n }\n\n switch (res.status) {\n case 502:\n return new TimeoutError(\n `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n )\n case 404:\n return new NotFoundError(await res.text())\n default:\n return new SandboxError(`${res.status} ${res.statusText}`)\n }\n}\n\nexport class OutputMessage {\n constructor(\n public readonly line: string,\n /**\n * Unix epoch in nanoseconds\n */\n public readonly timestamp: number,\n public readonly error: boolean\n ) {}\n\n public toString() {\n return this.line\n }\n}\n\n/**\n * Represents an error that occurred during the execution of a cell.\n * The error contains the name of the error, the value of the error, and the traceback.\n */\nexport class ExecutionError {\n constructor(\n /**\n * Name of the error.\n **/\n public name: string,\n /**\n * Value of the error.\n **/\n public value: string,\n /**\n * The raw traceback of the error.\n **/\n public traceback: string\n ) {}\n}\n\n/**\n * Represents a MIME type.\n */\nexport type MIMEType = string\n\ntype E2BData = {\n data: Record<string, unknown>\n graph: GraphTypes\n}\n\n/**\n * Dictionary that maps MIME types to their corresponding representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n} & E2BData\n\n/**\n * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.\n * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics\n *\n *\n * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented\n * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,\n * for the actual result the representation is always present for the result, the other representations are always optional.\n */\nexport class Result {\n /**\n * Text representation of the result.\n */\n readonly text?: string\n /**\n * HTML representation of the data.\n */\n readonly html?: string\n /**\n * Markdown representation of the data.\n */\n readonly markdown?: string\n /**\n * SVG representation of the data.\n */\n readonly svg?: string\n /**\n * PNG representation of the data.\n */\n readonly png?: string\n /**\n * JPEG representation of the data.\n */\n readonly jpeg?: string\n /**\n * PDF representation of the data.\n */\n readonly pdf?: string\n /**\n * LaTeX representation of the data.\n */\n readonly latex?: string\n /**\n * JSON representation of the data.\n */\n readonly json?: string\n /**\n * JavaScript representation of the data.\n */\n readonly javascript?: string\n /**\n * Contains the data from DataFrame.\n */\n readonly data?: Record<string, unknown>\n /**\n * Contains the graph data.\n */\n readonly graph?: GraphTypes\n /**\n * Extra data that can be included. Not part of the standard types.\n */\n readonly extra?: any\n\n readonly raw: RawData\n\n constructor(rawData: RawData, public readonly isMainResult: boolean) {\n const data = { ...rawData }\n delete data['type']\n delete data['is_main_result']\n\n this.text = data['text']\n this.html = data['html']\n this.markdown = data['markdown']\n this.svg = data['svg']\n this.png = data['png']\n this.jpeg = data['jpeg']\n this.pdf = data['pdf']\n this.latex = data['latex']\n this.json = data['json']\n this.javascript = data['javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.data = data['data']\n this.graph = data['graph']\n\n this.extra = {}\n\n for (const key of Object.keys(data)) {\n if (\n ![\n 'plain',\n 'html',\n 'markdown',\n 'svg',\n 'png',\n 'jpeg',\n 'pdf',\n 'latex',\n 'json',\n 'javascript',\n 'data',\n 'extra',\n ].includes(key)\n ) {\n this.extra[key] = data[key]\n }\n }\n }\n\n /**\n * Returns all the formats available for the result.\n *\n * @returns Array of strings representing the formats available for the result.\n */\n formats(): string[] {\n const formats = []\n if (this.html) {\n formats.push('html')\n }\n if (this.markdown) {\n formats.push('markdown')\n }\n if (this.svg) {\n formats.push('svg')\n }\n if (this.png) {\n formats.push('png')\n }\n if (this.jpeg) {\n formats.push('jpeg')\n }\n if (this.pdf) {\n formats.push('pdf')\n }\n if (this.latex) {\n formats.push('latex')\n }\n if (this.json) {\n formats.push('json')\n }\n if (this.javascript) {\n formats.push('javascript')\n }\n if (this.data) {\n formats.push('data')\n }\n\n for (const key of Object.keys(this.extra)) {\n formats.push(key)\n }\n\n return formats\n }\n\n /**\n * Returns the serializable representation of the result.\n */\n toJSON() {\n return {\n text: this.text,\n html: this.html,\n markdown: this.markdown,\n svg: this.svg,\n png: this.png,\n jpeg: this.jpeg,\n pdf: this.pdf,\n latex: this.latex,\n json: this.json,\n javascript: this.javascript,\n ...(Object.keys(this.extra).length > 0 ? { extra: this.extra } : {}),\n }\n }\n}\n\n/**\n * Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc.\n */\nexport type Logs = {\n /**\n * List of strings printed to stdout by prints, subprocesses, etc.\n */\n stdout: string[]\n /**\n * List of strings printed to stderr by prints, subprocesses, etc.\n */\n stderr: string[]\n}\n\n/**\n * Represents the result of a cell execution.\n */\nexport class Execution {\n constructor(\n /**\n * List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).\n */\n public results: Result[] = [],\n /**\n * Logs printed to stdout and stderr during execution.\n */\n public logs: Logs = { stdout: [], stderr: [] },\n /**\n * An Error object if an error occurred, null otherwise.\n */\n public error?: ExecutionError,\n /**\n * Execution count of the cell.\n */\n public executionCount?: number\n ) {}\n\n /**\n * Returns the text representation of the main result of the cell.\n */\n get text(): string | undefined {\n for (const data of this.results) {\n if (data.isMainResult) {\n return data.text\n }\n }\n }\n\n /**\n * Returns the serializable representation of the execution result.\n */\n toJSON() {\n return {\n results: this.results,\n logs: this.logs,\n error: this.error,\n }\n }\n}\n\nexport async function parseOutput(\n execution: Execution,\n line: string,\n onStdout?: (output: OutputMessage) => Promise<any> | any,\n onStderr?: (output: OutputMessage) => Promise<any> | any,\n onResult?: (data: Result) => Promise<any> | any\n) {\n const msg = JSON.parse(line)\n\n switch (msg.type) {\n case 'result':\n const result = new Result(\n { ...msg, type: undefined, is_main_result: undefined },\n msg.is_main_result\n )\n execution.results.push(result)\n if (onResult) {\n await onResult(result)\n }\n break\n case 'stdout':\n execution.logs.stdout.push(msg.text)\n if (onStdout) {\n await onStdout({\n error: false,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'stderr':\n execution.logs.stderr.push(msg.text)\n if (onStderr) {\n await onStderr({\n error: true,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'error':\n execution.error = new ExecutionError(msg.name, msg.value, msg.traceback)\n break\n case 'number_of_executions':\n execution.executionCount = msg.execution_count\n break\n }\n}\n","import { TimeoutError } from 'e2b'\n\nexport function formatRequestTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Request timed out — the \\'requestTimeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport function formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Execution timed out — the \\'timeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport async function* readLines(stream: ReadableStream<Uint8Array>) {\n const reader = stream.getReader();\n let buffer = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (value !== undefined) {\n buffer += new TextDecoder().decode(value)\n }\n\n if (done) {\n if (buffer.length > 0) {\n yield buffer\n }\n break\n }\n\n let newlineIdx = -1\n\n do {\n newlineIdx = buffer.indexOf('\\n')\n if (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx)\n buffer = buffer.slice(newlineIdx + 1)\n }\n } while (newlineIdx !== -1)\n }\n } finally {\n reader.releaseLock()\n }\n}\n","export const DEFAULT_TIMEOUT_MS = 60_000 // 1 minute\nexport const JUPYTER_PORT = 49999\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAc,gBAAd;;;ACAA,IAAAA,cAA6D;;;ACA7D,iBAA0D;AAG1D,SAAsB,aAAa,KAAe;AAAA;AAChD,QAAI,IAAI,IAAI;AACV;AAAA,IACF;AAEA,YAAQ,IAAI,QAAQ;AAAA,MAClB,KAAK;AACH,eAAO,IAAI;AAAA,UACT,GAAG,MAAM,IAAI,KAAK,CAAC;AAAA,QACrB;AAAA,MACF,KAAK;AACH,eAAO,IAAI,yBAAc,MAAM,IAAI,KAAK,CAAC;AAAA,MAC3C;AACE,eAAO,IAAI,wBAAa,GAAG,IAAI,MAAM,IAAI,IAAI,UAAU,EAAE;AAAA,IAC7D;AAAA,EACF;AAAA;AAqBO,IAAM,iBAAN,MAAqB;AAAA,EAC1B,YAIS,MAIA,OAIA,WACP;AATO;AAIA;AAIA;AAAA,EACN;AACL;AA4BO,IAAM,SAAN,MAAa;AAAA,EAwDlB,YAAY,SAAkC,cAAuB;AAAvB;AAC5C,UAAM,OAAO,mBAAK;AAClB,WAAO,KAAK,MAAM;AAClB,WAAO,KAAK,gBAAgB;AAE5B,SAAK,OAAO,KAAK,MAAM;AACvB,SAAK,OAAO,KAAK,MAAM;AACvB,SAAK,WAAW,KAAK,UAAU;AAC/B,SAAK,MAAM,KAAK,KAAK;AACrB,SAAK,MAAM,KAAK,KAAK;A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0B,KAAK;AAAA,MACvC;AAAA,IACF;AAAA;AAAA,EAEA,IAAc,aAAqB;AACjC,WAAQ,GAAG,KAAK,iBAAiB,QAAQ,SAAS,OAAO,MAAM,KAAK,QAAQ,YAAY,CAAC;AAAA,EAC3F;AACF;AAvLa,QACwB,kBAA0B;;;ADgB/D,IAAO,cAAQ;","names":["import_e2b","import_e2b","BaseSandbox","error"]}
package/dist/index.mjs CHANGED
@@ -58,8 +58,8 @@ var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")])
58
58
  // src/index.ts
59
59
  export * from "e2b";
60
60
 
61
- // src/codeInterpreter.ts
62
- import { Sandbox, TimeoutError as TimeoutError2 } from "e2b";
61
+ // src/sandbox.ts
62
+ import { Sandbox as BaseSandbox, InvalidArgumentError } from "e2b";
63
63
 
64
64
  // src/messaging.ts
65
65
  import { NotFoundError, SandboxError, TimeoutError } from "e2b";
@@ -259,7 +259,8 @@ function parseOutput(execution, line, onStdout, onStderr, onResult) {
259
259
  });
260
260
  }
261
261
 
262
- // src/codeInterpreter.ts
262
+ // src/utils.ts
263
+ import { TimeoutError as TimeoutError2 } from "e2b";
263
264
  function formatRequestTimeoutError(error) {
264
265
  if (error instanceof Error && error.name === "AbortError") {
265
266
  return new TimeoutError2("Request timed out \u2014 the 'requestTimeoutMs' option can be used to increase this timeout");
@@ -302,43 +303,34 @@ function readLines(stream) {
302
303
  }
303
304
  });
304
305
  }
305
- var _JupyterExtension = class _JupyterExtension {
306
- constructor(url, connectionConfig) {
307
- this.url = url;
308
- this.connectionConfig = connectionConfig;
309
- }
310
- /**
311
- * Runs the code in the specified context, if not specified, the default context is used.
312
- * You can reference previously defined variables, imports, and functions in the code.
313
- *
314
- * @param code The code to execute
315
- * @param opts Options for executing the code
316
- * @param opts.kernelID The context ID to run the code in
317
- * @param opts.onStdout Callback for handling stdout messages
318
- * @param opts.onStderr Callback for handling stderr messages
319
- * @param opts.onResult Callback for handling the final result
320
- * @param opts.envs Environment variables to set for the execution
321
- * @param opts.timeoutMs Max time to wait for the execution to finish
322
- * @param opts.requestTimeoutMs Max time to wait for the request to finish
323
- * @returns Execution object
324
- */
325
- execCell(code, opts) {
306
+
307
+ // src/consts.ts
308
+ var DEFAULT_TIMEOUT_MS = 6e4;
309
+ var JUPYTER_PORT = 49999;
310
+
311
+ // src/sandbox.ts
312
+ var Sandbox = class extends BaseSandbox {
313
+ runCode(code, opts) {
326
314
  return __async(this, null, function* () {
327
- var _a, _b;
315
+ var _a, _b, _c;
316
+ if ((opts == null ? void 0 : opts.context) && (opts == null ? void 0 : opts.language)) {
317
+ throw new InvalidArgumentError("You can provide context or language, but not both at the same time.");
318
+ }
328
319
  const controller = new AbortController();
329
320
  const requestTimeout = (_a = opts == null ? void 0 : opts.requestTimeoutMs) != null ? _a : this.connectionConfig.requestTimeoutMs;
330
321
  const reqTimer = requestTimeout ? setTimeout(() => {
331
322
  controller.abort();
332
323
  }, requestTimeout) : void 0;
333
324
  try {
334
- const res = yield fetch(`${this.url}/execute`, {
325
+ const res = yield fetch(`${this.jupyterUrl}/execute`, {
335
326
  method: "POST",
336
327
  headers: {
337
328
  "Content-Type": "application/json"
338
329
  },
339
330
  body: JSON.stringify({
340
331
  code,
341
- context_id: opts == null ? void 0 : opts.kernelID,
332
+ context_id: (_b = opts == null ? void 0 : opts.context) == null ? void 0 : _b.id,
333
+ language: opts == null ? void 0 : opts.language,
342
334
  env_vars: opts == null ? void 0 : opts.envs
343
335
  }),
344
336
  signal: controller.signal,
@@ -352,7 +344,7 @@ var _JupyterExtension = class _JupyterExtension {
352
344
  throw new Error(`Not response body: ${res.statusText} ${yield res == null ? void 0 : res.text()}`);
353
345
  }
354
346
  clearTimeout(reqTimer);
355
- const bodyTimeout = (_b = opts == null ? void 0 : opts.timeoutMs) != null ? _b : _JupyterExtension.execTimeoutMs;
347
+ const bodyTimeout = (_c = opts == null ? void 0 : opts.timeoutMs) != null ? _c : DEFAULT_TIMEOUT_MS;
356
348
  const bodyTimer = bodyTimeout ? setTimeout(() => {
357
349
  controller.abort();
358
350
  }, bodyTimeout) : void 0;
@@ -388,24 +380,24 @@ var _JupyterExtension = class _JupyterExtension {
388
380
  * Creates a new context to run code in.
389
381
  *
390
382
  * @param cwd The working directory for the context
391
- * @param kernelName The name of the context
383
+ * @param language The name of the context
392
384
  * @param requestTimeoutMs Max time to wait for the request to finish
393
385
  * @returns The context ID
394
386
  */
395
- createKernel() {
387
+ createCodeContext() {
396
388
  return __async(this, arguments, function* ({
397
389
  cwd,
398
- kernelName,
390
+ language,
399
391
  requestTimeoutMs
400
392
  } = {}) {
401
393
  try {
402
- const res = yield fetch(`${this.url}/contexts`, {
394
+ const res = yield fetch(`${this.jupyterUrl}/contexts`, {
403
395
  method: "POST",
404
396
  headers: {
405
397
  "Content-Type": "application/json"
406
398
  },
407
399
  body: JSON.stringify({
408
- name: kernelName,
400
+ language,
409
401
  cwd
410
402
  }),
411
403
  keepalive: true,
@@ -415,118 +407,22 @@ var _JupyterExtension = class _JupyterExtension {
415
407
  if (error) {
416
408
  throw error;
417
409
  }
418
- const data = yield res.json();
419
- return data.id;
420
- } catch (error) {
421
- throw formatRequestTimeoutError(error);
422
- }
423
- });
424
- }
425
- /**
426
- * Restarts the context.
427
- * Restarting will clear all variables, imports, and other settings set during previous executions.
428
- *
429
- * @param kernelID The context ID to restart
430
- * @param requestTimeoutMs Max time to wait for the request to finish
431
- */
432
- restartKernel() {
433
- return __async(this, arguments, function* ({
434
- kernelID,
435
- requestTimeoutMs
436
- } = {}) {
437
- try {
438
- kernelID = kernelID || _JupyterExtension.defaultKernelID;
439
- const res = yield fetch(`${this.url}/contexts/${kernelID}/restart`, {
440
- method: "POST",
441
- headers: {
442
- "Content-Type": "application/json"
443
- },
444
- keepalive: true,
445
- signal: this.connectionConfig.getSignal(requestTimeoutMs)
446
- });
447
- const error = yield extractError(res);
448
- if (error) {
449
- throw error;
450
- }
451
- } catch (error) {
452
- throw formatRequestTimeoutError(error);
453
- }
454
- });
455
- }
456
- /**
457
- * Shuts down the context.
458
- *
459
- * @param kernelID The context ID to shut down
460
- * @param requestTimeoutMs Max time to wait for the request to finish
461
- */
462
- shutdownKernel() {
463
- return __async(this, arguments, function* ({
464
- kernelID,
465
- requestTimeoutMs
466
- } = {}) {
467
- try {
468
- kernelID = kernelID || _JupyterExtension.defaultKernelID;
469
- const res = yield fetch(`${this.url}/contexts/${kernelID}`, {
470
- method: "DELETE",
471
- keepalive: true,
472
- signal: this.connectionConfig.getSignal(requestTimeoutMs)
473
- });
474
- const error = yield extractError(res);
475
- if (error) {
476
- throw error;
477
- }
478
- } catch (error) {
479
- throw formatRequestTimeoutError(error);
480
- }
481
- });
482
- }
483
- /**
484
- * Lists all available contexts.
485
- *
486
- * @param requestTimeoutMs Max time to wait for the request to finish
487
- * @returns List of context IDs and names
488
- */
489
- listKernels() {
490
- return __async(this, arguments, function* ({
491
- requestTimeoutMs
492
- } = {}) {
493
- try {
494
- const res = yield fetch(`${this.url}/contexts`, {
495
- keepalive: true,
496
- signal: this.connectionConfig.getSignal(requestTimeoutMs)
497
- });
498
- const error = yield extractError(res);
499
- if (error) {
500
- throw error;
501
- }
502
- return (yield res.json()).map((kernel) => ({ kernelID: kernel.id, name: kernel.name }));
410
+ return yield res.json();
503
411
  } catch (error) {
504
412
  throw formatRequestTimeoutError(error);
505
413
  }
506
414
  });
507
415
  }
508
- };
509
- _JupyterExtension.execTimeoutMs = 3e5;
510
- _JupyterExtension.defaultKernelID = "default";
511
- var JupyterExtension = _JupyterExtension;
512
- var _CodeInterpreter = class _CodeInterpreter extends Sandbox {
513
- constructor() {
514
- super(...arguments);
515
- this.notebook = new JupyterExtension(
516
- `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(_CodeInterpreter.jupyterPort)}`,
517
- this.connectionConfig
518
- );
416
+ get jupyterUrl() {
417
+ return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(JUPYTER_PORT)}`;
519
418
  }
520
419
  };
521
- _CodeInterpreter.defaultTemplate = "code-interpreter-beta";
522
- _CodeInterpreter.jupyterPort = 49999;
523
- var CodeInterpreter = _CodeInterpreter;
420
+ Sandbox.defaultTemplate = "code-interpreter-beta";
524
421
 
525
422
  // src/index.ts
526
- var src_default = CodeInterpreter;
423
+ var src_default = Sandbox;
527
424
  export {
528
- CodeInterpreter,
529
- JupyterExtension,
425
+ Sandbox,
530
426
  src_default as default
531
427
  };
532
428
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/codeInterpreter.ts","../src/messaging.ts"],"sourcesContent":["export * from 'e2b'\n\nexport { CodeInterpreter, JupyterExtension } from './codeInterpreter'\n\nexport type {\n Logs,\n ExecutionError,\n Result,\n Execution,\n MIMEType,\n RawData,\n OutputMessage,\n} from './messaging'\nexport type {\n ScaleType,\n GraphType,\n GraphTypes,\n Graph,\n BarGraph,\n BarData,\n LineGraph,\n ScatterGraph,\n BoxAndWhiskerGraph,\n BoxAndWhiskerData,\n PieGraph,\n PieData,\n SuperGraph,\n PointData,\n} from './graphs'\nimport { CodeInterpreter } from './codeInterpreter'\n\nexport default CodeInterpreter\n","import { ConnectionConfig, Sandbox, TimeoutError } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError } from './messaging'\n\nfunction formatRequestTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Request timed out — the \\'requestTimeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nfunction formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Execution timed out — the \\'timeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nasync function* readLines(stream: ReadableStream<Uint8Array>) {\n const reader = stream.getReader();\n let buffer = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (value !== undefined) {\n buffer += new TextDecoder().decode(value)\n }\n\n if (done) {\n if (buffer.length > 0) {\n yield buffer\n }\n break\n }\n\n let newlineIdx = -1\n\n do {\n newlineIdx = buffer.indexOf('\\n')\n if (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx)\n buffer = buffer.slice(newlineIdx + 1)\n }\n } while (newlineIdx !== -1)\n }\n } finally {\n reader.releaseLock()\n }\n}\n\n/**\n * Code interpreter module for executing code in a stateful context.\n */\nexport class JupyterExtension {\n private static readonly execTimeoutMs = 300_000\n private static readonly defaultKernelID = 'default'\n\n constructor(private readonly url: string, private readonly connectionConfig: ConnectionConfig) { }\n\n /**\n * Runs the code in the specified context, if not specified, the default context is used.\n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code The code to execute\n * @param opts Options for executing the code\n * @param opts.kernelID The context ID to run the code in\n * @param opts.onStdout Callback for handling stdout messages\n * @param opts.onStderr Callback for handling stderr messages\n * @param opts.onResult Callback for handling the final result\n * @param opts.envs Environment variables to set for the execution\n * @param opts.timeoutMs Max time to wait for the execution to finish\n * @param opts.requestTimeoutMs Max time to wait for the request to finish\n * @returns Execution object\n */\n async execCell(\n code: string,\n opts?: {\n kernelID?: string,\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n onResult?: (data: Result) => (Promise<any> | any),\n envs?: Record<string, string>,\n timeoutMs?: number,\n requestTimeoutMs?: number,\n },\n ): Promise<Execution> {\n const controller = new AbortController()\n\n const requestTimeout = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n try {\n const res = await fetch(`${this.url}/execute`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n code,\n context_id: opts?.kernelID,\n env_vars: opts?.envs,\n }),\n signal: controller.signal,\n keepalive: true,\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n if (!res.body) {\n throw new Error(`Not response body: ${res.statusText} ${await res?.text()}`)\n }\n\n clearTimeout(reqTimer)\n\n const bodyTimeout = opts?.timeoutMs ?? JupyterExtension.execTimeoutMs\n\n const bodyTimer = bodyTimeout\n ? setTimeout(() => {\n controller.abort()\n }, bodyTimeout)\n : undefined\n\n const execution = new Execution()\n\n\n try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult)\n }\n } catch (error) {\n throw formatExecutionTimeoutError(error)\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Creates a new context to run code in.\n *\n * @param cwd The working directory for the context\n * @param kernelName The name of the context\n * @param requestTimeoutMs Max time to wait for the request to finish\n * @returns The context ID\n */\n async createKernel({\n cwd,\n kernelName,\n requestTimeoutMs,\n }: {\n cwd?: string,\n kernelName?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<string> {\n try {\n\n const res = await fetch(`${this.url}/contexts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n name: kernelName,\n cwd,\n }),\n keepalive: true,\n signal: this.connectionConfig.getSignal(requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n const data = await res.json()\n return data.id\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Restarts the context.\n * Restarting will clear all variables, imports, and other settings set during previous executions.\n *\n * @param kernelID The context ID to restart\n * @param requestTimeoutMs Max time to wait for the request to finish\n */\n async restartKernel({\n kernelID,\n requestTimeoutMs,\n }: {\n kernelID?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<void> {\n try {\n kernelID = kernelID || JupyterExtension.defaultKernelID\n const res = await fetch(`${this.url}/contexts/${kernelID}/restart`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n keepalive: true,\n signal: this.connectionConfig.getSignal(requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Shuts down the context.\n *\n * @param kernelID The context ID to shut down\n * @param requestTimeoutMs Max time to wait for the request to finish\n */\n async shutdownKernel({\n kernelID,\n requestTimeoutMs,\n }: {\n kernelID?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<void> {\n try {\n\n kernelID = kernelID || JupyterExtension.defaultKernelID\n\n const res = await fetch(`${this.url}/contexts/${kernelID}`, {\n method: 'DELETE',\n keepalive: true,\n signal: this.connectionConfig.getSignal(requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Lists all available contexts.\n *\n * @param requestTimeoutMs Max time to wait for the request to finish\n * @returns List of context IDs and names\n */\n async listKernels({\n requestTimeoutMs,\n }: {\n requestTimeoutMs?: number,\n } = {}): Promise<{ kernelID: string, name: string }[]> {\n try {\n const res = await fetch(`${this.url}/contexts`, {\n keepalive: true,\n signal: this.connectionConfig.getSignal(requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n return (await res.json()).map((kernel: any) => ({ kernelID: kernel.id, name: kernel.name }))\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n}\n\n/**\n * Code interpreter module for executing code in a stateful context.\n */\nexport class CodeInterpreter extends Sandbox {\n protected static override readonly defaultTemplate: string = 'code-interpreter-beta'\n protected static readonly jupyterPort = 49999\n\n readonly notebook = new JupyterExtension(\n `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(CodeInterpreter.jupyterPort)}`,\n this.connectionConfig,\n )\n}\n","import { NotFoundError, SandboxError, TimeoutError } from 'e2b'\nimport { GraphTypes } from './graphs'\n\nexport async function extractError(res: Response) {\n if (res.ok) {\n return\n }\n\n switch (res.status) {\n case 502:\n return new TimeoutError(\n `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n )\n case 404:\n return new NotFoundError(await res.text())\n default:\n return new SandboxError(`${res.status} ${res.statusText}`)\n }\n}\n\nexport class OutputMessage {\n constructor(\n public readonly line: string,\n /**\n * Unix epoch in nanoseconds\n */\n public readonly timestamp: number,\n public readonly error: boolean\n ) {}\n\n public toString() {\n return this.line\n }\n}\n\n/**\n * Represents an error that occurred during the execution of a cell.\n * The error contains the name of the error, the value of the error, and the traceback.\n */\nexport class ExecutionError {\n constructor(\n /**\n * Name of the error.\n **/\n public name: string,\n /**\n * Value of the error.\n **/\n public value: string,\n /**\n * The raw traceback of the error.\n **/\n public traceback: string\n ) {}\n}\n\n/**\n * Represents a MIME type.\n */\nexport type MIMEType = string\n\ntype E2BData = {\n data: Record<string, unknown>\n graph: GraphTypes\n}\n\n/**\n * Dictionary that maps MIME types to their corresponding representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n} & E2BData\n\n/**\n * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.\n * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics\n *\n *\n * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented\n * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,\n * for the actual result the representation is always present for the result, the other representations are always optional.\n */\nexport class Result {\n /**\n * Text representation of the result.\n */\n readonly text?: string\n /**\n * HTML representation of the data.\n */\n readonly html?: string\n /**\n * Markdown representation of the data.\n */\n readonly markdown?: string\n /**\n * SVG representation of the data.\n */\n readonly svg?: string\n /**\n * PNG representation of the data.\n */\n readonly png?: string\n /**\n * JPEG representation of the data.\n */\n readonly jpeg?: string\n /**\n * PDF representation of the data.\n */\n readonly pdf?: string\n /**\n * LaTeX representation of the data.\n */\n readonly latex?: string\n /**\n * JSON representation of the data.\n */\n readonly json?: string\n /**\n * JavaScript representation of the data.\n */\n readonly javascript?: string\n /**\n * Contains the data from DataFrame.\n */\n readonly data?: Record<string, unknown>\n /**\n * Contains the graph data.\n */\n readonly graph?: GraphTypes\n /**\n * Extra data that can be included. Not part of the standard types.\n */\n readonly extra?: any\n\n readonly raw: RawData\n\n constructor(rawData: RawData, public readonly isMainResult: boolean) {\n const data = { ...rawData }\n delete data['type']\n delete data['is_main_result']\n\n this.text = data['text']\n this.html = data['html']\n this.markdown = data['markdown']\n this.svg = data['svg']\n this.png = data['png']\n this.jpeg = data['jpeg']\n this.pdf = data['pdf']\n this.latex = data['latex']\n this.json = data['json']\n this.javascript = data['javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.data = data['data']\n this.graph = data['graph']\n\n this.extra = {}\n\n for (const key of Object.keys(data)) {\n if (\n ![\n 'plain',\n 'html',\n 'markdown',\n 'svg',\n 'png',\n 'jpeg',\n 'pdf',\n 'latex',\n 'json',\n 'javascript',\n 'data',\n 'extra',\n ].includes(key)\n ) {\n this.extra[key] = data[key]\n }\n }\n }\n\n /**\n * Returns all the formats available for the result.\n *\n * @returns Array of strings representing the formats available for the result.\n */\n formats(): string[] {\n const formats = []\n if (this.html) {\n formats.push('html')\n }\n if (this.markdown) {\n formats.push('markdown')\n }\n if (this.svg) {\n formats.push('svg')\n }\n if (this.png) {\n formats.push('png')\n }\n if (this.jpeg) {\n formats.push('jpeg')\n }\n if (this.pdf) {\n formats.push('pdf')\n }\n if (this.latex) {\n formats.push('latex')\n }\n if (this.json) {\n formats.push('json')\n }\n if (this.javascript) {\n formats.push('javascript')\n }\n if (this.data) {\n formats.push('data')\n }\n\n for (const key of Object.keys(this.extra)) {\n formats.push(key)\n }\n\n return formats\n }\n\n /**\n * Returns the serializable representation of the result.\n */\n toJSON() {\n return {\n text: this.text,\n html: this.html,\n markdown: this.markdown,\n svg: this.svg,\n png: this.png,\n jpeg: this.jpeg,\n pdf: this.pdf,\n latex: this.latex,\n json: this.json,\n javascript: this.javascript,\n ...(Object.keys(this.extra).length > 0 ? { extra: this.extra } : {}),\n }\n }\n}\n\n/**\n * Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc.\n */\nexport type Logs = {\n /**\n * List of strings printed to stdout by prints, subprocesses, etc.\n */\n stdout: string[]\n /**\n * List of strings printed to stderr by prints, subprocesses, etc.\n */\n stderr: string[]\n}\n\n/**\n * Represents the result of a cell execution.\n */\nexport class Execution {\n constructor(\n /**\n * List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).\n */\n public results: Result[] = [],\n /**\n * Logs printed to stdout and stderr during execution.\n */\n public logs: Logs = { stdout: [], stderr: [] },\n /**\n * An Error object if an error occurred, null otherwise.\n */\n public error?: ExecutionError,\n /**\n * Execution count of the cell.\n */\n public executionCount?: number\n ) {}\n\n /**\n * Returns the text representation of the main result of the cell.\n */\n get text(): string | undefined {\n for (const data of this.results) {\n if (data.isMainResult) {\n return data.text\n }\n }\n }\n\n /**\n * Returns the serializable representation of the execution result.\n */\n toJSON() {\n return {\n results: this.results,\n logs: this.logs,\n error: this.error,\n }\n }\n}\n\nexport async function parseOutput(\n execution: Execution,\n line: string,\n onStdout?: (output: OutputMessage) => Promise<any> | any,\n onStderr?: (output: OutputMessage) => Promise<any> | any,\n onResult?: (data: Result) => Promise<any> | any\n) {\n const msg = JSON.parse(line)\n\n switch (msg.type) {\n case 'result':\n const result = new Result(\n { ...msg, type: undefined, is_main_result: undefined },\n msg.is_main_result\n )\n execution.results.push(result)\n if (onResult) {\n await onResult(result)\n }\n break\n case 'stdout':\n execution.logs.stdout.push(msg.text)\n if (onStdout) {\n await onStdout({\n error: false,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'stderr':\n execution.logs.stderr.push(msg.text)\n if (onStderr) {\n await onStderr({\n error: true,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'error':\n execution.error = new ExecutionError(msg.name, msg.value, msg.traceback)\n break\n case 'number_of_executions':\n execution.executionCount = msg.execution_count\n break\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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BACa,gBAAgB;AAD7B,kBAEa,kBAAkB;AAFrC,IAAM,mBAAN;AA6OA,IAAM,mBAAN,MAAM,yBAAwB,QAAQ;AAAA,EAAtC;AAAA;AAIL,SAAS,WAAW,IAAI;AAAA,MACtB,GAAG,KAAK,iBAAiB,QAAQ,SAAS,OAAO,MAAM,KAAK,QAAQ,iBAAgB,WAAW,CAAC;AAAA,MAChG,KAAK;AAAA,IACP;AAAA;AACF;AARa,iBACwB,kBAA0B;AADlD,iBAEe,cAAc;AAFnC,IAAM,kBAAN;;;ADvQP,IAAO,cAAQ;","names":["TimeoutError","TimeoutError","error"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/sandbox.ts","../src/messaging.ts","../src/utils.ts","../src/consts.ts"],"sourcesContent":["export * from 'e2b'\n\nexport { Sandbox } from './sandbox'\nexport type { Context } from './sandbox'\nexport type {\n Logs,\n ExecutionError,\n Result,\n Execution,\n MIMEType,\n RawData,\n OutputMessage,\n} from './messaging'\nexport type {\n ScaleType,\n GraphType,\n GraphTypes,\n Graph,\n BarGraph,\n BarData,\n LineGraph,\n ScatterGraph,\n BoxAndWhiskerGraph,\n BoxAndWhiskerData,\n PieGraph,\n PieData,\n SuperGraph,\n PointData,\n} from './graphs'\nimport { Sandbox } from './sandbox'\n\nexport default Sandbox\n","import { Sandbox as BaseSandbox, InvalidArgumentError } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError } from './messaging'\nimport { formatExecutionTimeoutError, formatRequestTimeoutError, readLines } from \"./utils\";\nimport { JUPYTER_PORT, DEFAULT_TIMEOUT_MS } from './consts'\nexport type Context = {\n id: string\n language: string\n cwd: string\n}\n\n/**\n * Code interpreter module for executing code in a stateful context.\n */\nexport class Sandbox extends BaseSandbox {\n protected static override readonly defaultTemplate: string = 'code-interpreter-beta'\n\n /**\n * Run the code for the specified language. If no language is specified, Python is used.\n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code The code to execute\n * @param opts Options for executing the code\n * @param opts.language Based on the value, a default context for the language is used. If not defined, the default Python context is used.\n * @param opts.onStdout Callback for handling stdout messages\n * @param opts.onStderr Callback for handling stderr messages\n * @param opts.onResult Callback for handling the final result\n * @param opts.envs Environment variables to set for the execution\n * @param opts.timeoutMs Max time to wait for the execution to finish\n * @param opts.requestTimeoutMs Max time to wait for the request to finish\n * @returns Execution object\n */\nasync runCode(\n code: string,\n opts?: {\n language?: string,\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n onResult?: (data: Result) => (Promise<any> | any),\n envs?: Record<string, string>,\n timeoutMs?: number,\n requestTimeoutMs?: number,\n },\n ): Promise<Execution>\n /**\n * Runs the code in the specified context, if not specified, the default context is used.\n * You can reference previously defined variables, imports, and functions in the code.\n *\n * @param code The code to execute\n * @param opts Options for executing the code\n * @param opts.context Concrete context to run the code in. If not specified, the default Python context is used.\n * @param opts.onStdout Callback for handling stdout messages\n * @param opts.onStderr Callback for handling stderr messages\n * @param opts.onResult Callback for handling the final result\n * @param opts.envs Environment variables to set for the execution\n * @param opts.timeoutMs Max time to wait for the execution to finish\n * @param opts.requestTimeoutMs Max time to wait for the request to finish\n * @returns Execution object\n */\n async runCode(\n code: string,\n opts?: {\n context?: Context,\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n onResult?: (data: Result) => (Promise<any> | any),\n envs?: Record<string, string>,\n timeoutMs?: number,\n requestTimeoutMs?: number,\n },\n ): Promise<Execution>\n async runCode(\n code: string,\n opts?: {\n language?: string,\n context?: Context,\n onStdout?: (output: OutputMessage) => (Promise<any> | any),\n onStderr?: (output: OutputMessage) => (Promise<any> | any),\n onResult?: (data: Result) => (Promise<any> | any),\n envs?: Record<string, string>,\n timeoutMs?: number,\n requestTimeoutMs?: number,\n },\n ): Promise<Execution> {\n if (opts?.context && opts?.language) {\n throw new InvalidArgumentError(\"You can provide context or language, but not both at the same time.\")\n }\n\n const controller = new AbortController()\n\n const requestTimeout = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs\n\n const reqTimer = requestTimeout ? setTimeout(() => {\n controller.abort()\n }, requestTimeout)\n : undefined\n\n try {\n const res = await fetch(`${this.jupyterUrl}/execute`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n code,\n context_id: opts?.context?.id,\n language: opts?.language,\n env_vars: opts?.envs,\n }),\n signal: controller.signal,\n keepalive: true,\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n if (!res.body) {\n throw new Error(`Not response body: ${res.statusText} ${await res?.text()}`)\n }\n\n clearTimeout(reqTimer)\n\n const bodyTimeout = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n const bodyTimer = bodyTimeout\n ? setTimeout(() => {\n controller.abort()\n }, bodyTimeout)\n : undefined\n\n const execution = new Execution()\n\n\n try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult)\n }\n } catch (error) {\n throw formatExecutionTimeoutError(error)\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n /**\n * Creates a new context to run code in.\n *\n * @param cwd The working directory for the context\n * @param language The name of the context\n * @param requestTimeoutMs Max time to wait for the request to finish\n * @returns The context ID\n */\n async createCodeContext({\n cwd,\n language,\n requestTimeoutMs,\n }: {\n cwd?: string,\n language?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<Context> {\n try {\n\n const res = await fetch(`${this.jupyterUrl}/contexts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n language: language,\n cwd,\n }),\n keepalive: true,\n signal: this.connectionConfig.getSignal(requestTimeoutMs),\n })\n\n const error = await extractError(res)\n if (error) {\n throw error\n }\n\n return await res.json()\n } catch (error) {\n throw formatRequestTimeoutError(error)\n }\n }\n\n protected get jupyterUrl(): string {\n return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(JUPYTER_PORT)}`\n }\n}\n","import { NotFoundError, SandboxError, TimeoutError } from 'e2b'\nimport { GraphTypes } from './graphs'\n\nexport async function extractError(res: Response) {\n if (res.ok) {\n return\n }\n\n switch (res.status) {\n case 502:\n return new TimeoutError(\n `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`\n )\n case 404:\n return new NotFoundError(await res.text())\n default:\n return new SandboxError(`${res.status} ${res.statusText}`)\n }\n}\n\nexport class OutputMessage {\n constructor(\n public readonly line: string,\n /**\n * Unix epoch in nanoseconds\n */\n public readonly timestamp: number,\n public readonly error: boolean\n ) {}\n\n public toString() {\n return this.line\n }\n}\n\n/**\n * Represents an error that occurred during the execution of a cell.\n * The error contains the name of the error, the value of the error, and the traceback.\n */\nexport class ExecutionError {\n constructor(\n /**\n * Name of the error.\n **/\n public name: string,\n /**\n * Value of the error.\n **/\n public value: string,\n /**\n * The raw traceback of the error.\n **/\n public traceback: string\n ) {}\n}\n\n/**\n * Represents a MIME type.\n */\nexport type MIMEType = string\n\ntype E2BData = {\n data: Record<string, unknown>\n graph: GraphTypes\n}\n\n/**\n * Dictionary that maps MIME types to their corresponding representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n} & E2BData\n\n/**\n * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook.\n * The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics\n *\n *\n * The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented\n * as a string, and the result can contain multiple types of data. The display calls don't have to have text representation,\n * for the actual result the representation is always present for the result, the other representations are always optional.\n */\nexport class Result {\n /**\n * Text representation of the result.\n */\n readonly text?: string\n /**\n * HTML representation of the data.\n */\n readonly html?: string\n /**\n * Markdown representation of the data.\n */\n readonly markdown?: string\n /**\n * SVG representation of the data.\n */\n readonly svg?: string\n /**\n * PNG representation of the data.\n */\n readonly png?: string\n /**\n * JPEG representation of the data.\n */\n readonly jpeg?: string\n /**\n * PDF representation of the data.\n */\n readonly pdf?: string\n /**\n * LaTeX representation of the data.\n */\n readonly latex?: string\n /**\n * JSON representation of the data.\n */\n readonly json?: string\n /**\n * JavaScript representation of the data.\n */\n readonly javascript?: string\n /**\n * Contains the data from DataFrame.\n */\n readonly data?: Record<string, unknown>\n /**\n * Contains the graph data.\n */\n readonly graph?: GraphTypes\n /**\n * Extra data that can be included. Not part of the standard types.\n */\n readonly extra?: any\n\n readonly raw: RawData\n\n constructor(rawData: RawData, public readonly isMainResult: boolean) {\n const data = { ...rawData }\n delete data['type']\n delete data['is_main_result']\n\n this.text = data['text']\n this.html = data['html']\n this.markdown = data['markdown']\n this.svg = data['svg']\n this.png = data['png']\n this.jpeg = data['jpeg']\n this.pdf = data['pdf']\n this.latex = data['latex']\n this.json = data['json']\n this.javascript = data['javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.data = data['data']\n this.graph = data['graph']\n\n this.extra = {}\n\n for (const key of Object.keys(data)) {\n if (\n ![\n 'plain',\n 'html',\n 'markdown',\n 'svg',\n 'png',\n 'jpeg',\n 'pdf',\n 'latex',\n 'json',\n 'javascript',\n 'data',\n 'extra',\n ].includes(key)\n ) {\n this.extra[key] = data[key]\n }\n }\n }\n\n /**\n * Returns all the formats available for the result.\n *\n * @returns Array of strings representing the formats available for the result.\n */\n formats(): string[] {\n const formats = []\n if (this.html) {\n formats.push('html')\n }\n if (this.markdown) {\n formats.push('markdown')\n }\n if (this.svg) {\n formats.push('svg')\n }\n if (this.png) {\n formats.push('png')\n }\n if (this.jpeg) {\n formats.push('jpeg')\n }\n if (this.pdf) {\n formats.push('pdf')\n }\n if (this.latex) {\n formats.push('latex')\n }\n if (this.json) {\n formats.push('json')\n }\n if (this.javascript) {\n formats.push('javascript')\n }\n if (this.data) {\n formats.push('data')\n }\n\n for (const key of Object.keys(this.extra)) {\n formats.push(key)\n }\n\n return formats\n }\n\n /**\n * Returns the serializable representation of the result.\n */\n toJSON() {\n return {\n text: this.text,\n html: this.html,\n markdown: this.markdown,\n svg: this.svg,\n png: this.png,\n jpeg: this.jpeg,\n pdf: this.pdf,\n latex: this.latex,\n json: this.json,\n javascript: this.javascript,\n ...(Object.keys(this.extra).length > 0 ? { extra: this.extra } : {}),\n }\n }\n}\n\n/**\n * Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc.\n */\nexport type Logs = {\n /**\n * List of strings printed to stdout by prints, subprocesses, etc.\n */\n stdout: string[]\n /**\n * List of strings printed to stderr by prints, subprocesses, etc.\n */\n stderr: string[]\n}\n\n/**\n * Represents the result of a cell execution.\n */\nexport class Execution {\n constructor(\n /**\n * List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).\n */\n public results: Result[] = [],\n /**\n * Logs printed to stdout and stderr during execution.\n */\n public logs: Logs = { stdout: [], stderr: [] },\n /**\n * An Error object if an error occurred, null otherwise.\n */\n public error?: ExecutionError,\n /**\n * Execution count of the cell.\n */\n public executionCount?: number\n ) {}\n\n /**\n * Returns the text representation of the main result of the cell.\n */\n get text(): string | undefined {\n for (const data of this.results) {\n if (data.isMainResult) {\n return data.text\n }\n }\n }\n\n /**\n * Returns the serializable representation of the execution result.\n */\n toJSON() {\n return {\n results: this.results,\n logs: this.logs,\n error: this.error,\n }\n }\n}\n\nexport async function parseOutput(\n execution: Execution,\n line: string,\n onStdout?: (output: OutputMessage) => Promise<any> | any,\n onStderr?: (output: OutputMessage) => Promise<any> | any,\n onResult?: (data: Result) => Promise<any> | any\n) {\n const msg = JSON.parse(line)\n\n switch (msg.type) {\n case 'result':\n const result = new Result(\n { ...msg, type: undefined, is_main_result: undefined },\n msg.is_main_result\n )\n execution.results.push(result)\n if (onResult) {\n await onResult(result)\n }\n break\n case 'stdout':\n execution.logs.stdout.push(msg.text)\n if (onStdout) {\n await onStdout({\n error: false,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'stderr':\n execution.logs.stderr.push(msg.text)\n if (onStderr) {\n await onStderr({\n error: true,\n line: msg.text,\n timestamp: new Date().getTime() * 1000,\n })\n }\n break\n case 'error':\n execution.error = new ExecutionError(msg.name, msg.value, msg.traceback)\n break\n case 'number_of_executions':\n execution.executionCount = msg.execution_count\n break\n }\n}\n","import { TimeoutError } from 'e2b'\n\nexport function formatRequestTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Request timed out — the \\'requestTimeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport function formatExecutionTimeoutError(error: unknown) {\n if (error instanceof Error && error.name === 'AbortError') {\n return new TimeoutError('Execution timed out — the \\'timeoutMs\\' option can be used to increase this timeout')\n }\n\n return error\n}\n\nexport async function* readLines(stream: ReadableStream<Uint8Array>) {\n const reader = stream.getReader();\n let buffer = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (value !== undefined) {\n buffer += new TextDecoder().decode(value)\n }\n\n if (done) {\n if (buffer.length > 0) {\n yield buffer\n }\n break\n }\n\n let newlineIdx = -1\n\n do {\n newlineIdx = buffer.indexOf('\\n')\n if (newlineIdx !== -1) {\n yield buffer.slice(0, newlineIdx)\n buffer = buffer.slice(newlineIdx + 1)\n }\n } while (newlineIdx !== -1)\n }\n } finally {\n reader.releaseLock()\n }\n}\n","export const DEFAULT_TIMEOUT_MS = 60_000 // 1 minute\nexport const JUPYTER_PORT = 49999\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,cAAc;;;ACAd,SAAS,WAAW,aAAa,4BAA4B;;;ACA7D,SAAS,eAAe,cAAc,oBAAoB;AAG1D,SAAsB,aAAa,KAAe;AAAA;AAChD,QAAI,IAAI,IAAI;AACV;AAAA,IACF;AAEA,YAAQ,IAAI,QAAQ;AAAA,MAClB,KAAK;AACH,eA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AACd,cAAM,0BAA0BA,MAAK;AAAA,MACvC;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUM,oBAQoB;AAAA,+CARF;AAAA,MACtB;AAAA,MACA;AAAA,MACA;AAAA,IACF,IAII,CAAC,GAAqB;AACxB,UAAI;AAEF,cAAM,MAAM,MAAM,MAAM,GAAG,KAAK,UAAU,aAAa;AAAA,UACrD,QAAQ;AAAA,UACR,SAAS;AAAA,YACP,gBAAgB;AAAA,UAClB;AAAA,UACA,MAAM,KAAK,UAAU;AAAA,YACnB;AAAA,YACA;AAAA,UACF,CAAC;AAAA,UACD,WAAW;AAAA,UACX,QAAQ,KAAK,iBAAiB,UAAU,gBAAgB;AAAA,QAC1D,CAAC;AAED,cAAM,QAAQ,MAAM,aAAa,GAAG;AACpC,YAAI,OAAO;AACT,gBAAM;AAAA,QACR;AAEA,eAAO,MAAM,IAAI,KAAK;AAAA,MACxB,SAAS,OAAO;AACd,cAAM,0BAA0B,KAAK;AAAA,MACvC;AAAA,IACF;AAAA;AAAA,EAEA,IAAc,aAAqB;AACjC,WAAQ,GAAG,KAAK,iBAAiB,QAAQ,SAAS,OAAO,MAAM,KAAK,QAAQ,YAAY,CAAC;AAAA,EAC3F;AACF;AAvLa,QACwB,kBAA0B;;;ADgB/D,IAAO,cAAQ;","names":["TimeoutError","TimeoutError","error"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e2b/code-interpreter",
3
- "version": "0.0.9-beta.70",
3
+ "version": "0.0.9-beta.72",
4
4
  "description": "E2B Code Interpreter - Stateful code execution",
5
5
  "homepage": "https://e2b.dev",
6
6
  "license": "MIT",