Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Add timeout handling to the relevant methods in python SDK (#97)
Jakub Novák244fd5be4fff
diff --git a/packages/python-sdk/e2b/constants.py b/packages/python-sdk/e2b/constants.pyindex e6a5a9a44..710ddde2d 100644--- a/packages/python-sdk/e2b/constants.py+++ b/packages/python-sdk/e2b/constants.py@@ -1,6 +1,7 @@SESSION_REFRESH_PERIOD = 5 # secondsWS_RECONNECT_INTERVAL = 6 # seconds+TIMEOUT = 60SESSION_DOMAIN = "ondevbook.com"WS_PORT = 49982WS_ROUTE = "/ws"diff --git a/packages/python-sdk/e2b/session/filesystem.py b/packages/python-sdk/e2b/session/filesystem.pyindex 2bec99e1e..6bed51b53 100644--- a/packages/python-sdk/e2b/session/filesystem.py+++ b/packages/python-sdk/e2b/session/filesystem.py@@ -1,6 +1,6 @@-import base64-from typing import Any, List+from typing import Any, List, Optional+from e2b.constants import TIMEOUTfrom e2b.session.exception import FilesystemException, RpcExceptionfrom e2b.session.filesystem_watcher import FilesystemWatcherfrom e2b.session.session_connection import SessionConnection@@ -52,52 +52,65 @@ class FilesystemManager:# self.service_name, "writeBase64", [path, base64_content]# )- async def read(self, path: str) -> str:+ async def read(self, path: str, timeout: Optional[int] = TIMEOUT) -> str:"""Reads the whole content of a file as an array of bytes.- :param path: path to a file- :return: content of a file+ :param path: Path to a file+ :param timeout: Timeout for the call+ :return: Content of a file"""try:- result: str = await self._session._call(self._service_name, "read", [path])+ result: str = await self._session._call(+ self._service_name, "read", [path], timeout=timeout+ )return resultexcept RpcException as e:raise FilesystemException(e.message) from e- async def write(self, path: str, content: str) -> None:+ async def write(+ self, path: str, content: str, timeout: Optional[int] = TIMEOUT+ ) -> None:"""Writes content to a file.- :param path: path to a file- :param content: content to write+ :param path: Path to a file+ :param content: Content to write+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time"""try:- await self._session._call(self._service_name, "write", [path, content])+ await self._session._call(+ self._service_name, "write", [path, content], timeout=timeout+ )except RpcException as e:raise FilesystemException(e.message) from e- async def remove(self, path: str) -> None:+ async def remove(self, path: str, timeout: Optional[int] = TIMEOUT) -> None:"""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 timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time"""try:- await self._session._call(self._service_name, "remove", [path])+ await self._session._call(+ self._service_name, "remove", [path], timeout=timeout+ )except RpcException as e:raise FilesystemException(e.message) from e- async def list(self, path: str) -> List[FileInfo]:+ async def list(self, path: str, timeout: Optional[int] = TIMEOUT) -> List[FileInfo]:"""List files in a directory.- :param path: path to a directory- :return: array of files in a directory+ :param path: Path to a directory+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time++ :return: Array of files in a directory"""try:result: List[Any] = await self._session._call(- self._service_name, "list", [path]+ self._service_name, "list", [path], timeout=timeout)return [FileInfo(is_dir=file_info["isDir"], name=file_info["name"])@@ -106,14 +119,17 @@ class FilesystemManager:except RpcException as e:raise FilesystemException(e.message) from e- async def make_dir(self, path: str) -> None:+ async def make_dir(self, path: str, timeout: Optional[int] = TIMEOUT) -> None:"""Creates a new directory and all directories along the way if needed on the specified path.- :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 timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time"""try:- await self._session._call(self._service_name, "makeDir", [path])+ await self._session._call(+ self._service_name, "makeDir", [path], timeout=timeout+ )except RpcException as e:raise FilesystemException(e.message) from e@@ -121,7 +137,7 @@ class FilesystemManager:"""Watches directory for filesystem events.- :param path: path to a directory that will be watched+ :param path: Path to a directory that will be watched:return: New watcher"""diff --git a/packages/python-sdk/e2b/session/filesystem_watcher.py b/packages/python-sdk/e2b/session/filesystem_watcher.pyindex bf2d34734..b64b21ee7 100644--- a/packages/python-sdk/e2b/session/filesystem_watcher.py+++ b/packages/python-sdk/e2b/session/filesystem_watcher.py@@ -1,6 +1,7 @@from enum import Enumfrom typing import Any, Awaitable, Callable, Optional, Set+from e2b.constants import TIMEOUTfrom e2b.session.exception import FilesystemException, RpcExceptionfrom e2b.session.session_connection import SessionConnectionfrom pydantic import BaseModel@@ -45,9 +46,11 @@ class FilesystemWatcher:self._unsubscribe: Optional[Callable[[], Awaitable[Any]]] = Noneself._listeners: Set[Callable[[FilesystemEvent], Any]] = set()- async def start(self) -> None:+ async def start(self, timeout: Optional[int] = TIMEOUT) -> None:"""Starts the filesystem watcher.++ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time"""if self._unsubscribe:return@@ -58,6 +61,7 @@ class FilesystemWatcher:self._handle_filesystem_events,"watchDir",self.path,+ timeout=timeout,)except RpcException as e:raise FilesystemException(e.message) from e@@ -78,9 +82,9 @@ class FilesystemWatcher:"""Adds a listener for filesystem events.- :param listener: a listener to add+ :param listener: Listener to add- :return: a function that removes the listener+ :return: Function that removes the listener"""self._listeners.add(listener)diff --git a/packages/python-sdk/e2b/session/main.py b/packages/python-sdk/e2b/session/main.pyindex fef69cde5..721850012 100644--- a/packages/python-sdk/e2b/session/main.py+++ b/packages/python-sdk/e2b/session/main.py@@ -1,6 +1,8 @@import loggingfrom typing import Any, Callable, List, Literal, Optional, Union+from async_timeout import timeout as async_timeout+from e2b.constants import TIMEOUTfrom e2b.session.code_snippet import CodeSnippetManager, OpenPortfrom e2b.session.filesystem import FilesystemManagerfrom e2b.session.process import ProcessManager@@ -100,9 +102,15 @@ class Session(SessionConnection):self._filesystem = FilesystemManager(session=self)self._process = ProcessManager(session=self)- async def open(self) -> None:- await super().open()- await self._code_snippet._subscribe()+ async def open(self, timeout: Optional[int] = TIMEOUT) -> None:+ """+ Opens the session.++ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time+ """+ async with async_timeout(timeout):+ await super().open()+ await self._code_snippet._subscribe()def _close_services(self):self._terminal._close()@@ -125,6 +133,7 @@ class Session(SessionConnection):id: Union[Environment, str],api_key: Optional[str] = None,on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,+ timeout: Optional[int] = TIMEOUT,_debug_hostname: Optional[str] = None,_debug_port: Optional[int] = None,_debug_dev_env: Optional[Literal["remote", "local"]] = None,@@ -147,6 +156,7 @@ class Session(SessionConnection)::param api_key: The API key to use:param edit_enabled: Whether the session state will be saved after exit:param on_scan_ports: A callback to handle opened ports+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time"""logging.info(f"Session {id if isinstance(id, str) else type(id)}")@@ -158,5 +168,5 @@ class Session(SessionConnection):_debug_port=_debug_port,_debug_dev_env=_debug_dev_env,)- await session.open()+ await session.open(timeout=timeout)return sessiondiff --git a/packages/python-sdk/e2b/session/process.py b/packages/python-sdk/e2b/session/process.pyindex b4af588b6..6500549c4 100644--- a/packages/python-sdk/e2b/session/process.py+++ b/packages/python-sdk/e2b/session/process.py@@ -1,7 +1,10 @@import asyncioimport logging+from asyncio.exceptions import TimeoutErrorfrom typing import Any, Awaitable, Callable, ClassVar, Coroutine, Dict, List, Optional+import async_timeout+from e2b.constants import TIMEOUTfrom e2b.session.env_vars import EnvVarsfrom e2b.session.exception import MultipleExceptions, ProcessException, RpcExceptionfrom e2b.session.out import OutStderrResponse, OutStdoutResponse@@ -137,26 +140,32 @@ class Process:self._finished = finishedself._output = output- async def send_stdin(self, data: str) -> None:+ async def send_stdin(self, data: str, timeout: Optional[int] = TIMEOUT) -> None:"""Sends data to the process stdin.:param data: Data to send+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time"""try:await self._session._call(- ProcessManager._service_name, "stdin", [self.process_id, data]+ ProcessManager._service_name,+ "stdin",+ [self.process_id, data],+ timeout=timeout,)except RpcException as e:raise ProcessException(e.message) from e- async def kill(self) -> None:+ async def kill(self, timeout: Optional[int] = TIMEOUT) -> None:"""Kills the process.++ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time"""try:await self._session._call(- ProcessManager._service_name, "kill", [self.process_id]+ ProcessManager._service_name, "kill", [self.process_id], timeout=timeout)except RpcException as e:raise ProcessException(e.message) from e@@ -189,6 +198,7 @@ class ProcessManager:env_vars: Optional[EnvVars] = None,rootdir: str = "",process_id: Optional[str] = None,+ timeout: Optional[int] = TIMEOUT,) -> Process:"""Starts a process in the environment.@@ -200,108 +210,114 @@ class ProcessManager::param env_vars: A dictionary of environment variables to set for the process:param rootdir: The root directory for the process:param process_id: The process id to use for the process. If not provided, a random id is generated+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time- :return: A process object.+ :return: A process object"""- if not env_vars:- env_vars = {}-- future_exit = DeferredFuture(self._process_cleanup)- process_id = process_id or create_id(12)-- unsub_all: Optional[Callable[[], Awaitable[Any]]] = None-- output = ProcessOutput()-- def handle_stdout(data: Dict[Any, Any]):- out = OutStdoutResponse(**data)-- message = ProcessMessage(- line=out.line,- timestamp=out.timestamp,- error=False,- )-- output._add_stdout(message)- if on_stdout:- on_stdout(message)-- def handle_stderr(data: Dict[Any, Any]):- out = OutStderrResponse(**data)-- message = ProcessMessage(- line=out.line,- timestamp=out.timestamp,- error=True,- )-- output._add_stderr(message)- if on_stderr:- on_stderr(message)-- try:- unsub_all = await self._session._handle_subscriptions(- self._session._subscribe(- self._service_name, future_exit, "onExit", process_id- ),- self._session._subscribe(- self._service_name, handle_stdout, "onStdout", process_id- ),- self._session._subscribe(- self._service_name, handle_stderr, "onStderr", process_id- ),+ with async_timeout.timeout(timeout):+ if not env_vars:+ env_vars = {}++ future_exit = DeferredFuture(self._process_cleanup)+ process_id = process_id or create_id(12)++ unsub_all: Optional[Callable[[], Awaitable[Any]]] = None++ output = ProcessOutput()++ def handle_stdout(data: Dict[Any, Any]):+ out = OutStdoutResponse(**data)++ message = ProcessMessage(+ line=out.line,+ timestamp=out.timestamp,+ error=False,+ )++ output._add_stdout(message)+ if on_stdout:+ on_stdout(message)++ def handle_stderr(data: Dict[Any, Any]):+ out = OutStderrResponse(**data)++ message = ProcessMessage(+ line=out.line,+ timestamp=out.timestamp,+ error=True,+ )++ output._add_stderr(message)+ if on_stderr:+ on_stderr(message)++ try:+ unsub_all = await self._session._handle_subscriptions(+ self._session._subscribe(+ self._service_name, future_exit, "onExit", process_id+ ),+ self._session._subscribe(+ self._service_name, handle_stdout, "onStdout", process_id+ ),+ self._session._subscribe(+ self._service_name, handle_stderr, "onStderr", process_id+ ),+ )+ except (RpcException, MultipleExceptions) as e:+ future_exit.cancel()++ if isinstance(e, RpcException):+ raise ProcessException(e.message) from e+ elif isinstance(e, MultipleExceptions):+ raise ProcessException(+ "Failed to subscribe to RPC services necessary for starting process"+ ) from e++ future_exit_handler_finish = DeferredFuture[ProcessOutput](+ self._process_cleanup)- except (RpcException, MultipleExceptions) as e:- future_exit.cancel()- if isinstance(e, RpcException):+ async def exit_handler():+ await future_exit+ logger.info(+ f"Handling process exit {process_id} - {future_exit._future.done()}",+ )+ if unsub_all:+ await unsub_all()+ if on_exit:+ on_exit()+ future_exit_handler_finish(output)++ exit_task = asyncio.create_task(exit_handler())+ self._process_cleanup.append(exit_task.cancel)++ async def trigger_exit():+ logger.info("Triggering exit")+ future_exit(None)+ await future_exit_handler_finish++ try:+ await self._session._call(+ self._service_name,+ "start",+ [+ process_id,+ cmd,+ env_vars,+ rootdir,+ ],+ )+ return Process(+ output=output,+ session=self._session,+ process_id=process_id,+ trigger_exit=trigger_exit,+ finished=future_exit_handler_finish,+ )+ except RpcException as e:+ await trigger_exit()raise ProcessException(e.message) from e- elif isinstance(e, MultipleExceptions):- raise ProcessException(- "Failed to subscribe to RPC services necessary for starting process"- ) from e-- future_exit_handler_finish = DeferredFuture[ProcessOutput](- self._process_cleanup- )-- async def exit_handler():- await future_exit- logger.info(- f"Handling process exit {process_id} - {future_exit._future.done()}",- )- if unsub_all:- await unsub_all()- if on_exit:- on_exit()- future_exit_handler_finish(output)-- exit_task = asyncio.create_task(exit_handler())- self._process_cleanup.append(exit_task.cancel)-- async def trigger_exit():- logger.info("Triggering exit")- future_exit(None)- await future_exit_handler_finish-- try:- await self._session._call(- self._service_name,- "start",- [- process_id,- cmd,- env_vars,- rootdir,- ],- )- return Process(- output=output,- session=self._session,- process_id=process_id,- trigger_exit=trigger_exit,- finished=future_exit_handler_finish,- )- except RpcException as e:- await trigger_exit()- raise ProcessException(e.message) from e+ except TimeoutError as e:+ logger.error(f"Timeout error during starting the process: {cmd}")+ await trigger_exit()+ raise ediff --git a/packages/python-sdk/e2b/session/session_connection.py b/packages/python-sdk/e2b/session/session_connection.pyindex 74d09dc6f..3e7475b98 100644--- a/packages/python-sdk/e2b/session/session_connection.py+++ b/packages/python-sdk/e2b/session/session_connection.py@@ -4,11 +4,18 @@ import tracebackfrom concurrent.futures import ThreadPoolExecutorfrom typing import Any, Awaitable, Callable, List, Literal, Optional, Union+import async_timeoutfrom e2b.api.client import NewSessionfrom e2b.api.client import Session as SessionInfofrom e2b.api.client.rest import ApiExceptionfrom e2b.api.main import client, configuration-from e2b.constants import SESSION_DOMAIN, SESSION_REFRESH_PERIOD, WS_PORT, WS_ROUTE+from e2b.constants import (+ SESSION_DOMAIN,+ SESSION_REFRESH_PERIOD,+ TIMEOUT,+ WS_PORT,+ WS_ROUTE,+)from e2b.session.exception import (AuthenticationException,MultipleExceptions,@@ -60,7 +67,7 @@ class SessionConnection:):if api_key is None:raise AuthenticationException(- 'API key is required, please visit https://e2b.dev/docs to get your API key',+ "API key is required, please visit https://e2b.dev/docs to get your API key",)self._id = id@@ -84,9 +91,9 @@ class SessionConnection:"""Get the hostname for the session or for the specified session's port.- :param port: specify if you want to connect to a specific port of the session+ :param port: Specify if you want to connect to a specific port of the session- :return: hostname of the session or session's port+ :return: Hostname of the session or session's port"""if not self._session:raise Exception(@@ -182,6 +189,7 @@ class SessionConnection:self._process_cleanup.append(refresh_handler.cancel)except Exception as e:logger.error(f"Failed to acquire session: {e}")+ await self.close()raise ehostname = self.get_hostname(self._debug_port or WS_PORT)@@ -197,13 +205,24 @@ class SessionConnection:)await self._rpc.connect()except Exception as e:+ await self.close()raise e- async def _call(self, service: str, method: str, params: List[Any] = []):+ async def _call(+ self,+ service: str,+ method: str,+ params: List[Any] = None,+ timeout: Optional[int] = TIMEOUT,+ ):+ if not params:+ params = []+if not self.is_open:raise SessionException("Session is not open")- return await self._rpc.send_message(f"{service}_{method}", params)+ async with async_timeout.timeout(timeout):+ return await self._rpc.send_message(f"{service}_{method}", params)async def _handle_subscriptions(self,@@ -248,9 +267,9 @@ class SessionConnection:return unsub_all- async def _unsubscribe(self, sub_id: str):+ async def _unsubscribe(self, sub_id: str, timeout: Optional[int] = TIMEOUT):sub = self._subscribers[sub_id]- await self._call(sub.service, "unsubscribe", [sub.id])+ await self._call(sub.service, "unsubscribe", [sub.id], timeout=timeout)del self._subscribers[sub_id]logger.info(f"Unsubscribed from {sub_id}")@@ -260,8 +279,11 @@ class SessionConnection:handler: Callable[[Any], Any],method: str,*params,+ timeout: Optional[int] = TIMEOUT,):- sub_id = await self._call(service, "subscribe", [method, *params])+ sub_id = await self._call(+ service, "subscribe", [method, *params], timeout=timeout+ )if not isinstance(sub_id, str):raise Exception(f"Failed to subscribe: ${sub_id}")@@ -273,7 +295,7 @@ class SessionConnection:)async def unsub():- await self._unsubscribe(sub_id)+ await self._unsubscribe(sub_id, timeout=timeout)return unsubdiff --git a/packages/python-sdk/e2b/session/terminal.py b/packages/python-sdk/e2b/session/terminal.pyindex 51aef9f6d..952a2bdf5 100644--- a/packages/python-sdk/e2b/session/terminal.py+++ b/packages/python-sdk/e2b/session/terminal.py@@ -1,6 +1,9 @@import asyncio+import loggingfrom typing import Any, Awaitable, Callable, Coroutine, List, Optional+import async_timeout+from e2b.constants import TIMEOUTfrom e2b.session.env_vars import EnvVarsfrom e2b.session.exception import MultipleExceptions, RpcException, TerminalExceptionfrom e2b.session.session_connection import SessionConnection@@ -8,6 +11,8 @@ from e2b.utils.future import DeferredFuturefrom e2b.utils.id import create_idfrom pydantic import BaseModel+logger = logging.getLogger(__file__)+class TerminalOutput(BaseModel):data = ""@@ -66,44 +71,55 @@ class Terminal:self._finished = finishedself._output = output- async def send_data(self, data: str) -> None:+ async def send_data(self, data: str, timeout: Optional[int] = TIMEOUT) -> None:"""Sends data to the terminal standard input.:param data: Data to send+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time"""try:await self._session._call(TerminalManager._service_name,"data",[self.terminal_id, data],+ timeout=timeout,)except RpcException as e:raise TerminalException(e.message) from e- async def resize(self, cols: int, rows: int) -> None:+ async def resize(+ self, cols: int, rows: int, timeout: Optional[int] = TIMEOUT+ ) -> None:"""Resizes the terminal tty.:param cols: Number of columns:param rows: Number of rows+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time"""try:await self._session._call(TerminalManager._service_name,"resize",[self.terminal_id, cols, rows],+ timeout=timeout,)except RpcException as e:raise TerminalException(e.message) from e- async def kill(self) -> None:+ async def kill(self, timeout: Optional[int] = TIMEOUT) -> None:"""Kill the terminal session.++ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time"""try:await self._session._call(- TerminalManager._service_name, "destroy", [self.terminal_id]+ TerminalManager._service_name,+ "destroy",+ [self.terminal_id],+ timeout=timeout,)except RpcException as e:raise TerminalException(e.message) from e@@ -137,12 +153,12 @@ class TerminalManager:on_exit: Optional[Callable[[], Any]] = None,cmd: Optional[str] = None,env_vars: Optional[EnvVars] = None,+ timeout: Optional[int] = TIMEOUT,) -> Terminal:"""Start a new terminal session.:param on_data: Callback that will be called when the terminal sends data- :param size: Initial size of the terminal:param rootdir: Working directory where will the terminal start:param terminal_id: Unique identifier of the terminal session:param on_exit: Callback that will be called when the terminal exits@@ -151,81 +167,92 @@ class TerminalManager::param cmd: If the `cmd` parameter is defined it will be executed as a commandand this terminal session will exit when the command exits:param env_vars: Environment variables that will be accessible inside of the terminal+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time:return: Terminal session"""- future_exit = DeferredFuture(self._process_cleanup)- terminal_id = terminal_id or create_id(12)-- unsub_all: Optional[Callable[[], Awaitable[Any]]] = None-- output = TerminalOutput()-- def handle_data(data: str):- output._add_data(data)- on_data(data)-- try:- unsub_all = await self._session._handle_subscriptions(- self._session._subscribe(- self._service_name, handle_data, "onData", terminal_id- ),- self._session._subscribe(- self._service_name, future_exit, "onExit", terminal_id- ),+ async with async_timeout.timeout(timeout):+ future_exit = DeferredFuture(self._process_cleanup)+ terminal_id = terminal_id or create_id(12)++ unsub_all: Optional[Callable[[], Awaitable[Any]]] = None++ output = TerminalOutput()++ def handle_data(data: str):+ output._add_data(data)+ on_data(data)++ try:+ unsub_all = await self._session._handle_subscriptions(+ self._session._subscribe(+ self._service_name, handle_data, "onData", terminal_id+ ),+ self._session._subscribe(+ self._service_name, future_exit, "onExit", terminal_id+ ),+ )+ except (RpcException, MultipleExceptions) as e:+ future_exit.cancel()++ if isinstance(e, RpcException):+ raise TerminalException(e.message) from e+ elif isinstance(e, MultipleExceptions):+ raise TerminalException(+ "Failed to subscribe to RPC services necessary for starting terminal"+ ) from e+ except asyncio.TimeoutError:+ future_exit.cancel()+ logger.error(f"Timeout error during starting the terminal: {cmd}")+ raise++ # TODO: Handle exit handler finish for exits (the same for processes)+ future_exit_handler_finish = DeferredFuture[TerminalOutput](+ self._process_cleanup)- except (RpcException, MultipleExceptions) as e:- future_exit.cancel()- if isinstance(e, RpcException):+ async def exit_handler():+ await future_exit++ if unsub_all:+ await unsub_all()++ if on_exit:+ on_exit()+ future_exit_handler_finish(output)++ exit_task = asyncio.create_task(exit_handler())+ self._process_cleanup.append(exit_task.cancel)++ async def trigger_exit():+ future_exit(None)+ await future_exit_handler_finish++ try:+ await self._session._call(+ self._service_name,+ "start",+ [+ terminal_id,+ cols,+ rows,+ env_vars if env_vars else {},+ cmd,+ rootdir,+ ],+ timeout=timeout,+ )+ return Terminal(+ terminal_id=terminal_id,+ session=self._session,+ trigger_exit=trigger_exit,+ finished=future_exit_handler_finish,+ output=output,+ )+ except RpcException as e:+ await trigger_exit()raise TerminalException(e.message) from e- elif isinstance(e, MultipleExceptions):- raise TerminalException(- "Failed to subscribe to RPC services necessary for starting terminal"- ) from e-- # TODO: Handle exit handler finish for exits (the same for processes)- future_exit_handler_finish = DeferredFuture[TerminalOutput](- self._process_cleanup- )-- async def exit_handler():- await future_exit-- if unsub_all:- await unsub_all()-- if on_exit:- on_exit()- future_exit_handler_finish(output)-- exit_task = asyncio.create_task(exit_handler())- self._process_cleanup.append(exit_task.cancel)-- async def trigger_exit():- future_exit(None)- await future_exit_handler_finish-- try:- await self._session._call(- self._service_name,- "start",- [- terminal_id,- cols,- rows,- env_vars if env_vars else {},- cmd,- rootdir,- ],- )- return Terminal(- terminal_id=terminal_id,- session=self._session,- trigger_exit=trigger_exit,- finished=future_exit_handler_finish,- output=output,- )- except RpcException as e:- await trigger_exit()- raise TerminalException(e.message) from e+ except asyncio.TimeoutError:+ logger.error(f"Timeout error during starting the terminal: {cmd}")+ await trigger_exit()+ raisediff --git a/packages/python-sdk/poetry.lock b/packages/python-sdk/poetry.lockindex 40d13b46e..e62f8b413 100644--- a/packages/python-sdk/poetry.lock+++ b/packages/python-sdk/poetry.lock@@ -598,13 +598,13 @@ test = ["appdirs (==1.4.4)", "covdefaults (>=2.3)", "pytest (>=7.4)", "pytest-co[[package]]name = "pluggy"-version = "1.2.0"+version = "1.3.0"description = "plugin and hook calling mechanisms for python"optional = false-python-versions = ">=3.7"+python-versions = ">=3.8"files = [- {file = "pluggy-1.2.0-py3-none-any.whl", hash = "sha256:c2fd55a7d7a3863cba1a013e4e2414658b1d07b6bc57b3919e0c63c9abb99849"},- {file = "pluggy-1.2.0.tar.gz", hash = "sha256:d12f0c4b579b15f5e054301bb226ee85eeeba08ffec228092f8defbaa3a4c4b3"},+ {file = "pluggy-1.3.0-py3-none-any.whl", hash = "sha256:d89c696a773f8bd377d18e5ecda92b7a3793cbe66c87060a6fb58c7b6e1061f7"},+ {file = "pluggy-1.3.0.tar.gz", hash = "sha256:cf61ae8f126ac6f7c451172cf30e3e43d3ca77615509771b3a984a0730651e12"},][package.extras]@@ -976,4 +976,4 @@ multidict = ">=4.0"[metadata]lock-version = "2.0"python-versions = "^3.8"-content-hash = "f647a60d1e72e35656c44252924d252f2865adac170777f2c9da67e2b7d5db40"+content-hash = "192dbb67addf4bf9e45ff15ce2fc5272c44701550ae9231c5b8f1e98223c9b18"diff --git a/packages/python-sdk/pyproject.toml b/packages/python-sdk/pyproject.tomlindex 1ecdcf852..3b7c47de5 100644--- a/packages/python-sdk/pyproject.toml+++ b/packages/python-sdk/pyproject.toml@@ -20,6 +20,7 @@ aenum = ">=3.1.11"websockets = "^11.0.3"jsonrpcclient = "^4.0.3"janus = "^1.0.0"+async-timeout = "^4.0.3"[tool.poetry.group.dev.dependencies]black = "^23.7.0"