🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
feat: add terminal toolkit timeout (#2945)
Wendong-Fan4906ad3e7b4e
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 1cf1cecd2..51dd1594b 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -26,7 +26,7 @@ body:attributes:label: What version of camel are you using?description: Run command `python3 -c 'print(__import__("camel").__version__)'` in your shell and paste the output here.- placeholder: E.g., 0.2.73a4+ placeholder: E.g., 0.2.73a5validations:required: truediff --git a/camel/__init__.py b/camel/__init__.pyindex ed93cffd7..6fa42d2f9 100644--- a/camel/__init__.py+++ b/camel/__init__.py@@ -14,7 +14,7 @@from camel.logger import disable_logging, enable_logging, set_log_level-__version__ = '0.2.73a4'+__version__ = '0.2.73a5'__all__ = ['__version__',diff --git a/camel/toolkits/base.py b/camel/toolkits/base.pyindex 343302b90..ba702c1d2 100644--- a/camel/toolkits/base.py+++ b/camel/toolkits/base.py@@ -48,7 +48,9 @@ class BaseToolkit(metaclass=AgentOpsMeta):super().__init_subclass__(**kwargs)for attr_name, attr_value in cls.__dict__.items():if callable(attr_value) and not attr_name.startswith("__"):- setattr(cls, attr_name, with_timeout(attr_value))+ # Skip methods that have manual timeout management+ if not getattr(attr_value, '_manual_timeout', False):+ setattr(cls, attr_name, with_timeout(attr_value))def get_tools(self) -> List[FunctionTool]:r"""Returns a list of FunctionTool objects representing thediff --git a/camel/toolkits/terminal_toolkit.py b/camel/toolkits/terminal_toolkit.pyindex c7dc02796..1db134d35 100644--- a/camel/toolkits/terminal_toolkit.py+++ b/camel/toolkits/terminal_toolkit.py@@ -17,6 +17,7 @@ import osimport platformimport queueimport shutil+import signalimport subprocessimport sysimport threading@@ -42,7 +43,7 @@ class TerminalToolkit(BaseToolkit):Args:timeout (Optional[float]): The timeout for terminal operations.- (default: :obj:`None`)+ (default: :obj:`20.0`)shell_sessions (Optional[Dict[str, Any]]): A dictionary to storeshell session information. If :obj:`None`, an empty dictionarywill be used. (default: :obj:`None`)@@ -70,7 +71,7 @@ class TerminalToolkit(BaseToolkit):def __init__(self,- timeout: Optional[float] = None,+ timeout: Optional[float] = 20.0,shell_sessions: Optional[Dict[str, Any]] = None,working_directory: Optional[str] = None,need_terminal: bool = True,@@ -78,6 +79,8 @@ class TerminalToolkit(BaseToolkit):clone_current_env: bool = False,safe_mode: bool = True,):+ # Store timeout before calling super().__init__+ self._timeout = timeoutsuper().__init__(timeout=timeout)self.shell_sessions = shell_sessions or {}self.os_type = platform.system()@@ -944,6 +947,11 @@ class TerminalToolkit(BaseToolkit):command = command.replace('pip', pip_path, 1)if not interactive:+ # Use preexec_fn to create a new process group on Unix systems+ preexec_fn = None+ if self.os_type in ['Darwin', 'Linux']:+ preexec_fn = os.setsid+proc = subprocess.Popen(command,shell=True,@@ -955,17 +963,55 @@ class TerminalToolkit(BaseToolkit):bufsize=1,universal_newlines=True,env=os.environ.copy(),+ preexec_fn=preexec_fn,)self.shell_sessions[id]["process"] = procself.shell_sessions[id]["running"] = True- stdout, stderr = proc.communicate()- output = stdout or ""- if stderr:- output += f"\nStderr Output:\n{stderr}"- self.shell_sessions[id]["output"] = output- self._update_terminal_output(output + "\n")- return output+ try:+ # Use the instance timeout if available+ stdout, stderr = proc.communicate(timeout=self.timeout)+ output = stdout or ""+ if stderr:+ output += f"\nStderr Output:\n{stderr}"+ self.shell_sessions[id]["output"] = output+ self.shell_sessions[id]["running"] = False+ self._update_terminal_output(output + "\n")+ return output+ except subprocess.TimeoutExpired:+ # Kill the entire process group on Unix systems+ if self.os_type in ['Darwin', 'Linux']:+ try:+ os.killpg(os.getpgid(proc.pid), signal.SIGTERM)+ # Give it a short time to terminate+ stdout, stderr = proc.communicate(timeout=1)+ except subprocess.TimeoutExpired:+ # Force kill the process group+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)+ stdout, stderr = proc.communicate()+ except ProcessLookupError:+ # Process already dead+ stdout, stderr = proc.communicate()+ else:+ # Windows fallback+ proc.terminate()+ try:+ stdout, stderr = proc.communicate(timeout=1)+ except subprocess.TimeoutExpired:+ proc.kill()+ stdout, stderr = proc.communicate()++ output = stdout or ""+ if stderr:+ output += f"\nStderr Output:\n{stderr}"+ error_msg = (+ f"\nCommand timed out after {self.timeout} seconds"+ )+ output += error_msg+ self.shell_sessions[id]["output"] = output+ self.shell_sessions[id]["running"] = False+ self._update_terminal_output(output + "\n")+ return output# Interactive mode with real-time streaming via PTYif self.os_type not in ['Darwin', 'Linux']:@@ -1075,6 +1121,9 @@ class TerminalToolkit(BaseToolkit):f"Detailed information: {detailed_error}")+ # Mark shell_exec to skip automatic timeout wrapping+ shell_exec._manual_timeout = True # type: ignore[attr-defined]+def shell_view(self, id: str) -> str:r"""View the full output history of a specified shell session.diff --git a/docs/conf.py b/docs/conf.pyindex c9a367e39..6d3ae7c70 100644--- a/docs/conf.py+++ b/docs/conf.py@@ -27,7 +27,7 @@ sys.path.insert(0, os.path.abspath('..'))project = 'CAMEL'copyright = '2024, CAMEL-AI.org'author = 'CAMEL-AI.org'-release = '0.2.73a4'+release = '0.2.73a5'html_favicon = ('https://raw.githubusercontent.com/camel-ai/camel/master/misc/favicon.png'diff --git a/pyproject.toml b/pyproject.tomlindex c6cc1ce5b..ee7eab5c6 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "camel-ai"-version = "0.2.73a4"+version = "0.2.73a5"description = "Communicative Agents for AI Society Study"authors = [{ name = "CAMEL-AI.org" }]requires-python = ">=3.10,<3.13"diff --git a/uv.lock b/uv.lockindex d6cec1534..18a8e41e6 100644--- a/uv.lock+++ b/uv.lock@@ -647,7 +647,7 @@ wheels = [[[package]]name = "camel-ai"-version = "0.2.73a4"+version = "0.2.73a5"source = { editable = "." }dependencies = [{ name = "colorama" },@@ -8400,7 +8400,7 @@ wheels = [[[package]]name = "weaviate-client"-version = "4.16.3"+version = "4.16.4"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "authlib" },@@ -8411,9 +8411,9 @@ dependencies = [{ name = "pydantic" },{ name = "validators" },]-sdist = { url = "https://files.pythonhosted.org/packages/43/09/fefbffd499da6d46d897eecde4942a5ce4880dc8fdccbbd2363704a6ba32/weaviate_client-4.16.3.tar.gz", hash = "sha256:e0c7f160787623fefcee0bfe2d160ad1b2f0178c5d1d92fea41de124a0cb1b2a", size = 779601, upload-time = "2025-07-22T07:59:49.873Z" }+sdist = { url = "https://files.pythonhosted.org/packages/b1/6a/be2257fbd890674204c393782e75b794cf0939a8dab8a4f1c0ab38d1663a/weaviate_client-4.16.4.tar.gz", hash = "sha256:50efc819274640564bbeca91405aef1674170e3d93f0bd7a9496b5b37d0fe746", size = 779617, upload-time = "2025-07-24T13:27:20.659Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/8f/7a/97cfe61a6610eacd9b81691052c50c01d100eb4b136fb9a4ccccabf098c7/weaviate_client-4.16.3-py3-none-any.whl", hash = "sha256:e970db032ce8ce20e9dc56d25fd1944d06fe90976c29b4ae56c3aa2991ab81f1", size = 597232, upload-time = "2025-07-22T07:59:48.084Z" },+ { url = "https://files.pythonhosted.org/packages/c1/a5/414c1452b786a27be1d1314c3051abf82af921ca20ada16df55c0d19997d/weaviate_client-4.16.4-py3-none-any.whl", hash = "sha256:299bab2ae822271ddc40005a7cd95f332e8243c7cff38df3bb9f4aca23221dcc", size = 597160, upload-time = "2025-07-24T13:27:18.97Z" },][[package]]