Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
[WIP] Draft JS SDK
Tomas Valenta701b68fc4e29
diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.tsindex 1c93f74b5..81c0fddb7 100644--- a/packages/js-sdk/src/api/index.ts+++ b/packages/js-sdk/src/api/index.ts@@ -3,19 +3,19 @@ import type { OpArgType, TypedFetch } from 'openapi-typescript-fetch'import type { components, paths } from './schema.gen'import { defaultHeaders } from './metadata'-import { DEBUG, DOMAIN, SECURE } from '../constants'+import { DOMAIN, DEBUG } from '../constants'const { Fetcher } = fetcher+export interface APIOpts {+ domain?: string+ debug?: boolean+}+class APIClient {private client = Fetcher.for<paths>()- constructor(private opts?: {- secure?: boolean,- domain?: string,- debug?: boolean,- }- ) {+ constructor(private opts?: APIOpts) {this.client.configure({baseUrl: this.apiHost,init: {@@ -24,24 +24,21 @@ class APIClient {})}- get secure() {- return this.opts?.secure ?? SECURE++ get debug() {+ return this.opts?.debug ?? DEBUG}get domain() {return this.opts?.domain ?? DOMAIN}- get debug() {- return this.opts?.debug ?? DEBUG- }-get apiDomain() {return this.debug ? 'localhost:3000' : `api.${this.domain}`}get apiHost() {- return `${this.secure && !this.debug ? 'https' : 'http'}://${this.apiDomain}`+ return `${this.debug ? 'http' : 'https'}://${this.apiDomain}`}get api() {diff --git a/packages/js-sdk/src/constants.ts b/packages/js-sdk/src/constants.tsindex 23e51e782..205fb3c57 100644--- a/packages/js-sdk/src/constants.ts+++ b/packages/js-sdk/src/constants.ts@@ -1,15 +1,8 @@-export const SANDBOX_REFRESH_PERIOD = 5_000 // 5s-export const WS_RECONNECT_INTERVAL = 150 // 150ms--export const TIMEOUT = 60_000 // 60s-export const DEBUG = process?.env?.E2B_DEBUG+export const DEBUG = (process?.env?.E2B_DEBUG || 'false').toLowerCase() === 'true'export const DOMAIN = process?.env?.E2B_DOMAIN || 'e2b.dev'-export const SECURE = (process?.env?.E2B_SECURE || 'true').toLowerCase() === 'true'export const API_DOMAIN = DEBUG ? 'localhost:3000' : `api.${DOMAIN}`-export const API_HOST = `${SECURE && !DEBUG ? 'https' : 'http'}://${API_DOMAIN}`-export const SANDBOX_DOMAIN = DOMAIN+export const API_HOST = `${DEBUG ? 'http' : 'https'}://${API_DOMAIN}`-export const ENVD_PORT = 49982-export const WS_ROUTE = '/ws'+export const RPC_PORT = 49982-export const FILE_ROUTE = '/file'+export const FILE_ROUTE = '/file'\ No newline at end of filediff --git a/packages/js-sdk/src/sandbox/codeSnippet.ts b/packages/js-sdk/src/sandbox/codeSnippet.tsdeleted file mode 100644index c4f681a61..000000000--- a/packages/js-sdk/src/sandbox/codeSnippet.ts+++ /dev/null@@ -1,9 +0,0 @@-export const codeSnippetService = 'codeSnippet'--export interface OpenPort {- state: string- ip: string- port: number-}--export type ScanOpenedPortsHandler = (ports: OpenPort[]) => Promise<void> | voiddiff --git a/packages/js-sdk/src/sandbox/envVars.ts b/packages/js-sdk/src/sandbox/envVars.tsdeleted file mode 100644index 5de6bb8a7..000000000--- a/packages/js-sdk/src/sandbox/envVars.ts+++ /dev/null@@ -1,3 +0,0 @@-export type EnvVars = {- [key: string]: string-}diff --git a/packages/js-sdk/src/sandbox/filesystemWatcher.ts b/packages/js-sdk/src/sandbox/filesystemWatcher.tsdeleted file mode 100644index ce1664d24..000000000--- a/packages/js-sdk/src/sandbox/filesystemWatcher.ts+++ /dev/null@@ -1,76 +0,0 @@-import { withTimeout } from '../utils/promise'-import { filesystemService } from './filesystem'-import { CallOpts, SandboxConnection } from './sandboxConnection'--export enum FilesystemOperation {- Create = 'Create',- Write = 'Write',- Remove = 'Remove',- Rename = 'Rename',- Chmod = 'Chmod',-}--export interface FilesystemEvent {- path: string;- name: string;- operation: FilesystemOperation;- // Unix epoch in nanoseconds- timestamp: number;- isDir: boolean;-}--export type FilesystemEventListener = (event: FilesystemEvent) => Promise<void> | void--class FilesystemWatcher {- // Listeners to filesystem events.- // Users of the this class can add their listeners to filesystem events- // via `this.addEventListeners`- private listeners: Set<FilesystemEventListener>- private rpcSubscriptionID?: string-- constructor(- private sessConn: SandboxConnection,- private path: string,- ) {- this.listeners = new Set<FilesystemEventListener>()- }-- // Starts watching the path that was passed to the contructor- async start(opts?: CallOpts) {- const start = async () => {- // Already started.- if (this.rpcSubscriptionID) return-- this.handleFilesystemEvents = this.handleFilesystemEvents.bind(this)-- this.rpcSubscriptionID = await this.sessConn._subscribe(- filesystemService,- this.handleFilesystemEvents,- 'watchDir',- this.path,- )- }- return await withTimeout(start, opts?.timeout)()- }-- // Stops watching the path and removes all listeners.- async stop() {- this.listeners.clear()- if (this.rpcSubscriptionID) {- await this.sessConn._unsubscribe(this.rpcSubscriptionID)- }- }-- addEventListener(l: FilesystemEventListener) {- this.listeners.add(l)- return () => this.listeners.delete(l)- }-- private handleFilesystemEvents(fsChange: FilesystemEvent) {- this.listeners.forEach((l) => {- l(fsChange)- })- }-}--export default FilesystemWatcherdiff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.tsindex f12c6fe76..e2853835b 100644--- a/packages/js-sdk/src/sandbox/index.ts+++ b/packages/js-sdk/src/sandbox/index.ts@@ -20,12 +20,7 @@ export type DownloadFileFormat =| 'text'export interface SandboxOpts extends SandboxConnectionOpts {- onScanPorts?: ScanOpenPortsHandler;- /** Timeout for sandbox to start */timeout?: number;- onStdout?: (out: ProcessMessage) => Promise<void> | void;- onStderr?: (out: ProcessMessage) => Promise<void> | void;- onExit?: (() => Promise<void> | void) | ((exitCode: number) => Promise<void> | void);}@@ -54,7 +49,7 @@ export interface SandboxOpts extends SandboxConnectionOpts {* await sandbox.close()* ```*/-export class Sandbox extends SandboxConnection {+export class Sandbox2 extends SandboxConnection {/*** Terminal manager used to create interactive terminals.*/diff --git a/packages/js-sdk/src/sandbox/rpc.ts b/packages/js-sdk/src/sandbox/rpc.tsdeleted file mode 100644index 2bacb3856..000000000--- a/packages/js-sdk/src/sandbox/rpc.ts+++ /dev/null@@ -1,431 +0,0 @@-// Based on https://github.com/radarsu/rpc-websocket-client--import IWebSocket from 'isomorphic-ws'--import { id } from '../utils/id'--export type RpcEventFunction = (- // @ts-ignore- e: IWebSocket.OpenEvent | IWebSocket.ErrorEvent-) => void-export type RpcMessageEventFunction = (e: IWebSocket.MessageEvent) => void-export type RpcCloseEventFunction = (e: IWebSocket.CloseEvent) => void--export type RpcNotificationEvent = (data: IRpcNotification) => void-export type RpcRequestEvent = (data: IRpcRequest) => void-export type RpcSuccessResponseEvent = (data: IRpcSuccessResponse) => void-export type RpcErrorResponseEvent = (data: IRpcErrorResponse) => void--export enum RpcVersions {- RPC_VERSION = '2.0'-}--export type RpcId = string | number--export interface IRpcData {- method: string;- params?: any;-}--export interface IRpcNotification extends IRpcData {- jsonrpc: RpcVersions.RPC_VERSION;-}--export interface IRpcRequest extends IRpcNotification {- // if not included its notification- id: RpcId;-}--export interface IRpcResponse {- id: RpcId;- jsonrpc: RpcVersions.RPC_VERSION;-}--export interface IRpcSuccessResponse extends IRpcResponse {- // if not included its notification- result: any;-}--export interface IRpcError {- code: number;- message: string;- data?: any;-}--export interface IRpcErrorResponse extends IRpcResponse {- error: IRpcError;-}--export interface IRpcWebSocketConfig {- responseTimeout: number;-}--export type RpcUnidentifiedMessage =- | IRpcRequest- | IRpcNotification- | IRpcSuccessResponse- | IRpcErrorResponse--export class RpcWebSocketClient {- // native websocket-- public ws: IWebSocket-- public onOpenHandlers: RpcEventFunction[] = []- public onAnyMessageHandlers: RpcMessageEventFunction[] = []-- public onNotification: RpcNotificationEvent[] = []- public onRequest: RpcRequestEvent[] = []- public onSuccessResponse: RpcSuccessResponseEvent[] = []- public onErrorResponse: RpcErrorResponseEvent[] = []-- public onErrorHandlers: RpcEventFunction[] = []- public onCloseHandlers: RpcCloseEventFunction[] = []-- public config: IRpcWebSocketConfig = {- responseTimeout: 10000- }-- private idAwaiter: {- [id: string]: (data?: any) => void;- } = {}-- // constructor- /**- * Does not start WebSocket connection!- * You need to call connect() method first.- * @memberof RpcWebSocketClient- */- public constructor() {- this.ws = undefined as any- }-- // public- /**- * Starts WebSocket connection. Returns Promise when connection is established.- * @param {string} url- * @param {(string | string[])} [protocols]- * @memberof RpcWebSocketClient- */- public connect(url: string, protocols?: string | string[]) {- this.ws = new IWebSocket(url, protocols)- return this.listen()- }-- // events- public onOpen(fn: RpcEventFunction) {- this.onOpenHandlers.push(fn)- }-- /**- * Native onMessage event. DO NOT USE THIS unless you really have to or for debugging purposes.- * Proper RPC events are onRequest, onNotification, onSuccessResponse and onErrorResponse (or just awaiting response).- * @param {RpcMessageEventFunction} fn- * @memberof RpcWebSocketClient- */- public onAnyMessage(fn: RpcMessageEventFunction) {- this.onAnyMessageHandlers.push(fn)- }-- public onError(fn: RpcEventFunction) {- this.onErrorHandlers.push(fn)- }-- public onClose(fn: RpcCloseEventFunction) {- this.onCloseHandlers.push(fn)- }-- /**- * Appends onmessage listener on native websocket with RPC handlers.- * If onmessage function was already there, it will call it on beggining.- * Useful if you want to use RPC WebSocket Client on already established WebSocket along with function changeSocket().- * @memberof RpcWebSocketClient- */- public listenMessages() {- let previousOnMessage: RpcMessageEventFunction | undefined- if (this.ws.onmessage) {- previousOnMessage = this.ws.onmessage.bind(this.ws)- }-- this.ws.onmessage = (e: IWebSocket.MessageEvent) => {- if (previousOnMessage) {- previousOnMessage(e)- }-- for (const handler of this.onAnyMessageHandlers) {- handler(e)- }-- const data: RpcUnidentifiedMessage = JSON.parse(e.data.toString())- if (this.isNotification(data)) {- // notification- for (const handler of this.onNotification) {- handler(data)- }- } else if (this.isRequest(data)) {- // request- for (const handler of this.onRequest) {- handler(data)- }- // responses- } else if (this.isSuccessResponse(data)) {- // success- for (const handler of this.onSuccessResponse) {- handler(data)- }-- // resolve awaiting function- this.idAwaiter[data.id](data.result)- } else if (this.isErrorResponse(data)) {- // error- for (const handler of this.onErrorResponse) {- handler(data)- }-- // resolve awaiting function- this.idAwaiter[data.id](data.error)- }- }- }-- // communication-- /**- * Creates and sends RPC request. Resolves when appropirate response is returned from server or after config.responseTimeout.- * @param {string} method- * @param {*} [params]- * @returns- * @memberof RpcWebSocketClient- */- public call(method: string, params?: any) {- return new Promise((resolve, reject) => {- const data = this.buildRequest(method, params)-- // give limited time for response- let timeout: number | NodeJS.Timeout- if (this.config.responseTimeout) {- timeout = setTimeout(() => {- // stop waiting for response- delete this.idAwaiter[data.id]- reject(- new Error(`Awaiting response to "${method}" with id: ${data.id} timed out.`)- )- }, this.config.responseTimeout)- }-- // expect response- this.idAwaiter[data.id] = (responseData?: any) => {- // stop timeout- clearInterval(timeout as number)- // stop waiting for response- delete this.idAwaiter[data.id]-- if (this.isRpcError(responseData)) {- reject(new Error(`RPC Error (${responseData.code}): ${responseData.message}`))- return- }-- resolve(responseData)- }-- const json = JSON.stringify(data)- this.ws.send(json)- })- }-- /**- * Creates and sends RPC Notification.- * @param {string} method- * @param {*} [params]- * @memberof RpcWebSocketClient- */- public notify(method: string, params?: any) {- this.ws.send(JSON.stringify(this.buildNotification(method, params)))- }-- // setup-- /**- * You can provide custom id generation function to replace default uuid/v1.- * @param {() => string} idFn- * @memberof RpcWebSocketClient- */- public customId(idFn: () => string) {- this.idFn = idFn- }-- /**- * Removed jsonrpc from sent messages. Good if you don't care about standards or need better performance.- * @memberof RpcWebSocketClient- */- public noRpc() {- this.buildRequest = this.buildRequestBase- this.buildNotification = this.buildNotificationBase- this.buildRpcSuccessResponse = this.buildRpcSuccessResponseBase- this.buildRpcErrorResponse = this.buildRpcErrorResponseBase- }-- /**- * Allows modifying configuration.- * @param {IRpcWebSocketConfig} options- * @memberof RpcWebSocketClient- */- public configure(options: IRpcWebSocketConfig) {- Object.assign(this.config, options)- }-- /**- * Allows you to change used native WebSocket client to another one.- * If you have already-connected WebSocket, use this with listenMessages().- * @param {WebSocket} ws- * @memberof RpcWebSocketClient- */- public changeSocket(ws: IWebSocket) {- this.ws = ws- }-- // private-- // events- private listen() {- return new Promise((resolve, reject) => {- // @ts-ignore- this.ws.onopen = (e: IWebSocket.OpenEvent) => {- for (const handler of this.onOpenHandlers) {- handler(e)- }- resolve(e)- }-- // listen for messages- this.listenMessages()-- // called before onclose- this.ws.onerror = (e: IWebSocket.ErrorEvent) => {- for (const handler of this.onErrorHandlers) {- handler(e)- }- }-- this.ws.onclose = (e: IWebSocket.CloseEvent) => {- for (const handler of this.onCloseHandlers) {- handler(e)- }- reject(new Error(`WebSocket closed with code: ${e.code} and reason: ${e.reason}`))- }- })- }-- // request- private buildRequest(method: string, params?: any): IRpcRequest {- const data = this.buildRequestBase(method, params)- data.jsonrpc = RpcVersions.RPC_VERSION- return data- }-- private buildRequestBase(method: string, params?: any): IRpcRequest {- const data: IRpcRequest = {} as any- data.id = this.idFn()- data.method = method-- if (params) {- data.params = params- }-- return data- }-- // notification- private buildNotification(method: string, params?: any): IRpcNotification {- const data = this.buildNotificationBase(method, params)- data.jsonrpc = RpcVersions.RPC_VERSION- return data- }-- private buildNotificationBase(- method: string,- params?: any- ): IRpcNotification {- const data: IRpcNotification = {} as any- data.method = method-- if (params) {- data.params = params- }-- return data- }-- // success response- private buildRpcSuccessResponse(- id: RpcId,- result: any- ): IRpcSuccessResponse {- const data = this.buildRpcSuccessResponseBase(id, result)- data.jsonrpc = RpcVersions.RPC_VERSION- return data- }-- private buildRpcSuccessResponseBase(- id: RpcId,- result: any- ): IRpcSuccessResponse {- const data: IRpcSuccessResponse = {} as any- data.id = id- data.result = result- return data- }-- // error response- private buildRpcErrorResponse(- id: RpcId,- error: IRpcError- ): IRpcErrorResponse {- const data = this.buildRpcErrorResponseBase(id, error)- data.jsonrpc = RpcVersions.RPC_VERSION- return data- }-- private buildRpcErrorResponseBase(- id: RpcId,- error: IRpcError- ): IRpcErrorResponse {- const data: IRpcErrorResponse = {} as any- data.id = id- data.error = error- return data- }-- private idFn(): RpcId {- return id(12)- }-- // tests- private isNotification(- data: RpcUnidentifiedMessage- ): data is IRpcNotification {- return !(data as any).id- }-- private isRequest(data: RpcUnidentifiedMessage): data is IRpcRequest {- return (data as any).method- }-- private isSuccessResponse(- data: RpcUnidentifiedMessage- ): data is IRpcSuccessResponse {- // eslint-disable-next-line no-prototype-builtins- return data.hasOwnProperty('result')- }-- private isErrorResponse(- data: RpcUnidentifiedMessage- ): data is IRpcErrorResponse {- // eslint-disable-next-line no-prototype-builtins- return data.hasOwnProperty('error')- }-- private isRpcError(data: any): data is IRpcError {- return typeof data?.code !== 'undefined'- }-}diff --git a/packages/js-sdk/src/sandbox/sandbox.ts b/packages/js-sdk/src/sandbox/sandbox.tsnew file mode 100644index 000000000..720e134d7--- /dev/null+++ b/packages/js-sdk/src/sandbox/sandbox.ts@@ -0,0 +1,170 @@+import { APIOpts } from '../api'+import { RPC_PORT, DEBUG, DOMAIN } from '../constants'+import { getApiKey } from '../utils/apiKey'+import { SandboxApi } from './sandboxApi'+import { SandboxRpc } from './sandboxRpc'++export interface EnvVars {+ [key: string]: string+}++export interface Logger {+ debug?: (message: string, ...args: unknown[]) => void+ info?: (message: string, ...args: unknown[]) => void+ warn?: (message: string, ...args: unknown[]) => void+ error?: (message: string, ...args: unknown[]) => void+}++export type SandboxMetadata = {+ [key: string]: string+}++export interface SandboxOpts extends APIOpts {+ /**+ * Sandbox Template ID or name.+ */+ template?: string+ apiKey?: string+ /**+ * Domain to use for the API requests. If not provided, the `E2B_DOMAIN` environment variable will be used.+ */+ domain?: string+ cwd?: string+ envVars?: EnvVars+ /**+ * A dictionary of strings that is stored alongside the running sandbox.+ * You can see this metadata when you list running sandboxes.+ */+ metadata?: SandboxMetadata+ logger?: Logger+ timeout?: number+}++export class Sandbox extends SandboxApi {+ private readonly rpc: SandboxRpc++ constructor(private readonly id: string, private readonly opts: Omit<SandboxOpts, 'timeout' | 'metadata' | 'template' | ''>) {+ super()++ const hostname = this.getHostname(RPC_PORT)+ const rpcUrl = `${this.debug ? 'http' : 'https'}://${hostname}`++ this.rpc = new SandboxRpc(rpcUrl)+ }++ private get debug() {+ return this.opts?.debug ?? DEBUG+ }++ private get domain() {+ return this.opts?.domain ?? DOMAIN+ }++ private get apiKey() {+ return getApiKey(this.opts?.apiKey)+ }++ private get envVars() {+ // return this.opts?.envVars ?? {}+ }++ private get cwd() {+ // return this.opts?.cwd ?? process.cwd()+ }++ /**+ * Creates a new Sandbox from the default `base` sandbox template.+ * @returns New Sandbox+ *+ * @constructs Sandbox+ */+ static async spawn<S extends typeof Sandbox>(this: S): Promise<InstanceType<S>>+ /**+ * Creates a new Sandbox from the template with the specified ID.+ * @param template Sandbox template ID or name+ * @returns New Sandbox+ */+ static async spawn<S extends typeof Sandbox>(this: S, template: string): Promise<InstanceType<S>>+ /**+ * Creates a new Sandbox from the specified options.+ * @param opts Sandbox options+ * @returns New Sandbox+ */+ static async spawn<S extends typeof Sandbox>(this: S, opts: SandboxOpts): Promise<InstanceType<S>>+ static async spawn(optsOrTemplate?: string | SandboxOpts) {+ const opts: SandboxOpts = typeof optsOrTemplate === 'string'+ ? { template: optsOrTemplate }+ : optsOrTemplate++ const sandboxID = await this.spawn(opts.template, opts)++ return new this(sandboxID)+ }++ /**+ * Reconnects to an existing Sandbox.+ * @param sandboxID Sandbox ID+ * @returns Existing Sandbox+ */+ static async connect<S extends typeof Sandbox>(this: S, sandboxID: string): Promise<InstanceType<S>>+ /**+ * Reconnects to an existing Sandbox.+ * @param opts Sandbox options+ * @returns Existing Sandbox+ */+ static async connect<S extends typeof Sandbox>(this: S, opts: Omit<SandboxOpts, 'id' | 'template'> & { sandboxID: string }): Promise<InstanceType<S>>+ static async connect<S extends typeof Sandbox>(this: S, sandboxIDorOpts: string | Omit<SandboxOpts, 'id' | 'template'> & { sandboxID: string }): Promise<InstanceType<S>> {+ let id: string+ let opts: SandboxOpts+ if (typeof sandboxIDorOpts === 'string') {+ id = sandboxIDorOpts+ opts = {}+ } else {+ id = sandboxIDorOpts.sandboxID+ opts = sandboxIDorOpts+ }++ return new this(sandboxID) as InstanceType<S>+ }++ /**+ * Get the hostname for the sandbox or for the specified sandbox's port.+ *+ * `getHostname` method requires `this` context - you may need to bind it.+ *+ * @param port Specify if you want to connect to a specific port of the sandbox+ * @returns Hostname of the sandbox or sandbox's port+ */+ getHostname(port: number) {+ if (this.debug) {+ if (port) {+ return `localhost:${port}`+ }++ return 'localhost'+ }++ const hostname = `${this.id}.${this.domain}`+ if (port) {+ return `${port}-${hostname}`+ }++ return hostname+ }++ async setTimeout(timeout: number) {+ await SandboxApi.setTimeout(this.id, timeout, {+ apiKey: this.apiKey,+ domain: this.domain,+ debug: this.debug,+ })+ }++ async kill() {+ await SandboxApi.kill(this.id, {+ apiKey: this.apiKey,+ domain: this.domain,+ debug: this.debug,+ })+ }+}diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.tsnew file mode 100644index 000000000..5c80b9f15--- /dev/null+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts@@ -0,0 +1,102 @@+import { APIClient, APIOpts, withAPIKey } from '../api'+import { getApiKey } from '../utils/apiKey'++export type SandboxMetadata = {+ [key: string]: string+}++export interface RunningSandbox {+ sandboxID: string+ templateID: string+ alias?: string+ metadata?: SandboxMetadata+ startedAt: Date+}++export class SandboxApi {+ static async kill(+ sandboxID: string,+ opts: APIOpts & { apiKey?: string } = {}+ ): Promise<void> {+ const apiKey = getApiKey(opts.apiKey)++ // TODO: Ensure the short id/long id works with kill++ const client = new APIClient(opts)+ const killSandbox = withAPIKey(+ client.api.path('/sandboxes/{sandboxID}').method('delete').create(),+ )++ await killSandbox(apiKey, { sandboxID })+ }++ static async list(opts: APIOpts & { apiKey?: string } = {}): Promise<RunningSandbox[]> {+ const apiKey = getApiKey(opts.apiKey)++ const client = new APIClient(opts)++ const listSandboxes = withAPIKey(+ client.api.path('/sandboxes').method('get').create(),+ )++ const res = await listSandboxes(apiKey, {})++ return res.data.map((sandbox) => ({+ sandboxID: this.getSandboxID(sandbox),+ templateID: sandbox.templateID,+ cpuCount: sandbox.cpuCount,+ memoryMB: sandbox.memoryMB,+ ...(sandbox.alias && { alias: sandbox.alias }),+ ...(sandbox.metadata && { metadata: sandbox.metadata }),+ startedAt: new Date(sandbox.startedAt),+ }))+ }++ protected static async spawn(+ template: string,+ opts: APIOpts & {+ metadata?: SandboxMetadata,+ apiKey?: string,+ timeout?: number,+ } = {}): Promise<string> {+ const apiKey = getApiKey(opts.apiKey)++ const client = new APIClient(opts)++ const createSandbox = withAPIKey(+ client.api.path('/sandboxes').method('post').create(),+ )++ const res = await createSandbox(apiKey, {+ templateID: template,+ metadata: opts.metadata,+ timeout: opts.timeout,+ })++ return this.getSandboxID(res.data)+ }++ protected static async setTimeout(+ sandboxID: string,+ timeout: number,+ opts: APIOpts & {+ apiKey?: string,+ } = {}): Promise<void> {+ const apiKey = getApiKey(opts.apiKey)++ const client = new APIClient(opts)++ const setSandboxTimeout = withAPIKey(+ client.api.path('/sandboxes/{sandboxID}/timeout').method('post').create(),+ )++ await setSandboxTimeout(apiKey, {+ sandboxID,+ duration: timeout,+ })+ }++ private static getSandboxID({ sandboxID, clientID }: { sandboxID: string, clientID: string }): string {+ return `${sandboxID}-${clientID}`+ }+}\ No newline at end of filediff --git a/packages/js-sdk/src/sandbox/sandboxConnection.ts b/packages/js-sdk/src/sandbox/sandboxConnection.tsindex a24c4c73f..f882cfbbe 100644--- a/packages/js-sdk/src/sandbox/sandboxConnection.ts+++ b/packages/js-sdk/src/sandbox/sandboxConnection.ts@@ -1,4 +1,4 @@-import { IRpcNotification, RpcWebSocketClient } from './rpc'+import { IRpcNotification } from './sandboxRpc'import { APIClient, components, withAPIKey } from '../api'import {@@ -21,20 +21,12 @@ import { EnvVars } from './envVars'import { getApiKey } from '../utils/apiKey'import { watchDirect } from '../gen'-// eslint-disable-next-line @typescript-eslint/no-explicit-any-type SubscriptionHandler = (result: any) => void-type Service =| typeof processService| typeof codeSnippetService| typeof filesystemService| typeof terminalService-interface Subscriber {- service: Service- subID: string- handler: SubscriptionHandler-}export interface Logger {debug?: (message: string, ...args: unknown[]) => void@@ -43,7 +35,7 @@ export interface Logger {error?: (message: string, ...args: unknown[]) => void}-export interface SandboxMetadata {+export type SandboxMetadata = {[key: string]: string}@@ -58,16 +50,8 @@ export interface RunningSandbox {export interface SandboxConnectionOpts {/*** Sandbox Template ID or name.- *- * If not specified, the 'base' template will be used.*/template?: string- /**- * @deprecated Use `template` instead.- *- * Sandbox Template ID or name.- */- id?: stringapiKey?: string/*** Domain to use for the API requests. If not provided, the `E2B_DOMAIN` environment variable will be used.@@ -87,18 +71,13 @@ export interface SandboxConnectionOpts {__debug_devEnv?: 'remote' | 'local'}-export interface CallOpts {- /** Timeout for the call in milliseconds */- timeout?: number-}-export class SandboxConnection {/*** Default working directory used in the sandbox.** You can change the working directory by setting the `cwd` property.**/- cwd: string | undefined+ cwd?: string/*** Default environment variables used in the sandbox.*@@ -107,12 +86,9 @@ export class SandboxConnection {envVars: EnvVarsprotected readonly logger: Logger- protected sandbox?: components['schemas']['Sandbox']- protected isOpen = false+ protected readonly sandbox?: components['schemas']['Sandbox']private readonly apiKey: string- private readonly rpc = new RpcWebSocketClient()- private subscribers: Subscriber[] = []private readonly client: APIClient// let's keep opts readonly, but public - for convenience, mainly when debugging@@ -123,11 +99,11 @@ export class SandboxConnection {if (!createCalled) {throw new Error("Sandbox can't be instantiated directly, use a `.create()` method instead of calling `new` to get a new sandbox.\n\n" +- 'Example of correct usage:\n' +- '```\n' +- "import { CodeInterpreter } from '@e2b/code-interpreter'\n" +- 'const myCodeInterpreter = await CodeInterpreter.create()\n' +- '``',+ 'Example of correct usage:\n' ++ '```\n' ++ "import { CodeInterpreter } from '@e2b/code-interpreter'\n" ++ 'const myCodeInterpreter = await CodeInterpreter.create()\n' ++ '``',)}@@ -183,94 +159,6 @@ export class SandboxConnection {)}- /**- * List all running sandboxes- *- * @param apiKey API key to use for authentication. If not provided, the `E2B_API_KEY` environment variable will be used.- * @param domain Domain to use for the API requests. If not provided, the `E2B_DOMAIN` environment variable will be used.- */- static async list(- apiKey?: string,- domain?: string,- ): Promise<RunningSandbox[]> {- apiKey = getApiKey(apiKey)-- const client = new APIClient({ domain })-- const listSandboxes = withAPIKey(- client.api.path('/sandboxes').method('get').create(),- )-- try {- const res = await listSandboxes(apiKey, {})-- return res.data.map((sandbox) => ({- sandboxID: `${sandbox.sandboxID}-${sandbox.clientID}`,- templateID: sandbox.templateID,- cpuCount: sandbox.cpuCount,- memoryMB: sandbox.memoryMB,- ...(sandbox.alias && { alias: sandbox.alias }),- ...(sandbox.metadata && { metadata: sandbox.metadata }),- startedAt: new Date(sandbox.startedAt),- }))- } catch (e) {- if (e instanceof listSandboxes.Error) {- const error = e.getActualType()- if (error.status === 401) {- throw new Error(- `Error listing sandboxes - (${error.status}) unauthenticated: ${error.data.message}`,- )- }- if (error.status === 500) {- throw new Error(- `Error listing sandboxes - (${error.status}) server error: ${error.data.message}`,- )- }- }- throw e- }- }-- /**- * List all running sandboxes- * @param sandboxID ID of the sandbox to kill- * @param apiKey API key to use for authentication. If not provided, the `E2B_API_KEY` environment variable will be used.- * @param domain Domain to use for the API requests. If not provided, the `E2B_DOMAIN` environment variable will be used.- */- static async kill(- sandboxID: string,- apiKey?: string,- domain?: string,- ): Promise<void> {- apiKey = getApiKey(apiKey)-- const shortID = sandboxID.split('-')[0]-- const client = new APIClient({ domain })- const killSandbox = withAPIKey(- client.api.path('/sandboxes/{sandboxID}').method('delete').create(),- )-- try {- await killSandbox(apiKey, { sandboxID: shortID })- } catch (e) {- if (e instanceof killSandbox.Error) {- const error = e.getActualType()- if (error.status === 401) {- throw new Error(- `Error killing sandbox (${sandboxID}) - (${error.status}) unauthenticated: ${error.data.message}`,- )- }- if (error.status === 500) {- throw new Error(- `Error killing sandbox (${sandboxID}) - (${error.status}) server error: ${error.data.message}`,- )- }- }- throw e- }- }-/*** Keep the sandbox alive for the specified duration.*@@ -394,8 +282,8 @@ export class SandboxConnection {return results.map((r) =>r.status === 'fulfilled' ? r.value : undefined,) as {- [P in keyof T]: Awaited<T[P]>- }+ [P in keyof T]: Awaited<T[P]>+ }}await Promise.all(@@ -432,8 +320,7 @@ export class SandboxConnection {if (typeof subID !== 'string') {throw new Error(- `Cannot subscribe to ${service}_${method}${- params.length > 0 ? ' with params [' + params.join(', ') + ']' : ''+ `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,)}`,@@ -446,8 +333,7 @@ export class SandboxConnection {subID,})this.logger.debug?.(- `Subscribed to "${service}_${method}"${- params.length > 0 ? ' with params [' + params.join(', ') + '] and' : ''+ `Subscribed to "${service}_${method}"${params.length > 0 ? ' with params [' + params.join(', ') + '] and' : ''} with id "${subID}"`,)@@ -583,8 +469,7 @@ export class SandboxConnection {this.rpc.onError(async (err) => {this.logger.debug?.(- `Error in WebSocket of sandbox "${this.id}": ${- err.message ?? err.code ?? err.toString()+ `Error in WebSocket of sandbox "${this.id}": ${err.message ?? err.code ?? err.toString()}. Trying to reconnect...`,)@@ -601,8 +486,7 @@ export class SandboxConnection {} catch (err: any) {// not warn, because this is somewhat expected behaviour during initializationthis.logger.debug?.(- `Failed reconnecting to sandbox "${this.id}": ${- err.message ?? err.code ?? err.toString()+ `Failed reconnecting to sandbox "${this.id}": ${err.message ?? err.code ?? err.toString()}`,)}@@ -617,72 +501,22 @@ export class SandboxConnection {this.rpc.onNotification.push(this.handleNotification.bind(this))- // We invoke the rpc.connect method in a separate promise because when using edge- // the rpc.connect does not throw or end on error.- ;(async () => {- try {- this.logger.debug?.(`Connecting to sandbox "${this.id}"`)- await this.rpc.connect(sandboxURL)- // eslint-disable-next-line @typescript-eslint/no-explicit-any- } catch (err: any) {- // not warn, because this is somewhat expected behaviour during initialization- this.logger.debug?.(- `Error connecting to sandbox "${this.id}": ${- err.message ?? err.code ?? err.toString()- }`,- )- }- })()-- await openingPromise- }-- private handleNotification(data: IRpcNotification) {- this.logger.debug?.('Handling notification:', data)- this.subscribers- .filter((s) => s.subID === data.params?.subscription)- .forEach((s) => s.handler(data.params?.result))- }-- private async refresh(sandboxID: string) {- this.logger.debug?.(`Started refreshing sandbox "${sandboxID}"`)-- try {- // eslint-disable-next-line no-constant-condition- while (true) {- if (!this.isOpen) {+ // We invoke the rpc.connect method in a separate promise because when using edge+ // the rpc.connect does not throw or end on error.+ ; (async () => {+ try {+ this.logger.debug?.(`Connecting to sandbox "${this.id}"`)+ await this.rpc.connect(sandboxURL)+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } catch (err: any) {+ // not warn, because this is somewhat expected behaviour during initializationthis.logger.debug?.(- `Cannot refresh sandbox ${this.id} - it was closed`,+ `Error connecting to sandbox "${this.id}": ${err.message ?? err.code ?? err.toString()+ }`,)- return}+ })()- await wait(SANDBOX_REFRESH_PERIOD)-- try {- await this.refreshSandbox(this.apiKey, {- sandboxID,- duration: 0,- })- this.logger.debug?.(`Refreshed sandbox "${sandboxID}"`)- } catch (e) {- if (e instanceof this.refreshSandbox.Error) {- const error = e.getActualType()- if (error.status === 404) {- this.logger.warn?.(- `Error refreshing sandbox - (${error.status}): ${error.data.message}`,- )- return- }- this.logger.warn?.(- `Refreshing sandbox "${sandboxID}" failed - (${error.status})`,- )- }- }- }- } finally {- this.logger.debug?.(`Stopped refreshing sandbox "${sandboxID}"`)- await this.close()- }+ await openingPromise}}diff --git a/packages/js-sdk/src/sandbox/sandboxRpc.ts b/packages/js-sdk/src/sandbox/sandboxRpc.tsnew file mode 100644index 000000000..712dc7973--- /dev/null+++ b/packages/js-sdk/src/sandbox/sandboxRpc.ts@@ -0,0 +1,19 @@+import { createPromiseClient, PromiseClient } from '@connectrpc/connect'+import { createConnectTransport } from '@connectrpc/connect-web'++import { FilesystemService } from '../envd/filesystem/v1/filesystem_connect'+import { ProcessService } from '../envd/process/v1/process_connect'++export class SandboxRpc {+ readonly filesystem: PromiseClient<typeof FilesystemService>+ readonly process: PromiseClient<typeof ProcessService>++ constructor(baseUrl: string) {+ const transport = createConnectTransport({+ baseUrl,+ })++ this.filesystem = createPromiseClient(FilesystemService, transport)+ this.process = createPromiseClient(ProcessService, transport)+ }+}diff --git a/packages/js-sdk/src/utils/apiKey.ts b/packages/js-sdk/src/utils/apiKey.tsindex be61e1a8d..368ed3006 100644--- a/packages/js-sdk/src/utils/apiKey.ts+++ b/packages/js-sdk/src/utils/apiKey.ts@@ -7,7 +7,7 @@ export function getApiKey(apiKey?: string): string {throw new AuthenticationError('API key is required, please visit https://e2b.dev/docs to get your API key. ' +'You can either set the environment variable `E2B_API_KEY` ' +- "or you can pass it directly to the sandbox like Sandbox.create({apiKey: 'e2b_...'})",+ "or you can pass it directly to the sandbox like Sandbox.create({ apiKey: 'e2b_...' })",)}