Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Add timeouts to JS SDK (#104)
Jakub Novák4ce867ce9c6a
diff --git a/.changeset/khaki-wolves-retire.md b/.changeset/khaki-wolves-retire.mdnew file mode 100644index 000000000..3ba75306a--- /dev/null+++ b/.changeset/khaki-wolves-retire.md@@ -0,0 +1,5 @@+---+"@e2b/sdk": patch+---++Add the possibility to timeout callsdiff --git a/packages/js-sdk/src/constants.ts b/packages/js-sdk/src/constants.tsindex a107cad32..91eab2afd 100644--- a/packages/js-sdk/src/constants.ts+++ b/packages/js-sdk/src/constants.ts@@ -1,6 +1,8 @@export const SESSION_REFRESH_PERIOD = 5_000 // 5sexport const WS_RECONNECT_INTERVAL = 600 // 600ms+export const TIMEOUT = 60_000 // 60s+export const SESSION_DOMAIN = 'ondevbook.com'export const WS_PORT = 49982export const WS_ROUTE = '/ws'diff --git a/packages/js-sdk/src/session/error.ts b/packages/js-sdk/src/error.tssimilarity index 52%rename from packages/js-sdk/src/session/error.tsrename to packages/js-sdk/src/error.tsindex 410cdb22e..b91f1fb02 100644--- a/packages/js-sdk/src/session/error.ts+++ b/packages/js-sdk/src/error.ts@@ -1,3 +1,10 @@+export class TimeoutError extends Error {+ constructor(message: any) {+ super(message)+ this.name = 'TimeoutError'+ }+}+export class AuthenticationError extends Error {constructor(message: any) {super(message)diff --git a/packages/js-sdk/src/session/filesystem.ts b/packages/js-sdk/src/session/filesystem.tsindex 3d4f2c28c..b56ef0efd 100644--- a/packages/js-sdk/src/session/filesystem.ts+++ b/packages/js-sdk/src/session/filesystem.ts@@ -1,4 +1,5 @@import FilesystemWatcher from './filesystemWatcher'+import { CallOpts } from './sessionConnection'export const filesystemService = 'filesystem'@@ -8,12 +9,12 @@ export interface FileInfo {}export interface FilesystemManager {- readonly write: (path: string, content: string) => Promise<void>+ readonly write: (path: string, content: string, opts?: CallOpts) => Promise<void>// readonly writeBytes: (path: string, content: Uint8Array) => Promise<void>- readonly read: (path: string) => Promise<string>+ readonly read: (path: string, opts?: CallOpts) => Promise<string>// readonly readBytes: (path: string) => Promise<Uint8Array>- readonly remove: (path: string) => Promise<void>- readonly list: (path: string) => Promise<FileInfo[]>- readonly makeDir: (path: string) => Promise<void>+ readonly remove: (path: string, opts?: CallOpts) => Promise<void>+ readonly list: (path: string, opts?: CallOpts) => Promise<FileInfo[]>+ readonly makeDir: (path: string, opts?: CallOpts) => Promise<void>readonly watchDir: (path: string) => FilesystemWatcher}diff --git a/packages/js-sdk/src/session/filesystemWatcher.ts b/packages/js-sdk/src/session/filesystemWatcher.tsindex 06049b6e1..68ca9d581 100644--- a/packages/js-sdk/src/session/filesystemWatcher.ts+++ b/packages/js-sdk/src/session/filesystemWatcher.ts@@ -1,5 +1,6 @@+import { withTimeout } from '../utils/promise'import { filesystemService } from './filesystem'-import { SessionConnection } from './sessionConnection'+import { CallOpts, SessionConnection } from './sessionConnection'export enum FilesystemOperation {Create = 'Create',@@ -32,18 +33,21 @@ class FilesystemWatcher {}// Starts watching the path that was passed to the contructor- async start() {- // Already started.- if (this.rpcSubscriptionID) return+ async start(opts: CallOpts) {+ const start = async () => {+ // Already started.+ if (this.rpcSubscriptionID) return- this.handleFilesystemEvents = this.handleFilesystemEvents.bind(this)+ this.handleFilesystemEvents = this.handleFilesystemEvents.bind(this)- this.rpcSubscriptionID = await this.sessConn.subscribe(- filesystemService,- this.handleFilesystemEvents,- 'watchDir',- this.path,- )+ 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.diff --git a/packages/js-sdk/src/session/index.ts b/packages/js-sdk/src/session/index.tsindex f8a7f9ddd..5e798df64 100644--- a/packages/js-sdk/src/session/index.ts+++ b/packages/js-sdk/src/session/index.ts@@ -2,7 +2,7 @@ import normalizePath from 'normalize-path'import { components } from '../api'import { id } from '../utils/id'-import { createDeferredPromise, formatSettledErrors } from '../utils/promise'+import { createDeferredPromise, formatSettledErrors, withTimeout } from '../utils/promise'import {ScanOpenedPortsHandler as ScanOpenPortsHandler,codeSnippetService,@@ -13,16 +13,24 @@ import {Process,ProcessManager,ProcessMessage,+ ProcessOpts,ProcessOutput,processService,} from './process'-import { SessionConnection, SessionConnectionOpts } from './sessionConnection'-import { Terminal, TerminalManager, TerminalOutput, terminalService } from './terminal'+import { CallOpts, SessionConnection, SessionConnectionOpts } from './sessionConnection'+import {+ Terminal,+ TerminalManager,+ TerminalOpts,+ TerminalOutput,+ terminalService,+} from './terminal'export type Environment = components['schemas']['Template']export interface SessionOpts extends SessionConnectionOpts {onScanPorts?: ScanOpenPortsHandler+ timeout?: number}export class Session extends SessionConnection {@@ -40,34 +48,42 @@ export class Session extends SessionConnection {this.filesystem = {/*** List files in a directory.- * @param path path to a directory+ * @param path Path to a directory+ * @param opts Call options+ * @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)* @returns Array of files in a directory*/- list: async path => {- return (await this.call(filesystemService, 'list', [path])) as FileInfo[]+ list: async (path, opts?: CallOpts) => {+ return (await this.call(filesystemService, 'list', [path], opts)) as FileInfo[]},/*** Reads the whole content of a file.- * @param path path to a file+ * @param path Path to a file+ * @param opts Call options+ * @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)* @returns Content of a file*/- read: async path => {- return (await this.call(filesystemService, 'read', [path])) as string+ read: async (path, opts?: CallOpts) => {+ return (await this.call(filesystemService, 'read', [path], opts)) as string},/*** Removes a file or a directory.- * @param path path to a file or a directory+ * @param path Path to a file or a directory+ * @param opts Call options+ * @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)*/- remove: async path => {- await this.call(filesystemService, 'remove', [path])+ remove: async (path, opts?: CallOpts) => {+ await this.call(filesystemService, 'remove', [path], opts)},/*** Writes content to a new file on path.- * @param path path to a new file. For example '/dirA/dirB/newFile.txt' when creating 'newFile.txt'- * @param content content to write to a new file+ * @param path Path to a new file. For example '/dirA/dirB/newFile.txt' when creating 'newFile.txt'+ * @param content Content to write to a new file+ * @param opts Call options+ * @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)*/- write: async (path, content) => {- await this.call(filesystemService, 'write', [path, content])+ write: async (path, content, opts?: CallOpts) => {+ await this.call(filesystemService, 'write', [path, content], opts)},// /**// * Write array of bytes to a file.@@ -97,15 +113,17 @@ export class Session extends SessionConnection {// },/*** Creates a new directory and all directories along the way if needed on the specified pth.- * @param path path to a new directory. For example '/dirA/dirB' when creating 'dirB'.+ * @param path Path to a new directory. For example '/dirA/dirB' when creating 'dirB'.+ * @param opts Call options+ * @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)*/- makeDir: async path => {- await this.call(filesystemService, 'makeDir', [path])+ makeDir: async (path, opts?: CallOpts) => {+ await this.call(filesystemService, 'makeDir', [path], opts)},/*** Watches directory for filesystem events.- * @param path path to a directory that will be watched- * @returns new watcher+ * @param path Path to a directory that will be watched+ * @returns New watcher*/watchDir: (path: string) => {this.logger.debug?.(`Watching directory "${path}"`)@@ -124,137 +142,165 @@ export class Session extends SessionConnection {cmd,rootdir = '',terminalID = id(12),- }) => {- this.logger.debug?.(`Starting terminal "${terminalID}"`)- const { promise: terminalExited, resolve: triggerExit } = createDeferredPromise()-- const output = new TerminalOutput()-- function handleData(data: string) {- output.addData(data)- onData?.(data)- }-- const [onDataSubID, onExitSubID] = await this.handleSubscriptions(- this.subscribe(terminalService, handleData, 'onData', terminalID),- this.subscribe(terminalService, triggerExit, 'onExit', terminalID),- )-- const { promise: unsubscribing, resolve: handleFinishUnsubscribing } =- createDeferredPromise<TerminalOutput>()+ timeout = undefined,+ }: TerminalOpts) => {+ const start = async ({+ onData,+ size,+ onExit,+ envVars,+ cmd,+ rootdir = '',+ terminalID = id(12),+ }: Omit<TerminalOpts, 'timeout'>) => {+ this.logger.debug?.(`Starting terminal "${terminalID}"`)+ const { promise: terminalExited, resolve: triggerExit } =+ createDeferredPromise()++ const output = new TerminalOutput()++ function handleData(data: string) {+ output.addData(data)+ onData?.(data)+ }- terminalExited.then(async () => {- const results = await Promise.allSettled([- this.unsubscribe(onExitSubID),- this.unsubscribe(onDataSubID),- ])- this.logger.debug?.(`Terminal "${terminalID}" exited`)+ const [onDataSubID, onExitSubID] = await this.handleSubscriptions(+ this.subscribe(terminalService, handleData, 'onData', terminalID),+ this.subscribe(terminalService, triggerExit, 'onExit', terminalID),+ )- const errMsg = formatSettledErrors(results)- if (errMsg) {- this.logger.error?.(errMsg)+ const { promise: unsubscribing, resolve: handleFinishUnsubscribing } =+ createDeferredPromise<TerminalOutput>()++ terminalExited.then(async () => {+ const results = await Promise.allSettled([+ this.unsubscribe(onExitSubID),+ this.unsubscribe(onDataSubID),+ ])+ this.logger.debug?.(`Terminal "${terminalID}" exited`)++ const errMsg = formatSettledErrors(results)+ if (errMsg) {+ this.logger.error?.(errMsg)+ }++ onExit?.()+ handleFinishUnsubscribing(output)+ })++ try {+ await this.call(terminalService, 'start', [+ terminalID,+ size.cols,+ size.rows,+ // Handle optional args for old devbookd compatibility+ ...(cmd !== undefined ? [envVars, cmd, rootdir] : []),+ ])+ } catch (err) {+ triggerExit()+ await unsubscribing+ throw err}- onExit?.()- handleFinishUnsubscribing(output)- })-- try {- await this.call(terminalService, 'start', [- terminalID,- size.cols,- size.rows,- // Handle optional args for old devbookd compatibility- ...(cmd !== undefined ? [envVars, cmd, rootdir] : []),- ])- } catch (err) {- triggerExit()- await unsubscribing- throw err+ return new Terminal(terminalID, this, triggerExit, unsubscribing, output)}-- return new Terminal(terminalID, this, triggerExit, unsubscribing, output)+ return await withTimeout(+ start,+ timeout,+ )({+ onData,+ size,+ onExit,+ envVars,+ cmd,+ rootdir,+ terminalID,+ })},}// Init Process handlerthis.process = {- start: async ({- cmd,- onStdout,- onStderr,- onExit,- envVars = {},- rootdir = '',- processID = id(12),- }) => {- if (!cmd) {- throw new Error('cmd is required')- }- this.logger.debug?.(`Starting process "${processID}"`)-- const { promise: processExited, resolve: triggerExit } = createDeferredPromise()-- const output = new ProcessOutput()-- function handleStdout(data: { line: string; timestamp: number }) {- const message = new ProcessMessage(data.line, data.timestamp, false)- output.addStdout(message)- onStdout?.(message)- }-- function handleStderr(data: { line: string; timestamp: number }) {- const message = new ProcessMessage(data.line, data.timestamp, true)- output.addStderr(message)- onStderr?.(message)- }+ start: async (opts: ProcessOpts) => {+ const start = async ({+ cmd,+ onStdout,+ onStderr,+ onExit,+ envVars = {},+ rootdir = '',+ processID = id(12),+ }: Omit<ProcessOpts, 'timeout'>) => {+ if (!cmd) {+ throw new Error('cmd is required')+ }+ this.logger.debug?.(`Starting process "${processID}"`)- const [onExitSubID, onStdoutSubID, onStderrSubID] =- await this.handleSubscriptions(- this.subscribe(processService, triggerExit, 'onExit', processID),- this.subscribe(processService, handleStdout, 'onStdout', processID),- this.subscribe(processService, handleStderr, 'onStderr', processID),- )+ const { promise: processExited, resolve: triggerExit } = createDeferredPromise()- const { promise: unsubscribing, resolve: handleFinishUnsubscribing } =- createDeferredPromise<ProcessOutput>()+ const output = new ProcessOutput()- processExited.then(async () => {- const results = await Promise.allSettled([- this.unsubscribe(onExitSubID),- onStdoutSubID ? this.unsubscribe(onStdoutSubID) : undefined,- onStderrSubID ? this.unsubscribe(onStderrSubID) : undefined,- ])- this.logger.debug?.(`Process "${processID}" exited`)+ function handleStdout(data: { line: string; timestamp: number }) {+ const message = new ProcessMessage(data.line, data.timestamp, false)+ output.addStdout(message)+ onStdout?.(message)+ }- const errMsg = formatSettledErrors(results)- if (errMsg) {- this.logger.error?.(errMsg)+ function handleStderr(data: { line: string; timestamp: number }) {+ const message = new ProcessMessage(data.line, data.timestamp, true)+ output.addStderr(message)+ onStderr?.(message)}- onExit?.()- handleFinishUnsubscribing(output)- })+ const [onExitSubID, onStdoutSubID, onStderrSubID] =+ await this.handleSubscriptions(+ this.subscribe(processService, triggerExit, 'onExit', processID),+ this.subscribe(processService, handleStdout, 'onStdout', processID),+ this.subscribe(processService, handleStderr, 'onStderr', processID),+ )++ const { promise: unsubscribing, resolve: handleFinishUnsubscribing } =+ createDeferredPromise<ProcessOutput>()++ processExited.then(async () => {+ const results = await Promise.allSettled([+ this.unsubscribe(onExitSubID),+ onStdoutSubID ? this.unsubscribe(onStdoutSubID) : undefined,+ onStderrSubID ? this.unsubscribe(onStderrSubID) : undefined,+ ])+ this.logger.debug?.(`Process "${processID}" exited`)++ const errMsg = formatSettledErrors(results)+ if (errMsg) {+ this.logger.error?.(errMsg)+ }++ onExit?.()+ handleFinishUnsubscribing(output)+ })++ try {+ await this.call(processService, 'start', [processID, cmd, envVars, rootdir])+ } catch (err) {+ triggerExit()+ await unsubscribing+ throw err+ }- try {- await this.call(processService, 'start', [processID, cmd, envVars, rootdir])- } catch (err) {- triggerExit()- await unsubscribing- throw err+ return new Process(processID, this, triggerExit, unsubscribing, output)}-- return new Process(processID, this, triggerExit, unsubscribing, output)+ const timeout = opts.timeout+ return await withTimeout(start, timeout)(opts)},}}static async create(opts: SessionOpts) {- return await new Session(opts).open()+ return new Session(opts).open({ timeout: opts?.timeout })}- override async open() {- await super.open()+ override async open(opts: CallOpts) {+ await super.open(opts)const portsHandler = this.onScanPorts? (ports: { State: string; Ip: string; Port: number }[]) =>diff --git a/packages/js-sdk/src/session/process.ts b/packages/js-sdk/src/session/process.tsindex 577caf22f..e448ebfbb 100644--- a/packages/js-sdk/src/session/process.ts+++ b/packages/js-sdk/src/session/process.ts@@ -1,5 +1,5 @@import { EnvVars } from './envVars'-import { SessionConnection } from './sessionConnection'+import { CallOpts, SessionConnection } from './sessionConnection'export const processService = 'process'@@ -100,20 +100,24 @@ export class Process {* Sends data to the process stdin.** @param data Data to send+ * @param opts Call options+ * @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)*/- async sendStdin(data: string): Promise<void> {- await this.session.call(processService, 'stdin', [this.processID, data])+ async sendStdin(data: string, opts?: CallOpts): Promise<void> {+ await this.session.call(processService, 'stdin', [this.processID, data], opts)}}+export interface ProcessOpts {+ cmd: string+ onStdout?: (out: ProcessMessage) => void+ onStderr?: (out: ProcessMessage) => void+ onExit?: () => void+ envVars?: EnvVars+ rootdir?: string+ processID?: string+ timeout?: number+}export interface ProcessManager {- readonly start: (opts: {- cmd: string- onStdout?: (out: ProcessMessage) => void- onStderr?: (out: ProcessMessage) => void- onExit?: () => void- envVars?: EnvVars- rootdir?: string- processID?: string- }) => Promise<Process>+ readonly start: (opts: ProcessOpts) => Promise<Process>}diff --git a/packages/js-sdk/src/session/sessionConnection.ts b/packages/js-sdk/src/session/sessionConnection.tsindex 5697d01ab..03edeb8ff 100644--- a/packages/js-sdk/src/session/sessionConnection.ts+++ b/packages/js-sdk/src/session/sessionConnection.ts@@ -8,10 +8,10 @@ import {WS_RECONNECT_INTERVAL,WS_ROUTE,} from '../constants'-import { assertFulfilled, formatSettledErrors } from '../utils/promise'+import { AuthenticationError } from '../error'+import { assertFulfilled, formatSettledErrors, withTimeout } from '../utils/promise'import wait from '../utils/wait'import { codeSnippetService } from './codeSnippet'-import { AuthenticationError } from './error'import { filesystemService } from './filesystem'import { processService } from './process'import { terminalService } from './terminal'@@ -47,6 +47,10 @@ export interface SessionConnectionOpts {__debug_devEnv?: 'remote' | 'local'}+export interface CallOpts {+ timeout?: number+}+const createSession = api.path('/sessions').method('post').create({ api_key: true })const refreshSession = api.path('/sessions/{sessionID}/refresh')@@ -80,8 +84,8 @@ export class SessionConnection {** `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 session- * @returns hostname of the session or session's port+ * @param port Specify if you want to connect to a specific port of the session+ * @returns Hostname of the session or session's port*/getHostname(port?: number) {if (this.opts.__debug_hostname) {@@ -139,135 +143,148 @@ export class SessionConnection {* Open a connection to a new session** `open` method requires `this` context - you may need to bind it.+ * @param opts Call options+ * @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)*/- async open() {- if (this.isOpen || !!this.session) {- throw new Error('Session connect was already called')- } else {- this.isOpen = true- }- this.logger.debug?.('Opening session...')+ async open(opts: CallOpts) {+ const open = async () => {+ if (this.isOpen || !!this.session) {+ throw new Error('Session connect was already called')+ } else {+ this.isOpen = true+ }+ this.logger.debug?.('Opening session...')- if (!this.opts.__debug_hostname) {- try {- const res = await createSession({- api_key: this.opts.apiKey,- codeSnippetID: this.opts.id,- editEnabled: false,- })- this.session = res.data- this.logger.debug?.(`Acquired session "${this.session.sessionID}"`)-- this.refresh(this.session.sessionID)- } catch (e) {- if (e instanceof createSession.Error) {- const error = e.getActualType()- if (error.status === 400) {- throw new Error(- `Error creating session - (${error.status}) bad request: ${error.data.message}`,- )- }- if (error.status === 401) {- throw new Error(- `Error creating session - (${error.status}) unauthenticated: ${error.data.message}`,- )- }- if (error.status === 500) {- throw new Error(- `Error creating session - (${error.status}) server error: ${error.data.message}`,- )+ if (!this.opts.__debug_hostname) {+ try {+ const res = await createSession({+ api_key: this.opts.apiKey,+ codeSnippetID: this.opts.id,+ editEnabled: false,+ })+ this.session = res.data+ this.logger.debug?.(`Acquired session "${this.session.sessionID}"`)++ this.refresh(this.session.sessionID)+ } catch (e) {+ if (e instanceof createSession.Error) {+ const error = e.getActualType()+ if (error.status === 400) {+ throw new Error(+ `Error creating session - (${error.status}) bad request: ${error.data.message}`,+ )+ }+ if (error.status === 401) {+ throw new Error(+ `Error creating session - (${error.status}) unauthenticated: ${error.data.message}`,+ )+ }+ if (error.status === 500) {+ throw new Error(+ `Error creating session - (${error.status}) server error: ${error.data.message}`,+ )+ }}+ throw e}- throw e}- }- const hostname = this.getHostname(this.opts.__debug_port || WS_PORT)+ const hostname = this.getHostname(this.opts.__debug_port || WS_PORT)- if (!hostname) {- throw new Error("Cannot get session's hostname")- }+ if (!hostname) {+ throw new Error("Cannot get session's hostname")+ }- const protocol = this.opts.__debug_devEnv === 'local' ? 'ws' : 'wss'- const sessionURL = `${protocol}://${hostname}${WS_ROUTE}`+ const protocol = this.opts.__debug_devEnv === 'local' ? 'ws' : 'wss'+ const sessionURL = `${protocol}://${hostname}${WS_ROUTE}`- this.rpc.onError(err => {- this.logger.warn?.(- `Error in WS session "${this.session?.sessionID}": ${- err.message ?? err.code ?? err.toString()- }. Trying to reconnect...`,- )- })+ this.rpc.onError(err => {+ this.logger.warn?.(+ `Error in WS session "${this.session?.sessionID}": ${+ err.message ?? err.code ?? err.toString()+ }. Trying to reconnect...`,+ )+ })- let isFinished = false- let resolveOpening: (() => void) | undefined- let rejectOpening: (() => void) | undefined+ let isFinished = false+ let resolveOpening: (() => void) | undefined+ let rejectOpening: (() => void) | undefined- const openingPromise = new Promise<void>((resolve, reject) => {- resolveOpening = () => {- if (isFinished) return- isFinished = true- resolve()- }- rejectOpening = () => {- if (isFinished) return- isFinished = true- reject()- }- })+ const openingPromise = new Promise<void>((resolve, reject) => {+ resolveOpening = () => {+ if (isFinished) return+ isFinished = true+ resolve()+ }+ rejectOpening = () => {+ if (isFinished) return+ isFinished = true+ reject()+ }+ })- this.rpc.onOpen(() => {- this.logger.debug?.(`Connected to session "${this.session?.sessionID}"`)- resolveOpening?.()- })+ this.rpc.onOpen(() => {+ this.logger.debug?.(`Connected to session "${this.session?.sessionID}"`)+ resolveOpening?.()+ })- this.rpc.onClose(async e => {- this.logger.debug?.(`Closing WS connection to session "${this.session?.sessionID}"`)- if (this.isOpen) {- await wait(WS_RECONNECT_INTERVAL)- this.logger.debug?.(`Reconnecting to session "${this.session?.sessionID}"`)- try {- // When the WS connection closes the subscribers in devbookd are removed.- // We want to delete the subscriber handlers here so there are no orphans.- this.subscribers = []- await this.rpc.connect(sessionURL)- this.logger.debug?.(`Reconnected to session "${this.session?.sessionID}"`)- // eslint-disable-next-line @typescript-eslint/no-explicit-any- } catch (err: any) {- this.logger.warn?.(- `Failed reconnecting to session "${this.session?.sessionID}": ${- err.message ?? err.code ?? err.toString()- }`,- )+ this.rpc.onClose(async () => {+ this.logger.debug?.(+ `Closing WS connection to session "${this.session?.sessionID}"`,+ )+ if (this.isOpen) {+ await wait(WS_RECONNECT_INTERVAL)+ this.logger.debug?.(`Reconnecting to session "${this.session?.sessionID}"`)+ try {+ // When the WS connection closes the subscribers in devbookd are removed.+ // We want to delete the subscriber handlers here so there are no orphans.+ this.subscribers = []+ await this.rpc.connect(sessionURL)+ this.logger.debug?.(`Reconnected to session "${this.session?.sessionID}"`)+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } catch (err: any) {+ this.logger.warn?.(+ `Failed reconnecting to session "${this.session?.sessionID}": ${+ err.message ?? err.code ?? err.toString()+ }`,+ )+ }+ } else {+ rejectOpening?.()}- } else {- rejectOpening?.()- }- })+ })- this.rpc.onNotification.push(this.handleNotification.bind(this))+ this.rpc.onNotification.push(this.handleNotification.bind(this))- try {- this.logger.debug?.(`Connection to session "${this.session?.sessionID}"`)- await this.rpc.connect(sessionURL)-- // eslint-disable-next-line @typescript-eslint/no-explicit-any- } catch (err: any) {- this.logger.warn?.(- `Error connecting to session "${this.session?.sessionID}": ${- err.message ?? err.code ?? err.toString()- }`,- )- }+ try {+ this.logger.debug?.(`Connection to session "${this.session?.sessionID}"`)+ await this.rpc.connect(sessionURL)++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } catch (err: any) {+ this.logger.warn?.(+ `Error connecting to session "${this.session?.sessionID}": ${+ err.message ?? err.code ?? err.toString()+ }`,+ )+ }- await openingPromise- return this+ await openingPromise+ return this+ }+ return await withTimeout(open, opts?.timeout)()}// eslint-disable-next-line @typescript-eslint/no-explicit-any- async call(service: Service, method: string, params?: any[]) {+ async call(service: Service, method: string, params?: any[], opts?: CallOpts) {this.logger.debug?.(`Calling "${service}_${method}" with params:`, params)- return this.rpc.call(`${service}_${method}`, 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<@@ -318,7 +335,8 @@ export class SessionConnection {if (typeof subID !== 'string') {throw new Error(// eslint-disable-next-line prettier/prettier- `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,)}`,@@ -332,7 +350,8 @@ export class SessionConnection {})this.logger.debug?.(// eslint-disable-next-line prettier/prettier- `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}"`,)@@ -384,7 +403,7 @@ export class SessionConnection {}} finally {this.logger.debug?.(`Stopped refreshing session "${sessionID}"`)- this.close()+ await this.close()}}}diff --git a/packages/js-sdk/src/session/terminal.ts b/packages/js-sdk/src/session/terminal.tsindex 252131ae8..bd69f54b5 100644--- a/packages/js-sdk/src/session/terminal.ts+++ b/packages/js-sdk/src/session/terminal.ts@@ -64,24 +64,30 @@ export class Terminal {}}+export type TerminalOpts = {+ onData: (data: string) => void+ onExit?: () => void+ size: { cols: number; rows: number }+ terminalID?: string+ /**+ * If the `cmd` parameter is defined it will be executed as a command+ * and this terminal session will exit when the command exits.+ */+ cmd?: string+ /**+ * Working directory where will the terminal start.+ */+ rootdir?: string+ /**+ * Environment variables that will be accessible inside of the terminal.+ */+ envVars?: EnvVars+ /**+ * Timeout in milliseconds (default is 60 seconds)+ */+ timeout?: number+}+export interface TerminalManager {- readonly start: (opts: {- onData: (data: string) => void- onExit?: () => void- size: { cols: number; rows: number }- terminalID?: string- /**- * If the `cmd` parameter is defined it will be executed as a command- * and this terminal session will exit when the command exits.- */- cmd?: string- /**- * Working directory where will the terminal start.- */- rootdir?: string- /**- * Environment variables that will be accessible inside of the terminal.- */- envVars?: EnvVars- }) => Promise<Terminal>+ readonly start: (opts: TerminalOpts) => Promise<Terminal>}diff --git a/packages/js-sdk/src/utils/promise.ts b/packages/js-sdk/src/utils/promise.tsindex 89d663739..b8ec94919 100644--- a/packages/js-sdk/src/utils/promise.ts+++ b/packages/js-sdk/src/utils/promise.ts@@ -1,3 +1,6 @@+import { TIMEOUT } from '../constants'+import { TimeoutError } from '../error'+export function assertFulfilled<T>(item: PromiseSettledResult<T>,): item is PromiseFulfilledResult<T> {@@ -37,3 +40,27 @@ export function createDeferredPromise<T = void>() {resolve: resolve!,}}++// eslint-disable-next-line @typescript-eslint/no-explicit-any+export function withTimeout<T extends (...args: any[]) => any>(+ fn: T,+ timeout: number = TIMEOUT,+): T {+ if (timeout === undefined || timeout <= 0 || timeout === Number.POSITIVE_INFINITY) {+ return fn+ }++ // Throw an error if it takes too long+ const timer = new Promise((resolve, reject) => {+ setTimeout(+ () =>+ reject(new TimeoutError(`Calling "${fn.name}" timeouted after ${timeout}ms.`)),+ timeout,+ )+ })++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ return ((...args: T extends (...args: infer A) => any ? A : never) => {+ return Promise.race([timer, fn(...args)])+ }) as T+}diff --git a/packages/js-sdk/test/timeout.test.mjs b/packages/js-sdk/test/timeout.test.mjsnew file mode 100644index 000000000..163593507--- /dev/null+++ b/packages/js-sdk/test/timeout.test.mjs@@ -0,0 +1,54 @@+import { expect, test } from 'vitest'++import { Session } from '../src'+import { TimeoutError } from '../src/error.ts'++const E2B_API_KEY = process.env.E2B_API_KEY++test('timeout session', async () => {+ await expect(+ Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY, timeout: 10 }),+ ).rejects.toThrow()+})++test('dont timeout session', async () => {+ const session = await Session.create({+ id: 'Nodejs',+ apiKey: E2B_API_KEY,+ timeout: 10000,+ })+ await session.close()+})++test('timeout filesystem', async () => {+ const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })+ await expect(+ session.filesystem.write('/home/test.txt', 'Hello World', { timeout: 10 }),+ ).rejects.toThrow(TimeoutError)+ await expect(+ session.filesystem.read('/home/test.txt', { timeout: 10 }),+ ).rejects.toThrow(TimeoutError)+ await expect(session.filesystem.list('/home', { timeout: 10 })).rejects.toThrow(+ TimeoutError,+ )+ await expect(+ session.filesystem.makeDir('/home/test/', { timeout: 10 }),+ ).rejects.toThrow(TimeoutError)+ await session.filesystem.write('/home/test.txt', 'Hello World')+ await expect(+ session.filesystem.remove('/home/test.txt', { timeout: 10 }),+ ).rejects.toThrow(TimeoutError)+})++test('timeout process', async () => {+ const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })+ await expect(+ session.process.start({ cmd: "node -e 'setTimeout(() => {}, 10000)'", timeout: 10 }),+ ).rejects.toThrow(TimeoutError)+ const process = await session.process.start({+ cmd: "while true; do echo 'Hello World'; sleep 1; done",+ })+ await expect(process.sendStdin('Hello World', { timeout: 10 })).rejects.toThrow(+ TimeoutError,+ )+})