Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

enhance: TerminalToolkit with performance improvements and bug fixes (#3626)

Wendong-Fan11e521ab8486
diff --git a/camel/toolkits/terminal_toolkit/terminal_toolkit.py b/camel/toolkits/terminal_toolkit/terminal_toolkit.py
index 83c69faee..82f2f7512 100644
--- a/camel/toolkits/terminal_toolkit/terminal_toolkit.py
+++ b/camel/toolkits/terminal_toolkit/terminal_toolkit.py
@@ -19,7 +19,7 @@ import subprocess
import sys
import threading
import time
-from queue import Empty, Queue
+from queue import Empty, Full, Queue
from typing import Any, Dict, List, Optional
from camel.logger import get_logger
@@ -118,6 +118,8 @@ class TerminalToolkit(BaseToolkit):
# Thread-safe guard for concurrent access to
# shell_sessions and session state
self._session_lock = threading.RLock()
+ # Condition variable for efficient waiting on new output
+ self._output_condition = threading.Condition(self._session_lock)
# Initialize docker_workdir with proper type
self.docker_workdir: Optional[str] = None
@@ -207,7 +209,7 @@ class TerminalToolkit(BaseToolkit):
)
except NotFound:
raise RuntimeError(
- f"Container '{docker_container_name}' not found. "
+ f"Container '{docker_container_name}' not found."
)
# Ensure the working directory exists inside the container
@@ -224,10 +226,6 @@ class TerminalToolkit(BaseToolkit):
f"[Docker] Failed to ensure workdir "
f"'{self.docker_workdir}': {e}"
)
- except NotFound:
- raise RuntimeError(
- f"Docker container '{docker_container_name}' not found."
- )
except APIError as e:
raise RuntimeError(f"Failed to connect to Docker daemon: {e}")
@@ -398,34 +396,13 @@ class TerminalToolkit(BaseToolkit):
"using system Python"
)
- def _adapt_command_for_environment(self, command: str) -> str:
- r"""Adapt command to use virtual environment if available."""
- # Only adapt for local backend
- if self.use_docker_backend:
- return command
-
- # Check if we have any virtual environment (cloned or initial)
- env_path = None
+ def _get_venv_path(self) -> Optional[str]:
+ r"""Get the virtual environment path if available."""
if self.cloned_env_path and os.path.exists(self.cloned_env_path):
- env_path = self.cloned_env_path
+ return self.cloned_env_path
elif self.initial_env_path and os.path.exists(self.initial_env_path):
- env_path = self.initial_env_path
-
- if not env_path:
- return command
-
- # Check if command starts with python or pip
- command_lower = command.strip().lower()
- if command_lower.startswith('python'):
- # Replace 'python' with the virtual environment python
- return command.replace('python', f'"{self.python_executable}"', 1)
- elif command_lower.startswith('pip'):
- # Replace 'pip' with python -m pip from virtual environment
- return command.replace(
- 'pip', f'"{self.python_executable}" -m pip', 1
- )
-
- return command
+ return self.initial_env_path
+ return None
def _write_to_log(self, log_file: str, content: str) -> None:
r"""Write content to log file with optional ANSI stripping.
@@ -455,6 +432,24 @@ class TerminalToolkit(BaseToolkit):
session = self.shell_sessions[session_id]
def reader():
+ def safe_put(data: str) -> None:
+ """Put data to queue, dropping if full to prevent blocking."""
+ try:
+ session["output_stream"].put_nowait(data)
+ except Full:
+ # Queue is full, log warning and continue
+ # Data is still written to log file, so not lost
+ logger.warning(
+ f"[SESSION {session_id}] Output queue full, "
+ f"dropping data (still logged to file)"
+ )
+ return
+ # Notify waiters that new output is available
+ # Done outside try-except to avoid catching unrelated
+ # exceptions
+ with self._output_condition:
+ self._output_condition.notify_all()
+
try:
if session["backend"] == "local":
# For local processes, read line by line from stdout
@@ -462,8 +457,8 @@ class TerminalToolkit(BaseToolkit):
for line in iter(
session["process"].stdout.readline, ''
):
- session["output_stream"].put(line)
self._write_to_log(session["log_file"], line)
+ safe_put(line)
finally:
session["process"].stdout.close()
elif session["backend"] == "docker":
@@ -485,10 +480,10 @@ class TerminalToolkit(BaseToolkit):
decoded_data = data.decode(
'utf-8', errors='ignore'
)
- session["output_stream"].put(decoded_data)
self._write_to_log(
session["log_file"], decoded_data
)
+ safe_put(decoded_data)
# Check if the process is still running
if not self.docker_api_client.exec_inspect(
session["exec_id"]
@@ -508,9 +503,11 @@ class TerminalToolkit(BaseToolkit):
)
finally:
try:
- with self._session_lock:
+ with self._output_condition:
if session_id in self.shell_sessions:
self.shell_sessions[session_id]["running"] = False
+ # Notify waiters that session has terminated
+ self._output_condition.notify_all()
except Exception:
pass
@@ -521,7 +518,6 @@ class TerminalToolkit(BaseToolkit):
self,
id: str,
idle_duration: float = 0.5,
- check_interval: float = 0.1,
max_wait: float = 5.0,
) -> str:
r"""Collects output from a session until it's idle or a max wait time
@@ -531,8 +527,6 @@ class TerminalToolkit(BaseToolkit):
id (str): The session ID.
idle_duration (float): How long the stream must be empty to be
considered idle.(default: 0.5)
- check_interval (float): The time to sleep between checks.
- (default: 0.1)
max_wait (float): The maximum total time to wait for the process
to go idle. (default: 5.0)
@@ -544,11 +538,15 @@ class TerminalToolkit(BaseToolkit):
if id not in self.shell_sessions:
return f"Error: No session found with ID '{id}'."
- output_parts = []
- idle_time = 0.0
- start_time = time.time()
+ output_parts: List[str] = []
+ last_output_time = time.time()
+ start_time = last_output_time
+
+ while True:
+ elapsed = time.time() - start_time
+ if elapsed >= max_wait:
+ break
- while time.time() - start_time < max_wait:
new_output = self.shell_view(id)
# Check for terminal state messages from shell_view
@@ -565,20 +563,34 @@ class TerminalToolkit(BaseToolkit):
if new_output.startswith("Error: No session found"):
return new_output
- if new_output:
+ # Check if this is actual output or just the idle message
+ if new_output and not new_output.startswith("[No new output]"):
output_parts.append(new_output)
- idle_time = 0.0 # Reset idle timer
+ last_output_time = time.time() # Reset idle timer
else:
- idle_time += check_interval
+ # No new output, check if we've been idle long enough
+ idle_time = time.time() - last_output_time
if idle_time >= idle_duration:
# Process is idle, success
return "".join(output_parts)
- time.sleep(check_interval)
+
+ # Calculate remaining time for idle and max_wait
+ time_until_idle = idle_duration - (time.time() - last_output_time)
+ time_until_max = max_wait - (time.time() - start_time)
+ # Wait for the shorter of: idle timeout, max timeout, or a
+ # reasonable check interval
+ wait_time = max(0.0, min(time_until_idle, time_until_max))
+
+ if wait_time > 0:
+ # Use condition variable to wait efficiently
+ # Wake up when new output arrives or timeout expires
+ with self._output_condition:
+ self._output_condition.wait(timeout=wait_time)
# If we exit the loop, it means max_wait was reached.
# Check one last time for any final output.
final_output = self.shell_view(id)
- if final_output:
+ if final_output and not final_output.startswith("[No new output]"):
output_parts.append(final_output)
warning_message = (
@@ -620,11 +632,21 @@ class TerminalToolkit(BaseToolkit):
if self.use_docker_backend:
# For Docker, we always run commands in a shell
- # to support complex commands
- command = f'bash -c "{command}"'
+ # to support complex commands.
+ # Use shlex.quote to properly escape the command string.
+ command = f'bash -c {shlex.quote(command)}'
else:
- # For local execution, check if we need to use cloned environment
- command = self._adapt_command_for_environment(command)
+ # For local execution, activate virtual environment if available
+ env_path = self._get_venv_path()
+ if env_path:
+ if self.os_type == 'Windows':
+ activate = os.path.join(
+ env_path, "Scripts", "activate.bat"
+ )
+ command = f'call "{activate}" && {command}'
+ else:
+ activate = os.path.join(env_path, "bin", "activate")
+ command = f'. "{activate}" && {command}'
session_id = id
@@ -697,12 +719,6 @@ class TerminalToolkit(BaseToolkit):
self.log_dir, f"session_{session_id}.log"
)
- self._write_to_log(
- session_log_file,
- f"--- Starting non-blocking session at {time.ctime()} ---\n"
- f"> {command}\n",
- )
-
# PYTHONUNBUFFERED=1 for real-time output
# Without this, Python subprocesses buffer output (4KB buffer)
# and shell_view() won't see output until buffer fills or process
@@ -711,11 +727,24 @@ class TerminalToolkit(BaseToolkit):
env_vars["PYTHONUNBUFFERED"] = "1"
docker_env = {"PYTHONUNBUFFERED": "1"}
+ # Check and create session atomically to prevent race condition
with self._session_lock:
+ if session_id in self.shell_sessions:
+ existing_session = self.shell_sessions[session_id]
+ if existing_session.get("running", False):
+ return (
+ f"Error: Session '{session_id}' already exists "
+ f"and is running. Use a different ID or kill "
+ f"the existing session first."
+ )
+
+ # Create session entry while holding the lock
self.shell_sessions[session_id] = {
"id": session_id,
"process": None,
- "output_stream": Queue(),
+ # Limit queue size to prevent memory exhaustion
+ # (~100MB with 10k items of ~10KB each)
+ "output_stream": Queue(maxsize=10000),
"command_history": [command],
"running": True,
"log_file": session_log_file,
@@ -724,6 +753,12 @@ class TerminalToolkit(BaseToolkit):
else "local",
}
+ self._write_to_log(
+ session_log_file,
+ f"--- Starting non-blocking session at {time.ctime()} ---\n"
+ f"> {command}\n",
+ )
+
process = None
exec_socket = None
try:
@@ -969,9 +1004,11 @@ class TerminalToolkit(BaseToolkit):
str: The output from the shell session after the user's command has
been executed, or help information for general queries.
"""
- logger.info("\n" + "=" * 60)
- logger.info("LLM Agent needs your help!")
- logger.info(f"PROMPT: {prompt}")
+ # Use print for user-facing messages since this is an interactive
+ # function that requires terminal input via input()
+ print("\n" + "=" * 60)
+ print("LLM Agent needs your help!")
+ print(f"PROMPT: {prompt}")
# Case 1: Session doesn't exist - offer to create one
if id not in self.shell_sessions:
@@ -980,9 +1017,7 @@ class TerminalToolkit(BaseToolkit):
if not user_input:
return "No user response."
else:
- logger.info(
- f"Creating session '{id}' and executing command..."
- )
+ print(f"Creating session '{id}' and executing command...")
result = self.shell_exec(id, user_input, block=True)
return (
f"Session '{id}' created and "
@@ -999,11 +1034,11 @@ class TerminalToolkit(BaseToolkit):
last_output.strip() if last_output.strip() else "(no output)"
)
- logger.info(f"SESSION: '{id}' (active)")
- logger.info("=" * 60)
- logger.info("--- LAST OUTPUT ---")
- logger.info(last_output_display)
- logger.info("-------------------")
+ print(f"SESSION: '{id}' (active)")
+ print("=" * 60)
+ print("--- LAST OUTPUT ---")
+ print(last_output_display)
+ print("-------------------")
try:
user_input = input("Your input: ").strip()
diff --git a/camel/toolkits/terminal_toolkit/utils.py b/camel/toolkits/terminal_toolkit/utils.py
index 3f2c0dd3b..99347272d 100644
--- a/camel/toolkits/terminal_toolkit/utils.py
+++ b/camel/toolkits/terminal_toolkit/utils.py
@@ -18,6 +18,7 @@ import re
import shutil
import subprocess
import sys
+import tempfile
import venv
from typing import Optional, Set, Tuple
@@ -25,6 +26,15 @@ from camel.logger import get_logger
logger = get_logger(__name__)
+# Pre-compiled regex patterns for command safety checks
+_CMD_PATTERN = re.compile(
+ r'(?:^|;|\||&&)\s*\b([a-zA-Z_/][\w\-/]*)', re.IGNORECASE
+)
+_QUOTED_STRING_PATTERN = re.compile(r'''["'][^"']*["']''')
+# Match cd command with optional quoted or unquoted path
+# Handles: cd path, cd "path with spaces", cd 'path with spaces'
+_CD_PATTERN = re.compile(r'\bcd\s+(["\'][^"\']*["\']|[^\s;|&]+)')
+
def check_command_safety(
command: str,
@@ -97,13 +107,12 @@ def check_command_safety(
]
# Remove quoted strings to avoid false positives
- clean_command = re.sub(r'''["'][^"']*["']''', ' ', command)
+ clean_command = _QUOTED_STRING_PATTERN.sub(' ', command)
# If whitelist mode, check ALL commands against the whitelist
if allowed_commands is not None:
# Extract all command words (at start or after operators)
- cmd_pattern = r'(?:^|;|\||&&)\s*\b([a-zA-Z_/][\w\-/]*)'
- found_commands = re.findall(cmd_pattern, clean_command, re.IGNORECASE)
+ found_commands = _CMD_PATTERN.findall(clean_command)
for cmd in found_commands:
if cmd.lower() not in allowed_commands:
return (
@@ -148,16 +157,28 @@ def sanitize_command(
if not is_safe:
return False, reason
- # Additional check for Docker backend: prevent cd outside working directory
+ # Additional check for local backend: prevent cd outside working directory
if not use_docker_backend and working_dir and 'cd ' in command:
# Extract cd commands and check their targets
- cd_pattern = r'\bcd\s+([^\s;|&]+)'
- for match in re.finditer(cd_pattern, command):
+ # Normalize working_dir to ensure consistent comparison
+ normalized_working_dir = os.path.normpath(os.path.abspath(working_dir))
+ for match in _CD_PATTERN.finditer(command):
target_path = match.group(1).strip('\'"')
- target_dir = os.path.abspath(
- os.path.join(working_dir, target_path)
+ target_dir = os.path.normpath(
+ os.path.abspath(os.path.join(working_dir, target_path))
)
- if not target_dir.startswith(working_dir):
+ # Use os.path.commonpath for safe path comparison
+ try:
+ common = os.path.commonpath(
+ [normalized_working_dir, target_dir]
+ )
+ if common != normalized_working_dir:
+ return (
+ False,
+ "Cannot 'cd' outside of the working directory.",
+ )
+ except ValueError:
+ # Different drives on Windows or other path issues
return False, "Cannot 'cd' outside of the working directory."
return True, command
@@ -198,7 +219,10 @@ def ensure_uv_available(update_callback=None) -> Tuple[bool, Optional[str]]:
os_type = platform.system()
# Install uv using the official installer script
- if os_type in ['darwin', 'linux'] or os_type.startswith('linux'):
+ if os_type.lower() in [
+ 'darwin',
+ 'linux',
+ ] or os_type.lower().startswith('linux'):
# Use curl to download and execute the installer
install_cmd = "curl -LsSf https://astral.sh/uv/install.sh | sh"
result = subprocess.run(
@@ -226,7 +250,7 @@ def ensure_uv_available(update_callback=None) -> Tuple[bool, Optional[str]]:
)
return True, uv_executable
- elif os_type == 'Windows':
+ elif os_type.lower() == 'windows':
# Use PowerShell to install uv on Windows
install_cmd = (
"powershell -ExecutionPolicy Bypass -c "
@@ -293,8 +317,6 @@ def setup_initial_env_with_uv(
"pip",
"setuptools",
"wheel",
- "pyautogui",
- "plotly",
]
subprocess.run(
[
@@ -350,8 +372,6 @@ def setup_initial_env_with_venv(
"pip",
"setuptools",
"wheel",
- "pyautogui",
- "plotly",
]
subprocess.run(
[pip_path, "install", "--upgrade", *essential_packages],
@@ -382,7 +402,20 @@ def setup_initial_env_with_venv(
def clone_current_environment(
env_path: str, working_dir: str, update_callback=None
) -> bool:
- r"""Create a new Python virtual environment, optionally using uv."""
+ r"""Clone the current Python environment to a new virtual environment.
+
+ This function creates a new virtual environment with the same Python
+ version as the current environment and installs all packages from
+ the current environment.
+
+ Args:
+ env_path: Path where the new environment will be created.
+ working_dir: Working directory for subprocess commands.
+ update_callback: Optional callback for status updates.
+
+ Returns:
+ True if the environment was created successfully, False otherwise.
+ """
try:
if os.path.exists(env_path):
if update_callback:
@@ -391,17 +424,37 @@ def clone_current_environment(
if update_callback:
update_callback(
- f"Creating new Python environment at: {env_path}\n"
+ f"Cloning current Python environment to: {env_path}\n"
)
+ # Get current Python version
+ current_version = f"{sys.version_info.major}.{sys.version_info.minor}"
+
+ # Get list of installed packages in current environment
+ if update_callback:
+ update_callback("Collecting installed packages...\n")
+
+ freeze_result = subprocess.run(
+ [sys.executable, "-m", "pip", "freeze"],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+ if freeze_result.returncode != 0:
+ if update_callback:
+ update_callback(
+ "Warning: Failed to get installed packages, "
+ "creating empty environment\n"
+ )
+ installed_packages = ""
+ else:
+ installed_packages = freeze_result.stdout.strip()
+
# Try to use uv if available
success, uv_path = ensure_uv_available(update_callback)
- if success and uv_path:
- # Get current Python version
- current_version = (
- f"{sys.version_info.major}.{sys.version_info.minor}"
- )
+ if success and uv_path:
+ # Create venv with uv
subprocess.run(
[uv_path, "venv", "--python", current_version, env_path],
check=True,
@@ -416,7 +469,7 @@ def clone_current_environment(
else:
python_path = os.path.join(env_path, "bin", "python")
- # Install pip and setuptools using uv
+ # Install pip, setuptools, wheel first
subprocess.run(
[
uv_path,
@@ -434,10 +487,38 @@ def clone_current_environment(
timeout=300,
)
- if update_callback:
- update_callback(
- "[UV] Cloned Python environment created successfully!\n"
+ # Install cloned packages if any
+ if installed_packages:
+ if update_callback:
+ update_callback("Installing cloned packages with uv...\n")
+ # Write requirements to temp file (auto-deleted)
+ fd, requirements_file = tempfile.mkstemp(
+ suffix=".txt", prefix="requirements_", dir=working_dir
)
+ try:
+ with os.fdopen(fd, "w") as f:
+ f.write(installed_packages)
+ subprocess.run(
+ [
+ uv_path,
+ "pip",
+ "install",
+ "--python",
+ python_path,
+ "-r",
+ requirements_file,
+ ],
+ check=True,
+ capture_output=True,
+ cwd=working_dir,
+ timeout=600,
+ )
+ finally:
+ if os.path.exists(requirements_file):
+ os.remove(requirements_file)
+
+ if update_callback:
+ update_callback("[UV] Environment cloned successfully!\n")
return True
else:
# Fallback to standard venv
@@ -448,46 +529,76 @@ def clone_current_environment(
venv.create(env_path, with_pip=True, symlinks=False)
- # Ensure pip is properly available
+ # Get python/pip path
if platform.system() == 'Windows':
python_path = os.path.join(env_path, "Scripts", "python.exe")
else:
python_path = os.path.join(env_path, "bin", "python")
- if os.path.exists(python_path):
- subprocess.run(
- [python_path, "-m", "pip", "install", "--upgrade", "pip"],
- check=True,
- capture_output=True,
- cwd=working_dir,
- timeout=60,
- )
+ if not os.path.exists(python_path):
if update_callback:
update_callback(
- "New Python environment created successfully with pip!"
+ f"Warning: Python executable not found at "
+ f"{python_path}\n"
)
- else:
+ return False
+
+ # Upgrade pip
+ subprocess.run(
+ [python_path, "-m", "pip", "install", "--upgrade", "pip"],
+ check=True,
+ capture_output=True,
+ cwd=working_dir,
+ timeout=60,
+ )
+
+ # Install cloned packages if any
+ if installed_packages:
if update_callback:
- update_callback(
- f"Warning: Python executable not found at "
- f"{python_path}"
+ update_callback("Installing cloned packages with pip...\n")
+ # Write requirements to temp file (auto-deleted)
+ fd, requirements_file = tempfile.mkstemp(
+ suffix=".txt", prefix="requirements_", dir=working_dir
+ )
+ try:
+ with os.fdopen(fd, "w") as f:
+ f.write(installed_packages)
+ subprocess.run(
+ [
+ python_path,
+ "-m",
+ "pip",
+ "install",
+ "-r",
+ requirements_file,
+ ],
+ check=True,
+ capture_output=True,
+ cwd=working_dir,
+ timeout=600,
)
+ finally:
+ if os.path.exists(requirements_file):
+ os.remove(requirements_file)
+
+ if update_callback:
+ update_callback("Environment cloned successfully!\n")
return True
except subprocess.CalledProcessError as e:
error_msg = e.stderr.decode() if e.stderr else str(e)
if update_callback:
- update_callback(f"Failed to create environment: {error_msg}\n")
- logger.error(f"Failed to create environment: {error_msg}")
+ update_callback(f"Failed to clone environment: {error_msg}\n")
+ logger.error(f"Failed to clone environment: {error_msg}")
return False
except subprocess.TimeoutExpired:
if update_callback:
- update_callback("Environment creation timed out\n")
+ update_callback("Environment cloning timed out\n")
return False
except Exception as e:
if update_callback:
- update_callback(f"Failed to create environment: {e!s}\n")
- logger.error(f"Failed to create environment: {e}")
+ update_callback(f"Failed to clone environment: {e!s}\n")
+ logger.error(f"Failed to clone environment: {e}")
return False