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

feat: enhance terminal toolkit (#1846)

jjyaoao6af1dedc105c
diff --git a/camel/toolkits/terminal_toolkit.py b/camel/toolkits/terminal_toolkit.py
index e66f28b69..db4cb9faa 100644
--- a/camel/toolkits/terminal_toolkit.py
+++ b/camel/toolkits/terminal_toolkit.py
@@ -12,9 +12,16 @@
# limitations under the License.
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+import atexit
import os
+import platform
+import queue
import subprocess
-from typing import Any, Dict, List, Optional
+import sys
+import threading
+import venv
+from queue import Queue
+from typing import Any, Dict, List, Optional, Tuple
from camel.logger import get_logger
from camel.toolkits.base import BaseToolkit
@@ -36,7 +43,19 @@ class TerminalToolkit(BaseToolkit):
timeout (Optional[float]): The timeout for terminal operations.
shell_sessions (Optional[Dict[str, Any]]): A dictionary to store
shell session information. If None, an empty dictionary will be
- used.
+ used. (default: :obj:`{}`)
+ working_dir (str): The working directory for operations.
+ If specified, all execution and write operations will be restricted
+ to this directory. Read operations can access paths outside this
+ directory.(default: :obj:`"./workspace"`)
+ need_terminal (bool): Whether to create a terminal interface.
+ (default: :obj:`True`)
+ use_shell_mode (bool): Whether to use shell mode for command execution.
+ (default: :obj:`True`)
+ clone_current_env (bool): Whether to clone the current Python
+ environment.(default: :obj:`False`)
+ safe_mode (bool): Whether to enable safe mode to restrict operations.
+ (default: :obj:`True`)
Note:
Most functions are compatible with Unix-based systems (macOS, Linux).
@@ -48,14 +67,260 @@ class TerminalToolkit(BaseToolkit):
self,
timeout: Optional[float] = None,
shell_sessions: Optional[Dict[str, Any]] = None,
+ working_dir: str = "./workspace",
+ need_terminal: bool = True,
+ use_shell_mode: bool = True,
+ clone_current_env: bool = False,
+ safe_mode: bool = True,
):
- import platform
-
super().__init__(timeout=timeout)
self.shell_sessions = shell_sessions or {}
- self.os_type = (
- platform.system()
- ) # 'Windows', 'Darwin' (macOS), 'Linux'
+ self.os_type = platform.system()
+ self.output_queue: Queue[str] = Queue()
+ self.agent_queue: Queue[str] = Queue()
+ self.terminal_ready = threading.Event()
+ self.gui_thread = None
+ self.safe_mode = safe_mode
+
+ self.cloned_env_path = None
+ self.use_shell_mode = use_shell_mode
+
+ self.python_executable = sys.executable
+ self.is_macos = platform.system() == 'Darwin'
+
+ atexit.register(self.__del__)
+
+ if not os.path.exists(working_dir):
+ os.makedirs(working_dir, exist_ok=True)
+ self.working_dir = os.path.abspath(working_dir)
+ self._update_terminal_output(
+ f"Working directory set to: {self.working_dir}\n"
+ )
+ if self.safe_mode:
+ self._update_terminal_output(
+ "Safe mode enabled: Write operations can only "
+ "be performed within the working directory\n"
+ )
+
+ if clone_current_env:
+ self.cloned_env_path = os.path.join(self.working_dir, ".venv")
+ self._clone_current_environment()
+ else:
+ self.cloned_env_path = None
+
+ if need_terminal:
+ if self.is_macos:
+ # macOS uses non-GUI mode
+ logger.info("Detected macOS environment, using non-GUI mode")
+ self._setup_file_output()
+ self.terminal_ready.set()
+ else:
+ # Other platforms use normal GUI
+ self.gui_thread = threading.Thread(
+ target=self._create_terminal, daemon=True
+ )
+ self.gui_thread.start()
+ self.terminal_ready.wait(timeout=5)
+
+ def _setup_file_output(self):
+ r"""Set up file output to replace GUI, using a fixed file to simulate
+ terminal.
+ """
+
+ self.log_file = os.path.join(os.getcwd(), "camel_terminal.txt")
+
+ if os.path.exists(self.log_file):
+ with open(self.log_file, "w") as f:
+ f.truncate(0)
+ f.write("CAMEL Terminal Session\n")
+ f.write("=" * 50 + "\n")
+ f.write(f"Working Directory: {os.getcwd()}\n")
+ f.write("=" * 50 + "\n\n")
+ else:
+ with open(self.log_file, "w") as f:
+ f.write("CAMEL Terminal Session\n")
+ f.write("=" * 50 + "\n")
+ f.write(f"Working Directory: {os.getcwd()}\n")
+ f.write("=" * 50 + "\n\n")
+
+ # Inform the user
+ logger.info(f"Terminal output redirected to: {self.log_file}")
+
+ def file_update(output: str):
+ try:
+ # Directly append to the end of the file
+ with open(self.log_file, "a") as f:
+ f.write(output)
+ # If the output does not end with a newline, add one
+ if output and not output.endswith('\n'):
+ f.write('\n')
+ # Ensure the agent also receives the output
+ self.agent_queue.put(output)
+ except Exception as e:
+ logger.error(f"Failed to write to terminal: {e}")
+
+ # Replace the update method
+ self._update_terminal_output = file_update
+
+ def _clone_current_environment(self):
+ r"""Create a new Python virtual environment."""
+ try:
+ if os.path.exists(self.cloned_env_path):
+ self._update_terminal_output(
+ f"Using existing environment: {self.cloned_env_path}\n"
+ )
+ return
+
+ self._update_terminal_output(
+ f"Creating new Python environment at:{self.cloned_env_path}\n"
+ )
+
+ venv.create(self.cloned_env_path, with_pip=True)
+ self._update_terminal_output(
+ "New Python environment created successfully!\n"
+ )
+
+ except Exception as e:
+ self._update_terminal_output(
+ f"Failed to create environment: {e!s}\n"
+ )
+ logger.error(f"Failed to create environment: {e}")
+
+ def _create_terminal(self):
+ r"""Create a terminal GUI."""
+
+ try:
+ import tkinter as tk
+ from tkinter import scrolledtext
+
+ def update_terminal():
+ try:
+ while True:
+ output = self.output_queue.get_nowait()
+ if isinstance(output, bytes):
+ output = output.decode('utf-8', errors='replace')
+ self.terminal.insert(tk.END, output)
+ self.terminal.see(tk.END)
+ except queue.Empty:
+ if hasattr(self, 'root') and self.root:
+ self.root.after(100, update_terminal)
+
+ self.root = tk.Tk()
+ self.root.title(f"{self.os_type} Terminal")
+
+ self.root.geometry("800x600")
+ self.root.minsize(400, 300)
+
+ self.terminal = scrolledtext.ScrolledText(
+ self.root,
+ wrap=tk.WORD,
+ bg='black',
+ fg='white',
+ font=('Consolas', 10),
+ insertbackground='white', # Cursor color
+ )
+ self.terminal.pack(fill=tk.BOTH, expand=True)
+
+ # Set the handling for closing the window
+ def on_closing():
+ self.root.quit()
+ self.root.destroy()
+ self.root = None
+
+ self.root.protocol("WM_DELETE_WINDOW", on_closing)
+
+ # Start updating
+ update_terminal()
+
+ # Mark the terminal as ready
+ self.terminal_ready.set()
+
+ # Start the main loop
+ self.root.mainloop()
+
+ except Exception as e:
+ logger.error(f"Failed to create terminal: {e}")
+ self.terminal_ready.set()
+
+ def _update_terminal_output(self, output: str):
+ r"""Update terminal output and send to agent.
+
+ Args:
+ output (str): The output to be sent to the agent
+ """
+ try:
+ # If it is macOS , only write to file
+ if self.is_macos:
+ if hasattr(self, 'log_file'):
+ with open(self.log_file, "a") as f:
+ f.write(output)
+ # Ensure the agent also receives the output
+ self.agent_queue.put(output)
+ return
+
+ # For other cases, try to update the GUI (if it exists)
+ if hasattr(self, 'root') and self.root:
+ self.output_queue.put(output)
+
+ # Always send to agent queue
+ self.agent_queue.put(output)
+
+ except Exception as e:
+ logger.error(f"Failed to update terminal output: {e}")
+
+ def _is_path_within_working_dir(self, path: str) -> bool:
+ r"""Check if the path is within the working directory.
+
+ Args:
+ path (str): The path to check
+
+ Returns:
+ bool: Returns True if the path is within the working directory,
+ otherwise returns False
+ """
+ abs_path = os.path.abspath(path)
+ return abs_path.startswith(self.working_dir)
+
+ def _enforce_working_dir_for_execution(self, path: str) -> Optional[str]:
+ r"""Enforce working directory restrictions, return error message
+ if execution path is not within the working directory.
+
+ Args:
+ path (str): The path to be used for executing operations
+
+ Returns:
+ Optional[str]: Returns error message if the path is not within
+ the working directory, otherwise returns None
+ """
+ if not self._is_path_within_working_dir(path):
+ return (
+ f"Operation restriction: Execution path {path} must "
+ f"be within working directory {self.working_dir}"
+ )
+ return None
+
+ def _copy_external_file_to_workdir(
+ self, external_file: str
+ ) -> Optional[str]:
+ r"""Copy external file to working directory.
+
+ Args:
+ external_file (str): The path of the external file
+
+ Returns:
+ Optional[str]: New path after copying to the working directory,
+ returns None on failure
+ """
+ try:
+ import shutil
+
+ filename = os.path.basename(external_file)
+ new_path = os.path.join(self.working_dir, filename)
+ shutil.copy2(external_file, new_path)
+ return new_path
+ except Exception as e:
+ logger.error(f"Failed to copy file: {e}")
+ return None
def file_find_in_content(
self, file: str, regex: str, sudo: bool = False
@@ -72,6 +337,7 @@ class TerminalToolkit(BaseToolkit):
Returns:
str: Matching content found in the file.
"""
+
if not os.path.exists(file):
return f"File not found: {file}"
@@ -80,6 +346,9 @@ class TerminalToolkit(BaseToolkit):
command = []
if sudo:
+ error_msg = self._enforce_working_dir_for_execution(file)
+ if error_msg:
+ return error_msg
command.extend(["sudo"])
if self.os_type in ['Darwin', 'Linux']: # macOS or Linux
@@ -119,38 +388,283 @@ class TerminalToolkit(BaseToolkit):
else: # Windows
# For Windows, we use dir command with /s for recursive search
# and /b for bare format
+
pattern = glob
file_path = os.path.join(path, pattern).replace('/', '\\')
command.extend(["cmd", "/c", "dir", "/s", "/b", file_path])
try:
result = subprocess.run(
- command, check=False, capture_output=True, text=True
+ command,
+ check=False,
+ capture_output=True,
+ text=True,
+ shell=False,
)
- return result.stdout.strip()
+
+ output = result.stdout.strip()
+ if self.os_type == 'Windows':
+ output = output.replace('\\', '/')
+ return output
except subprocess.SubprocessError as e:
logger.error(f"Error finding files by name: {e}")
return f"Error: {e!s}"
- def shell_exec(self, id: str, exec_dir: str, command: str) -> str:
- r"""Execute commands in a specified shell session.
+ def _sanitize_command(self, command: str, exec_dir: str) -> Tuple:
+ r"""Check and modify command to ensure safety.
+
+ Args:
+ command (str): The command to check
+ exec_dir (str): The directory to execute the command in
+
+ Returns:
+ Tuple: (is safe, modified command or error message)
+ """
+ if not self.safe_mode:
+ return True, command
+
+ if not command or command.strip() == "":
+ return False, "Empty command"
+
+ # Use shlex for safer command parsing
+ import shlex
+
+ try:
+ parts = shlex.split(command)
+ except ValueError as e:
+ # Handle malformed commands (e.g., unbalanced quotes)
+ return False, f"Invalid command format: {e}"
+
+ if not parts:
+ return False, "Empty command"
+
+ # Get base command
+ base_cmd = parts[0].lower()
+
+ # Handle special commands
+ if base_cmd in ['cd', 'chdir']:
+ # Check if cd command attempts to leave the working directory
+ if len(parts) > 1:
+ target_dir = parts[1].strip('"\'')
+ if (
+ target_dir.startswith('/')
+ or target_dir.startswith('\\')
+ or ':' in target_dir
+ ):
+ # Absolute path
+ abs_path = os.path.abspath(target_dir)
+ else:
+ # Relative path
+ abs_path = os.path.abspath(
+ os.path.join(exec_dir, target_dir)
+ )
+
+ if not self._is_path_within_working_dir(abs_path):
+ return False, (
+ f"Safety restriction: Cannot change to directory "
+ f"outside of working directory {self.working_dir}"
+ )
+
+ # Check file operation commands
+ elif base_cmd in [
+ 'rm',
+ 'del',
+ 'rmdir',
+ 'rd',
+ 'deltree',
+ 'erase',
+ 'unlink',
+ 'shred',
+ 'srm',
+ 'wipe',
+ 'remove',
+ ]:
+ # Check targets of delete commands
+ for _, part in enumerate(parts[1:], 1):
+ if part.startswith('-') or part.startswith(
+ '/'
+ ): # Skip options
+ continue
+
+ target = part.strip('"\'')
+ if (
+ target.startswith('/')
+ or target.startswith('\\')
+ or ':' in target
+ ):
+ # Absolute path
+ abs_path = os.path.abspath(target)
+ else:
+ # Relative path
+ abs_path = os.path.abspath(os.path.join(exec_dir, target))
+
+ if not self._is_path_within_working_dir(abs_path):
+ return False, (
+ f"Safety restriction: Cannot delete files outside "
+ f"of working directory {self.working_dir}"
+ )
+
+ # Check write/modify commands
+ elif base_cmd in [
+ 'touch',
+ 'mkdir',
+ 'md',
+ 'echo',
+ 'cat',
+ 'cp',
+ 'copy',
+ 'mv',
+ 'move',
+ 'rename',
+ 'ren',
+ 'write',
+ 'output',
+ ]:
+ # Check for redirection symbols
+ full_cmd = command.lower()
+ if '>' in full_cmd:
+ # Find the file path after redirection
+ redirect_parts = command.split('>')
+ if len(redirect_parts) > 1:
+ output_file = (
+ redirect_parts[1].strip().split()[0].strip('"\'')
+ )
+ if (
+ output_file.startswith('/')
+ or output_file.startswith('\\')
+ or ':' in output_file
+ ):
+ # Absolute path
+ abs_path = os.path.abspath(output_file)
+ else:
+ # Relative path
+ abs_path = os.path.abspath(
+ os.path.join(exec_dir, output_file)
+ )
+
+ if not self._is_path_within_working_dir(abs_path):
+ return False, (
+ f"Safety restriction: Cannot write to file "
+ f"outside of working directory {self.working_dir}"
+ )
+
+ # For cp/mv commands, check target paths
+ if base_cmd in ['cp', 'copy', 'mv', 'move']:
+ # Simple handling, assuming the last parameter is the target
+ if len(parts) > 2:
+ target = parts[-1].strip('"\'')
+ if (
+ target.startswith('/')
+ or target.startswith('\\')
+ or ':' in target
+ ):
+ # Absolute path
+ abs_path = os.path.abspath(target)
+ else:
+ # Relative path
+ abs_path = os.path.abspath(
+ os.path.join(exec_dir, target)
+ )
+
+ if not self._is_path_within_working_dir(abs_path):
+ return False, (
+ f"Safety restriction: Cannot write to file "
+ f"outside of working directory {self.working_dir}"
+ )
+
+ # Check dangerous commands
+ elif base_cmd in [
+ 'sudo',
+ 'su',
+ 'chmod',
+ 'chown',
+ 'chgrp',
+ 'passwd',
+ 'mkfs',
+ 'fdisk',
+ 'dd',
+ 'shutdown',
+ 'reboot',
+ 'halt',
+ 'poweroff',
+ 'init',
+ ]:
+ return False, (
+ f"Safety restriction: Command '{base_cmd}' may affect system "
+ f"security and is prohibited"
+ )
+
+ # Check network commands
+ elif base_cmd in ['ssh', 'telnet', 'ftp', 'sftp', 'nc', 'netcat']:
+ return False, (
+ f"Safety restriction: Network command '{base_cmd}' "
+ f"is prohibited"
+ )
+
+ # Add copy functionality - copy from external to working directory
+ elif base_cmd == 'safecopy':
+ # Custom command: safecopy <source file> <target file>
+ if len(parts) != 3:
+ return False, "Usage: safecopy <source file> <target file>"
+
+ source = parts[1].strip('\'"')
+ target = parts[2].strip('\'"')
+
+ # Check if source file exists
+ if not os.path.exists(source):
+ return False, f"Source file does not exist: {source}"
+
+ # Ensure target is within working directory
+ if (
+ target.startswith('/')
+ or target.startswith('\\')
+ or ':' in target
+ ):
+ # Absolute path
+ abs_target = os.path.abspath(target)
+ else:
+ # Relative path
+ abs_target = os.path.abspath(os.path.join(exec_dir, target))
+
+ if not self._is_path_within_working_dir(abs_target):
+ return False, (
+ f"Safety restriction: Target file must be within "
+ f"working directory {self.working_dir}"
+ )
+
+ # Replace with safe copy command
+ if self.os_type == 'Windows':
+ return True, f"copy \"{source}\" \"{abs_target}\""
+ else:
+ return True, f"cp \"{source}\" \"{abs_target}\""
+
+ return True, command
+
+ def shell_exec(self, id: str, command: str) -> str:
+ r"""Execute commands. This can be used to execute various commands,
+ such as writing code, executing code, and running commands.
Args:
id (str): Unique identifier of the target shell session.
- exec_dir (str): Working directory for command execution (must use
- absolute path).
command (str): Shell command to execute.
Returns:
str: Output of the command execution or error message.
"""
- if not os.path.isabs(exec_dir):
- return f"exec_dir must be an absolute path: {exec_dir}"
+ # Command execution must be within the working directory
+ error_msg = self._enforce_working_dir_for_execution(self.working_dir)
+ if error_msg:
+ return error_msg
- if not os.path.exists(exec_dir):
- return f"Directory not found: {exec_dir}"
+ if self.safe_mode:
+ is_safe, sanitized_command = self._sanitize_command(
+ command, self.working_dir
+ )
+ if not is_safe:
+ return f"Command rejected: {sanitized_command}"
+ command = sanitized_command
- # If the session doesn't exist, create a new one
+ # If the session does not exist, create a new session
if id not in self.shell_sessions:
self.shell_sessions[id] = {
"process": None,
@@ -159,48 +673,97 @@ class TerminalToolkit(BaseToolkit):
}
try:
- # Execute the command in the specified directory
- process = subprocess.Popen(
- command,
- shell=True,
- cwd=exec_dir,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- stdin=subprocess.PIPE,
- text=False,
- )
-
- # Store the process and mark as running
- self.shell_sessions[id]["process"] = process
- self.shell_sessions[id]["running"] = True
- self.shell_sessions[id]["output"] = ""
+ # First, log the command to be executed
+ self._update_terminal_output(f"\n$ {command}\n")
+
+ if command.startswith('python') or command.startswith('pip'):
+ if self.cloned_env_path:
+ if self.os_type == 'Windows':
+ base_path = os.path.join(
+ self.cloned_env_path, "Scripts"
+ )
+ python_path = os.path.join(base_path, "python.exe")
+ pip_path = os.path.join(base_path, "pip.exe")
+ else:
+ base_path = os.path.join(self.cloned_env_path, "bin")
+ python_path = os.path.join(base_path, "python")
+ pip_path = os.path.join(base_path, "pip")
+ else:
+ python_path = self.python_executable
+ pip_path = f'"{python_path}" -m pip'
+
+ if command.startswith('python'):
+ command = command.replace('python', f'"{python_path}"', 1)
+ elif command.startswith('pip'):
+ command = command.replace('pip', pip_path, 1)
+
+ if self.is_macos:
+ # Type safe version - macOS uses subprocess.run
+ process = subprocess.run(
+ command,
+ shell=True,
+ cwd=self.working_dir,
+ capture_output=True,
+ text=True,
+ env=os.environ.copy(),
+ )
- # Get initial output (non-blocking)
- stdout, stderr = "", ""
- try:
- if process.stdout:
- stdout = process.stdout.read().decode('utf-8')
+ # Process the output
+ output = process.stdout or ""
if process.stderr:
- stderr = process.stderr.read().decode('utf-8')
- except Exception as e:
- logger.error(f"Error reading initial output: {e}")
- return f"Error: {e!s}"
+ output += f"\nStderr Output:\n{process.stderr}"
+
+ # Update session information and terminal
+ self.shell_sessions[id]["output"] = output
+ self._update_terminal_output(output + "\n")
+
+ return output
+
+ else:
+ # Non-macOS systems use the Popen method
+ proc = subprocess.Popen(
+ command,
+ shell=True,
+ cwd=self.working_dir,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ stdin=subprocess.PIPE,
+ text=True,
+ bufsize=1,
+ universal_newlines=True,
+ env=os.environ.copy(),
+ )
- output = stdout
- if stderr:
- output += f"\nErrors:\n{stderr}"
+ # Store the process and mark it as running
+ self.shell_sessions[id]["process"] = proc
+ self.shell_sessions[id]["running"] = True
- self.shell_sessions[id]["output"] = output
- return (
- f"Command started in session '{id}'. Initial output: {output}"
- )
+ # Get output
+ stdout, stderr = proc.communicate()
- except subprocess.SubprocessError as e:
- self.shell_sessions[id]["running"] = False
- error_msg = f"Error executing command: {e}"
- self.shell_sessions[id]["output"] = error_msg
+ output = stdout or ""
+ if stderr:
+ output += f"\nStderr Output:\n{stderr}"
+
+ # Update session information and terminal
+ self.shell_sessions[id]["output"] = output
+ self._update_terminal_output(output + "\n")
+
+ return output
+
+ except Exception as e:
+ error_msg = f"Command execution error: {e!s}"
logger.error(error_msg)
- return error_msg
+ self._update_terminal_output(f"\nError: {error_msg}\n")
+
+ # More detailed error information
+ import traceback
+
+ detailed_error = traceback.format_exc()
+ return (
+ f"Error: {error_msg}\n\n"
+ f"Detailed information: {detailed_error}"
+ )
def shell_view(self, id: str) -> str:
r"""View the content of a specified shell session.
@@ -215,50 +778,29 @@ class TerminalToolkit(BaseToolkit):
return f"Shell session not found: {id}"
session = self.shell_sessions[id]
- process = session.get("process")
- if process is None:
- return f"No active process in session '{id}'"
+ try:
+ # Check process status
+ if session["process"].poll() is not None:
+ session["running"] = False
- # Try to get any new output
- if session["running"] and process.poll() is None:
+ # Collect all new output from agent queue
+ new_output = ""
try:
- # Non-blocking read from stdout/stderr
- stdout_data, stderr_data = "", ""
- if process.stdout and process.stdout.readable():
- stdout_data = process.stdout.read1().decode('utf-8')
- if process.stderr and process.stderr.readable():
- stderr_data = process.stderr.read1().decode('utf-8')
-
- if stdout_data:
- session["output"] += stdout_data
- if stderr_data:
- session["output"] += f"\nErrors:\n{stderr_data}"
- except Exception as e:
- logger.error(f"Error getting process output: {e}")
- return f"Error: {e!s}"
+ while True:
+ output = self.agent_queue.get_nowait()
+ new_output += output
+ session["output"] += output
+ except queue.Empty:
+ pass
- # Check if the process has completed
- if process.poll() is not None and session["running"]:
- try:
- # Get remaining output if any
- stdout_data, stderr_data = "", ""
- if process.stdout and process.stdout.readable():
- stdout_data = process.stdout.read().decode('utf-8')
- if process.stderr and process.stderr.readable():
- stderr_data = process.stderr.read().decode('utf-8')
-
- if stdout_data:
- session["output"] += stdout_data
- if stderr_data:
- session["output"] += f"\nErrors:\n{stderr_data}"
- except Exception as e:
- logger.error(f"Error getting final process output: {e}")
- return f"Error: {e!s}"
- finally:
- session["running"] = False
+ return new_output or session["output"]
- return session["output"]
+ except Exception as e:
+ error_msg = f"Error reading terminal output: {e}"
+ self._update_terminal_output(f"\nError: {error_msg}\n")
+ logger.error(error_msg)
+ return f"Error: {e!s}"
def shell_wait(self, id: str, seconds: Optional[int] = None) -> str:
r"""Wait for the running process in a specified shell session to
@@ -281,33 +823,40 @@ class TerminalToolkit(BaseToolkit):
if process is None:
return f"No active process in session '{id}'"
- if not session["running"]:
+ if not session["running"] or process.poll() is not None:
return f"Process in session '{id}' is not running"
try:
- # Use communicate with timeout
- stdout, stderr = process.communicate(timeout=seconds)
-
- if stdout:
- stdout_str = (
- stdout.decode('utf-8')
- if isinstance(stdout, bytes)
- else stdout
+ if hasattr(process, 'communicate'):
+ # Use communicate with timeout
+ stdout, stderr = process.communicate(timeout=seconds)
+
+ if stdout:
+ stdout_str = (
+ stdout.decode('utf-8')
+ if isinstance(stdout, bytes)
+ else stdout
+ )
+ session["output"] += stdout_str
+ if stderr:
+ stderr_str = (
+ stderr.decode('utf-8')
+ if isinstance(stderr, bytes)
+ else stderr
+ )
+ if stderr_str:
+ session["output"] += f"\nStderr Output:\n{stderr_str}"
+
+ session["running"] = False
+ return (
+ f"Process completed in session '{id}'. "
+ f"Output: {session['output']}"
)
- session["output"] += stdout_str
- if stderr:
- stderr_str = (
- stderr.decode('utf-8')
- if isinstance(stderr, bytes)
- else stderr
+ else:
+ return (
+ f"Process already completed in session '{id}'. "
+ f"Output: {session['output']}"
)
- session["output"] += f"\nErrors:\n{stderr_str}"
-
- session["running"] = False
- return (
- f"Process completed in session '{id}'. "
- f"Output: {session['output']}"
- )
except subprocess.TimeoutExpired:
return (
@@ -404,6 +953,71 @@ class TerminalToolkit(BaseToolkit):
logger.error(f"Error killing process: {e}")
return f"Error killing process: {e!s}"
+ def __del__(self):
+ r"""Clean up resources when the object is being destroyed.
+ Terminates all running processes and closes any open file handles.
+ """
+ # Log that cleanup is starting
+ logger.info("TerminalToolkit cleanup initiated")
+
+ # Clean up all processes in shell sessions
+ for session_id, session in self.shell_sessions.items():
+ process = session.get("process")
+ if process is not None and session.get("running", False):
+ try:
+ logger.info(
+ f"Terminating process in session '{session_id}'"
+ )
+
+ # Close process input/output streams if open
+ if (
+ hasattr(process, 'stdin')
+ and process.stdin
+ and not process.stdin.closed
+ ):
+ process.stdin.close()
+
+ # Terminate the process
+ process.terminate()
+ try:
+ # Give the process a short time to terminate gracefully
+ process.wait(timeout=3)
+ except subprocess.TimeoutExpired:
+ # Force kill if the process doesn't terminate
+ # gracefully
+ logger.warning(
+ f"Process in session '{session_id}' did not "
+ f"terminate gracefully, forcing kill"
+ )
+ process.kill()
+
+ # Mark the session as not running
+ session["running"] = False
+
+ except Exception as e:
+ logger.error(
+ f"Error cleaning up process in session "
+ f"'{session_id}': {e}"
+ )
+
+ # Close file output if it exists
+ if hasattr(self, 'log_file') and self.is_macos:
+ try:
+ logger.info(f"Final terminal log saved to: {self.log_file}")
+ except Exception as e:
+ logger.error(f"Error logging file information: {e}")
+
+ # Clean up GUI resources if they exist
+ if hasattr(self, 'root') and self.root:
+ try:
+ logger.info("Closing terminal GUI")
+ self.root.quit()
+ self.root.destroy()
+ except Exception as e:
+ logger.error(f"Error closing terminal GUI: {e}")
+
+ logger.info("TerminalToolkit cleanup completed")
+
def get_tools(self) -> List[FunctionTool]:
r"""Returns a list of FunctionTool objects representing the functions
in the toolkit.
diff --git a/examples/toolkits/terminal_toolkit.py b/examples/toolkits/terminal_toolkit.py
index 00357504d..18a14390c 100644
--- a/examples/toolkits/terminal_toolkit.py
+++ b/examples/toolkits/terminal_toolkit.py
@@ -22,6 +22,10 @@ from camel.types import ModelPlatformType, ModelType
# Get current script directory
base_dir = os.path.dirname(os.path.abspath(__file__))
+# Define workspace directory for the toolkit
+workspace_dir = os.path.join(
+ os.path.dirname(os.path.dirname(base_dir)), "workspace"
+)
# Define system message
sys_msg = (
@@ -31,7 +35,7 @@ sys_msg = (
)
# Set model config
-tools = TerminalToolkit().get_tools()
+tools = TerminalToolkit(working_dir=workspace_dir).get_tools()
model_config_dict = ChatGPTConfig(
temperature=0.0,
@@ -52,28 +56,31 @@ camel_agent = ChatAgent(
camel_agent.reset()
# Define a user message for creating logs directory
-usr_msg = f"Create a 'logs' directory in '{base_dir}'"
+usr_msg = (
+ f"Create a 'logs' directory in '{workspace_dir}' and list its contents"
+)
# Get response information
response = camel_agent.step(usr_msg)
print(str(response.info['tool_calls'])[:1000])
"""
===============================================================================
-[ToolCallingRecord(tool_name='shell_exec', args={'id': 'shell_session_1',
-'exec_dir': '/Users/enrei/Desktop/camel0302/camel/examples/toolkits',
-'command': 'mkdir logs'}, result="Command started in session
-'shell_session_1'. Initial output: ",
-tool_call_id='call_8xSHligODzyfPOMG81dGxNF2'), ToolCallingRecord
-(tool_name='shell_wait', args={'id': 'shell_session_1', 'seconds': None},
-result="Process completed in session 'shell_session_1'. Output: ",
-tool_call_id='call_3RZ8Pg2BlmfFoYWgmEVONdcE')]
+[ToolCallingRecord(tool_name='shell_exec', args={'id': 'session1', 'exec_dir':
+'/Users/enrei/Desktop/camel0302/camel/workspace', 'command': 'mkdir logs'},
+result='', tool_call_id='call_ekWtDhrwxOg20lz55pqLEKvm'), ToolCallingRecord
+(tool_name='shell_exec', args={'id': 'session2', 'exec_dir': '/Users/enrei/
+Desktop/camel0302/camel/workspace/logs', 'command': 'ls -la'}, result='total
+0\ndrwxr-xr-x 2 enrei staff 64 Mar 30 04:29 .\ndrwxr-xr-x 4 enrei staff
+128 Mar 30 04:29 ..\n', tool_call_id='call_FNdkLkvUahtEZUf7YZiJrjfo')]
===============================================================================
"""
# Define a user message for creating log files
-usr_msg = f"""Create 'app.log' in the logs directory at '{os.path.join
-(base_dir, 'logs')}' with content: 'INFO: Application started successfully at
-2024-03-10'"""
+usr_msg = (
+ f"Create 'app.log' in the logs directory at "
+ f"'{os.path.join(workspace_dir, 'logs')}' with content: INFO: Application "
+ f"started successfully at 2024-03-10 and show the file content"
+)
# Get response information
camel_agent.reset()
@@ -82,20 +89,20 @@ print(str(response.info['tool_calls'])[:1000])
"""
===============================================================================
[ToolCallingRecord(tool_name='shell_exec', args={'id': 'create_log_file',
-'exec_dir': '/Users/enrei/Desktop/camel0302/camel/examples/toolkits/logs',
-'command': "echo 'INFO: Application started successfully at 2024-03-10' > app.
-log"}, result="Command started in session 'create_log_file'. Initial output:
-", tool_call_id='call_IK0vsGszfjw3hn5Jda1R8t4A'), ToolCallingRecord
-(tool_name='shell_wait', args={'id': 'create_log_file', 'seconds': 5},
-result="Process completed in session 'create_log_file'. Output: ",
-tool_call_id='call_ta8ksNQvrPcdvBgmAro692uJ')]
+'exec_dir': '/Users/enrei/Desktop/camel0302/camel/workspace/logs', 'command':
+"echo 'INFO: Application started successfully at 2024-03-10' > app.log"},
+result='', tool_call_id='call_bctQQYnWgAuPp1ga7a7xM6bo'), ToolCallingRecord
+(tool_name='shell_exec', args={'id': 'show_log_file_content', 'exec_dir': '/
+Users/enrei/Desktop/camel0302/camel/workspace/logs', 'command': 'cat app.
+log'}, result='INFO: Application started successfully at 2024-03-10\n',
+tool_call_id='call_wPYJBG3eYrUsjFJYIYYynxuz')]
===============================================================================
"""
# Define a user message for searching in logs
usr_msg = (
f"Search for 'INFO' keyword in the log file at "
- f"'{os.path.join(base_dir, 'logs', 'app.log')}'"
+ f"'{os.path.join(workspace_dir, 'logs', 'app.log')}'"
)
# Get response information
@@ -105,14 +112,16 @@ print(str(response.info['tool_calls'])[:1000])
"""
===============================================================================
[ToolCallingRecord(tool_name='file_find_in_content', args={'file': '/Users/
-enrei/Desktop/camel0302/camel/examples/toolkits/logs/app.log', 'regex':
-'INFO', 'sudo': False}, result='INFO: Application started successfully at
-2024-03-10', tool_call_id='call_mrrHw9rEwfLwJeSD1j0zooLd')]
+enrei/Desktop/camel0302/camel/workspace/logs/app.log', 'regex': 'INFO',
+'sudo': False}, result='INFO: Application started successfully at 2024-03-10',
+ tool_call_id='call_PpeRUsldHyg5jSPLZxiGoVfq')]
===============================================================================
"""
# Define a user message for cleaning up logs
-usr_msg = f"Remove the 'logs' directory and all its contents in '{base_dir}'"
+usr_msg = (
+ f"Remove the 'logs' directory and all its contents in '{workspace_dir}'"
+)
# Get response information
camel_agent.reset()
@@ -121,12 +130,8 @@ print(response.info['tool_calls'])
"""
===============================================================================
[ToolCallingRecord(tool_name='shell_exec', args={'id': 'remove_logs',
-'exec_dir': '/Users/enrei/Desktop/camel0302/camel/examples/toolkits',
-'command': 'rm -rf logs'}, result="Command started in session 'remove_logs'.
-Initial output: ", tool_call_id='call_DzBjpYowMmGbUrZ1C24TNuOy'),
-ToolCallingRecord(tool_name='shell_wait', args={'id': 'remove_logs',
-'seconds': None}, result="Process completed in session 'remove_logs'. Output:
-", tool_call_id='call_BchqhziSRi7t3av279Nt1u6E')]
+'exec_dir': '/Users/enrei/Desktop/camel0302/camel/workspace', 'command': 'rm
+-rf logs'}, result='', tool_call_id='call_A2kUkVIAhkD9flWmmpTlS9FA')]
===============================================================================
"""
@@ -143,6 +148,67 @@ print(response.info['tool_calls'])
bots', 'glob': '*'}, result='examples/bots\nexamples/bots/discord_bot.
py\nexamples/bots/discord_bot_installation_management.py\nexamples/bots/
slack_bot_use_msg_queue.py\nexamples/bots/discord_bot_use_msg_queue.
-py\nexamples/bots/slack_bot.py', tool_call_id='call_PBtQ7qzk2K9fnrtrTASbpeDb')]
+py\nexamples/bots/slack_bot.py', tool_call_id='call_LzRjSotNqKOWwU4yHcstlnG9')]
===============================================================================
"""
+
+# Define a user message for testing resource cleanup via __del__ method
+print("\n\n================ Testing Resource Cleanup ================")
+usr_msg = (
+ "Start a long-running process that sleeps for 300 seconds in the "
+ "background, then show me the list of running processes"
+)
+
+
+# Get response information for starting the process
+camel_agent.reset()
+response = camel_agent.step(usr_msg)
+print(str(response.info['tool_calls'])[:1000])
+"""
+===============================================================================
+[ToolCallingRecord(tool_name='shell_exec', args={'id': 'session1', 'exec_dir':
+'/tmp', 'command': 'sleep 300 & echo $!'}, result='Operation restriction:
+Execution path /tmp must be within working directory /home/jjyaoao/openSource/
+camel/workspace', tool_call_id='call_G7TcVUJs195Er6yocORHysXP'),
+ToolCallingRecord(tool_name='shell_exec', args={'id': 'session1', 'exec_dir':
+'/home/jjyaoao/openSource/camel/workspace', 'command': 'sleep 300 & echo $!'},
+result='10804\n', tool_call_id='call_mncQosy3b4cuc1j5MGiltohH'),
+ToolCallingRecord(tool_name='shell_exec', args={'id': 'session2', 'exec_dir':
+'/home/jjyaoao/openSource/camel/workspace', 'command': 'ps aux'},
+result='USER PID %CPU %MEM VSZ RSS TTY STAT START TIME
+COMMAND\nroot 1 0.0 0.2 170104 12368 ? Ss 10:06 0:00
+/sbin/init\nroot 2 0.0 0.0 2776 1928 ? Sl 10:06 0:00
+/init\nroot 8 0.0 0.0 2776 4 ? Sl 10:06 0:00
+plan9 --control-socket 7 --log-level=debug --log-file=/dev/null ...',
+tool_call_id='call_UvxQrsb1GpfDHTQQc6rLoQ3P')]
+===============================================================================
+"""
+# Define a user message to check if the process was terminated by __del__
+usr_msg = "Check if there are any sleep processes running on the system"
+
+# Get response information for checking the processes
+camel_agent.reset()
+response = camel_agent.step(usr_msg)
+print(str(response.info['tool_calls'])[:1000])
+"""
+===============================================================================
+[ToolCallingRecord(tool_name='shell_exec', args={'id': 'check_sleep_processes',
+'exec_dir': '/', 'command': 'ps aux | grep sleep'}, result='Operation
+restriction: Execution path / must be within working directory
+/home/jjyaoao/openSource/camel/workspace', tool_call_id=
+'call_gbhmZ3mwpB07uPtVF3FxZaHu'), ToolCallingRecord(tool_name='shell_exec',
+args={'id': 'check_sleep_processes', 'exec_dir':
+'/home/jjyaoao/openSource/camel/workspace', 'command': 'ps aux | grep sleep'},
+result='root 11385 0.0 0.0 2620 532 pts/4 S+ 11:16 0:00
+/bin/sh -c ps aux | grep sleep\nroot 11387 0.0 0.0 8172 656 pts/4
+S+ 11:16 0:00 grep sleep\n', tool_call_id='call_gSZqRaqNAtYjUXOfvVuaObw2')]
+===============================================================================
+"""
+
+usr_msg = "help me use uv pip install pptx, and create a ppt, and show me the"
+" output of the terminal"
+
+# Get response information for checking the processes
+camel_agent.reset()
+response = camel_agent.step(usr_msg)
+print(str(response.info['tool_calls']))
diff --git a/test/toolkits/test_terminal_toolkit.py b/test/toolkits/test_terminal_toolkit.py
index c7b32e570..5e039ae78 100644
--- a/test/toolkits/test_terminal_toolkit.py
+++ b/test/toolkits/test_terminal_toolkit.py
@@ -22,8 +22,8 @@ from camel.toolkits import TerminalToolkit
@pytest.fixture
-def terminal_toolkit():
- return TerminalToolkit()
+def terminal_toolkit(temp_dir):
+ return TerminalToolkit(working_dir=temp_dir, safe_mode=False)
@pytest.fixture
@@ -100,7 +100,6 @@ def test_shell_exec(terminal_toolkit, temp_dir):
# Test basic command execution
result = terminal_toolkit.shell_exec(
"test_session",
- str(temp_dir),
"echo 'Hello World'",
)
assert "Hello World" in result
@@ -108,22 +107,13 @@ def test_shell_exec(terminal_toolkit, temp_dir):
# Test command with error
result = terminal_toolkit.shell_exec(
"test_session",
- str(temp_dir),
"nonexistent_command",
)
assert "not found" in result.lower()
- # Test with relative path
- result = terminal_toolkit.shell_exec(
- "test_session",
- "relative/path",
- "echo 'test'",
- )
- assert "must be an absolute path" in result.lower()
-
# Test session persistence
session_id = "persistent_session"
- terminal_toolkit.shell_exec(session_id, str(temp_dir), "echo 'test1'")
+ terminal_toolkit.shell_exec(session_id, "echo 'test1'")
assert session_id in terminal_toolkit.shell_sessions
assert terminal_toolkit.shell_sessions[session_id]["output"] != ""
@@ -135,12 +125,10 @@ def test_shell_exec_multiple_sessions(terminal_toolkit, temp_dir):
result1 = terminal_toolkit.shell_exec(
session1,
- str(temp_dir),
"echo 'Session 1'",
)
result2 = terminal_toolkit.shell_exec(
session2,
- str(temp_dir),
"echo 'Session 2'",
)