Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Alias DataAnalysis as CodeInterpreter; Hide JS SDK internal methods

Tomas Valenta1e3312467de0
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 7e8d2390d..60da7b443 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -24,6 +24,10 @@ export type { ProcessManager } from './sandbox/process'
export type { EnvVars } from './sandbox/envVars'
export { runCode, CodeRuntime } from './runCode' // Export CodeRuntime enum as value, not as type, so it can be actually used in consumer code
// export { runCmd } from './runCmd'
-export { Artifact, DataAnalysis} from './templates/dataAnalysis'
+
+import { DataAnalysis } from './templates/dataAnalysis'
+export { DataAnalysis as CodeInterpreter }
+
+export { Artifact, DataAnalysis } from './templates/dataAnalysis'
export type { RunPythonOpts } from './templates/dataAnalysis'
export default Sandbox
diff --git a/packages/js-sdk/src/sandbox/filesystemWatcher.ts b/packages/js-sdk/src/sandbox/filesystemWatcher.ts
index fe9b4ebbe..aa36ca69c 100644
--- a/packages/js-sdk/src/sandbox/filesystemWatcher.ts
+++ b/packages/js-sdk/src/sandbox/filesystemWatcher.ts
@@ -43,7 +43,7 @@ class FilesystemWatcher {
this.handleFilesystemEvents = this.handleFilesystemEvents.bind(this)
- this.rpcSubscriptionID = await this.sessConn.subscribe(
+ this.rpcSubscriptionID = await this.sessConn._subscribe(
filesystemService,
this.handleFilesystemEvents,
'watchDir',
@@ -57,7 +57,7 @@ class FilesystemWatcher {
async stop() {
this.listeners.clear()
if (this.rpcSubscriptionID) {
- await this.sessConn.unsubscribe(this.rpcSubscriptionID)
+ await this.sessConn._unsubscribe(this.rpcSubscriptionID)
}
}
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index f73706b6a..6bbc04b9f 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -48,7 +48,7 @@ export class Sandbox extends SandboxConnection {
* @returns Array of files in a directory
*/
list: async (path, opts?: CallOpts) => {
- return (await this.call(
+ return (await this._call(
filesystemService,
'list',
[_resolvePath(path)],
@@ -63,7 +63,7 @@ export class Sandbox extends SandboxConnection {
* @returns Content of a file
*/
read: async (path, opts?: CallOpts) => {
- return (await this.call(
+ return (await this._call(
filesystemService,
'read',
[_resolvePath(path)],
@@ -77,7 +77,7 @@ export class Sandbox extends SandboxConnection {
* @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)
*/
remove: async (path, opts?: CallOpts) => {
- await this.call(
+ await this._call(
filesystemService,
'remove',
[_resolvePath(path)],
@@ -92,7 +92,7 @@ export class Sandbox extends SandboxConnection {
* @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)
*/
write: async (path, content, opts?: CallOpts) => {
- await this.call(
+ await this._call(
filesystemService,
'write',
[_resolvePath(path), content],
@@ -110,7 +110,7 @@ export class Sandbox extends SandboxConnection {
// We need to convert the byte array to base64 string without using browser or node specific APIs.
// This should be achieved by the node polyfills.
const base64Content = Buffer.from(content).toString('base64')
- await this.call(filesystemService, 'writeBase64', [
+ await this._call(filesystemService, 'writeBase64', [
_resolvePath(path),
base64Content,
])
@@ -121,7 +121,7 @@ export class Sandbox extends SandboxConnection {
* @returns byte array representing the content of a file
*/
readBytes: async (path: string) => {
- const base64Content = (await this.call(
+ const base64Content = (await this._call(
filesystemService,
'readBase64',
[_resolvePath(path)],
@@ -137,7 +137,7 @@ export class Sandbox extends SandboxConnection {
* @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)
*/
makeDir: async (path, opts?: CallOpts) => {
- await this.call(
+ await this._call(
filesystemService,
'makeDir',
[_resolvePath(path)],
@@ -201,9 +201,9 @@ export class Sandbox extends SandboxConnection {
onData?.(data)
}
- const [onDataSubID, onExitSubID] = await this.handleSubscriptions(
- this.subscribe(terminalService, handleData, 'onData', terminalID),
- this.subscribe(terminalService, triggerExit, 'onExit', terminalID),
+ const [onDataSubID, onExitSubID] = await this._handleSubscriptions(
+ this._subscribe(terminalService, handleData, 'onData', terminalID),
+ this._subscribe(terminalService, triggerExit, 'onExit', terminalID),
)
const { promise: unsubscribing, resolve: handleFinishUnsubscribing } =
@@ -211,8 +211,8 @@ export class Sandbox extends SandboxConnection {
terminalExited.then(async () => {
const results = await Promise.allSettled([
- this.unsubscribe(onExitSubID),
- this.unsubscribe(onDataSubID),
+ this._unsubscribe(onExitSubID),
+ this._unsubscribe(onDataSubID),
])
this.logger.debug?.(`Terminal "${terminalID}" exited`)
@@ -226,7 +226,7 @@ export class Sandbox extends SandboxConnection {
})
try {
- await this.call(terminalService, 'start', [
+ await this._call(terminalService, 'start', [
terminalID,
size.cols,
size.rows,
@@ -329,15 +329,15 @@ export class Sandbox extends SandboxConnection {
}
const [onExitSubID, onStdoutSubID, onStderrSubID] =
- await this.handleSubscriptions(
- this.subscribe(processService, handleExit, 'onExit', processID),
- this.subscribe(
+ await this._handleSubscriptions(
+ this._subscribe(processService, handleExit, 'onExit', processID),
+ this._subscribe(
processService,
handleStdout,
'onStdout',
processID,
),
- this.subscribe(
+ this._subscribe(
processService,
handleStderr,
'onStderr',
@@ -350,9 +350,9 @@ export class Sandbox extends SandboxConnection {
processExited.then(async () => {
const results = await Promise.allSettled([
- this.unsubscribe(onExitSubID),
- onStdoutSubID ? this.unsubscribe(onStdoutSubID) : undefined,
- onStderrSubID ? this.unsubscribe(onStderrSubID) : undefined,
+ this._unsubscribe(onExitSubID),
+ onStdoutSubID ? this._unsubscribe(onStdoutSubID) : undefined,
+ onStderrSubID ? this._unsubscribe(onStderrSubID) : undefined,
])
this.logger.debug?.(`Process "${processID}" exited`)
@@ -372,7 +372,7 @@ export class Sandbox extends SandboxConnection {
})
try {
- await this.call(processService, 'start', [
+ await this._call(processService, 'start', [
processID,
cmd,
envVars,
@@ -435,9 +435,9 @@ export class Sandbox extends SandboxConnection {
)
: undefined
- await this.handleSubscriptions(
+ await this._handleSubscriptions(
portsHandler
- ? this.subscribe(codeSnippetService, portsHandler, 'scanOpenedPorts')
+ ? this._subscribe(codeSnippetService, portsHandler, 'scanOpenedPorts')
: undefined,
)
diff --git a/packages/js-sdk/src/sandbox/process.ts b/packages/js-sdk/src/sandbox/process.ts
index 676db595a..4bbb0bc96 100644
--- a/packages/js-sdk/src/sandbox/process.ts
+++ b/packages/js-sdk/src/sandbox/process.ts
@@ -119,7 +119,7 @@ export class Process {
*/
async kill(): Promise<void> {
try {
- await this.sandbox.call(processService, 'kill', [this.processID])
+ await this.sandbox._call(processService, 'kill', [this.processID])
} finally {
this.triggerExit()
await this.finished
@@ -141,7 +141,7 @@ export class Process {
* @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)
*/
async sendStdin(data: string, opts?: CallOpts): Promise<void> {
- await this.sandbox.call(
+ await this.sandbox._call(
processService,
'stdin',
[this.processID, data],
diff --git a/packages/js-sdk/src/sandbox/sandboxConnection.ts b/packages/js-sdk/src/sandbox/sandboxConnection.ts
index 9a0f70126..37f4e1c93 100644
--- a/packages/js-sdk/src/sandbox/sandboxConnection.ts
+++ b/packages/js-sdk/src/sandbox/sandboxConnection.ts
@@ -141,7 +141,7 @@ export class SandboxConnection {
this.logger.debug?.('Unsubscribing...')
const results = await Promise.allSettled(
- this.subscribers.map((s) => this.unsubscribe(s.subID)),
+ this.subscribers.map((s) => this._unsubscribe(s.subID)),
)
results.forEach((r) => {
if (r.status === 'rejected') {
@@ -157,6 +157,97 @@ export class SandboxConnection {
}
}
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ async _call(
+ service: Service,
+ method: string,
+ params?: any[],
+ opts?: CallOpts,
+ ) {
+ this.logger.debug?.(`Calling "${service}_${method}" with params:`, params)
+
+ // Without the async function, the `this` context is lost.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const call = async (method: string, params?: any[]) =>
+ await this.rpc.call(method, params)
+
+ return await withTimeout(call, opts?.timeout)(
+ `${service}_${method}`,
+ params,
+ )
+ }
+
+ async _handleSubscriptions<
+ T extends (ReturnType<SandboxConnection['_subscribe']> | undefined)[],
+ >(
+ ...subs: T
+ ): Promise<{
+ [P in keyof T]: Awaited<T[P]>;
+ }> {
+ const results = await Promise.allSettled(subs)
+
+ if (results.every((r) => r.status === 'fulfilled')) {
+ return results.map((r) =>
+ r.status === 'fulfilled' ? r.value : undefined,
+ ) as {
+ [P in keyof T]: Awaited<T[P]>;
+ }
+ }
+
+ await Promise.all(
+ results
+ .filter(assertFulfilled)
+ .map((r) => (r.value ? this._unsubscribe(r.value) : undefined)),
+ )
+
+ throw new Error(formatSettledErrors(results))
+ }
+
+ // eslint-disable-next-line @typescript-eslint/member-ordering
+ async _unsubscribe(subID: string) {
+ const subscription = this.subscribers.find((s) => s.subID === subID)
+ if (!subscription) return
+
+ await this._call(subscription.service, 'unsubscribe', [subscription.subID])
+
+ this.subscribers = this.subscribers.filter((s) => s !== subscription)
+ this.logger.debug?.(
+ `Unsubscribed '${subID}' from '${subscription.service}'`,
+ )
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/member-ordering
+ async _subscribe(
+ service: Service,
+ handler: SubscriptionHandler,
+ method: string,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ...params: any[]
+ ) {
+ const subID = await this._call(service, 'subscribe', [method, ...params])
+
+ if (typeof subID !== 'string') {
+ throw new Error(
+ `Cannot subscribe to ${service}_${method}${params.length > 0 ? ' with params [' + params.join(', ') + ']' : ''
+ }. Expected response should have been a subscription ID, instead we got ${JSON.stringify(
+ subID,
+ )}`,
+ )
+ }
+
+ this.subscribers.push({
+ handler,
+ service,
+ subID,
+ })
+ this.logger.debug?.(
+ `Subscribed to "${service}_${method}"${params.length > 0 ? ' with params [' + params.join(', ') + '] and' : ''
+ } with id "${subID}"`,
+ )
+
+ return subID
+ }
+
/**
* Open a connection to a new sandbox
*
@@ -300,97 +391,6 @@ export class SandboxConnection {
return await withTimeout(open, opts?.timeout)()
}
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- async call(
- service: Service,
- method: string,
- params?: any[],
- opts?: CallOpts,
- ) {
- this.logger.debug?.(`Calling "${service}_${method}" with params:`, params)
-
- // Without the async function, the `this` context is lost.
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const call = async (method: string, params?: any[]) =>
- await this.rpc.call(method, params)
-
- return await withTimeout(call, opts?.timeout)(
- `${service}_${method}`,
- params,
- )
- }
-
- async handleSubscriptions<
- T extends (ReturnType<SandboxConnection['subscribe']> | undefined)[],
- >(
- ...subs: T
- ): Promise<{
- [P in keyof T]: Awaited<T[P]>;
- }> {
- const results = await Promise.allSettled(subs)
-
- if (results.every((r) => r.status === 'fulfilled')) {
- return results.map((r) =>
- r.status === 'fulfilled' ? r.value : undefined,
- ) as {
- [P in keyof T]: Awaited<T[P]>;
- }
- }
-
- await Promise.all(
- results
- .filter(assertFulfilled)
- .map((r) => (r.value ? this.unsubscribe(r.value) : undefined)),
- )
-
- throw new Error(formatSettledErrors(results))
- }
-
- // eslint-disable-next-line @typescript-eslint/member-ordering
- async unsubscribe(subID: string) {
- const subscription = this.subscribers.find((s) => s.subID === subID)
- if (!subscription) return
-
- await this.call(subscription.service, 'unsubscribe', [subscription.subID])
-
- this.subscribers = this.subscribers.filter((s) => s !== subscription)
- this.logger.debug?.(
- `Unsubscribed '${subID}' from '${subscription.service}'`,
- )
- }
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/member-ordering
- async subscribe(
- service: Service,
- handler: SubscriptionHandler,
- method: string,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- ...params: any[]
- ) {
- const subID = await this.call(service, 'subscribe', [method, ...params])
-
- if (typeof subID !== 'string') {
- throw new Error(
- `Cannot subscribe to ${service}_${method}${params.length > 0 ? ' with params [' + params.join(', ') + ']' : ''
- }. Expected response should have been a subscription ID, instead we got ${JSON.stringify(
- subID,
- )}`,
- )
- }
-
- this.subscribers.push({
- handler,
- service,
- subID,
- })
- this.logger.debug?.(
- `Subscribed to "${service}_${method}"${params.length > 0 ? ' with params [' + params.join(', ') + '] and' : ''
- } with id "${subID}"`,
- )
-
- return subID
- }
-
private handleNotification(data: IRpcNotification) {
this.logger.debug?.('Handling notification:', data)
this.subscribers
diff --git a/packages/js-sdk/src/sandbox/terminal.ts b/packages/js-sdk/src/sandbox/terminal.ts
index 87596765f..4e4cb4e0b 100644
--- a/packages/js-sdk/src/sandbox/terminal.ts
+++ b/packages/js-sdk/src/sandbox/terminal.ts
@@ -45,7 +45,7 @@ export class Terminal {
async kill(): Promise<void> {
try {
// TODO: Change the "destroy" to "kill" in devbookd
- await this.sandbox.call(terminalService, 'destroy', [this.terminalID])
+ await this.sandbox._call(terminalService, 'destroy', [this.terminalID])
} finally {
this.triggerExit()
await this.finished
@@ -65,7 +65,7 @@ export class Terminal {
* @param data Data to send
*/
async sendData(data: string): Promise<void> {
- await this.sandbox.call(terminalService, 'data', [this.terminalID, data])
+ await this.sandbox._call(terminalService, 'data', [this.terminalID, data])
}
/**
@@ -75,7 +75,7 @@ export class Terminal {
* @param rows Number of rows
*/
async resize({ cols, rows }: { cols: number; rows: number }): Promise<void> {
- await this.sandbox.call(terminalService, 'resize', [
+ await this.sandbox._call(terminalService, 'resize', [
this.terminalID,
cols,
rows,
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index 412b1438b..e98a69bb5 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -31,4 +31,5 @@ from .sandbox import (
)
from .templates import (
DataAnalysis,
+ CodeInterpreter,
)
diff --git a/packages/python-sdk/e2b/templates/__init__.py b/packages/python-sdk/e2b/templates/__init__.py
index 8aaeeadb6..7c752c6fc 100644
--- a/packages/python-sdk/e2b/templates/__init__.py
+++ b/packages/python-sdk/e2b/templates/__init__.py
@@ -1 +1 @@
-from .data_analysis import Artifact, DataAnalysis
+from .data_analysis import Artifact, DataAnalysis, CodeInterpreter
diff --git a/packages/python-sdk/e2b/templates/data_analysis.py b/packages/python-sdk/e2b/templates/data_analysis.py
index f82854174..b513ff9a6 100644
--- a/packages/python-sdk/e2b/templates/data_analysis.py
+++ b/packages/python-sdk/e2b/templates/data_analysis.py
@@ -133,3 +133,6 @@ class DataAnalysis(Sandbox):
self._install_packages(
"sudo apt-get install -y", package_names, timeout=timeout
)
+
+
+CodeInterpreter = DataAnalysis