@e2b/code-interpreter 0.0.9-beta.6 → 0.0.9-beta.8

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/dist/index.js CHANGED
@@ -80,6 +80,7 @@ __export(src_exports, {
80
80
  default: () => src_default
81
81
  });
82
82
  module.exports = __toCommonJS(src_exports);
83
+ __reExport(src_exports, require("e2b"), module.exports);
83
84
 
84
85
  // src/codeInterpreter.ts
85
86
  var import_e2b2 = require("e2b");
@@ -453,12 +454,11 @@ var _CodeInterpreter = class _CodeInterpreter extends import_e2b2.Sandbox {
453
454
  );
454
455
  }
455
456
  };
456
- _CodeInterpreter.defaultTemplate = "ci-no-ws";
457
+ _CodeInterpreter.defaultTemplate = "code-interpreter-stateful";
457
458
  _CodeInterpreter.jupyterPort = 49999;
458
459
  var CodeInterpreter = _CodeInterpreter;
459
460
 
460
461
  // src/index.ts
461
- __reExport(src_exports, require("e2b"), module.exports);
462
462
  var src_default = CodeInterpreter;
463
463
  // Annotate the CommonJS export names for ESM import in node:
464
464
  0 && (module.exports = {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/codeInterpreter.ts","../src/messaging.ts"],"sourcesContent":["export { CodeInterpreter, JupyterExtension } from './codeInterpreter'\n\nexport type { Logs, ExecutionError, Result, Execution, MIMEType, RawData, OutputMessage } from './messaging'\n\nimport { CodeInterpreter } from './codeInterpreter'\n\nexport * from 'e2b'\n\nexport default CodeInterpreter\n","import { ConnectionConfig, Sandbox } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError } from './messaging'\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\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 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 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 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 }),\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 try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult)\n }\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n }\n\n async createKernel({\n cwd,\n kernelName,\n requestTimeoutMs,\n }: {\n cwd?: string,\n kernelName?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<string> {\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 }\n\n async restartKernel({\n kernelID,\n requestTimeoutMs,\n }: {\n kernelID?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<void> {\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 }\n\n async shutdownKernel({\n kernelID,\n requestTimeoutMs,\n }: {\n kernelID?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<void> {\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 }\n\n async listKernels({\n requestTimeoutMs,\n }: {\n requestTimeoutMs?: number,\n } = {}): Promise<{ kernelID: string, name: string }[]> {\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 }\n}\n\nexport class CodeInterpreter extends Sandbox {\n protected static override readonly defaultTemplate: string = 'ci-no-ws'\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'\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\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\n/**\n * Dictionary that maps MIME types to their corresponding string representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n}\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 * 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.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 ].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\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({ ...msg, type: undefined, is_main_result: undefined }, msg.is_main_result)\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}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA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AAE,UAAU,OAAO,IAAI,MAAM,OAAO,KAAK,EAAE;AAAA,IAC7F;AAAA;AACF;AAlKa,kBACa,gBAAgB;AAD7B,kBAEa,kBAAkB;AAFrC,IAAM,mBAAN;AAoKA,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;;;ADpMP,wBAAc,gBANd;AAQA,IAAO,cAAQ;","names":["import_e2b","error"]}
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 { Logs, ExecutionError, Result, Execution, MIMEType, RawData, OutputMessage } from './messaging'\n\nimport { CodeInterpreter } from './codeInterpreter'\n\nexport default CodeInterpreter\n","import { ConnectionConfig, Sandbox } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError } from './messaging'\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\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 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 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 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 }),\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 try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult)\n }\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n }\n\n async createKernel({\n cwd,\n kernelName,\n requestTimeoutMs,\n }: {\n cwd?: string,\n kernelName?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<string> {\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 }\n\n async restartKernel({\n kernelID,\n requestTimeoutMs,\n }: {\n kernelID?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<void> {\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 }\n\n async shutdownKernel({\n kernelID,\n requestTimeoutMs,\n }: {\n kernelID?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<void> {\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 }\n\n async listKernels({\n requestTimeoutMs,\n }: {\n requestTimeoutMs?: number,\n } = {}): Promise<{ kernelID: string, name: string }[]> {\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 }\n}\n\nexport class CodeInterpreter extends Sandbox {\n protected static override readonly defaultTemplate: string = 'code-interpreter-stateful'\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'\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\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\n/**\n * Dictionary that maps MIME types to their corresponding string representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n}\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 * 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.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 ].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\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({ ...msg, type: undefined, is_main_result: undefined }, msg.is_main_result)\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}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAc,gBAAd;;;ACAA,IAAAA,cAA0C;;;ACA1C,iBAA0D;AAE1D,SAAsB,aAAa,KAAe;AAAA;AAChD,QAAI,IAAI,IAAI;AACV;AAAA,IACF;AAEA,YAAQ,IAAI,QAAQ;AAAA,MAClB,KAAK;AACH,eAAO,IAAI;AAAA,UACT,G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AAW,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;;;ADlMP,IAAO,cAAQ;","names":["import_e2b","error"]}
package/dist/index.mjs CHANGED
@@ -55,6 +55,9 @@ var __asyncGenerator = (__this, __arguments, generator) => {
55
55
  };
56
56
  var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it);
57
57
 
58
+ // src/index.ts
59
+ export * from "e2b";
60
+
58
61
  // src/codeInterpreter.ts
59
62
  import { Sandbox } from "e2b";
60
63
 
@@ -427,12 +430,11 @@ var _CodeInterpreter = class _CodeInterpreter extends Sandbox {
427
430
  );
428
431
  }
429
432
  };
430
- _CodeInterpreter.defaultTemplate = "ci-no-ws";
433
+ _CodeInterpreter.defaultTemplate = "code-interpreter-stateful";
431
434
  _CodeInterpreter.jupyterPort = 49999;
432
435
  var CodeInterpreter = _CodeInterpreter;
433
436
 
434
437
  // src/index.ts
435
- export * from "e2b";
436
438
  var src_default = CodeInterpreter;
437
439
  export {
438
440
  CodeInterpreter,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/codeInterpreter.ts","../src/messaging.ts","../src/index.ts"],"sourcesContent":["import { ConnectionConfig, Sandbox } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError } from './messaging'\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\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 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 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 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 }),\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 try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult)\n }\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n }\n\n async createKernel({\n cwd,\n kernelName,\n requestTimeoutMs,\n }: {\n cwd?: string,\n kernelName?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<string> {\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 }\n\n async restartKernel({\n kernelID,\n requestTimeoutMs,\n }: {\n kernelID?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<void> {\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 }\n\n async shutdownKernel({\n kernelID,\n requestTimeoutMs,\n }: {\n kernelID?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<void> {\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 }\n\n async listKernels({\n requestTimeoutMs,\n }: {\n requestTimeoutMs?: number,\n } = {}): Promise<{ kernelID: string, name: string }[]> {\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 }\n}\n\nexport class CodeInterpreter extends Sandbox {\n protected static override readonly defaultTemplate: string = 'ci-no-ws'\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'\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\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\n/**\n * Dictionary that maps MIME types to their corresponding string representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n}\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 * 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.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 ].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\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({ ...msg, type: undefined, is_main_result: undefined }, msg.is_main_result)\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}","export { CodeInterpreter, JupyterExtension } from './codeInterpreter'\n\nexport type { Logs, ExecutionError, Result, Execution, MIMEType, RawData, OutputMessage } from './messaging'\n\nimport { CodeInterpreter } from './codeInterpreter'\n\nexport * from 'e2b'\n\nexport default CodeInterpreter\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAA2B,eAAe;;;ACA1C,SAAS,eAAe,cAAc,oBAAoB;AAE1D,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,cAAc,MAAM,IAAI,KAAK,CAAC;AAAA,MAC3C;AACE,eAAO,IAAI,aAAa,GAAG,IAAI,MAAM,IAAI,IAAI,UAAU,EAAE;AAAA,IAC7D;AAAA,EACF;AAAA;AAsBO,IAAM,iBAAN,MAAqB;AAAA,EAC1B,YAIS,MAIA,OAIA,WACP;AATO;AAIA;AAIA;AAAA,EACL;AACN;AAuBO,IAAM,SAAN,MAAa;AAAA,EAgDlB,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;AACrB,SAAK,OAAO,KAAK,MAAM;AACvB,SAAK,MAAM,KAAK,KAAK;AACrB,SAAK,QAAQ,KAAK,OAAO;AACzB,SAAK,OAAO,KAAK,MAAM;AACvB,SAAK,aAAa,KAAK,YAAY;AACnC,SAAK,eAAe;AACpB,SAAK,MAAM;AAEX,SAAK,Q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C9C,WAAW;AAAA,QACX,QAAQ,KAAK,iBAAiB,UAAU,gBAAgB;AAAA,MAC1D,CAAC;AAED,YAAM,QAAQ,MAAM,aAAa,GAAG;AACpC,UAAI,OAAO;AACT,cAAM;AAAA,MACR;AAEA,cAAQ,MAAM,IAAI,KAAK,GAAG,IAAI,CAAC,YAAiB,EAAE,UAAU,OAAO,IAAI,MAAM,OAAO,KAAK,EAAE;AAAA,IAC7F;AAAA;AACF;AAlKa,kBACa,gBAAgB;AAD7B,kBAEa,kBAAkB;AAFrC,IAAM,mBAAN;AAoKA,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;;;AEpMP,cAAc;AAEd,IAAO,cAAQ;","names":["error"]}
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 { Logs, ExecutionError, Result, Execution, MIMEType, RawData, OutputMessage } from './messaging'\n\nimport { CodeInterpreter } from './codeInterpreter'\n\nexport default CodeInterpreter\n","import { ConnectionConfig, Sandbox } from 'e2b'\n\nimport { Result, Execution, OutputMessage, parseOutput, extractError } from './messaging'\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\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 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 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 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 }),\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 try {\n for await (const chunk of readLines(res.body)) {\n await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult)\n }\n } finally {\n clearTimeout(bodyTimer)\n }\n\n return execution\n }\n\n async createKernel({\n cwd,\n kernelName,\n requestTimeoutMs,\n }: {\n cwd?: string,\n kernelName?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<string> {\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 }\n\n async restartKernel({\n kernelID,\n requestTimeoutMs,\n }: {\n kernelID?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<void> {\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 }\n\n async shutdownKernel({\n kernelID,\n requestTimeoutMs,\n }: {\n kernelID?: string,\n requestTimeoutMs?: number,\n } = {}): Promise<void> {\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 }\n\n async listKernels({\n requestTimeoutMs,\n }: {\n requestTimeoutMs?: number,\n } = {}): Promise<{ kernelID: string, name: string }[]> {\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 }\n}\n\nexport class CodeInterpreter extends Sandbox {\n protected static override readonly defaultTemplate: string = 'code-interpreter-stateful'\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'\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\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\n/**\n * Dictionary that maps MIME types to their corresponding string representations of the data.\n */\nexport type RawData = {\n [key: MIMEType]: string\n}\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 * 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.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 ].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\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({ ...msg, type: undefined, is_main_result: undefined }, msg.is_main_result)\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}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,cAAc;;;ACAd,SAA2B,eAAe;;;ACA1C,SAAS,eAAe,cAAc,oBAAoB;AAE1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lKa,kBACa,gBAAgB;AAD7B,kBAEa,kBAAkB;AAFrC,IAAM,mBAAN;AAoKA,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;;;ADlMP,IAAO,cAAQ;","names":["error"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e2b/code-interpreter",
3
- "version": "0.0.9-beta.6",
3
+ "version": "0.0.9-beta.8",
4
4
  "description": "E2B Code Interpreter - Stateful code execution",
5
5
  "homepage": "https://e2b.dev",
6
6
  "license": "MIT",