@e2b/code-interpreter 0.0.8-multikernel-code-interpreterer.1 → 0.0.9-multikernel-code-interpreterer.0
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.d.ts +8 -4
- package/dist/index.js +9 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +9 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -252,12 +252,16 @@ declare class JupyterExtension {
|
|
|
252
252
|
* Once the kernel is created, this method establishes a WebSocket connection to the new kernel for
|
|
253
253
|
* real-time communication.
|
|
254
254
|
*
|
|
255
|
-
* @param cwd Sets the current working directory where the kernel should start. Defaults to "/home/user".
|
|
256
|
-
* @param kernelName The name of the kernel to create, useful if you have multiple kernel types. If not provided, the default kernel will be used.
|
|
257
255
|
* @returns A promise that resolves with the ID of the newly created kernel.
|
|
258
256
|
* @throws {Error} Throws an error if the kernel creation fails.
|
|
259
|
-
|
|
260
|
-
|
|
257
|
+
* @param opts The options to configure the new kernel.
|
|
258
|
+
* @param opts.cwd The working directory for the new kernel.
|
|
259
|
+
* @param opts.kernelName The name of the kernel to create.
|
|
260
|
+
*/
|
|
261
|
+
createKernel(opts?: {
|
|
262
|
+
cwd?: string;
|
|
263
|
+
kernelName?: string;
|
|
264
|
+
}): Promise<string>;
|
|
261
265
|
/**
|
|
262
266
|
* Restarts an existing Jupyter kernel. This can be useful to reset the kernel's state or to recover from errors.
|
|
263
267
|
*
|
package/dist/index.js
CHANGED
|
@@ -567,14 +567,17 @@ var JupyterExtension = class {
|
|
|
567
567
|
* Once the kernel is created, this method establishes a WebSocket connection to the new kernel for
|
|
568
568
|
* real-time communication.
|
|
569
569
|
*
|
|
570
|
-
* @param cwd Sets the current working directory where the kernel should start. Defaults to "/home/user".
|
|
571
|
-
* @param kernelName The name of the kernel to create, useful if you have multiple kernel types. If not provided, the default kernel will be used.
|
|
572
570
|
* @returns A promise that resolves with the ID of the newly created kernel.
|
|
573
571
|
* @throws {Error} Throws an error if the kernel creation fails.
|
|
572
|
+
* @param opts The options to configure the new kernel.
|
|
573
|
+
* @param opts.cwd The working directory for the new kernel.
|
|
574
|
+
* @param opts.kernelName The name of the kernel to create.
|
|
574
575
|
*/
|
|
575
|
-
createKernel(
|
|
576
|
-
return __async(this,
|
|
577
|
-
|
|
576
|
+
createKernel() {
|
|
577
|
+
return __async(this, arguments, function* (opts = {
|
|
578
|
+
cwd: "/home/user"
|
|
579
|
+
}) {
|
|
580
|
+
const kernelName = opts.kernelName || "python3";
|
|
578
581
|
const data = { path: id(16), kernel: { name: kernelName }, type: "notebook", name: id(16) };
|
|
579
582
|
const response = yield fetch(
|
|
580
583
|
`${this.sandbox.getProtocol()}://${this.sandbox.getHostname(
|
|
@@ -597,7 +600,7 @@ var JupyterExtension = class {
|
|
|
597
600
|
)}/api/sessions/${sessionID}`,
|
|
598
601
|
{
|
|
599
602
|
method: "PATCH",
|
|
600
|
-
body: JSON.stringify({ path: cwd })
|
|
603
|
+
body: JSON.stringify({ path: opts.cwd })
|
|
601
604
|
}
|
|
602
605
|
);
|
|
603
606
|
if (!patchResponse.ok) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/code-interpreter.ts","../src/messaging.ts","../src/utils.ts"],"sourcesContent":["export { CodeInterpreter, JupyterExtension } from './code-interpreter'\n\nexport type { Logs, ExecutionError, Result, Execution, MIMEType, RawData } from './messaging'\n\nimport { CodeInterpreter } from './code-interpreter'\n\nexport * from 'e2b'\n\nexport default CodeInterpreter\n","import { ProcessMessage, Sandbox, SandboxOpts } from 'e2b'\nimport { Result, JupyterKernelWebSocket, Execution } from './messaging'\nimport { createDeferredPromise, id } from './utils'\n\ninterface Kernels {\n [kernelID: string]: JupyterKernelWebSocket\n}\n\n/**\n * E2B code interpreter sandbox extension.\n */\nexport class CodeInterpreter extends Sandbox {\n private static template = 'code-interpreter-multikernel'\n\n readonly notebook = new JupyterExtension(this)\n\n constructor(opts?: SandboxOpts, createCalled = false) {\n super({ template: opts?.template || CodeInterpreter.template, ...opts }, createCalled)\n }\n\n override async _open(opts?: { timeout?: number }) {\n await super._open({ timeout: opts?.timeout })\n await this.notebook.connect(opts?.timeout)\n\n return this\n }\n\n override async close() {\n await this.notebook.close()\n await super.close()\n }\n}\n\nexport class JupyterExtension {\n private readonly connectedKernels: Kernels = {}\n\n private readonly kernelIDPromise = createDeferredPromise<string>()\n private readonly setDefaultKernelID = this.kernelIDPromise.resolve\n\n private get defaultKernelID() {\n return this.kernelIDPromise.promise\n }\n\n constructor(private sandbox: CodeInterpreter) {}\n\n async connect(timeout?: number) {\n return this.startConnectingToDefaultKernel(this.setDefaultKernelID, {\n timeout\n })\n }\n\n /**\n * Executes a code cell in a notebool cell.\n *\n * This method sends the provided code to a specified kernel in a remote notebook for execution.\n\n * @param code The code to be executed in the notebook cell.\n * @param kernelID The ID of the kernel to execute the code on. If not provided, the default kernel is used.\n * @param onStdout A callback function to handle standard output messages from the code execution.\n * @param onStderr A callback function to handle standard error messages from the code execution.\n * @param onResult A callback function to handle display data messages from the code execution.\n * @param timeout The maximum time to wait for the code execution to complete, in milliseconds.\n * @returns A promise that resolves with the result of the code execution.\n */\n async execCell(\n code: string,\n {\n kernelID,\n onStdout,\n onStderr,\n onResult,\n timeout\n }: {\n kernelID?: string\n onStdout?: (msg: ProcessMessage) => any\n onStderr?: (msg: ProcessMessage) => any\n onResult?: (data: Result) => any\n timeout?: number\n } = {}\n ): Promise<Execution> {\n kernelID = kernelID || (await this.defaultKernelID)\n const ws =\n this.connectedKernels[kernelID] ||\n (await this.connectToKernelWS(kernelID))\n\n return await ws.sendExecutionMessage(\n code,\n onStdout,\n onStderr,\n onResult,\n timeout\n )\n }\n\n private async startConnectingToDefaultKernel(\n resolve: (value: string) => void,\n opts?: { timeout?: number }\n ) {\n const kernelID = (\n await this.sandbox.filesystem.read('/root/.jupyter/kernel_id', opts)\n ).trim()\n await this.connectToKernelWS(kernelID)\n resolve(kernelID)\n }\n\n /**\n * Connects to a kernel's WebSocket.\n *\n * This method establishes a WebSocket connection to the specified kernel. It is used internally\n * to facilitate real-time communication with the kernel, enabling operations such as executing\n * code and receiving output. The connection details are managed within the method, including\n * the retrieval of the necessary WebSocket URL from the kernel's information.\n *\n * @param kernelID The unique identifier of the kernel to connect to.\n * @param sessionID The unique identifier of the session to connect to.\n * @throws {Error} Throws an error if the connection to the kernel's WebSocket cannot be established.\n */\n private async connectToKernelWS(kernelID: string, sessionID?: string) {\n const url = `${this.sandbox.getProtocol('ws')}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels/${kernelID}/channels`\n\n sessionID = sessionID || id(16)\n const ws = new JupyterKernelWebSocket(url, sessionID)\n await ws.connect()\n this.connectedKernels[kernelID] = ws\n\n return ws\n }\n\n /**\n * Creates a new Jupyter kernel. It can be useful if you want to have multiple independent code execution environments.\n *\n * The kernel can be optionally configured to start in a specific working directory and/or\n * with a specific kernel name. If no kernel name is provided, the default kernel will be used.\n * Once the kernel is created, this method establishes a WebSocket connection to the new kernel for\n * real-time communication.\n *\n * @param cwd Sets the current working directory where the kernel should start. Defaults to \"/home/user\".\n * @param kernelName The name of the kernel to create, useful if you have multiple kernel types. If not provided, the default kernel will be used.\n * @returns A promise that resolves with the ID of the newly created kernel.\n * @throws {Error} Throws an error if the kernel creation fails.\n */\n async createKernel(\n cwd: string = '/home/user',\n kernelName?: string\n ): Promise<string> {\n kernelName = kernelName || 'python3'\n\n\n const data = { path: id(16), kernel: {name: kernelName}, type: \"notebook\", name: id(16) }\n\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/sessions`,\n {\n method: 'POST',\n body: JSON.stringify(data)\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to create kernel: ${response.statusText}`)\n }\n\n\n const sessionInfo = await response.json()\n const kernelID = sessionInfo.kernel.id\n const sessionID = sessionInfo.id\n\n const patchResponse = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/sessions/${sessionID}`,\n {\n method: 'PATCH',\n body: JSON.stringify({path: cwd})\n }\n )\n\n if (!patchResponse.ok) {\n throw new Error(`Failed to create kernel: ${response.statusText}`)\n }\n\n\n await this.connectToKernelWS(kernelID, sessionID)\n\n return kernelID\n }\n\n /**\n * Restarts an existing Jupyter kernel. This can be useful to reset the kernel's state or to recover from errors.\n *\n * @param kernelID The unique identifier of the kernel to restart. If not provided, the default kernel is restarted.\n * @throws {Error} Throws an error if the kernel restart fails or if the operation times out.\n */\n async restartKernel(kernelID?: string) {\n kernelID = kernelID || (await this.defaultKernelID)\n this.connectedKernels[kernelID].close()\n delete this.connectedKernels[kernelID]\n\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels/${kernelID}/restart`,\n {\n method: 'POST'\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to restart kernel ${kernelID}`)\n }\n\n await this.connectToKernelWS(kernelID)\n }\n\n /**\n * Shuts down an existing Jupyter kernel. This method is used to gracefully terminate a kernel's process.\n\n * @param kernelID The unique identifier of the kernel to shutdown. If not provided, the default kernel is shutdown.\n * @throws {Error} Throws an error if the kernel shutdown fails or if the operation times out.\n */\n async shutdownKernel(kernelID?: string) {\n kernelID = kernelID || (await this.defaultKernelID)\n this.connectedKernels[kernelID].close()\n delete this.connectedKernels[kernelID]\n\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels/${kernelID}`,\n {\n method: 'DELETE'\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to shutdown kernel ${kernelID}`)\n }\n }\n\n /**\n * Lists all available Jupyter kernels.\n *\n * This method fetches a list of all currently available Jupyter kernels from the server. It can be used\n * to retrieve the IDs of all kernels that are currently running or available for connection.\n *\n * @returns A promise that resolves to an array of kernel IDs.\n * @throws {Error} Throws an error if the request to list kernels fails.\n */\n async listKernels(): Promise<string[]> {\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels`,\n {\n method: 'GET'\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to list kernels: ${response.statusText}`)\n }\n\n return (await response.json()).map((kernel: { id: string }) => kernel.id)\n }\n\n /**\n * Close all the websocket connections to the kernels. It doesn't shutdown the kernels.\n */\n async close() {\n for (const kernelID of Object.keys(this.connectedKernels)) {\n this.connectedKernels[kernelID].close()\n }\n }\n}\n","import IWebSocket from 'isomorphic-ws'\nimport { ProcessMessage } from 'e2b'\nimport { id } from './utils'\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 tracebackRaw: string[]\n ) { }\n\n /**\n * Returns the traceback of the error as a string.\n */\n get traceback(): string {\n return this.tracebackRaw.join('\\n')\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(data: RawData, public readonly isMainResult: boolean) {\n this.text = data['text/plain']\n this.html = data['text/html']\n this.markdown = data['text/markdown']\n this.svg = data['image/svg+xml']\n this.png = data['image/png']\n this.jpeg = data['image/jpeg']\n this.pdf = data['application/pdf']\n this.latex = data['text/latex']\n this.json = data['application/json']\n this.javascript = data['application/javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.extra = {}\n for (const key of Object.keys(data)) {\n if (\n ![\n 'text/plain',\n 'text/html',\n 'text/markdown',\n 'image/svg+xml',\n 'image/png',\n 'image/jpeg',\n 'application/pdf',\n 'text/latex',\n 'application/json',\n 'application/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,\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\n/**\n * Represents the execution of a cell in the Jupyter kernel.\n * It's an internal class used by JupyterKernelWebSocket.\n */\nclass CellExecution {\n execution: Execution\n onStdout?: (out: ProcessMessage) => any\n onStderr?: (out: ProcessMessage) => any\n onResult?: (data: Result) => any\n inputAccepted: boolean = false\n\n constructor(\n onStdout?: (out: ProcessMessage) => any,\n onStderr?: (out: ProcessMessage) => any,\n onResult?: (data: Result) => any\n ) {\n this.execution = new Execution([], { stdout: [], stderr: [] })\n this.onStdout = onStdout\n this.onStderr = onStderr\n this.onResult = onResult\n }\n}\n\ninterface Cells {\n [id: string]: CellExecution\n}\n\nexport class JupyterKernelWebSocket {\n // native websocket\n private _ws?: IWebSocket\n\n private set ws(ws: IWebSocket) {\n this._ws = ws\n }\n\n private get ws() {\n if (!this._ws) {\n throw new Error('WebSocket is not connected.')\n }\n return this._ws\n }\n\n private idAwaiter: {\n [id: string]: (data?: any) => void\n } = {}\n\n private cells: Cells = {}\n\n // constructor\n /**\n * Does not start WebSocket connection!\n * You need to call connect() method first.\n */\n constructor(private readonly url: string, private readonly sessionID: string) { }\n\n // public\n /**\n * Starts WebSocket connection.\n */\n connect() {\n this._ws = new IWebSocket(this.url)\n return this.listen()\n }\n\n // events\n /**\n * Listens for messages from WebSocket server.\n *\n * Message types:\n * https://jupyter-client.readthedocs.io/en/stable/messaging.html\n *\n */\n public listenMessages() {\n this.ws.onmessage = (e: IWebSocket.MessageEvent) => {\n const message = JSON.parse(e.data.toString())\n\n const parentMsgId = message.parent_header.msg_id\n if (parentMsgId == undefined) {\n console.warn(`Parent message ID not found.\\n Message: ${message}`)\n return\n }\n\n const cell = this.cells[parentMsgId]\n if (!cell) {\n return\n }\n\n const execution = cell.execution\n if (message.msg_type == 'error') {\n execution.error = new ExecutionError(\n message.content.ename,\n message.content.evalue,\n message.content.traceback\n )\n } else if (message.msg_type == 'stream') {\n if (message.content.name == 'stdout') {\n execution.logs.stdout.push(message.content.text)\n if (cell?.onStdout) {\n cell.onStdout(\n new ProcessMessage(\n message.content.text,\n new Date().getTime() * 1_000_000,\n false\n )\n )\n }\n } else if (message.content.name == 'stderr') {\n execution.logs.stderr.push(message.content.text)\n if (cell?.onStderr) {\n cell.onStderr(\n new ProcessMessage(\n message.content.text,\n new Date().getTime() * 1_000_000,\n true\n )\n )\n }\n }\n } else if (message.msg_type == 'display_data') {\n const result = new Result(message.content.data, false)\n execution.results.push(result)\n if (cell.onResult) {\n cell.onResult(result)\n }\n } else if (message.msg_type == 'execute_result') {\n const result = new Result(message.content.data, true)\n execution.results.push(result)\n if (cell.onResult) {\n cell.onResult(result)\n }\n } else if (message.msg_type == 'status') {\n if (message.content.execution_state == 'idle') {\n if (cell.inputAccepted) {\n this.idAwaiter[parentMsgId](execution)\n }\n } else if (message.content.execution_state == 'error') {\n execution.error = new ExecutionError(\n message.content.ename,\n message.content.evalue,\n message.content.traceback\n )\n this.idAwaiter[parentMsgId](execution)\n }\n } else if (message.msg_type == 'execute_reply') {\n if (message.content.status == 'error') {\n execution.error = new ExecutionError(\n message.content.ename,\n message.content.evalue,\n message.content.traceback\n )\n } else if (message.content.status == 'ok') {\n return\n }\n } else if (message.msg_type == 'execute_input') {\n cell.inputAccepted = true\n cell.execution.executionCount = message.content.execution_count\n } else {\n console.warn('[UNHANDLED MESSAGE TYPE]:', message.msg_type)\n }\n }\n }\n\n // communication\n /**\n * Sends code to be executed by Jupyter kernel.\n * @param code Code to be executed.\n * @param onStdout Callback for stdout messages.\n * @param onStderr Callback for stderr messages.\n * @param onResult Callback function to handle the result and display calls of the code execution.\n * @param timeout Time in milliseconds to wait for response.\n * @returns Promise with execution result.\n */\n public sendExecutionMessage(\n code: string,\n onStdout?: (out: ProcessMessage) => any,\n onStderr?: (out: ProcessMessage) => any,\n onResult?: (data: Result) => any,\n timeout?: number\n ) {\n return new Promise<Execution>((resolve, reject) => {\n const msgID = id(16)\n const data = this.sendExecuteRequest(msgID, code)\n\n // give limited time for response\n let timeoutSet: number | NodeJS.Timeout\n if (timeout) {\n timeoutSet = setTimeout(() => {\n // stop waiting for response\n delete this.idAwaiter[msgID]\n reject(\n new Error(\n `Awaiting response to \"${code}\" with id: ${msgID} timed out.`\n )\n )\n }, timeout)\n }\n\n // expect response\n this.cells[msgID] = new CellExecution(onStdout, onStderr, onResult)\n this.idAwaiter[msgID] = (responseData: Execution) => {\n // stop timeout\n clearInterval(timeoutSet as number)\n // stop waiting for response\n delete this.idAwaiter[msgID]\n\n resolve(responseData)\n }\n\n const json = JSON.stringify(data)\n this.ws.send(json)\n })\n }\n\n /**\n * Listens for messages from WebSocket server.\n */\n private listen() {\n return new Promise((resolve, reject) => {\n this.ws.onopen = (e: unknown) => {\n resolve(e)\n }\n\n // listen for messages\n this.listenMessages()\n\n this.ws.onclose = (e: IWebSocket.CloseEvent) => {\n reject(\n new Error(\n `WebSocket closed with code: ${e.code} and reason: ${e.reason}`\n )\n )\n }\n })\n }\n\n /**\n * Creates a websocket message for code execution.\n * @param msg_id Unique message id.\n * @param code Code to be executed.\n */\n private sendExecuteRequest(msg_id: string, code: string) {\n return {\n header: {\n msg_id: msg_id,\n username: 'e2b',\n session: this.sessionID,\n msg_type: 'execute_request',\n version: '5.3'\n },\n parent_header: {},\n metadata: {},\n content: {\n code: code,\n silent: false,\n store_history: true,\n user_expressions: {},\n allow_stdin: false\n }\n }\n }\n\n /**\n * Closes WebSocket connection.\n */\n close() {\n this.ws.close()\n }\n}\n","export function createDeferredPromise<T = void>() {\n let resolve: (value: T) => void\n let reject: (reason?: unknown) => void\n const promise = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n })\n\n return {\n promise,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n reject: reject!,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n resolve: resolve!\n }\n}\n\nexport function id(length: number) {\n let result = ''\n const characters =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n const charactersLength = characters.length\n for (let i = 0; i < length; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength))\n }\n return result\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,cAAqD;;;ACArD,2BAAuB;AACvB,iBAA+B;;;ACDxB,SAAS,wBAAkC;AAChD,MAAI;AACJ,MAAI;AACJ,QAAM,UAAU,IAAI,QAAW,CAAC,KAAK,QAAQ;AAC3C,cAAU;AACV,aAAS;AAAA,EACX,CAAC;AAED,SAAO;AAAA,IACL;AAAA;AAAA,IAEA;AAAA;AAAA,IAEA;AAAA,EACF;AACF;AAEO,SAAS,GAAG,QAAgB;AACjC,MAAI,SAAS;AACb,QAAM,aACJ;AACF,QAAM,mBAAmB,WAAW;AACpC,WAAS,IAAI,GAAG,IAAI,QAAQ,KAA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M,2BAA2B,SAAS,YAAY;AAAA,MAClE;AAEA,cAAQ,MAAM,SAAS,KAAK,GAAG,IAAI,CAAC,WAA2B,OAAO,EAAE;AAAA,IAC1E;AAAA;AAAA;AAAA;AAAA;AAAA,EAKM,QAAQ;AAAA;AACZ,iBAAW,YAAY,OAAO,KAAK,KAAK,gBAAgB,GAAG;AACzD,aAAK,iBAAiB,QAAQ,EAAE,MAAM;AAAA,MACxC;AAAA,IACF;AAAA;AACF;;;AD/QA,wBAAc,gBANd;AAQA,IAAO,cAAQ;","names":["import_e2b","IWebSocket"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/code-interpreter.ts","../src/messaging.ts","../src/utils.ts"],"sourcesContent":["export { CodeInterpreter, JupyterExtension } from './code-interpreter'\n\nexport type { Logs, ExecutionError, Result, Execution, MIMEType, RawData } from './messaging'\n\nimport { CodeInterpreter } from './code-interpreter'\n\nexport * from 'e2b'\n\nexport default CodeInterpreter\n","import { ProcessMessage, Sandbox, SandboxOpts } from 'e2b'\nimport { Result, JupyterKernelWebSocket, Execution } from './messaging'\nimport { createDeferredPromise, id } from './utils'\n\ninterface Kernels {\n [kernelID: string]: JupyterKernelWebSocket\n}\n\n/**\n * E2B code interpreter sandbox extension.\n */\nexport class CodeInterpreter extends Sandbox {\n private static template = 'code-interpreter-multikernel'\n\n readonly notebook = new JupyterExtension(this)\n\n constructor(opts?: SandboxOpts, createCalled = false) {\n super({ template: opts?.template || CodeInterpreter.template, ...opts }, createCalled)\n }\n\n override async _open(opts?: { timeout?: number }) {\n await super._open({ timeout: opts?.timeout })\n await this.notebook.connect(opts?.timeout)\n\n return this\n }\n\n override async close() {\n await this.notebook.close()\n await super.close()\n }\n}\n\nexport class JupyterExtension {\n private readonly connectedKernels: Kernels = {}\n\n private readonly kernelIDPromise = createDeferredPromise<string>()\n private readonly setDefaultKernelID = this.kernelIDPromise.resolve\n\n private get defaultKernelID() {\n return this.kernelIDPromise.promise\n }\n\n constructor(private sandbox: CodeInterpreter) {}\n\n async connect(timeout?: number) {\n return this.startConnectingToDefaultKernel(this.setDefaultKernelID, {\n timeout\n })\n }\n\n /**\n * Executes a code cell in a notebool cell.\n *\n * This method sends the provided code to a specified kernel in a remote notebook for execution.\n\n * @param code The code to be executed in the notebook cell.\n * @param kernelID The ID of the kernel to execute the code on. If not provided, the default kernel is used.\n * @param onStdout A callback function to handle standard output messages from the code execution.\n * @param onStderr A callback function to handle standard error messages from the code execution.\n * @param onResult A callback function to handle display data messages from the code execution.\n * @param timeout The maximum time to wait for the code execution to complete, in milliseconds.\n * @returns A promise that resolves with the result of the code execution.\n */\n async execCell(\n code: string,\n {\n kernelID,\n onStdout,\n onStderr,\n onResult,\n timeout\n }: {\n kernelID?: string\n onStdout?: (msg: ProcessMessage) => any\n onStderr?: (msg: ProcessMessage) => any\n onResult?: (data: Result) => any\n timeout?: number\n } = {}\n ): Promise<Execution> {\n kernelID = kernelID || (await this.defaultKernelID)\n const ws =\n this.connectedKernels[kernelID] ||\n (await this.connectToKernelWS(kernelID))\n\n return await ws.sendExecutionMessage(\n code,\n onStdout,\n onStderr,\n onResult,\n timeout\n )\n }\n\n private async startConnectingToDefaultKernel(\n resolve: (value: string) => void,\n opts?: { timeout?: number }\n ) {\n const kernelID = (\n await this.sandbox.filesystem.read('/root/.jupyter/kernel_id', opts)\n ).trim()\n await this.connectToKernelWS(kernelID)\n resolve(kernelID)\n }\n\n /**\n * Connects to a kernel's WebSocket.\n *\n * This method establishes a WebSocket connection to the specified kernel. It is used internally\n * to facilitate real-time communication with the kernel, enabling operations such as executing\n * code and receiving output. The connection details are managed within the method, including\n * the retrieval of the necessary WebSocket URL from the kernel's information.\n *\n * @param kernelID The unique identifier of the kernel to connect to.\n * @param sessionID The unique identifier of the session to connect to.\n * @throws {Error} Throws an error if the connection to the kernel's WebSocket cannot be established.\n */\n private async connectToKernelWS(kernelID: string, sessionID?: string) {\n const url = `${this.sandbox.getProtocol('ws')}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels/${kernelID}/channels`\n\n sessionID = sessionID || id(16)\n const ws = new JupyterKernelWebSocket(url, sessionID)\n await ws.connect()\n this.connectedKernels[kernelID] = ws\n\n return ws\n }\n\n /**\n * Creates a new Jupyter kernel. It can be useful if you want to have multiple independent code execution environments.\n *\n * The kernel can be optionally configured to start in a specific working directory and/or\n * with a specific kernel name. If no kernel name is provided, the default kernel will be used.\n * Once the kernel is created, this method establishes a WebSocket connection to the new kernel for\n * real-time communication.\n *\n * @returns A promise that resolves with the ID of the newly created kernel.\n * @throws {Error} Throws an error if the kernel creation fails.\n * @param opts The options to configure the new kernel.\n * @param opts.cwd The working directory for the new kernel.\n * @param opts.kernelName The name of the kernel to create.\n */\n async createKernel(opts: { cwd?: string, kernelName?: string } = {\n cwd:'/home/user',\n}): Promise<string> {\n const kernelName = opts.kernelName || 'python3'\n\n\n const data = { path: id(16), kernel: {name: kernelName}, type: \"notebook\", name: id(16) }\n\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/sessions`,\n {\n method: 'POST',\n body: JSON.stringify(data)\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to create kernel: ${response.statusText}`)\n }\n\n\n const sessionInfo = await response.json()\n const kernelID = sessionInfo.kernel.id\n const sessionID = sessionInfo.id\n\n const patchResponse = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/sessions/${sessionID}`,\n {\n method: 'PATCH',\n body: JSON.stringify({path: opts.cwd})\n }\n )\n\n if (!patchResponse.ok) {\n throw new Error(`Failed to create kernel: ${response.statusText}`)\n }\n\n\n await this.connectToKernelWS(kernelID, sessionID)\n\n return kernelID\n }\n\n /**\n * Restarts an existing Jupyter kernel. This can be useful to reset the kernel's state or to recover from errors.\n *\n * @param kernelID The unique identifier of the kernel to restart. If not provided, the default kernel is restarted.\n * @throws {Error} Throws an error if the kernel restart fails or if the operation times out.\n */\n async restartKernel(kernelID?: string) {\n kernelID = kernelID || (await this.defaultKernelID)\n this.connectedKernels[kernelID].close()\n delete this.connectedKernels[kernelID]\n\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels/${kernelID}/restart`,\n {\n method: 'POST'\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to restart kernel ${kernelID}`)\n }\n\n await this.connectToKernelWS(kernelID)\n }\n\n /**\n * Shuts down an existing Jupyter kernel. This method is used to gracefully terminate a kernel's process.\n\n * @param kernelID The unique identifier of the kernel to shutdown. If not provided, the default kernel is shutdown.\n * @throws {Error} Throws an error if the kernel shutdown fails or if the operation times out.\n */\n async shutdownKernel(kernelID?: string) {\n kernelID = kernelID || (await this.defaultKernelID)\n this.connectedKernels[kernelID].close()\n delete this.connectedKernels[kernelID]\n\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels/${kernelID}`,\n {\n method: 'DELETE'\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to shutdown kernel ${kernelID}`)\n }\n }\n\n /**\n * Lists all available Jupyter kernels.\n *\n * This method fetches a list of all currently available Jupyter kernels from the server. It can be used\n * to retrieve the IDs of all kernels that are currently running or available for connection.\n *\n * @returns A promise that resolves to an array of kernel IDs.\n * @throws {Error} Throws an error if the request to list kernels fails.\n */\n async listKernels(): Promise<string[]> {\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels`,\n {\n method: 'GET'\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to list kernels: ${response.statusText}`)\n }\n\n return (await response.json()).map((kernel: { id: string }) => kernel.id)\n }\n\n /**\n * Close all the websocket connections to the kernels. It doesn't shutdown the kernels.\n */\n async close() {\n for (const kernelID of Object.keys(this.connectedKernels)) {\n this.connectedKernels[kernelID].close()\n }\n }\n}\n","import IWebSocket from 'isomorphic-ws'\nimport { ProcessMessage } from 'e2b'\nimport { id } from './utils'\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 tracebackRaw: string[]\n ) { }\n\n /**\n * Returns the traceback of the error as a string.\n */\n get traceback(): string {\n return this.tracebackRaw.join('\\n')\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(data: RawData, public readonly isMainResult: boolean) {\n this.text = data['text/plain']\n this.html = data['text/html']\n this.markdown = data['text/markdown']\n this.svg = data['image/svg+xml']\n this.png = data['image/png']\n this.jpeg = data['image/jpeg']\n this.pdf = data['application/pdf']\n this.latex = data['text/latex']\n this.json = data['application/json']\n this.javascript = data['application/javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.extra = {}\n for (const key of Object.keys(data)) {\n if (\n ![\n 'text/plain',\n 'text/html',\n 'text/markdown',\n 'image/svg+xml',\n 'image/png',\n 'image/jpeg',\n 'application/pdf',\n 'text/latex',\n 'application/json',\n 'application/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,\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\n/**\n * Represents the execution of a cell in the Jupyter kernel.\n * It's an internal class used by JupyterKernelWebSocket.\n */\nclass CellExecution {\n execution: Execution\n onStdout?: (out: ProcessMessage) => any\n onStderr?: (out: ProcessMessage) => any\n onResult?: (data: Result) => any\n inputAccepted: boolean = false\n\n constructor(\n onStdout?: (out: ProcessMessage) => any,\n onStderr?: (out: ProcessMessage) => any,\n onResult?: (data: Result) => any\n ) {\n this.execution = new Execution([], { stdout: [], stderr: [] })\n this.onStdout = onStdout\n this.onStderr = onStderr\n this.onResult = onResult\n }\n}\n\ninterface Cells {\n [id: string]: CellExecution\n}\n\nexport class JupyterKernelWebSocket {\n // native websocket\n private _ws?: IWebSocket\n\n private set ws(ws: IWebSocket) {\n this._ws = ws\n }\n\n private get ws() {\n if (!this._ws) {\n throw new Error('WebSocket is not connected.')\n }\n return this._ws\n }\n\n private idAwaiter: {\n [id: string]: (data?: any) => void\n } = {}\n\n private cells: Cells = {}\n\n // constructor\n /**\n * Does not start WebSocket connection!\n * You need to call connect() method first.\n */\n constructor(private readonly url: string, private readonly sessionID: string) { }\n\n // public\n /**\n * Starts WebSocket connection.\n */\n connect() {\n this._ws = new IWebSocket(this.url)\n return this.listen()\n }\n\n // events\n /**\n * Listens for messages from WebSocket server.\n *\n * Message types:\n * https://jupyter-client.readthedocs.io/en/stable/messaging.html\n *\n */\n public listenMessages() {\n this.ws.onmessage = (e: IWebSocket.MessageEvent) => {\n const message = JSON.parse(e.data.toString())\n\n const parentMsgId = message.parent_header.msg_id\n if (parentMsgId == undefined) {\n console.warn(`Parent message ID not found.\\n Message: ${message}`)\n return\n }\n\n const cell = this.cells[parentMsgId]\n if (!cell) {\n return\n }\n\n const execution = cell.execution\n if (message.msg_type == 'error') {\n execution.error = new ExecutionError(\n message.content.ename,\n message.content.evalue,\n message.content.traceback\n )\n } else if (message.msg_type == 'stream') {\n if (message.content.name == 'stdout') {\n execution.logs.stdout.push(message.content.text)\n if (cell?.onStdout) {\n cell.onStdout(\n new ProcessMessage(\n message.content.text,\n new Date().getTime() * 1_000_000,\n false\n )\n )\n }\n } else if (message.content.name == 'stderr') {\n execution.logs.stderr.push(message.content.text)\n if (cell?.onStderr) {\n cell.onStderr(\n new ProcessMessage(\n message.content.text,\n new Date().getTime() * 1_000_000,\n true\n )\n )\n }\n }\n } else if (message.msg_type == 'display_data') {\n const result = new Result(message.content.data, false)\n execution.results.push(result)\n if (cell.onResult) {\n cell.onResult(result)\n }\n } else if (message.msg_type == 'execute_result') {\n const result = new Result(message.content.data, true)\n execution.results.push(result)\n if (cell.onResult) {\n cell.onResult(result)\n }\n } else if (message.msg_type == 'status') {\n if (message.content.execution_state == 'idle') {\n if (cell.inputAccepted) {\n this.idAwaiter[parentMsgId](execution)\n }\n } else if (message.content.execution_state == 'error') {\n execution.error = new ExecutionError(\n message.content.ename,\n message.content.evalue,\n message.content.traceback\n )\n this.idAwaiter[parentMsgId](execution)\n }\n } else if (message.msg_type == 'execute_reply') {\n if (message.content.status == 'error') {\n execution.error = new ExecutionError(\n message.content.ename,\n message.content.evalue,\n message.content.traceback\n )\n } else if (message.content.status == 'ok') {\n return\n }\n } else if (message.msg_type == 'execute_input') {\n cell.inputAccepted = true\n cell.execution.executionCount = message.content.execution_count\n } else {\n console.warn('[UNHANDLED MESSAGE TYPE]:', message.msg_type)\n }\n }\n }\n\n // communication\n /**\n * Sends code to be executed by Jupyter kernel.\n * @param code Code to be executed.\n * @param onStdout Callback for stdout messages.\n * @param onStderr Callback for stderr messages.\n * @param onResult Callback function to handle the result and display calls of the code execution.\n * @param timeout Time in milliseconds to wait for response.\n * @returns Promise with execution result.\n */\n public sendExecutionMessage(\n code: string,\n onStdout?: (out: ProcessMessage) => any,\n onStderr?: (out: ProcessMessage) => any,\n onResult?: (data: Result) => any,\n timeout?: number\n ) {\n return new Promise<Execution>((resolve, reject) => {\n const msgID = id(16)\n const data = this.sendExecuteRequest(msgID, code)\n\n // give limited time for response\n let timeoutSet: number | NodeJS.Timeout\n if (timeout) {\n timeoutSet = setTimeout(() => {\n // stop waiting for response\n delete this.idAwaiter[msgID]\n reject(\n new Error(\n `Awaiting response to \"${code}\" with id: ${msgID} timed out.`\n )\n )\n }, timeout)\n }\n\n // expect response\n this.cells[msgID] = new CellExecution(onStdout, onStderr, onResult)\n this.idAwaiter[msgID] = (responseData: Execution) => {\n // stop timeout\n clearInterval(timeoutSet as number)\n // stop waiting for response\n delete this.idAwaiter[msgID]\n\n resolve(responseData)\n }\n\n const json = JSON.stringify(data)\n this.ws.send(json)\n })\n }\n\n /**\n * Listens for messages from WebSocket server.\n */\n private listen() {\n return new Promise((resolve, reject) => {\n this.ws.onopen = (e: unknown) => {\n resolve(e)\n }\n\n // listen for messages\n this.listenMessages()\n\n this.ws.onclose = (e: IWebSocket.CloseEvent) => {\n reject(\n new Error(\n `WebSocket closed with code: ${e.code} and reason: ${e.reason}`\n )\n )\n }\n })\n }\n\n /**\n * Creates a websocket message for code execution.\n * @param msg_id Unique message id.\n * @param code Code to be executed.\n */\n private sendExecuteRequest(msg_id: string, code: string) {\n return {\n header: {\n msg_id: msg_id,\n username: 'e2b',\n session: this.sessionID,\n msg_type: 'execute_request',\n version: '5.3'\n },\n parent_header: {},\n metadata: {},\n content: {\n code: code,\n silent: false,\n store_history: true,\n user_expressions: {},\n allow_stdin: false\n }\n }\n }\n\n /**\n * Closes WebSocket connection.\n */\n close() {\n this.ws.close()\n }\n}\n","export function createDeferredPromise<T = void>() {\n let resolve: (value: T) => void\n let reject: (reason?: unknown) => void\n const promise = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n })\n\n return {\n promise,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n reject: reject!,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n resolve: resolve!\n }\n}\n\nexport function id(length: number) {\n let result = ''\n const characters =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n const charactersLength = characters.length\n for (let i = 0; i < length; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength))\n }\n return result\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,cAAqD;;;ACArD,2BAAuB;AACvB,iBAA+B;;;ACDxB,SAAS,wBAAkC;AAChD,MAAI;AACJ,MAAI;AACJ,QAAM,UAAU,IAAI,QAAW,CAAC,KAAK,QAAQ;AAC3C,cAAU;AACV,aAAS;AAAA,EACX,CAAC;AAED,SAAO;AAAA,IACL;AAAA;AAAA,IAEA;AAAA;AAAA,IAEA;AAAA,EACF;AACF;AAEO,SAAS,GAAG,QAAgB;AACjC,MAAI,SAAS;AACb,QAAM,aACJ;AACF,QAAM,mBAAmB,WAAW;AACpC,WAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,cAAU,WAAW,OAAO,KAAK,MAAM,KAAK,OAAO,IAAI,gBAAgB,CAAC;AAAA,EAC1E;AACA,SAAO;AACT;;;ADlBO,IAAM,iBAAN,MAAqB;AAAA,EAC1B,YAIS,MAIA,OAIA,cACP;AATO;AAIA;AAIA;AAAA,EACL;AAAA;AAAA;AAAA;AAAA,EAKJ,IAAI,YAAoB;AACtB,WAAO,KAAK,aAAa,KAAK,IAAI;AAAA,EACpC;AACF;AAuBO,IAAM,SAAN,MAAa;AAAA,EAgDlB,YAAY,MAA+B,cAAuB;AAAvB;AACzC,SAAK,OAAO,KAAK,YAAY;AAC7B,SAAK,OAAO,KAAK,WAAW;AAC5B,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.mjs
CHANGED
|
@@ -532,14 +532,17 @@ var JupyterExtension = class {
|
|
|
532
532
|
* Once the kernel is created, this method establishes a WebSocket connection to the new kernel for
|
|
533
533
|
* real-time communication.
|
|
534
534
|
*
|
|
535
|
-
* @param cwd Sets the current working directory where the kernel should start. Defaults to "/home/user".
|
|
536
|
-
* @param kernelName The name of the kernel to create, useful if you have multiple kernel types. If not provided, the default kernel will be used.
|
|
537
535
|
* @returns A promise that resolves with the ID of the newly created kernel.
|
|
538
536
|
* @throws {Error} Throws an error if the kernel creation fails.
|
|
537
|
+
* @param opts The options to configure the new kernel.
|
|
538
|
+
* @param opts.cwd The working directory for the new kernel.
|
|
539
|
+
* @param opts.kernelName The name of the kernel to create.
|
|
539
540
|
*/
|
|
540
|
-
createKernel(
|
|
541
|
-
return __async(this,
|
|
542
|
-
|
|
541
|
+
createKernel() {
|
|
542
|
+
return __async(this, arguments, function* (opts = {
|
|
543
|
+
cwd: "/home/user"
|
|
544
|
+
}) {
|
|
545
|
+
const kernelName = opts.kernelName || "python3";
|
|
543
546
|
const data = { path: id(16), kernel: { name: kernelName }, type: "notebook", name: id(16) };
|
|
544
547
|
const response = yield fetch(
|
|
545
548
|
`${this.sandbox.getProtocol()}://${this.sandbox.getHostname(
|
|
@@ -562,7 +565,7 @@ var JupyterExtension = class {
|
|
|
562
565
|
)}/api/sessions/${sessionID}`,
|
|
563
566
|
{
|
|
564
567
|
method: "PATCH",
|
|
565
|
-
body: JSON.stringify({ path: cwd })
|
|
568
|
+
body: JSON.stringify({ path: opts.cwd })
|
|
566
569
|
}
|
|
567
570
|
);
|
|
568
571
|
if (!patchResponse.ok) {
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/code-interpreter.ts","../src/messaging.ts","../src/utils.ts","../src/index.ts"],"sourcesContent":["import { ProcessMessage, Sandbox, SandboxOpts } from 'e2b'\nimport { Result, JupyterKernelWebSocket, Execution } from './messaging'\nimport { createDeferredPromise, id } from './utils'\n\ninterface Kernels {\n [kernelID: string]: JupyterKernelWebSocket\n}\n\n/**\n * E2B code interpreter sandbox extension.\n */\nexport class CodeInterpreter extends Sandbox {\n private static template = 'code-interpreter-multikernel'\n\n readonly notebook = new JupyterExtension(this)\n\n constructor(opts?: SandboxOpts, createCalled = false) {\n super({ template: opts?.template || CodeInterpreter.template, ...opts }, createCalled)\n }\n\n override async _open(opts?: { timeout?: number }) {\n await super._open({ timeout: opts?.timeout })\n await this.notebook.connect(opts?.timeout)\n\n return this\n }\n\n override async close() {\n await this.notebook.close()\n await super.close()\n }\n}\n\nexport class JupyterExtension {\n private readonly connectedKernels: Kernels = {}\n\n private readonly kernelIDPromise = createDeferredPromise<string>()\n private readonly setDefaultKernelID = this.kernelIDPromise.resolve\n\n private get defaultKernelID() {\n return this.kernelIDPromise.promise\n }\n\n constructor(private sandbox: CodeInterpreter) {}\n\n async connect(timeout?: number) {\n return this.startConnectingToDefaultKernel(this.setDefaultKernelID, {\n timeout\n })\n }\n\n /**\n * Executes a code cell in a notebool cell.\n *\n * This method sends the provided code to a specified kernel in a remote notebook for execution.\n\n * @param code The code to be executed in the notebook cell.\n * @param kernelID The ID of the kernel to execute the code on. If not provided, the default kernel is used.\n * @param onStdout A callback function to handle standard output messages from the code execution.\n * @param onStderr A callback function to handle standard error messages from the code execution.\n * @param onResult A callback function to handle display data messages from the code execution.\n * @param timeout The maximum time to wait for the code execution to complete, in milliseconds.\n * @returns A promise that resolves with the result of the code execution.\n */\n async execCell(\n code: string,\n {\n kernelID,\n onStdout,\n onStderr,\n onResult,\n timeout\n }: {\n kernelID?: string\n onStdout?: (msg: ProcessMessage) => any\n onStderr?: (msg: ProcessMessage) => any\n onResult?: (data: Result) => any\n timeout?: number\n } = {}\n ): Promise<Execution> {\n kernelID = kernelID || (await this.defaultKernelID)\n const ws =\n this.connectedKernels[kernelID] ||\n (await this.connectToKernelWS(kernelID))\n\n return await ws.sendExecutionMessage(\n code,\n onStdout,\n onStderr,\n onResult,\n timeout\n )\n }\n\n private async startConnectingToDefaultKernel(\n resolve: (value: string) => void,\n opts?: { timeout?: number }\n ) {\n const kernelID = (\n await this.sandbox.filesystem.read('/root/.jupyter/kernel_id', opts)\n ).trim()\n await this.connectToKernelWS(kernelID)\n resolve(kernelID)\n }\n\n /**\n * Connects to a kernel's WebSocket.\n *\n * This method establishes a WebSocket connection to the specified kernel. It is used internally\n * to facilitate real-time communication with the kernel, enabling operations such as executing\n * code and receiving output. The connection details are managed within the method, including\n * the retrieval of the necessary WebSocket URL from the kernel's information.\n *\n * @param kernelID The unique identifier of the kernel to connect to.\n * @param sessionID The unique identifier of the session to connect to.\n * @throws {Error} Throws an error if the connection to the kernel's WebSocket cannot be established.\n */\n private async connectToKernelWS(kernelID: string, sessionID?: string) {\n const url = `${this.sandbox.getProtocol('ws')}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels/${kernelID}/channels`\n\n sessionID = sessionID || id(16)\n const ws = new JupyterKernelWebSocket(url, sessionID)\n await ws.connect()\n this.connectedKernels[kernelID] = ws\n\n return ws\n }\n\n /**\n * Creates a new Jupyter kernel. It can be useful if you want to have multiple independent code execution environments.\n *\n * The kernel can be optionally configured to start in a specific working directory and/or\n * with a specific kernel name. If no kernel name is provided, the default kernel will be used.\n * Once the kernel is created, this method establishes a WebSocket connection to the new kernel for\n * real-time communication.\n *\n * @param cwd Sets the current working directory where the kernel should start. Defaults to \"/home/user\".\n * @param kernelName The name of the kernel to create, useful if you have multiple kernel types. If not provided, the default kernel will be used.\n * @returns A promise that resolves with the ID of the newly created kernel.\n * @throws {Error} Throws an error if the kernel creation fails.\n */\n async createKernel(\n cwd: string = '/home/user',\n kernelName?: string\n ): Promise<string> {\n kernelName = kernelName || 'python3'\n\n\n const data = { path: id(16), kernel: {name: kernelName}, type: \"notebook\", name: id(16) }\n\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/sessions`,\n {\n method: 'POST',\n body: JSON.stringify(data)\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to create kernel: ${response.statusText}`)\n }\n\n\n const sessionInfo = await response.json()\n const kernelID = sessionInfo.kernel.id\n const sessionID = sessionInfo.id\n\n const patchResponse = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/sessions/${sessionID}`,\n {\n method: 'PATCH',\n body: JSON.stringify({path: cwd})\n }\n )\n\n if (!patchResponse.ok) {\n throw new Error(`Failed to create kernel: ${response.statusText}`)\n }\n\n\n await this.connectToKernelWS(kernelID, sessionID)\n\n return kernelID\n }\n\n /**\n * Restarts an existing Jupyter kernel. This can be useful to reset the kernel's state or to recover from errors.\n *\n * @param kernelID The unique identifier of the kernel to restart. If not provided, the default kernel is restarted.\n * @throws {Error} Throws an error if the kernel restart fails or if the operation times out.\n */\n async restartKernel(kernelID?: string) {\n kernelID = kernelID || (await this.defaultKernelID)\n this.connectedKernels[kernelID].close()\n delete this.connectedKernels[kernelID]\n\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels/${kernelID}/restart`,\n {\n method: 'POST'\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to restart kernel ${kernelID}`)\n }\n\n await this.connectToKernelWS(kernelID)\n }\n\n /**\n * Shuts down an existing Jupyter kernel. This method is used to gracefully terminate a kernel's process.\n\n * @param kernelID The unique identifier of the kernel to shutdown. If not provided, the default kernel is shutdown.\n * @throws {Error} Throws an error if the kernel shutdown fails or if the operation times out.\n */\n async shutdownKernel(kernelID?: string) {\n kernelID = kernelID || (await this.defaultKernelID)\n this.connectedKernels[kernelID].close()\n delete this.connectedKernels[kernelID]\n\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels/${kernelID}`,\n {\n method: 'DELETE'\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to shutdown kernel ${kernelID}`)\n }\n }\n\n /**\n * Lists all available Jupyter kernels.\n *\n * This method fetches a list of all currently available Jupyter kernels from the server. It can be used\n * to retrieve the IDs of all kernels that are currently running or available for connection.\n *\n * @returns A promise that resolves to an array of kernel IDs.\n * @throws {Error} Throws an error if the request to list kernels fails.\n */\n async listKernels(): Promise<string[]> {\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels`,\n {\n method: 'GET'\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to list kernels: ${response.statusText}`)\n }\n\n return (await response.json()).map((kernel: { id: string }) => kernel.id)\n }\n\n /**\n * Close all the websocket connections to the kernels. It doesn't shutdown the kernels.\n */\n async close() {\n for (const kernelID of Object.keys(this.connectedKernels)) {\n this.connectedKernels[kernelID].close()\n }\n }\n}\n","import IWebSocket from 'isomorphic-ws'\nimport { ProcessMessage } from 'e2b'\nimport { id } from './utils'\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 tracebackRaw: string[]\n ) { }\n\n /**\n * Returns the traceback of the error as a string.\n */\n get traceback(): string {\n return this.tracebackRaw.join('\\n')\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(data: RawData, public readonly isMainResult: boolean) {\n this.text = data['text/plain']\n this.html = data['text/html']\n this.markdown = data['text/markdown']\n this.svg = data['image/svg+xml']\n this.png = data['image/png']\n this.jpeg = data['image/jpeg']\n this.pdf = data['application/pdf']\n this.latex = data['text/latex']\n this.json = data['application/json']\n this.javascript = data['application/javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.extra = {}\n for (const key of Object.keys(data)) {\n if (\n ![\n 'text/plain',\n 'text/html',\n 'text/markdown',\n 'image/svg+xml',\n 'image/png',\n 'image/jpeg',\n 'application/pdf',\n 'text/latex',\n 'application/json',\n 'application/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,\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\n/**\n * Represents the execution of a cell in the Jupyter kernel.\n * It's an internal class used by JupyterKernelWebSocket.\n */\nclass CellExecution {\n execution: Execution\n onStdout?: (out: ProcessMessage) => any\n onStderr?: (out: ProcessMessage) => any\n onResult?: (data: Result) => any\n inputAccepted: boolean = false\n\n constructor(\n onStdout?: (out: ProcessMessage) => any,\n onStderr?: (out: ProcessMessage) => any,\n onResult?: (data: Result) => any\n ) {\n this.execution = new Execution([], { stdout: [], stderr: [] })\n this.onStdout = onStdout\n this.onStderr = onStderr\n this.onResult = onResult\n }\n}\n\ninterface Cells {\n [id: string]: CellExecution\n}\n\nexport class JupyterKernelWebSocket {\n // native websocket\n private _ws?: IWebSocket\n\n private set ws(ws: IWebSocket) {\n this._ws = ws\n }\n\n private get ws() {\n if (!this._ws) {\n throw new Error('WebSocket is not connected.')\n }\n return this._ws\n }\n\n private idAwaiter: {\n [id: string]: (data?: any) => void\n } = {}\n\n private cells: Cells = {}\n\n // constructor\n /**\n * Does not start WebSocket connection!\n * You need to call connect() method first.\n */\n constructor(private readonly url: string, private readonly sessionID: string) { }\n\n // public\n /**\n * Starts WebSocket connection.\n */\n connect() {\n this._ws = new IWebSocket(this.url)\n return this.listen()\n }\n\n // events\n /**\n * Listens for messages from WebSocket server.\n *\n * Message types:\n * https://jupyter-client.readthedocs.io/en/stable/messaging.html\n *\n */\n public listenMessages() {\n this.ws.onmessage = (e: IWebSocket.MessageEvent) => {\n const message = JSON.parse(e.data.toString())\n\n const parentMsgId = message.parent_header.msg_id\n if (parentMsgId == undefined) {\n console.warn(`Parent message ID not found.\\n Message: ${message}`)\n return\n }\n\n const cell = this.cells[parentMsgId]\n if (!cell) {\n return\n }\n\n const execution = cell.execution\n if (message.msg_type == 'error') {\n execution.error = new ExecutionError(\n message.content.ename,\n message.content.evalue,\n message.content.traceback\n )\n } else if (message.msg_type == 'stream') {\n if (message.content.name == 'stdout') {\n execution.logs.stdout.push(message.content.text)\n if (cell?.onStdout) {\n cell.onStdout(\n new ProcessMessage(\n message.content.text,\n new Date().getTime() * 1_000_000,\n false\n )\n )\n }\n } else if (message.content.name == 'stderr') {\n execution.logs.stderr.push(message.content.text)\n if (cell?.onStderr) {\n cell.onStderr(\n new ProcessMessage(\n message.content.text,\n new Date().getTime() * 1_000_000,\n true\n )\n )\n }\n }\n } else if (message.msg_type == 'display_data') {\n const result = new Result(message.content.data, false)\n execution.results.push(result)\n if (cell.onResult) {\n cell.onResult(result)\n }\n } else if (message.msg_type == 'execute_result') {\n const result = new Result(message.content.data, true)\n execution.results.push(result)\n if (cell.onResult) {\n cell.onResult(result)\n }\n } else if (message.msg_type == 'status') {\n if (message.content.execution_state == 'idle') {\n if (cell.inputAccepted) {\n this.idAwaiter[parentMsgId](execution)\n }\n } else if (message.content.execution_state == 'error') {\n execution.error = new ExecutionError(\n message.content.ename,\n message.content.evalue,\n message.content.traceback\n )\n this.idAwaiter[parentMsgId](execution)\n }\n } else if (message.msg_type == 'execute_reply') {\n if (message.content.status == 'error') {\n execution.error = new ExecutionError(\n message.content.ename,\n message.content.evalue,\n message.content.traceback\n )\n } else if (message.content.status == 'ok') {\n return\n }\n } else if (message.msg_type == 'execute_input') {\n cell.inputAccepted = true\n cell.execution.executionCount = message.content.execution_count\n } else {\n console.warn('[UNHANDLED MESSAGE TYPE]:', message.msg_type)\n }\n }\n }\n\n // communication\n /**\n * Sends code to be executed by Jupyter kernel.\n * @param code Code to be executed.\n * @param onStdout Callback for stdout messages.\n * @param onStderr Callback for stderr messages.\n * @param onResult Callback function to handle the result and display calls of the code execution.\n * @param timeout Time in milliseconds to wait for response.\n * @returns Promise with execution result.\n */\n public sendExecutionMessage(\n code: string,\n onStdout?: (out: ProcessMessage) => any,\n onStderr?: (out: ProcessMessage) => any,\n onResult?: (data: Result) => any,\n timeout?: number\n ) {\n return new Promise<Execution>((resolve, reject) => {\n const msgID = id(16)\n const data = this.sendExecuteRequest(msgID, code)\n\n // give limited time for response\n let timeoutSet: number | NodeJS.Timeout\n if (timeout) {\n timeoutSet = setTimeout(() => {\n // stop waiting for response\n delete this.idAwaiter[msgID]\n reject(\n new Error(\n `Awaiting response to \"${code}\" with id: ${msgID} timed out.`\n )\n )\n }, timeout)\n }\n\n // expect response\n this.cells[msgID] = new CellExecution(onStdout, onStderr, onResult)\n this.idAwaiter[msgID] = (responseData: Execution) => {\n // stop timeout\n clearInterval(timeoutSet as number)\n // stop waiting for response\n delete this.idAwaiter[msgID]\n\n resolve(responseData)\n }\n\n const json = JSON.stringify(data)\n this.ws.send(json)\n })\n }\n\n /**\n * Listens for messages from WebSocket server.\n */\n private listen() {\n return new Promise((resolve, reject) => {\n this.ws.onopen = (e: unknown) => {\n resolve(e)\n }\n\n // listen for messages\n this.listenMessages()\n\n this.ws.onclose = (e: IWebSocket.CloseEvent) => {\n reject(\n new Error(\n `WebSocket closed with code: ${e.code} and reason: ${e.reason}`\n )\n )\n }\n })\n }\n\n /**\n * Creates a websocket message for code execution.\n * @param msg_id Unique message id.\n * @param code Code to be executed.\n */\n private sendExecuteRequest(msg_id: string, code: string) {\n return {\n header: {\n msg_id: msg_id,\n username: 'e2b',\n session: this.sessionID,\n msg_type: 'execute_request',\n version: '5.3'\n },\n parent_header: {},\n metadata: {},\n content: {\n code: code,\n silent: false,\n store_history: true,\n user_expressions: {},\n allow_stdin: false\n }\n }\n }\n\n /**\n * Closes WebSocket connection.\n */\n close() {\n this.ws.close()\n }\n}\n","export function createDeferredPromise<T = void>() {\n let resolve: (value: T) => void\n let reject: (reason?: unknown) => void\n const promise = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n })\n\n return {\n promise,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n reject: reject!,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n resolve: resolve!\n }\n}\n\nexport function id(length: number) {\n let result = ''\n const characters =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n const charactersLength = characters.length\n for (let i = 0; i < length; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength))\n }\n return result\n}\n","export { CodeInterpreter, JupyterExtension } from './code-interpreter'\n\nexport type { Logs, ExecutionError, Result, Execution, MIMEType, RawData } from './messaging'\n\nimport { CodeInterpreter } from './code-interpreter'\n\nexport * from 'e2b'\n\nexport default CodeInterpreter\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAyB,eAA4B;;;ACArD,OAAO,gBAAgB;AACvB,SAAS,sBAAsB;;;ACDxB,SAAS,wBAAkC;AAChD,MAAI;AACJ,MAAI;AACJ,QAAM,UAAU,IAAI,QAAW,CAAC,KAAK,QAAQ;AAC3C,cAAU;AACV,aAAS;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AACrC,YAAM,WAAW,MAAM;AAAA,QACrB,GAAG,KAAK,QAAQ,YAAY,OAAO,KAAK,QAAQ;AAAA,UAC9C;AAAA,QACF;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,QACV;AAAA,MACF;AAEA,UAAI,CAAC,SAAS,IAAI;AAChB,cAAM,IAAI,MAAM,2BAA2B,SAAS,YAAY;AAAA,MAClE;AAEA,cAAQ,MAAM,SAAS,KAAK,GAAG,IAAI,CAAC,WAA2B,OAAO,EAAE;AAAA,IAC1E;AAAA;AAAA;AAAA;AAAA;AAAA,EAKM,QAAQ;AAAA;AACZ,iBAAW,YAAY,OAAO,KAAK,KAAK,gBAAgB,GAAG;AACzD,aAAK,iBAAiB,QAAQ,EAAE,MAAM;AAAA,MACxC;AAAA,IACF;AAAA;AACF;;;AG/QA,cAAc;AAEd,IAAO,cAAQ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/code-interpreter.ts","../src/messaging.ts","../src/utils.ts","../src/index.ts"],"sourcesContent":["import { ProcessMessage, Sandbox, SandboxOpts } from 'e2b'\nimport { Result, JupyterKernelWebSocket, Execution } from './messaging'\nimport { createDeferredPromise, id } from './utils'\n\ninterface Kernels {\n [kernelID: string]: JupyterKernelWebSocket\n}\n\n/**\n * E2B code interpreter sandbox extension.\n */\nexport class CodeInterpreter extends Sandbox {\n private static template = 'code-interpreter-multikernel'\n\n readonly notebook = new JupyterExtension(this)\n\n constructor(opts?: SandboxOpts, createCalled = false) {\n super({ template: opts?.template || CodeInterpreter.template, ...opts }, createCalled)\n }\n\n override async _open(opts?: { timeout?: number }) {\n await super._open({ timeout: opts?.timeout })\n await this.notebook.connect(opts?.timeout)\n\n return this\n }\n\n override async close() {\n await this.notebook.close()\n await super.close()\n }\n}\n\nexport class JupyterExtension {\n private readonly connectedKernels: Kernels = {}\n\n private readonly kernelIDPromise = createDeferredPromise<string>()\n private readonly setDefaultKernelID = this.kernelIDPromise.resolve\n\n private get defaultKernelID() {\n return this.kernelIDPromise.promise\n }\n\n constructor(private sandbox: CodeInterpreter) {}\n\n async connect(timeout?: number) {\n return this.startConnectingToDefaultKernel(this.setDefaultKernelID, {\n timeout\n })\n }\n\n /**\n * Executes a code cell in a notebool cell.\n *\n * This method sends the provided code to a specified kernel in a remote notebook for execution.\n\n * @param code The code to be executed in the notebook cell.\n * @param kernelID The ID of the kernel to execute the code on. If not provided, the default kernel is used.\n * @param onStdout A callback function to handle standard output messages from the code execution.\n * @param onStderr A callback function to handle standard error messages from the code execution.\n * @param onResult A callback function to handle display data messages from the code execution.\n * @param timeout The maximum time to wait for the code execution to complete, in milliseconds.\n * @returns A promise that resolves with the result of the code execution.\n */\n async execCell(\n code: string,\n {\n kernelID,\n onStdout,\n onStderr,\n onResult,\n timeout\n }: {\n kernelID?: string\n onStdout?: (msg: ProcessMessage) => any\n onStderr?: (msg: ProcessMessage) => any\n onResult?: (data: Result) => any\n timeout?: number\n } = {}\n ): Promise<Execution> {\n kernelID = kernelID || (await this.defaultKernelID)\n const ws =\n this.connectedKernels[kernelID] ||\n (await this.connectToKernelWS(kernelID))\n\n return await ws.sendExecutionMessage(\n code,\n onStdout,\n onStderr,\n onResult,\n timeout\n )\n }\n\n private async startConnectingToDefaultKernel(\n resolve: (value: string) => void,\n opts?: { timeout?: number }\n ) {\n const kernelID = (\n await this.sandbox.filesystem.read('/root/.jupyter/kernel_id', opts)\n ).trim()\n await this.connectToKernelWS(kernelID)\n resolve(kernelID)\n }\n\n /**\n * Connects to a kernel's WebSocket.\n *\n * This method establishes a WebSocket connection to the specified kernel. It is used internally\n * to facilitate real-time communication with the kernel, enabling operations such as executing\n * code and receiving output. The connection details are managed within the method, including\n * the retrieval of the necessary WebSocket URL from the kernel's information.\n *\n * @param kernelID The unique identifier of the kernel to connect to.\n * @param sessionID The unique identifier of the session to connect to.\n * @throws {Error} Throws an error if the connection to the kernel's WebSocket cannot be established.\n */\n private async connectToKernelWS(kernelID: string, sessionID?: string) {\n const url = `${this.sandbox.getProtocol('ws')}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels/${kernelID}/channels`\n\n sessionID = sessionID || id(16)\n const ws = new JupyterKernelWebSocket(url, sessionID)\n await ws.connect()\n this.connectedKernels[kernelID] = ws\n\n return ws\n }\n\n /**\n * Creates a new Jupyter kernel. It can be useful if you want to have multiple independent code execution environments.\n *\n * The kernel can be optionally configured to start in a specific working directory and/or\n * with a specific kernel name. If no kernel name is provided, the default kernel will be used.\n * Once the kernel is created, this method establishes a WebSocket connection to the new kernel for\n * real-time communication.\n *\n * @returns A promise that resolves with the ID of the newly created kernel.\n * @throws {Error} Throws an error if the kernel creation fails.\n * @param opts The options to configure the new kernel.\n * @param opts.cwd The working directory for the new kernel.\n * @param opts.kernelName The name of the kernel to create.\n */\n async createKernel(opts: { cwd?: string, kernelName?: string } = {\n cwd:'/home/user',\n}): Promise<string> {\n const kernelName = opts.kernelName || 'python3'\n\n\n const data = { path: id(16), kernel: {name: kernelName}, type: \"notebook\", name: id(16) }\n\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/sessions`,\n {\n method: 'POST',\n body: JSON.stringify(data)\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to create kernel: ${response.statusText}`)\n }\n\n\n const sessionInfo = await response.json()\n const kernelID = sessionInfo.kernel.id\n const sessionID = sessionInfo.id\n\n const patchResponse = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/sessions/${sessionID}`,\n {\n method: 'PATCH',\n body: JSON.stringify({path: opts.cwd})\n }\n )\n\n if (!patchResponse.ok) {\n throw new Error(`Failed to create kernel: ${response.statusText}`)\n }\n\n\n await this.connectToKernelWS(kernelID, sessionID)\n\n return kernelID\n }\n\n /**\n * Restarts an existing Jupyter kernel. This can be useful to reset the kernel's state or to recover from errors.\n *\n * @param kernelID The unique identifier of the kernel to restart. If not provided, the default kernel is restarted.\n * @throws {Error} Throws an error if the kernel restart fails or if the operation times out.\n */\n async restartKernel(kernelID?: string) {\n kernelID = kernelID || (await this.defaultKernelID)\n this.connectedKernels[kernelID].close()\n delete this.connectedKernels[kernelID]\n\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels/${kernelID}/restart`,\n {\n method: 'POST'\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to restart kernel ${kernelID}`)\n }\n\n await this.connectToKernelWS(kernelID)\n }\n\n /**\n * Shuts down an existing Jupyter kernel. This method is used to gracefully terminate a kernel's process.\n\n * @param kernelID The unique identifier of the kernel to shutdown. If not provided, the default kernel is shutdown.\n * @throws {Error} Throws an error if the kernel shutdown fails or if the operation times out.\n */\n async shutdownKernel(kernelID?: string) {\n kernelID = kernelID || (await this.defaultKernelID)\n this.connectedKernels[kernelID].close()\n delete this.connectedKernels[kernelID]\n\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels/${kernelID}`,\n {\n method: 'DELETE'\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to shutdown kernel ${kernelID}`)\n }\n }\n\n /**\n * Lists all available Jupyter kernels.\n *\n * This method fetches a list of all currently available Jupyter kernels from the server. It can be used\n * to retrieve the IDs of all kernels that are currently running or available for connection.\n *\n * @returns A promise that resolves to an array of kernel IDs.\n * @throws {Error} Throws an error if the request to list kernels fails.\n */\n async listKernels(): Promise<string[]> {\n const response = await fetch(\n `${this.sandbox.getProtocol()}://${this.sandbox.getHostname(\n 8888\n )}/api/kernels`,\n {\n method: 'GET'\n }\n )\n\n if (!response.ok) {\n throw new Error(`Failed to list kernels: ${response.statusText}`)\n }\n\n return (await response.json()).map((kernel: { id: string }) => kernel.id)\n }\n\n /**\n * Close all the websocket connections to the kernels. It doesn't shutdown the kernels.\n */\n async close() {\n for (const kernelID of Object.keys(this.connectedKernels)) {\n this.connectedKernels[kernelID].close()\n }\n }\n}\n","import IWebSocket from 'isomorphic-ws'\nimport { ProcessMessage } from 'e2b'\nimport { id } from './utils'\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 tracebackRaw: string[]\n ) { }\n\n /**\n * Returns the traceback of the error as a string.\n */\n get traceback(): string {\n return this.tracebackRaw.join('\\n')\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(data: RawData, public readonly isMainResult: boolean) {\n this.text = data['text/plain']\n this.html = data['text/html']\n this.markdown = data['text/markdown']\n this.svg = data['image/svg+xml']\n this.png = data['image/png']\n this.jpeg = data['image/jpeg']\n this.pdf = data['application/pdf']\n this.latex = data['text/latex']\n this.json = data['application/json']\n this.javascript = data['application/javascript']\n this.isMainResult = isMainResult\n this.raw = data\n\n this.extra = {}\n for (const key of Object.keys(data)) {\n if (\n ![\n 'text/plain',\n 'text/html',\n 'text/markdown',\n 'image/svg+xml',\n 'image/png',\n 'image/jpeg',\n 'application/pdf',\n 'text/latex',\n 'application/json',\n 'application/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,\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\n/**\n * Represents the execution of a cell in the Jupyter kernel.\n * It's an internal class used by JupyterKernelWebSocket.\n */\nclass CellExecution {\n execution: Execution\n onStdout?: (out: ProcessMessage) => any\n onStderr?: (out: ProcessMessage) => any\n onResult?: (data: Result) => any\n inputAccepted: boolean = false\n\n constructor(\n onStdout?: (out: ProcessMessage) => any,\n onStderr?: (out: ProcessMessage) => any,\n onResult?: (data: Result) => any\n ) {\n this.execution = new Execution([], { stdout: [], stderr: [] })\n this.onStdout = onStdout\n this.onStderr = onStderr\n this.onResult = onResult\n }\n}\n\ninterface Cells {\n [id: string]: CellExecution\n}\n\nexport class JupyterKernelWebSocket {\n // native websocket\n private _ws?: IWebSocket\n\n private set ws(ws: IWebSocket) {\n this._ws = ws\n }\n\n private get ws() {\n if (!this._ws) {\n throw new Error('WebSocket is not connected.')\n }\n return this._ws\n }\n\n private idAwaiter: {\n [id: string]: (data?: any) => void\n } = {}\n\n private cells: Cells = {}\n\n // constructor\n /**\n * Does not start WebSocket connection!\n * You need to call connect() method first.\n */\n constructor(private readonly url: string, private readonly sessionID: string) { }\n\n // public\n /**\n * Starts WebSocket connection.\n */\n connect() {\n this._ws = new IWebSocket(this.url)\n return this.listen()\n }\n\n // events\n /**\n * Listens for messages from WebSocket server.\n *\n * Message types:\n * https://jupyter-client.readthedocs.io/en/stable/messaging.html\n *\n */\n public listenMessages() {\n this.ws.onmessage = (e: IWebSocket.MessageEvent) => {\n const message = JSON.parse(e.data.toString())\n\n const parentMsgId = message.parent_header.msg_id\n if (parentMsgId == undefined) {\n console.warn(`Parent message ID not found.\\n Message: ${message}`)\n return\n }\n\n const cell = this.cells[parentMsgId]\n if (!cell) {\n return\n }\n\n const execution = cell.execution\n if (message.msg_type == 'error') {\n execution.error = new ExecutionError(\n message.content.ename,\n message.content.evalue,\n message.content.traceback\n )\n } else if (message.msg_type == 'stream') {\n if (message.content.name == 'stdout') {\n execution.logs.stdout.push(message.content.text)\n if (cell?.onStdout) {\n cell.onStdout(\n new ProcessMessage(\n message.content.text,\n new Date().getTime() * 1_000_000,\n false\n )\n )\n }\n } else if (message.content.name == 'stderr') {\n execution.logs.stderr.push(message.content.text)\n if (cell?.onStderr) {\n cell.onStderr(\n new ProcessMessage(\n message.content.text,\n new Date().getTime() * 1_000_000,\n true\n )\n )\n }\n }\n } else if (message.msg_type == 'display_data') {\n const result = new Result(message.content.data, false)\n execution.results.push(result)\n if (cell.onResult) {\n cell.onResult(result)\n }\n } else if (message.msg_type == 'execute_result') {\n const result = new Result(message.content.data, true)\n execution.results.push(result)\n if (cell.onResult) {\n cell.onResult(result)\n }\n } else if (message.msg_type == 'status') {\n if (message.content.execution_state == 'idle') {\n if (cell.inputAccepted) {\n this.idAwaiter[parentMsgId](execution)\n }\n } else if (message.content.execution_state == 'error') {\n execution.error = new ExecutionError(\n message.content.ename,\n message.content.evalue,\n message.content.traceback\n )\n this.idAwaiter[parentMsgId](execution)\n }\n } else if (message.msg_type == 'execute_reply') {\n if (message.content.status == 'error') {\n execution.error = new ExecutionError(\n message.content.ename,\n message.content.evalue,\n message.content.traceback\n )\n } else if (message.content.status == 'ok') {\n return\n }\n } else if (message.msg_type == 'execute_input') {\n cell.inputAccepted = true\n cell.execution.executionCount = message.content.execution_count\n } else {\n console.warn('[UNHANDLED MESSAGE TYPE]:', message.msg_type)\n }\n }\n }\n\n // communication\n /**\n * Sends code to be executed by Jupyter kernel.\n * @param code Code to be executed.\n * @param onStdout Callback for stdout messages.\n * @param onStderr Callback for stderr messages.\n * @param onResult Callback function to handle the result and display calls of the code execution.\n * @param timeout Time in milliseconds to wait for response.\n * @returns Promise with execution result.\n */\n public sendExecutionMessage(\n code: string,\n onStdout?: (out: ProcessMessage) => any,\n onStderr?: (out: ProcessMessage) => any,\n onResult?: (data: Result) => any,\n timeout?: number\n ) {\n return new Promise<Execution>((resolve, reject) => {\n const msgID = id(16)\n const data = this.sendExecuteRequest(msgID, code)\n\n // give limited time for response\n let timeoutSet: number | NodeJS.Timeout\n if (timeout) {\n timeoutSet = setTimeout(() => {\n // stop waiting for response\n delete this.idAwaiter[msgID]\n reject(\n new Error(\n `Awaiting response to \"${code}\" with id: ${msgID} timed out.`\n )\n )\n }, timeout)\n }\n\n // expect response\n this.cells[msgID] = new CellExecution(onStdout, onStderr, onResult)\n this.idAwaiter[msgID] = (responseData: Execution) => {\n // stop timeout\n clearInterval(timeoutSet as number)\n // stop waiting for response\n delete this.idAwaiter[msgID]\n\n resolve(responseData)\n }\n\n const json = JSON.stringify(data)\n this.ws.send(json)\n })\n }\n\n /**\n * Listens for messages from WebSocket server.\n */\n private listen() {\n return new Promise((resolve, reject) => {\n this.ws.onopen = (e: unknown) => {\n resolve(e)\n }\n\n // listen for messages\n this.listenMessages()\n\n this.ws.onclose = (e: IWebSocket.CloseEvent) => {\n reject(\n new Error(\n `WebSocket closed with code: ${e.code} and reason: ${e.reason}`\n )\n )\n }\n })\n }\n\n /**\n * Creates a websocket message for code execution.\n * @param msg_id Unique message id.\n * @param code Code to be executed.\n */\n private sendExecuteRequest(msg_id: string, code: string) {\n return {\n header: {\n msg_id: msg_id,\n username: 'e2b',\n session: this.sessionID,\n msg_type: 'execute_request',\n version: '5.3'\n },\n parent_header: {},\n metadata: {},\n content: {\n code: code,\n silent: false,\n store_history: true,\n user_expressions: {},\n allow_stdin: false\n }\n }\n }\n\n /**\n * Closes WebSocket connection.\n */\n close() {\n this.ws.close()\n }\n}\n","export function createDeferredPromise<T = void>() {\n let resolve: (value: T) => void\n let reject: (reason?: unknown) => void\n const promise = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n })\n\n return {\n promise,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n reject: reject!,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n resolve: resolve!\n }\n}\n\nexport function id(length: number) {\n let result = ''\n const characters =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n const charactersLength = characters.length\n for (let i = 0; i < length; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength))\n }\n return result\n}\n","export { CodeInterpreter, JupyterExtension } from './code-interpreter'\n\nexport type { Logs, ExecutionError, Result, Execution, MIMEType, RawData } from './messaging'\n\nimport { CodeInterpreter } from './code-interpreter'\n\nexport * from 'e2b'\n\nexport default CodeInterpreter\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAyB,eAA4B;;;ACArD,OAAO,gBAAgB;AACvB,SAAS,sBAAsB;;;ACDxB,SAAS,wBAAkC;AAChD,MAAI;AACJ,MAAI;AACJ,QAAM,UAAU,IAAI,QAAW,CAAC,KAAK,QAAQ;AAC3C,cAAU;AACV,aAAS;AAAA,EACX,CAAC;AAED,SAAO;AAAA,IACL;AAAA;AAAA,IAEA;AAAA;AAAA,IAEA;AAAA,EACF;AACF;AAEO,SAAS,GAAG,QAAgB;AACjC,MAAI,SAAS;AACb,QAAM,aACJ;AACF,QAAM,mBAAmB,WAAW;AACpC,WAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,cAAU,WAAW,OAAO,KAAK,MAAM,KAAK,OAAO,IAAI,gBAAgB,CAAC;AAAA,EAC1E;AACA,SAAO;AACT;;;ADlBO,IAAM,iBAAN,MAAqB;AAAA,EAC1B,YAIS,MAIA,OAIA,cACP;AATO;AAIA;AAIA;AAAA,EACL;AAAA;AAAA;AAAA;AAAA,EAKJ,IAAI,YAAoB;AACtB,WAAO,KAAK,aAAa,KAAK,IAAI;AAAA,EACpC;AACF;AAuBO,IAAM,SA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