@e2b/code-interpreter 0.0.8 → 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 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
- createKernel(cwd?: string, kernelName?: string): Promise<string>;
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
@@ -478,7 +478,7 @@ var _CodeInterpreter = class extends import_e2b2.Sandbox {
478
478
  }
479
479
  };
480
480
  var CodeInterpreter = _CodeInterpreter;
481
- CodeInterpreter.template = "code-interpreter-stateful";
481
+ CodeInterpreter.template = "code-interpreter-multikernel";
482
482
  var JupyterExtension = class {
483
483
  constructor(sandbox) {
484
484
  this.sandbox = sandbox;
@@ -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(cwd = "/home/user", kernelName) {
576
- return __async(this, null, function* () {
577
- kernelName = kernelName || "python3";
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-stateful'\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,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;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AAG;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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AAW,aAAa,MAAM,KAAK;AACnC,WAAK,iBAAiB,QAAQ,EAAE,MAAM;AACtC,aAAO,KAAK,iBAAiB,QAAQ;AAErC,YAAM,WAAW,MAAM;AAAA,QACrB,GAAG,KAAK,QAAQ,YAAY,OAAO,KAAK,QAAQ;AAAA,UAC9C;AAAA,QACF,iBAAiB;AAAA,QACjB;AAAA,UACE,QAAQ;AAAA,QACV;AAAA,MACF;AAEA,UAAI,CAAC,SAAS,IAAI;AAChB,cAAM,IAAI,MAAM,6BAA6B,UAAU;AAAA,MACzD;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWM,cAAiC;AAAA;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;;;AD/QA,wBAAc,gBANd;AAQA,IAAO,cAAQ;","names":["import_e2b","IWebSocket"]}
package/dist/index.mjs CHANGED
@@ -443,7 +443,7 @@ var _CodeInterpreter = class extends Sandbox {
443
443
  }
444
444
  };
445
445
  var CodeInterpreter = _CodeInterpreter;
446
- CodeInterpreter.template = "code-interpreter-stateful";
446
+ CodeInterpreter.template = "code-interpreter-multikernel";
447
447
  var JupyterExtension = class {
448
448
  constructor(sandbox) {
449
449
  this.sandbox = sandbox;
@@ -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(cwd = "/home/user", kernelName) {
541
- return __async(this, null, function* () {
542
- kernelName = kernelName || "python3";
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) {
@@ -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-stateful'\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;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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,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,SAAN,MAAa;AAAA,EAgDlB,YAAY,MAA+B,cAAuB;AAAvB;AACzC,SAAK,OAAO,KAAK,YAAY;AAC7B,SAAK,OAAO,KAAK,WAAW;AAC5B,SAAK,WAAW,KAAK,eAAe;AACpC,SAAK,MAAM,KAAK,eAAe;AAC/B,SAAK,MAAM,KAAK,WAAW;AAC3B,SAAK,OAAO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AAkB,QAAQ;AAAA,IACvC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQM,eAAe,UAAmB;AAAA;AACtC,iBAAW,aAAa,MAAM,KAAK;AACnC,WAAK,iBAAiB,QAAQ,EAAE,MAAM;AACtC,aAAO,KAAK,iBAAiB,QAAQ;AAErC,YAAM,WAAW,MAAM;AAAA,QACrB,GAAG,KAAK,QAAQ,YAAY,OAAO,KAAK,QAAQ;AAAA,UAC9C;AAAA,QACF,iBAAiB;AAAA,QACjB;AAAA,UACE,QAAQ;AAAA,QACV;AAAA,MACF;AAEA,UAAI,CAAC,SAAS,IAAI;AAChB,cAAM,IAAI,MAAM,6BAA6B,UAAU;AAAA,MACzD;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWM,cAAiC;AAAA;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":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e2b/code-interpreter",
3
- "version": "0.0.8",
3
+ "version": "0.0.9-multikernel-code-interpreterer.0",
4
4
  "description": "E2B Code Interpreter - Stateful code execution",
5
5
  "homepage": "https://e2b.dev",
6
6
  "license": "MIT",
@@ -22,6 +22,15 @@
22
22
  "main": "dist/index.js",
23
23
  "module": "dist/index.mjs",
24
24
  "types": "dist/index.d.ts",
25
+ "scripts": {
26
+ "prepublishOnly": "pnpm build",
27
+ "build": "tsc --noEmit && tsup",
28
+ "dev": "tsup --watch",
29
+ "test": "vitest run",
30
+ "test:coverage": "vitest run --coverage",
31
+ "check-deps": "knip",
32
+ "update-deps": "ncu -u && pnpm i"
33
+ },
25
34
  "devDependencies": {
26
35
  "@types/node": "^18.18.6",
27
36
  "@types/ws": "^8.5.10",
@@ -60,13 +69,5 @@
60
69
  },
61
70
  "browserslist": [
62
71
  "defaults"
63
- ],
64
- "scripts": {
65
- "build": "tsc --noEmit && tsup",
66
- "dev": "tsup --watch",
67
- "test": "vitest run",
68
- "test:coverage": "vitest run --coverage",
69
- "check-deps": "knip",
70
- "update-deps": "ncu -u && pnpm i"
71
- }
72
- }
72
+ ]
73
+ }
package/LICENSE DELETED
@@ -1,201 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.