Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(tool): implement builtin tools with ToolBase inheritance and add comprehensive tests (#1502)
DavdGaofa47b0770615
diff --git a/pyproject.toml b/pyproject.tomlindex 0d836afb3..efe94b215 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -42,6 +42,7 @@ dependencies = ["aiofiles","tree_sitter","tree_sitter_bash",+ "ripgrep",][project.optional-dependencies]diff --git a/src/agentscope/agent/_state.py b/src/agentscope/agent/_state.pyindex 7b4a15054..889a0fd15 100644--- a/src/agentscope/agent/_state.py+++ b/src/agentscope/agent/_state.py@@ -4,10 +4,112 @@ import uuidfrom pydantic import BaseModel, Field+import aiofiles.os+from ..message import TextBlock, DataBlock, Msgfrom ..tool import PermissionContext+class ReadCacheEntry(BaseModel):+ """The read file cache."""++ lines: list[str]+ updated_at: float+ bytes: float+ file_path: str+++class ToolContext(BaseModel):+ """The tool context, e.g. tool cache"""++ max_cache_files: int = Field(default=100, gt=1)+ """The maximum number of cached files."""+ max_cache_bytes: float = Field(default=25000, gt=10000)+ """The maximum size of the accumulated read file cache."""+ read_file_cache: list[ReadCacheEntry] = Field(default_factory=list)+ """The cache for Read/Write/Edit file tools."""++ activated_groups: list[str] = Field(default_factory=list)+ """The names of the activated tool groups, each group contains a set of+ tools."""++ async def get_cache(self, file_path: str) -> ReadCacheEntry | None:+ """Get cached file content if still valid.++ Args:+ file_path: The absolute path of the file.++ Returns:+ The cached entry if valid, otherwise None.+ """++ # Find the cache entry+ for entry in self.read_file_cache:+ if entry.file_path == file_path:+ # Check if cache is still valid+ try:+ updated_at = await aiofiles.os.path.getmtime(file_path)+ if updated_at == entry.updated_at:+ return entry+ else:+ # Cache is outdated, remove it+ self.read_file_cache.remove(entry)+ return None+ except Exception:+ # File might not exist anymore+ self.read_file_cache.remove(entry)+ return None+ return None++ async def cache_file(self, file_path: str, lines: list[str]) -> None:+ """Cache file content with LRU eviction.++ Args:+ file_path: The absolute path of the file.+ lines: The lines of the file content.+ """+ try:+ updated_at = await aiofiles.os.path.getmtime(file_path)+ except Exception:+ # Cannot get mtime, skip caching+ return++ # Calculate size in KB+ new_entry_bytes = (+ sum(len(line.encode("utf-8")) for line in lines) / 1024+ )++ # Remove existing cache for this file if present+ self.read_file_cache = [+ entry+ for entry in self.read_file_cache+ if entry.file_path != file_path+ ]++ # Evict the oldest entries if exceeding max_cache_files+ while len(self.read_file_cache) >= self.max_cache_files:+ self.read_file_cache.pop(0)++ # Evict the oldest entries if exceeding max_cache_bytes+ current_size = sum(entry.bytes for entry in self.read_file_cache)+ while (+ self.read_file_cache+ and current_size + new_entry_bytes > self.max_cache_bytes+ ):+ removed = self.read_file_cache.pop(0)+ current_size -= removed.bytes++ # Add new entry to the end (most recent)+ self.read_file_cache.append(+ ReadCacheEntry(+ lines=lines,+ updated_at=updated_at,+ bytes=new_entry_bytes,+ file_path=file_path,+ ),+ )++class AgentState(BaseModel):"""The agent state that should be saved and loaded from storage."""@@ -22,13 +124,16 @@ class AgentState(BaseModel):cur_iter: int = 0"""The current iteration of the agent's reasoning-acting loop."""- # The tool state, e.g. the active tool groups- activated_groups: list[str] = Field(default_factory=list)- """The names of the activated tool groups, each group contains a set of- tools."""-+ # =================================================================+ # The permission context+ # =================================================================permission_context: PermissionContext = Field(default_factory=PermissionContext,)"""The permission context that will be passed to the toolkit to determinethe tool permissions."""++ # =================================================================+ # The tool context+ # =================================================================+ tool_context: ToolContext = Field(default_factory=ToolContext)diff --git a/src/agentscope/tool/__init__.py b/src/agentscope/tool/__init__.pyindex a9d4c1906..840e7edb0 100644--- a/src/agentscope/tool/__init__.py+++ b/src/agentscope/tool/__init__.py@@ -15,7 +15,15 @@ from ._permission import (PermissionMode,PermissionBehavior,)-+from ._builtin import (+ ResetTools,+ Bash,+ Edit,+ Glob,+ Grep,+ Read,+ Write,+)__all__ = ["Toolkit",@@ -32,4 +40,11 @@ __all__ = ["MCPTool","ToolChoice","Function",+ "ResetTools",+ "Bash",+ "Edit",+ "Glob",+ "Grep",+ "Read",+ "Write",]diff --git a/src/agentscope/tool/_adapters.py b/src/agentscope/tool/_adapters.pyindex ea409dd7c..3ecda7842 100644--- a/src/agentscope/tool/_adapters.py+++ b/src/agentscope/tool/_adapters.py@@ -117,7 +117,7 @@ class MCPTool(ToolBase):| None = None,session: Any | None = None,timeout: float | None = None,- ):+ ) -> None:"""Initialize the MCPTool.Args:diff --git a/src/agentscope/tool/_base.py b/src/agentscope/tool/_base.pyindex 9c1be0822..312af22ab 100644--- a/src/agentscope/tool/_base.py+++ b/src/agentscope/tool/_base.py@@ -1,9 +1,18 @@# -*- coding: utf-8 -*-+# pylint: disable=unused-argument"""The tool protocol in agentscope."""+import osfrom abc import abstractmethod, ABC-from typing import AsyncGenerator, Any+from pathlib import Path+from typing import AsyncGenerator, Any, List-from ._permission import PermissionContext, PermissionDecision+from ._constants import DEFAULT_DANGEROUS_FILES, DEFAULT_DANGEROUS_DIRECTORIES+from ._permission import (+ PermissionContext,+ PermissionDecision,+ PermissionRule,+ PermissionBehavior,+)from ._response import ToolChunk@@ -27,6 +36,13 @@ class ToolBase(ABC):"""The name of the MCP server this tool belongs to, which is required ifthis tool is an MCP tool."""+ # Class attributes for dangerous path checking+ dangerous_files: list[str] = DEFAULT_DANGEROUS_FILES+ """List of dangerous files that should be protected from auto-editing."""+ dangerous_directories: list[str] = DEFAULT_DANGEROUS_DIRECTORIES+ """List of dangerous directories that should be protected from+ auto-editing."""+@abstractmethodasync def check_permissions(self,@@ -35,6 +51,127 @@ class ToolBase(ABC):) -> PermissionDecision:"""Check permissions for the tool usage."""+ def match_rule(+ self,+ rule_content: str | None,+ tool_input: dict[str, Any],+ ) -> bool:+ """Check if a permission rule matches the tool input.++ .. note:: This is an optional method. The default implementation+ mirrors Claude Code's behavior: a rule with no content (``None``)+ is a tool-name-level rule that matches every invocation; a rule+ with content requires the tool to override this method with its+ own matching logic, otherwise it returns ``False``.++ This means:+ - ``_FunctionTool`` and ``MCPTool`` (which do not override this)+ can still be controlled at the tool-name level via rules like+ ``{"tool_name": "my_tool", "rule_content": None}``.+ - Specific tools (Bash, Read, Write, Edit, Glob, Grep) override+ this method to support fine-grained pattern matching.++ Args:+ rule_content (`str | None`):+ The rule pattern to match. ``None`` means "match all+ invocations of this tool" (tool-name-level rule).+ tool_input (`dict[str, Any]`):+ The tool input data++ Returns:+ `bool`:+ True if the rule matches, False otherwise+ """+ # None rule_content = tool-name-level rule, matches everything+ return rule_content is None++ def generate_suggestions(+ self,+ tool_input: dict[str, Any],+ ) -> List[PermissionRule]:+ """Generate suggested permission rules for the tool input.++ .. note:: The default implementation mirrors Claude Code's MCP tool+ behavior: suggest a single tool-name-level rule (``rule_content=None``)+ that allows all invocations of this tool. Tools can override this to+ provide finer-grained suggestions.++ For example:+ - File tools (Read/Write/Edit): suggest a glob pattern covering the+ parent directory (e.g., "src/main.py" -> "src/**")+ - Bash: suggest command prefix patterns (e.g., "git commit -m 'xxx'"+ -> "git commit:*")+ - Grep/Glob: suggest patterns based on search paths++ Args:+ tool_input (`dict[str, Any]`):+ The tool input data++ Returns:+ `List[PermissionRule]`:+ List of suggested permission rules (usually 1, max 5 for+ compound operations)+ """+ return [+ PermissionRule(+ tool_name=self.name,+ rule_content=None,+ behavior=PermissionBehavior.ALLOW,+ source="suggested",+ ),+ ]++ def _is_dangerous_path(self, file_path: str) -> bool:+ """Check if a file path is dangerous (sensitive file or directory).++ A path is considered dangerous if:+ 1. The filename matches a dangerous file (e.g., .bashrc, .gitconfig)+ 2. Any path segment matches a dangerous directory (e.g., .git, .ssh)++ Case-insensitive matching is used to prevent bypasses on+ case-insensitive filesystems (macOS, Windows).++ Args:+ file_path (`str`):+ The file path to check++ Returns:+ `bool`:+ True if the path is dangerous and should require explicit+ permission++ Example:+ >>> self._is_dangerous_path("/home/user/.bashrc")+ True+ >>> self._is_dangerous_path("/home/user/.git/config")+ True+ >>> self._is_dangerous_path("/home/user/project/main.py")+ False+ """++ # Normalize path+ abs_path = os.path.abspath(os.path.expanduser(file_path))++ # Split path into segments+ path_parts = Path(abs_path).parts+ path_parts_lower = [p.lower() for p in path_parts]++ # Check if filename matches dangerous files (case-insensitive)+ filename = os.path.basename(abs_path)+ filename_lower = filename.lower()+ for dangerous_file in self.dangerous_files:+ if filename_lower == dangerous_file.lower():+ return True++ # Check if any path segment matches dangerous directories+ # (case-insensitive)+ for dangerous_dir in self.dangerous_directories:+ dangerous_dir_lower = dangerous_dir.lower()+ if dangerous_dir_lower in path_parts_lower:+ return True++ return False+@abstractmethodasync def __call__(self,diff --git a/src/agentscope/tool/_builtin/__init__.py b/src/agentscope/tool/_builtin/__init__.pyindex 34dedf851..66e2c22ab 100644--- a/src/agentscope/tool/_builtin/__init__.py+++ b/src/agentscope/tool/_builtin/__init__.py@@ -2,5 +2,20 @@"""The builtin tools in agentscope."""from ._meta import ResetTools+from ._bash import Bash+from ._edit import Edit+from ._glob import Glob+from ._grep import Grep+from ._read import Read+from ._write import Write-__all__ = ["ResetTools"]++__all__ = [+ "ResetTools",+ "Bash",+ "Edit",+ "Glob",+ "Grep",+ "Read",+ "Write",+]diff --git a/src/agentscope/tool/_builtin/_bash.py b/src/agentscope/tool/_builtin/_bash.pynew file mode 100644index 000000000..38c84c512--- /dev/null+++ b/src/agentscope/tool/_builtin/_bash.py@@ -0,0 +1,676 @@+# -*- coding: utf-8 -*-+"""The bash tool in agentscope."""+import os+from typing import AsyncGenerator, Any, List+import re+import asyncio++from ._bash_parser import BashCommandParser+from .._base import ToolBase+from .._permission import (+ PermissionContext,+ PermissionDecision,+ PermissionBehavior,+ PermissionMode,+ PermissionRule,+)+from ...message import TextBlock+from .._response import ToolChunk+++class Bash(ToolBase):+ """The bash tool."""++ name: str = "Bash"+ """The tool name presented to the agent."""++ description: str = """Executes a bash command and returns its output.++The working directory persists between commands, but shell state does+not. The shell environment is initialized from the user's profile+(bash or zsh).++IMPORTANT: Avoid using this tool to run `find`, `grep`, `cat`, `head`,+`tail`, `sed`, `awk`, or `echo` commands, unless explicitly instructed+or after you have verified that a dedicated tool cannot accomplish your+task. Instead, use the appropriate dedicated tool as this will provide+a much better experience for the user:++ - File search: Use Glob (NOT find or ls)+ - Content search: Use Grep (NOT grep or rg)+ - Read files: Use Read (NOT cat/head/tail)+ - Edit files: Use Edit (NOT sed/awk)+ - Write files: Use Write (NOT echo >/cat <<EOF)+ - Communication: Output text directly (NOT echo/printf)++While the Bash tool can do similar things, it's better to use the+built-in tools as they provide a better user experience and make it+easier to review tool calls and give permission.++# Instructions+ - If your command will create new directories or files, first use+ this tool to run `ls` to verify the parent directory exists and is+ the correct location.+ - Always quote file paths that contain spaces with double quotes in+ your command (e.g., cd "path with spaces/file.txt")+ - Try to maintain your current working directory throughout the+ session by using absolute paths and avoiding usage of `cd`. You may+ use `cd` if the User explicitly requests it.+ - You may specify an optional timeout in milliseconds (up to 600000ms+ / 10 minutes). By default, your command will timeout after 120000ms+ (2 minutes).+ - Write a clear, concise description of what your command does. For+ simple commands, keep it brief (5-10 words). For complex commands+ (piped commands, obscure flags, or anything hard to understand at a+ glance), include enough context so that the user can understand what+ your command will do.+ - When issuing multiple commands:+ - If the commands are independent and can run in parallel, make+ multiple Bash tool calls in a single message. Example: if you need+ to run "git status" and "git diff", send a single message with two+ Bash tool calls in parallel.+ - If the commands depend on each other and must run sequentially,+ use a single Bash call with '&&' to chain them together.+ - Use ';' only when you need to run commands sequentially but don't+ care if earlier commands fail.+ - DO NOT use newlines to separate commands (newlines are ok in+ quoted strings).+ - For git commands:+ - Prefer to create a new commit rather than amending an existing+ commit.+ - Before running destructive operations (e.g., git reset --hard, git+ push --force, git checkout --), consider whether there is a safer+ alternative that achieves the same goal. Only use destructive+ operations when they are truly the best approach.+ - Never skip hooks (--no-verify) or bypass signing (--no-gpg-sign,+ -c commit.gpgsign=false) unless the user has explicitly asked for+ it. If a hook fails, investigate and fix the underlying issue.+ - Avoid unnecessary `sleep` commands:+ - Do not sleep between commands that can run immediately — just run+ them.+ - Do not retry failing commands in a sleep loop — diagnose the root+ cause or consider an alternative approach.+ - If you must sleep, keep the duration short (1-5 seconds) to avoid+ blocking the user."""+ """The description presented to the agent."""++ input_schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "command": {+ "type": "string",+ "description": "The bash command to execute.",+ },+ "description": {+ "type": "string",+ "description": (+ "Clear, concise description of what this command "+ "does. For simple commands, keep it brief (5-10 "+ "words). For complex commands, include enough "+ "context."+ ),+ },+ "timeout": {+ "type": "integer",+ "description": (+ "Optional timeout in milliseconds "+ "(default: 120000, max: 600000)"+ ),+ "default": 120000,+ "maximum": 600000,+ "minimum": 0,+ },+ },+ "required": ["command"],+ }++ is_mcp: bool = False+ is_read_only: bool = False+ is_concurrency_safe: bool = False++ def __init__(+ self,+ additional_dangerous_files: list[str] | None = None,+ additional_dangerous_directories: list[str] | None = None,+ ) -> None:+ """Initialize the bash tool.++ Args:+ additional_dangerous_files (`list[str] | None`, optional):+ Additional dangerous files to check (added to built-in+ defaults). Use this to add project-specific sensitive files+ like '.env' or '.secrets'.+ additional_dangerous_directories (`list[str] | None`, optional):+ Additional dangerous directories to check (added to built-in+ defaults). Use this to add project-specific sensitive+ directories.+ """++ self._bash_parser = BashCommandParser()++ # Merge class-level dangerous paths with additional ones+ self.dangerous_files = self.__class__.dangerous_files.copy()+ if additional_dangerous_files:+ self.dangerous_files.extend(additional_dangerous_files)++ self.dangerous_directories = (+ self.__class__.dangerous_directories.copy()+ )+ if additional_dangerous_directories:+ self.dangerous_directories.extend(additional_dangerous_directories)++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Check permissions for bash command execution.++ This method implements Bash-specific permission checks:+ 0. Injection risk check (detect dynamic shell structures)+ 1. Read-only command check (auto-allow safe commands)+ 2. Dangerous command pattern check (safety check, bypass-immune)+ 3. Sed constraint check (safety check, bypass-immune)+ 4. Dangerous path check for config files (safety check, bypass-immune)+ 5. Dangerous removal path check for system dirs (bypass-immune)+ 6. ACCEPT_EDITS mode filesystem command check++ Args:+ tool_input (`dict[str, Any]`):+ The tool input containing "command" key+ context (`PermissionContext`):+ The permission context with mode and rules++ Returns:+ `PermissionDecision`:+ ALLOW for safe operations, ASK for dangerous operations,+ PASSTHROUGH to let Engine continue with rule matching+ """++ command = tool_input.get("command", "")+ if not command:+ return PermissionDecision(+ behavior=PermissionBehavior.PASSTHROUGH,+ message="Empty command",+ )++ # 0. Injection check: detect dynamic shell structures that cannot be+ # statically analyzed (command substitution, process substitution,+ # control flow, etc.). Must run before read-only check so that+ # `$(rm -rf /)` inside an otherwise-safe command is caught.+ injection_reason = self._bash_parser.check_injection_risk(command)+ if injection_reason:+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message=f"Permission required: {injection_reason}",+ decision_reason="Safety check: command contains dynamic "+ "expansion that cannot be statically analyzed",+ )++ # 1. Check if command is read-only (auto-allow)+ if self._bash_parser.is_read_only_command(command):+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message="Permission granted for read-only command",+ decision_reason="Read-only command is allowed",+ )++ # 2. Check for dangerous commands (safety check, bypass-immune)+ dangerous_pattern = self._bash_parser.check_dangerous_command(command)+ if dangerous_pattern:+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message=f"Permission required: Command contains dangerous "+ f"pattern: {dangerous_pattern}",+ decision_reason="Safety check: dangerous command pattern "+ "detected",+ )++ # 3. Check for sed constraints (safety check, bypass-immune)+ sed_error = self._bash_parser.check_sed_constraints(+ command,+ self.dangerous_files,+ )+ if sed_error:+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message=f"Permission required: {sed_error}",+ decision_reason="Safety check: sed in-place modification "+ "of dangerous file",+ )++ # 4. Check for dangerous paths in sensitive config files/dirs+ # (safety check, bypass-immune)+ dangerous_paths = self._extract_dangerous_paths_from_bash(command)+ if dangerous_paths:+ paths_str = ", ".join(dangerous_paths)+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message=f"Permission required: Bash command operates on "+ f"sensitive paths: {paths_str}",+ decision_reason="Safety check: dangerous file or "+ "directory in bash command",+ )++ # 5. Check for dangerous removal paths: rm/rmdir targeting system+ # critical directories like /, /usr, /etc, ~ (bypass-immune).+ # Checked separately from step 4 because these paths are not in the+ # dangerous_files/directories lists — they are system-level paths+ # that should never be removed regardless of user configuration.+ removal_path = self._check_dangerous_removal_path(command)+ if removal_path:+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message=f"Dangerous removal operation detected: "+ f"'{removal_path}'\n\nThis command would remove a critical "+ f"system directory. This requires explicit approval and "+ f"cannot be auto-allowed by permission rules.",+ decision_reason="Safety check: dangerous removal of "+ "critical system path",+ )++ # 6. Check ACCEPT_EDITS mode for filesystem commands+ if context.mode == PermissionMode.ACCEPT_EDITS:+ filesystem_commands = [+ "mkdir",+ "touch",+ "rm",+ "rmdir",+ "mv",+ "cp",+ "sed",+ ]+ base_command = (+ command.strip().split()[0] if command.strip() else ""+ )++ if base_command in filesystem_commands:+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"Permission granted for '{base_command}' "+ f"command (accept edits mode - filesystem command)",+ decision_reason=f"Filesystem command '{base_command}' "+ f"is auto-allowed in accept edits mode",+ )++ # 6. Passthrough to let Engine continue with rule matching+ return PermissionDecision(+ behavior=PermissionBehavior.PASSTHROUGH,+ message=f"Execute bash command: {command}",+ )++ def match_rule(+ self,+ rule_content: str | None,+ tool_input: dict[str, Any],+ ) -> bool:+ r"""Match Bash command using regex-based wildcard matching.++ Implements wildcard matching with escape sequences:+ - Supports \* for literal asterisk and \\ for literal backslash+ - Special optimization: "git *" matches both "git" and "git add"+ - Prefix pattern (e.g., "git:*"): matches commands starting with "git "+ - Wildcard pattern: converts to regex with proper escape handling+ - Substring pattern: exact substring matching+ - If rule_content is None, matches all invocations+ (tool-name-level rule)++ Args:+ rule_content: The command pattern to match, or None to match all+ tool_input: Must contain a "command" key with the command string++ Returns:+ True if pattern matches the command+ """+ # None = tool-name-level rule, matches everything+ if rule_content is None:+ return True++ command = tool_input.get("command", "")++ # Check if pattern is a prefix pattern (ends with :*)+ if rule_content.endswith(":*"):+ prefix = rule_content[:-2].strip()+ return command.startswith(prefix + " ") or command == prefix++ # Check if pattern has unescaped wildcards+ def has_wildcards(pattern: str) -> bool:+ """Check if pattern contains unescaped * wildcards."""+ i = 0+ while i < len(pattern):+ if pattern[i] == "\\":+ i += 2 # Skip escaped character+ elif pattern[i] == "*":+ return True+ else:+ i += 1+ return False++ if not has_wildcards(rule_content):+ # No wildcards, but may have escape sequences+ # Convert escape sequences for matching+ pattern = rule_content+ pattern = pattern.replace("\\\\", "\x00BACKSLASH\x00")+ pattern = pattern.replace("\\*", "*")+ pattern = pattern.replace("\x00BACKSLASH\x00", "\\")+ # Use substring matching with converted pattern+ return pattern in command++ # Convert wildcard pattern to regex with escape handling+ # Use placeholders for escaped sequences+ ESCAPED_STAR = "\x00ESCAPED_STAR\x00"+ ESCAPED_BACKSLASH = "\x00ESCAPED_BACKSLASH\x00"++ pattern = rule_content+ # Replace \\ with placeholder+ pattern = pattern.replace("\\\\", ESCAPED_BACKSLASH)+ # Replace \* with placeholder+ pattern = pattern.replace("\\*", ESCAPED_STAR)++ # Manually escape regex special characters (except *)+ # Don't use re.escape() as it escapes spaces too+ special_chars = r".^$+?{}[]|()"+ for char in special_chars:+ pattern = pattern.replace(char, "\\" + char)++ # Convert * to regex .* (match any characters)+ pattern = pattern.replace("*", ".*")++ # Restore escaped sequences+ pattern = pattern.replace(ESCAPED_STAR, r"\*")+ pattern = pattern.replace(ESCAPED_BACKSLASH, r"\\")++ # Special optimization: "git *" should match both "git" and "git add"+ # Pattern: if ends with .*, make it optional+ if pattern.endswith(".*"):+ base_pattern = pattern[:-2] # Remove .*+ # Try exact match first (handles trailing space)+ base_pattern = base_pattern.rstrip()+ if re.fullmatch(base_pattern, command):+ return True++ # Full regex match+ try:+ return bool(re.fullmatch(pattern, command))+ except re.error:+ # Invalid regex, fall back to substring matching+ return rule_content.replace("*", "") in command++ def generate_suggestions(+ self,+ tool_input: dict[str, Any],+ ) -> List["PermissionRule"]:+ """Generate suggested permission rules for Bash commands.++ Generates prefix rules based on command + subcommand (two words).+ For example, "git commit -m 'xxx'" generates "git commit:*".++ Args:+ tool_input (`dict[str, Any]`):+ The tool input data containing "command" key++ Returns:+ `List[PermissionRule]`:+ List of suggested permission rules based on command prefixes+ """++ command = tool_input.get("command", "")+ if not command:+ return []++ # Use bash parser to extract command prefixes+ prefixes = self._bash_parser.extract_command_prefixes(+ command,+ max_prefixes=5,+ )++ if not prefixes:+ # Cannot extract any prefix, return empty+ return []++ # Generate rules for each prefix+ rules = []+ for prefix in prefixes:+ rules.append(+ PermissionRule(+ tool_name="Bash",+ rule_content=f"{prefix}:*",+ behavior=PermissionBehavior.ALLOW,+ source="suggested",+ ),+ )++ return rules++ def _extract_dangerous_paths_from_bash(+ self,+ command: str,+ ) -> list[str]:+ """Extract dangerous paths from a bash command using tree-sitter.++ Checks for dangerous paths in:+ - File-manipulating commands (rm, mv, cp, chmod, chown, sed, touch)+ - Output redirections (>, >>)++ Args:+ command (`str`):+ The bash command string++ Returns:+ `list[str]`:+ List of dangerous paths found in the command+ """+ dangerous_paths = []++ # Use tree-sitter to extract file paths+ file_paths = self._bash_parser.extract_file_paths(command)++ for _cmd_name, path in file_paths:+ if self._is_dangerous_path(path):+ dangerous_paths.append(path)++ return dangerous_paths++ def _check_dangerous_removal_path(self, command: str) -> str | None:+ """Check if an rm/rmdir command targets a critical system path.++ Detects commands like `rm -rf /`, `rm -rf /usr`, `rmdir ~` that+ would destroy critical system directories. Unlike _is_dangerous_path+ (which checks against a configurable list of sensitive config files),+ this checks against a fixed set of system-level paths that must+ never be removed regardless of user configuration.++ Dangerous paths are:+ - Root directory (/)+ - Home directory (~)+ - Wildcard alone (*) or as dir/* (removes everything)+ - Direct children of root (/usr, /etc, /tmp, /var, etc.)++ Args:+ command (`str`):+ The bash command string++ Returns:+ `str | None`:+ The dangerous path if found, None otherwise+ """+ tokens = command.strip().split()+ if not tokens:+ return None++ # Find rm or rmdir subcommands (handle compound commands)+ try:+ tree = self._bash_parser.parser.parse(bytes(command, "utf8"))+ subcommands = self._bash_parser.split_compound_command(+ tree.root_node,+ command,+ )+ except Exception:+ subcommands = [command]++ # Check each subcommand for rm/rmdir+ for subcmd in subcommands:+ subcmd_tokens = subcmd.strip().split()+ if not subcmd_tokens:+ continue+ base = subcmd_tokens[0]+ if base not in ("rm", "rmdir"):+ continue++ # Collect non-flag arguments as potential paths+ i = 1+ while i < len(subcmd_tokens):+ tok = subcmd_tokens[i]+ # Skip flags+ if tok.startswith("-"):+ i += 1+ continue+ path = tok.strip("'\"")+ if self._is_dangerous_removal_path(path):+ return path+ i += 1++ return None++ def _is_dangerous_removal_path(self, path: str) -> bool:+ """Check if a path is a critical system directory that must not be+ removed.++ Args:+ path (`str`):+ The path to check (may be relative, absolute, or contain ~)++ Returns:+ `bool`:+ True if removing this path would be catastrophic+ """++ # Bare wildcard+ if path in ("*", "./*", "/"):+ return True+ # Ends with /* — removes everything in a directory+ if path.endswith("/*") or path.endswith("\\*"):+ return True++ # Expand tilde and resolve to absolute path+ expanded = os.path.expanduser(path)+ # Don't resolve symlinks — /tmp is a symlink on macOS but is+ # still a root-child and should be flagged+ abs_path = os.path.normpath(os.path.abspath(expanded))++ # Home directory+ home = os.path.expanduser("~")+ if abs_path == home:+ return True++ # Root itself+ if abs_path == "/":+ return True++ # Direct children of root: /usr, /etc, /tmp, /var, /bin, etc.+ parent = os.path.dirname(abs_path)+ if parent == "/":+ return True++ return False++ async def __call__( # type: ignore[override]+ self,+ command: str,+ description: str = "",+ timeout: int = 120000,+ ) -> AsyncGenerator[ToolChunk, None]:+ """Execute the bash and return the output.++ Args:+ command: The bash command to execute.+ description: Optional description of what the command does.+ timeout: Timeout in milliseconds (default: 120000, max: 600000).++ Yields:+ ToolChunk: The tool execution result with stdout/stderr content.+ """++ # Clamp timeout to max 600000ms and convert to seconds+ timeout_ms = min(timeout, 600000)+ timeout_sec = timeout_ms / 1000.0++ try:+ # Create subprocess+ process = await asyncio.create_subprocess_shell(+ command,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )++ # Wait for completion with timeout+ stdout_bytes, stderr_bytes = await asyncio.wait_for(+ process.communicate(),+ timeout=timeout_sec,+ )++ # Decode and normalize line endings+ stdout = stdout_bytes.decode("utf-8", errors="replace").replace(+ "\r\n",+ "\n",+ )+ stderr = stderr_bytes.decode("utf-8", errors="replace").replace(+ "\r\n",+ "\n",+ )++ # Combine output+ output = stdout+ if stderr:+ if output:+ output += "\n"+ output += stderr++ # Truncate if exceeds 30000 characters+ if len(output) > 30000:+ output = output[:30000] + "\n... (output truncated)"++ # Check exit code+ if process.returncode != 0:+ # Command failed+ result = f"Command failed: {command}\n"+ if stdout:+ result += f"\nStdout:\n{stdout}"+ if stderr:+ result += f"\nStderr:\n{stderr}"++ # Truncate error message if needed+ if len(result) > 30000:+ result = result[:30000] + "\n... (output truncated)"++ yield ToolChunk(+ content=[TextBlock(text=result)],+ state="error",+ is_last=True,+ )+ else:+ # Command succeeded - note: ToolChunk uses "running" state+ # which will be converted to "finished" in ToolResponse+ yield ToolChunk(+ content=[TextBlock(text=output)],+ state="running",+ is_last=True,+ )++ except asyncio.TimeoutError:+ # Timeout occurred+ error_msg = f"Command timed out after {timeout_ms}ms: {command}"+ yield ToolChunk(+ content=[TextBlock(text=error_msg)],+ state="error",+ is_last=True,+ )++ except Exception as e:+ # Other errors+ error_msg = f"Command failed: {command}\nError: {str(e)}"+ yield ToolChunk(+ content=[TextBlock(text=error_msg)],+ state="error",+ is_last=True,+ )diff --git a/src/agentscope/tool/_permission/_bash_parser.py b/src/agentscope/tool/_builtin/_bash_parser.pysimilarity index 62%rename from src/agentscope/tool/_permission/_bash_parser.pyrename to src/agentscope/tool/_builtin/_bash_parser.pyindex f495c0f3c..013297e83 100644--- a/src/agentscope/tool/_permission/_bash_parser.py+++ b/src/agentscope/tool/_builtin/_bash_parser.py@@ -12,9 +12,14 @@ information for permission rule generation, including:from typing import List, Optional, Set, Tuple+import re+import shlex+import tree_sitter_bash as tsbashfrom tree_sitter import Language, Parser, Node+from .._constants import DANGEROUS_NODE_TYPES, DANGEROUS_COMMANDS+# Commands that are considered safe and don't require permission rulesSAFE_COMMANDS: Set[str] = {@@ -165,7 +170,7 @@ class BashCommandParser:try:tree = self.parser.parse(bytes(cmd, "utf8"))root = tree.root_node- subcommands = self._split_compound_command(root, cmd)+ subcommands = self.split_compound_command(root, cmd)# All subcommands must be read-onlyfor subcmd in subcommands:@@ -450,7 +455,7 @@ class BashCommandParser:root = tree.root_node# Split compound commands- subcommands = self._split_compound_command(root, command)+ subcommands = self.split_compound_command(root, command)# Extract prefixes from each subcommandprefixes = []@@ -467,7 +472,7 @@ class BashCommandParser:return prefixes- def _split_compound_command(self, root: Node, command: str) -> List[str]:+ def split_compound_command(self, root: Node, command: str) -> List[str]:"""Split compound commands using tree-sitter for precise parsing.Recognizes: &&, ||, ;, |@@ -587,3 +592,281 @@ class BashCommandParser:return resultreturn None++ def check_dangerous_command(self, command: str) -> Optional[str]:+ """Check if command contains dangerous patterns.++ Uses word-boundary aware matching to avoid false positives like+ 'git add' matching 'dd' pattern.++ Args:+ command (`str`):+ The bash command to check++ Returns:+ `Optional[str]`:+ The matched dangerous pattern if found, None otherwise+ """++ # Normalize command for matching+ normalized = " ".join(command.split())++ # Check each dangerous pattern+ for pattern in DANGEROUS_COMMANDS:+ # For single-word patterns like "dd", use word boundary matching+ # to avoid false positives (e.g., "git add" shouldn't match "dd")+ if " " not in pattern and len(pattern) <= 4:+ # Single word pattern - use word boundaries+ regex = r"\b" + re.escape(pattern) + r"\b"+ if re.search(regex, normalized):+ return pattern+ else:+ # Multi-word pattern or longer pattern - use substring match+ if pattern in normalized:+ return pattern++ return None++ # pylint: disable=too-many-return-statements, too-many-branches+ def check_sed_constraints(+ self,+ command: str,+ dangerous_files: List[str],+ ) -> str | None:+ """Check if sed command violates safety constraints.++ Implements allowlist/denylist system:+ - Allowlist: Line printing (sed -n 'Np') and substitution (sed 's///')+ - Denylist: Dangerous operations (w/W/e/E), file writes, command+ execution++ Args:+ command: The bash command to check+ dangerous_files: List of dangerous file patterns++ Returns:+ Error message if dangerous sed operation found, None otherwise+ """++ if "sed" not in command:+ return None++ # Parse command using shlex+ try:+ tokens = shlex.split(command)+ except ValueError:+ return "sed command has invalid shell syntax"++ # Find sed command position+ sed_idx = None+ for i, token in enumerate(tokens):+ if token == "sed" or token.endswith("/sed"):+ sed_idx = i+ break++ if sed_idx is None:+ return None++ # Extract flags and expressions+ args = tokens[sed_idx + 1 :]+ flags = []+ expressions = []+ file_args = []+ i = 0+ found_first_expr = False++ while i < len(args):+ arg = args[i]++ # Handle flags+ if arg.startswith("-") and not arg.startswith("--"):+ # Combined flags like -nE+ flag_chars = arg[1:]+ for char in flag_chars:+ flags.append(char)+ # -i flag may have optional backup extension argument+ # But only skip if next arg doesn't look like an expression+ if "i" in flag_chars and i + 1 < len(args):+ next_arg = args[i + 1]+ # Skip backup extension only if it's not an expression+ # or file+ if (+ not next_arg.startswith("-")+ and not next_arg.startswith("s")+ and "." not in next_arg+ ):+ i += 1 # Skip backup extension+ elif arg == "--in-place":+ flags.append("i")+ if i + 1 < len(args):+ next_arg = args[i + 1]+ if (+ not next_arg.startswith("-")+ and not next_arg.startswith("s")+ and "." not in next_arg+ ):+ i += 1+ elif arg in ["-e", "--expression"]:+ if i + 1 < len(args):+ expressions.append(args[i + 1])+ i += 1+ elif not arg.startswith("-"):+ # First non-flag, non-option arg is expression (if no -e used)+ if not found_first_expr:+ expressions.append(arg)+ found_first_expr = True+ else:+ file_args.append(arg)++ i += 1++ # If no expressions found, command is invalid+ if not expressions:+ return "sed command missing expression"++ # Validate flags - only allow specific flags+ allowed_flags = {"n", "E", "e", "i"}+ for flag in flags:+ if flag not in allowed_flags:+ return f"sed flag -{flag} not allowed"++ # Check allowlist patterns+ has_n_flag = "n" in flags+ has_i_flag = "i" in flags++ for expr in expressions:+ # Denylist checks first - dangerous operations+ # Check for write operations (w, W) - must be at end or followed+ # by space/filename+ if (+ re.search(r"/[wW]\s+\S+", expr)+ or expr.endswith("/w")+ or expr.endswith("/W")+ ):+ return "sed write operation (w/W) not allowed"++ # Check for execute operations (e, E) - must be at end or+ # followed by space+ if (+ re.search(r"/[eE](?:\s|$)", expr)+ or expr.endswith("/e")+ or expr.endswith("/E")+ ):+ return "sed execute operation (e/E) not allowed"++ # Check for dangerous patterns+ if "{" in expr or "}" in expr:+ return "sed curly braces not allowed"+ if expr.startswith("!"):+ return "sed negation (!) not allowed"+ if "#" in expr and not expr.startswith("s#"):+ return "sed comments not allowed"++ # Pattern 1: Line printing with -n flag (sed -n 'Np' or 'N,Mp')+ if has_n_flag:+ # Match: number followed by 'p', or range 'N,Mp'+ if re.match(+ r"^\d+p$",+ expr,+ ) or re.match(+ r"^\d+,\d+p$",+ expr,+ ):+ continue++ # Pattern 2: Substitution command+ # (sed 's/pattern/replacement/flags')+ if (+ expr.startswith("s/")+ or expr.startswith("s|")+ or expr.startswith("s#")+ ):+ delimiter = expr[1]+ parts = expr[2:].split(delimiter)+ if len(parts) >= 2:+ # Valid substitution+ # Check substitution flags (g, p, number, etc.)+ if len(parts) > 2:+ sub_flags = parts[2]+ # Allow common substitution flags+ if all(c in "gp0123456789" for c in sub_flags):+ continue+ else:+ continue++ # If we reach here, expression doesn't match allowlist+ return f"sed expression '{expr}' not in allowlist"++ # Check -i flag with dangerous files+ if has_i_flag and file_args:+ for file_path in file_args:+ for dangerous_file in dangerous_files:+ if dangerous_file in file_path or file_path.endswith(+ dangerous_file,+ ):+ return f"sed -i modifying dangerous file: {file_path}"++ return None++ def check_injection_risk(self, command: str) -> Optional[str]:+ """Check if command contains structures that cannot be statically+ analyzed.++ This detects command substitution, process substitution, complex+ expansions, control flow, and other dynamic shell features that+ make it impossible to determine the command's behavior without+ execution.++ Args:+ command (`str`):+ The bash command to check++ Returns:+ `Optional[str]`:+ Reason string if command is too complex, None if it can be+ statically analyzed++ Examples:+ >>> parser.check_injection_risk("ls -la")+ None+ >>> parser.check_injection_risk("rm $(find . -name '*.tmp')")+ "Command contains command_substitution which cannot be statically+ analyzed"+ >>> parser.check_injection_risk("for f in *.txt; do cat $f; done")+ "Command contains for_statement which cannot be statically+ analyzed"+ """++ try:+ tree = self.parser.parse(bytes(command, "utf8"))+ return self._walk_for_dangerous_nodes(tree.root_node)+ except Exception:+ # If parsing fails, be conservative and require review+ return "Command parsing failed, cannot verify safety"++ def _walk_for_dangerous_nodes(self, node: Node) -> Optional[str]:+ """Recursively walk AST to find dangerous node types.++ Args:+ node (`Node`):+ The AST node to check++ Returns:+ `Optional[str]`:+ Reason string if dangerous node found, None otherwise+ """++ # Check if this node is a dangerous type+ if node.type in DANGEROUS_NODE_TYPES:+ return (+ f"Command contains {node.type} which cannot be "+ f"statically analyzed"+ )++ # Recursively check children+ for child in node.children:+ result = self._walk_for_dangerous_nodes(child)+ if result:+ return result++ return Nonediff --git a/src/agentscope/tool/_builtin/_edit.py b/src/agentscope/tool/_builtin/_edit.pynew file mode 100644index 000000000..0ff2ce30d--- /dev/null+++ b/src/agentscope/tool/_builtin/_edit.py@@ -0,0 +1,430 @@+# -*- coding: utf-8 -*-+"""The edit tool in agentscope."""+import fnmatch+import os+from typing import Any, List, TYPE_CHECKING++import aiofiles++from .._base import ToolBase+from .._permission import (+ PermissionContext,+ PermissionDecision,+ PermissionBehavior,+ PermissionMode,+ PermissionRule,+)+from .._response import ToolChunk+from ...message import TextBlock++if TYPE_CHECKING:+ from ...agent import AgentState+else:+ AgentState = Any+++class Edit(ToolBase):+ """The edit tool for performing exact string replacements in files."""++ name: str = "Edit"+ """The tool name presented to the agent."""++ description: str = """Performs exact string replacements in files.++Usage:+- You must use your `Read` tool at least once in the conversation+ before editing. This tool will error if you attempt an edit without+ reading the file.+- When editing text from Read tool output, ensure you preserve the+ exact indentation (tabs/spaces) as it appears AFTER the line number+ prefix. The line number prefix format is: line number + tab.+ Everything after that is the actual file content to match. Never+ include any part of the line number prefix in the old_string or+ new_string.+- ALWAYS prefer editing existing files in the codebase. NEVER write+ new files unless explicitly required.+- Only use emojis if the user explicitly requests it. Avoid adding+ emojis to files unless asked.+- The edit will FAIL if `old_string` is not unique in the file.""" # noqa: E501+ """The description presented to the agent."""++ input_schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string",+ "description": "The absolute path to the file to edit.",+ },+ "old_string": {+ "type": "string",+ "description": (+ "The exact string to replace. Must match exactly "+ "including whitespace and indentation."+ ),+ },+ "new_string": {+ "type": "string",+ "description": "The string to replace old_string with.",+ },+ "replace_all": {+ "type": "boolean",+ "description": (+ "If true, replace all occurrences. If false "+ "(default), only replace if there is exactly one "+ "occurrence."+ ),+ "default": False,+ },+ },+ "required": ["file_path", "old_string", "new_string"],+ }++ is_mcp: bool = False+ is_read_only: bool = False+ is_concurrency_safe: bool = False++ def __init__(+ self,+ additional_dangerous_files: list[str] | None = None,+ additional_dangerous_directories: list[str] | None = None,+ ) -> None:+ """Initialize the edit tool.++ Args:+ additional_dangerous_files (`list[str] | None`, optional):+ Additional dangerous files to check (added to built-in+ defaults). Use this to add project-specific sensitive files+ like '.env' or '.secrets'.+ additional_dangerous_directories (`list[str] | None`, optional):+ Additional dangerous directories to check (added to built-in+ defaults). Use this to add project-specific sensitive+ directories.+ """+ # Merge class-level dangerous paths with additional ones+ self.dangerous_files = self.__class__.dangerous_files.copy()+ if additional_dangerous_files:+ self.dangerous_files.extend(additional_dangerous_files)++ self.dangerous_directories = (+ self.__class__.dangerous_directories.copy()+ )+ if additional_dangerous_directories:+ self.dangerous_directories.extend(additional_dangerous_directories)++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Check permissions for file editing.++ This method implements Edit-specific permission checks:+ 1. Dangerous path check (safety check, bypass-immune)+ 2. ACCEPT_EDITS mode check for files in working directories++ Args:+ tool_input (`dict[str, Any]`):+ The tool input containing "file_path" key+ context (`PermissionContext`):+ The permission context with mode and rules++ Returns:+ `PermissionDecision`:+ ASK for dangerous paths, ALLOW for safe operations in+ ACCEPT_EDITS mode, PASSTHROUGH otherwise+ """++ file_path = tool_input.get("file_path")+ if not file_path:+ return PermissionDecision(+ behavior=PermissionBehavior.PASSTHROUGH,+ message="No file path provided",+ )++ # 1. Check for dangerous paths (safety check, bypass-immune)+ if self._is_dangerous_path(file_path):+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message=f"Permission required: Edit operation on "+ f"sensitive file {file_path}",+ decision_reason="Safety check: dangerous file or directory",+ )++ # 2. Check ACCEPT_EDITS mode for files in working directories+ if context.mode == PermissionMode.ACCEPT_EDITS:+ if self._path_in_allowed_working_path(file_path, context):+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"Permission granted for editing {file_path} "+ f"(accept edits mode - in working directory)",+ decision_reason="File is in working directory and not "+ "a dangerous path",+ )++ # 3. Return PASSTHROUGH to let PermissionEngine check allow rules+ # This ensures allow rules can grant Edit permissions+ return PermissionDecision(+ behavior=PermissionBehavior.PASSTHROUGH,+ message="",+ )++ def _path_in_allowed_working_path(+ self,+ file_path: str,+ context: PermissionContext,+ ) -> bool:+ """Check if a file path is within any allowed working directory.++ Args:+ file_path (`str`):+ The file path to check+ context (`PermissionContext`):+ The permission context containing working directories++ Returns:+ `bool`:+ True if the path is within any allowed working directory+ """++ # Get all working directories (current directory + additional)+ current_dir = os.getcwd()+ additional_dirs = list(context.working_directories.keys())+ all_working_dirs = [current_dir] + additional_dirs++ # Normalize paths+ abs_file_path = os.path.abspath(os.path.expanduser(file_path))++ # Check if file path is in any working directory+ for working_dir in all_working_dirs:+ abs_working_dir = os.path.abspath(os.path.expanduser(working_dir))+ try:+ # Check if file_path is inside working_dir+ os.path.relpath(abs_file_path, abs_working_dir)+ if (+ abs_file_path.startswith(abs_working_dir + os.sep)+ or abs_file_path == abs_working_dir+ ):+ return True+ except ValueError:+ # On Windows, relpath raises ValueError if paths are on+ # different drives+ continue++ return False++ def match_rule(+ self,+ rule_content: str | None,+ tool_input: dict[str, Any],+ ) -> bool:+ """Check if a permission rule matches the file path.++ Matches rule_content as a glob pattern against the "file_path"+ parameter using fnmatch. If rule_content is None, matches all+ invocations (tool-name-level rule).++ Args:+ rule_content (`str | None`):+ Glob pattern to match against the file path (e.g., "src/**"),+ or None to match all invocations+ tool_input (`dict[str, Any]`):+ The tool input data containing "file_path" key++ Returns:+ `bool`:+ True if the glob pattern matches the file path, False otherwise+ """+ if rule_content is None:+ return True++ file_path = tool_input.get("file_path", "")+ if not file_path:+ return False+ return fnmatch.fnmatch(file_path, rule_content)++ def generate_suggestions(+ self,+ tool_input: dict[str, Any],+ ) -> List[PermissionRule]:+ """Generate suggested permission rules for the file path.++ Suggests a glob pattern covering the parent directory of the file,+ allowing the user to grant permission for the entire directory at once.++ Args:+ tool_input (`dict[str, Any]`):+ The tool input data containing "file_path" key++ Returns:+ `List[PermissionRule]`:+ A single suggested rule covering the parent directory+ (e.g., file "/src/main.py" -> rule "src/**")+ """+ file_path = tool_input.get("file_path", "")+ if not file_path:+ return []++ parent = os.path.dirname(file_path)+ pattern = (parent.rstrip("/") + "/**") if parent else "**"++ return [+ PermissionRule(+ tool_name=self.name,+ rule_content=pattern,+ behavior=PermissionBehavior.ALLOW,+ source="suggested",+ ),+ ]++ async def __call__( # type: ignore[override]+ self,+ file_path: str,+ old_string: str,+ new_string: str,+ replace_all: bool = False,+ _agent_state: AgentState | None = None,+ ) -> ToolChunk:+ """Execute the edit and return the result."""+ # Validate file_path is absolute+ if not os.path.isabs(file_path):+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"Error: file_path must be an absolute "+ f"path, got: {file_path}"+ ),+ ),+ ],+ state="error",+ is_last=True,+ )++ # Check file exists+ if not os.path.exists(file_path):+ return ToolChunk(+ content=[+ TextBlock(text=f"Error: File not found: {file_path}"),+ ],+ state="error",+ is_last=True,+ )++ # Check old_string != new_string+ if old_string == new_string:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "Error: old_string and new_string are "+ "identical. No changes to make."+ ),+ ),+ ],+ state="error",+ is_last=True,+ )++ content = None+ if _agent_state is not None:+ cache = await _agent_state.tool_context.get_cache(file_path)+ if cache is None:+ # Haven't read this file before+ return ToolChunk(+ content=[+ TextBlock(+ text="Error: To edit a file, you must first read "+ "it using the Read tool.",+ ),+ ],+ state="error",+ is_last=True,+ )+ content = "".join(cache.lines)+ else:+ # No state provided, read from disk+ try:+ async with aiofiles.open(+ file_path,+ "r",+ encoding="utf-8",+ ) as f:+ content = await f.read()+ except Exception as e:+ return ToolChunk(+ content=[TextBlock(text=f"Error reading file: {str(e)}")],+ state="error",+ is_last=True,+ )++ # Count occurrences+ occurrences = content.count(old_string)++ # If occurrences == 0, raise error+ if occurrences == 0:+ return ToolChunk(+ content=[+ TextBlock(+ text=f"Error: old_string not found in {file_path}",+ ),+ ],+ state="error",+ is_last=True,+ )++ # If occurrences > 1 and not replace_all, raise error+ if occurrences > 1 and not replace_all:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"Error: old_string appears {occurrences} "+ f"times in {file_path}. Set replace_all=true "+ f"to replace all occurrences, or make "+ f"old_string more specific."+ ),+ ),+ ],+ state="error",+ is_last=True,+ )++ # Perform replacement+ if replace_all:+ updated_content = content.replace(old_string, new_string)+ else:+ updated_content = content.replace(+ old_string,+ new_string,+ 1,+ )++ # Write updated content back to file+ try:+ async with aiofiles.open(+ file_path,+ "w",+ encoding="utf-8",+ ) as f:+ await f.write(updated_content)+ except Exception as e:+ return ToolChunk(+ content=[TextBlock(text=f"Error writing file: {str(e)}")],+ state="error",+ is_last=True,+ )++ # Return success message+ replacement_msg = (+ f"all {occurrences} occurrences" if replace_all else "1 occurrence"+ )+ return ToolChunk(+ content=[+ TextBlock(+ text=f"Successfully replaced {replacement_msg} "+ f"in {file_path}",+ ),+ ],+ state="running",+ is_last=True,+ )diff --git a/src/agentscope/tool/_builtin/_glob.py b/src/agentscope/tool/_builtin/_glob.pynew file mode 100644index 000000000..8ed13c3bc--- /dev/null+++ b/src/agentscope/tool/_builtin/_glob.py@@ -0,0 +1,314 @@+# -*- coding: utf-8 -*-+"""The glob tool in agentscope."""+import fnmatch+import os+import re+from typing import Any, List++from .._base import ToolBase+from .._permission import (+ PermissionContext,+ PermissionDecision,+ PermissionBehavior,+ PermissionRule,+)+from .._response import ToolChunk+from ...message import TextBlock+++class Glob(ToolBase):+ """The glob tool for fast file pattern matching."""++ name: str = "Glob"+ """The tool name presented to the agent."""++ description: str = """Fast file pattern matching tool that works with+any codebase size.++Supports glob patterns like "**/*.js" or "src/**/*.ts" and returns+matching file paths sorted by modification time (newest first).++Use this tool when you need to find files by pattern across the+codebase.""" # ignore: E501+ """The description presented to the agent."""++ input_schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "pattern": {+ "type": "string",+ "description": "The glob pattern to match against "+ "(e.g., '**/*.py', 'src/**/*.ts')",+ },+ "path": {+ "type": "string",+ "description": "The base directory to search from "+ "(defaults to current working directory)",+ },+ },+ "required": ["pattern"],+ }++ is_mcp: bool = False+ is_read_only: bool = True+ is_concurrency_safe: bool = True++ def __init__(self) -> None:+ """Initialize the glob tool."""++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Check permissions for glob pattern matching.++ Glob is a read-only tool. Return PASSTHROUGH to let the engine+ handle EXPLORE mode and rule matching.+ """+ return PermissionDecision(+ behavior=PermissionBehavior.PASSTHROUGH,+ message="Glob pattern matching is read-only.",+ )++ def match_rule(+ self,+ rule_content: str | None,+ tool_input: dict[str, Any],+ ) -> bool:+ """Check if a permission rule matches the glob pattern or path.++ Matches rule_content as a glob pattern against the "pattern" or "path"+ parameters. This allows rules to match either the search pattern itself+ or the directory being searched. If rule_content is None, matches all+ invocations (tool-name-level rule).++ Args:+ rule_content (`str | None`):+ Glob pattern to match (e.g., "src/**" to match searches in+ src), or None to match all invocations+ tool_input (`dict[str, Any]`):+ The tool input data containing "pattern" and optional "path"++ Returns:+ `bool`:+ True if the rule matches the pattern or path, False otherwise+ """+ # None = tool-name-level rule, matches everything+ if rule_content is None:+ return True++ # Try matching against the search path first+ path = tool_input.get("path", "")+ if path and fnmatch.fnmatch(path, rule_content):+ return True++ # Fall back to matching against the pattern itself+ pattern = tool_input.get("pattern", "")+ if pattern and fnmatch.fnmatch(pattern, rule_content):+ return True++ return False++ def generate_suggestions(+ self,+ tool_input: dict[str, Any],+ ) -> List[PermissionRule]:+ """Generate suggested permission rules for the glob search.++ Suggests a rule based on the search path. If no path is provided,+ suggests a rule for the current directory.++ Args:+ tool_input (`dict[str, Any]`):+ The tool input data containing optional "path" key++ Returns:+ `List[PermissionRule]`:+ A single suggested rule covering the search directory+ """+ path = tool_input.get("path", "")+ if not path:+ path = os.getcwd()++ # Normalize path and create pattern+ abs_path = os.path.abspath(path)+ pattern = abs_path.rstrip("/") + "/**"++ return [+ PermissionRule(+ tool_name=self.name,+ rule_content=pattern,+ behavior=PermissionBehavior.ALLOW,+ source="suggested",+ ),+ ]++ def glob_part_to_regex(self, part: str) -> re.Pattern:+ """Convert a glob pattern part to a regex pattern.++ Args:+ part: A single part of a glob pattern (e.g., '*.py', 'test_??.py')++ Returns:+ A compiled regex pattern+ """+ regex_str = ""+ i = 0+ while i < len(part):+ c = part[i]+ if c == "*":+ regex_str += ".*"+ elif c == "?":+ regex_str += "."+ elif c in ".^$+{}[]|()\\":+ regex_str += "\\" + c+ else:+ regex_str += c+ i += 1+ return re.compile(f"^{regex_str}$")++ def collect_all(self, current_dir: str, results: list[str]) -> None:+ """Recursively collect all files in a directory.++ Args:+ current_dir: The directory to collect files from+ results: The list to append matched file paths to+ """+ try:+ for root, _dirs, files in os.walk(current_dir):+ for file in files:+ results.append(os.path.join(root, file))+ except (PermissionError, OSError):+ # Skip unreadable directories silently+ pass++ def match_parts(+ self,+ parts: list[str],+ part_index: int,+ current_dir: str,+ results: list[str],+ ) -> None:+ """Recursively match path parts against directory entries.++ Args:+ parts: The split glob pattern parts+ part_index: The current index in the parts array+ current_dir: The current directory being traversed+ results: The list to append matched file paths to+ """+ if part_index >= len(parts):+ return++ part = parts[part_index]+ is_last = part_index == len(parts) - 1++ if part == "**":+ if is_last:+ self.collect_all(current_dir, results)+ else:+ # Match in current directory+ self.match_parts(parts, part_index + 1, current_dir, results)+ # Recursively match in subdirectories+ try:+ with os.scandir(current_dir) as entries:+ for entry in entries:+ if entry.is_dir(follow_symlinks=False):+ self.match_parts(+ parts,+ part_index,+ entry.path,+ results,+ )+ except (PermissionError, OSError):+ # Skip unreadable directories silently+ pass+ else:+ regex = self.glob_part_to_regex(part)+ try:+ with os.scandir(current_dir) as entries:+ for entry in entries:+ if regex.match(entry.name):+ full_path = entry.path+ if is_last:+ if entry.is_file(follow_symlinks=False):+ results.append(full_path)+ elif entry.is_dir(follow_symlinks=False):+ self.match_parts(+ parts,+ part_index + 1,+ full_path,+ results,+ )+ except (PermissionError, OSError):+ # Skip unreadable directories silently+ pass++ def glob_match(self, pattern: str, base_dir: str) -> list[str]:+ """Match files against a glob pattern starting from the given+ base directory.++ Args:+ pattern: The glob pattern to match against+ base_dir: The base directory to search from++ Returns:+ A list of matched file paths+ """+ results: list[str] = []+ parts = pattern.split("/")+ self.match_parts(parts, 0, base_dir, results)+ return results++ async def __call__( # type: ignore[override]+ self,+ pattern: str,+ path: str | None = None,+ ) -> ToolChunk:+ """Execute the glob pattern matching and return the results.++ Args:+ pattern: The glob pattern to match against+ path: Optional base directory to search from (defaults to cwd)++ Returns:+ `ToolChunk`:+ The content contains the matched file paths joined by+ newlines, or an error message if the directory is not found or+ no files match the pattern.+ """+ base_dir = path if path else os.getcwd()++ if not os.path.exists(base_dir):+ return ToolChunk(+ content=[TextBlock(text=f"Directory not found: {base_dir}")],+ state="error",+ is_last=True,+ )++ matches = self.glob_match(pattern, base_dir)++ # Sort by modification time (newest first)+ try:+ matches.sort(key=lambda p: os.stat(p).st_mtime, reverse=True)+ except (OSError, FileNotFoundError):+ # If we can't stat some files, just keep the unsorted order+ pass++ if len(matches) == 0:+ return ToolChunk(+ content=[+ TextBlock(+ text=f"No files found matching pattern: {pattern}",+ ),+ ],+ state="running",+ is_last=True,+ )++ return ToolChunk(+ content=[TextBlock(text="\n".join(matches))],+ state="running",+ is_last=True,+ )diff --git a/src/agentscope/tool/_builtin/_grep.py b/src/agentscope/tool/_builtin/_grep.pynew file mode 100644index 000000000..564226c80--- /dev/null+++ b/src/agentscope/tool/_builtin/_grep.py@@ -0,0 +1,462 @@+# -*- coding: utf-8 -*-+"""The grep tool in agentscope."""+import asyncio+import fnmatch+import os+import shutil+from typing import Any, List, Literal++from .._base import ToolBase+from .._permission import (+ PermissionContext,+ PermissionDecision,+ PermissionBehavior,+ PermissionRule,+)+from .._response import ToolChunk+from ...message import TextBlock+++# Version control system directories to exclude from searches+VCS_DIRECTORIES_TO_EXCLUDE = [+ ".git",+ ".svn",+ ".hg",+ ".bzr",+ ".jj",+ ".sl",+]++# Default cap on grep results when head_limit is unspecified+DEFAULT_HEAD_LIMIT = 250+++class RipgrepTimeoutError(Exception):+ """Custom error class for ripgrep timeouts."""++ def __init__(self, message: str, partial_results: list[str]):+ super().__init__(message)+ self.partial_results = partial_results+++class Grep(ToolBase):+ """The grep tool for searching file contents using ripgrep."""++ name: str = "Grep"+ """The tool name presented to the agent."""++ description: str = """A powerful search tool built on ripgrep++ Usage:+- ALWAYS use Grep for search tasks. NEVER invoke `grep` or `rg` as a Bash command. The Grep tool has been optimized for correct permissions and access.+- Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")+- Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")+- Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts per file+- Context lines: use context parameter or -A/-B/-C for lines after/before/around matches+- Case-insensitive search: set i to true+- Multiline regex: set multiline to true for patterns spanning multiple lines+- Limit results: use head_limit to cap the number of results returned""" # noqa: E501+ """The description presented to the agent."""++ input_schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "pattern": {+ "type": "string",+ "description": "The regular expression pattern to search "+ "for in file contents.",+ },+ "path": {+ "type": "string",+ "description": "File or directory to search in. Defaults "+ "to current working directory.",+ },+ "output_mode": {+ "type": "string",+ "enum": ["content", "files_with_matches", "count"],+ "description": "Output mode: 'content' shows matching lines "+ "(supports -A/-B/-C context, -n line numbers, "+ "head_limit), 'files_with_matches' shows file "+ "paths (supports head_limit), 'count' shows "+ "match counts (supports head_limit). "+ "Defaults to 'files_with_matches'.",+ "default": "files_with_matches",+ },+ "glob": {+ "type": "string",+ "description": "Glob pattern to filter files (e.g., '*.js', "+ "'*.{ts,tsx}').",+ },+ "type": {+ "type": "string",+ "description": "File type to search (rg --type). "+ "Common types: js, py, rust, go, java, etc.",+ },+ "-A": {+ "type": "integer",+ "description": "Number of lines to show after each match. "+ "Requires output_mode: 'content'.",+ },+ "-B": {+ "type": "integer",+ "description": "Number of lines to show before each match. "+ "Requires output_mode: 'content'.",+ },+ "-C": {+ "type": "integer",+ "description": "Alias for context.",+ },+ "context": {+ "type": "integer",+ "description": "Number of context lines to show before and "+ "after matches. Requires output_mode: "+ "'content'.",+ },+ "n": {+ "type": "boolean",+ "description": "Show line numbers in output. Requires "+ "output_mode: 'content'. Defaults to true.",+ "default": True,+ },+ "i": {+ "type": "boolean",+ "description": "Case insensitive search.",+ "default": False,+ },+ "case_insensitive": {+ "type": "boolean",+ "description": "Case insensitive search (alias for i).",+ "default": False,+ },+ "multiline": {+ "type": "boolean",+ "description": "Enable multiline mode where . matches "+ "newlines and patterns can span lines. "+ "Default: false.",+ "default": False,+ },+ "head_limit": {+ "type": "integer",+ "description": "Limit output to first N lines/entries. "+ "Defaults to 250 when unspecified. "+ "Pass 0 for unlimited.",+ },+ "offset": {+ "type": "integer",+ "description": "Skip first N lines/entries before applying "+ "head_limit. Defaults to 0.",+ "default": 0,+ },+ },+ "required": ["pattern"],+ }++ is_mcp: bool = False+ is_read_only: bool = True+ is_concurrency_safe: bool = True++ def __init__(self) -> None:+ """Initialize the grep tool."""+ self._rg_path = shutil.which("rg")++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Check permissions for grep search."""+ return PermissionDecision(+ behavior=PermissionBehavior.PASSTHROUGH,+ message="Grep search is read-only.",+ )++ def match_rule(+ self,+ rule_content: str | None,+ tool_input: dict[str, Any],+ ) -> bool:+ """Check if a permission rule matches the grep search path.++ Matches rule_content as a glob pattern against the "path" parameter.+ If no path is given, falls back to the current working directory.+ If rule_content is None, matches all invocations (tool-name-level+ rule).++ Args:+ rule_content (`str | None`):+ Glob pattern to match against the search path (e.g., "src/**"),+ or None to match all invocations+ tool_input (`dict[str, Any]`):+ The tool input data containing optional "path" key++ Returns:+ `bool`:+ True if the glob pattern matches the search path, False+ otherwise+ """+ # None = tool-name-level rule, matches everything+ if rule_content is None:+ return True++ path = tool_input.get("path", "")+ if not path:+ path = os.getcwd()+ return fnmatch.fnmatch(path, rule_content)++ def generate_suggestions(+ self,+ tool_input: dict[str, Any],+ ) -> List[PermissionRule]:+ """Generate suggested permission rules for the grep search path.++ Suggests a rule based on the search path. If no path is provided,+ suggests a rule for the current directory.++ Args:+ tool_input (`dict[str, Any]`):+ The tool input data containing optional "path" key++ Returns:+ `List[PermissionRule]`:+ A single suggested rule covering the search directory+ """+ path = tool_input.get("path", "")+ if not path:+ path = os.getcwd()++ abs_path = os.path.abspath(path)+ pattern = abs_path.rstrip("/") + "/**"++ return [+ PermissionRule(+ tool_name=self.name,+ rule_content=pattern,+ behavior=PermissionBehavior.ALLOW,+ source="suggested",+ ),+ ]++ def _apply_head_limit(+ self,+ items: list[str],+ limit: int | None,+ offset: int = 0,+ ) -> tuple[list[str], int | None]:+ """Apply head_limit and offset to a list of items.++ Returns (sliced_items, applied_limit_if_truncated).+ """+ if limit == 0:+ return items[offset:], None+ effective_limit = limit if limit is not None else DEFAULT_HEAD_LIMIT+ sliced = items[offset : offset + effective_limit]+ was_truncated = len(items) - offset > effective_limit+ return sliced, (effective_limit if was_truncated else None)++ async def _run_ripgrep(+ self,+ args: list[str],+ search_path: str,+ timeout: int = 30,+ ) -> list[str]:+ """Run ripgrep and return output lines."""+ full_args: list = [self._rg_path, *args, search_path]++ proc = await asyncio.create_subprocess_exec(+ *full_args,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )++ try:+ stdout, stderr = await asyncio.wait_for(+ proc.communicate(),+ timeout=timeout,+ )+ except asyncio.TimeoutError as e:+ proc.kill()+ await proc.communicate()+ raise RipgrepTimeoutError(+ f"Ripgrep search timed out after {timeout} seconds. "+ "Try searching a more specific path or pattern.",+ [],+ ) from e++ # returncode 0 = matches found, 1 = no matches (both are success)+ if proc.returncode not in (0, 1):+ error_msg = stderr.decode("utf-8", errors="ignore").strip()+ raise RuntimeError(+ f"ripgrep error (code {proc.returncode}): {error_msg}",+ )++ raw = stdout.decode("utf-8", errors="ignore")+ lines = [+ line.rstrip("\r") for line in raw.split("\n") if line.rstrip("\r")+ ]+ return lines++ async def __call__( # type: ignore[override]+ self,+ pattern: str,+ path: str | None = None,+ output_mode: Literal[+ "content",+ "files_with_matches",+ "count",+ ] = "files_with_matches",+ glob: str | None = None,+ type: str | None = None, # pylint: disable=redefined-builtin+ i: bool = False,+ case_insensitive: bool = False,+ context: int | None = None,+ multiline: bool = False,+ head_limit: int | None = None,+ offset: int = 0,+ n: bool = True,+ **kwargs: Any,+ ) -> ToolChunk:+ """Execute the grep search using ripgrep.++ Args:+ pattern: The regex pattern to search for+ path: The directory or file path to search in+ output_mode: Output mode ('content', 'files_with_matches', 'count')+ glob: Glob pattern to filter files+ type: File type to filter by (rg --type)+ i: Case-insensitive search (rg -i)+ case_insensitive: Alias for i (backward compatibility)+ context: Number of context lines around matches+ multiline: Enable multiline regex matching+ head_limit: Maximum number of results to return+ (default 250, 0=unlimited)+ offset: Skip first N results+ n: Show line numbers (content mode only, default True)+ **kwargs: Additional parameters (-A, -B, -C)+ """+ if self._rg_path is None:+ return ToolChunk(+ content=[+ TextBlock(+ text="ripgrep (rg) not found. Please install it: "+ "macOS: brew install ripgrep | "+ "Linux: apt/yum install ripgrep | "+ "Windows: choco install ripgrep",+ ),+ ],+ state="error",+ is_last=True,+ )++ search_path = path or os.getcwd()++ args: list[str] = ["--hidden"]++ # Exclude VCS directories+ for vcs_dir in VCS_DIRECTORIES_TO_EXCLUDE:+ args.extend(["--glob", f"!{vcs_dir}"])++ # Limit line length to prevent base64/minified content+ args.extend(["--max-columns", "500"])++ # Multiline mode+ if multiline:+ args.extend(["-U", "--multiline-dotall"])++ # Case insensitive (support both i and case_insensitive+ # for compatibility)+ if i or case_insensitive:+ args.append("-i")++ # Output mode flags+ if output_mode == "files_with_matches":+ args.append("-l")+ elif output_mode == "count":+ args.append("-c")++ # Line numbers (content mode only)+ if n and output_mode == "content":+ args.append("-n")++ # Context flags (content mode only)+ if output_mode == "content":+ A = kwargs.get("-A")+ B = kwargs.get("-B")+ C = kwargs.get("-C")++ if context is not None:+ args.extend(["-C", str(context)])+ elif C is not None:+ args.extend(["-C", str(C)])+ else:+ if B is not None:+ args.extend(["-B", str(B)])+ if A is not None:+ args.extend(["-A", str(A)])++ # Pattern — use -e if it starts with a dash+ if pattern.startswith("-"):+ args.extend(["-e", pattern])+ else:+ args.append(pattern)++ # File type filter+ if type is not None:+ args.extend(["--type", type])++ # Glob filter+ if glob is not None:+ raw_patterns = glob.split()+ glob_patterns: list[str] = []+ for raw in raw_patterns:+ if "{" in raw and "}" in raw:+ glob_patterns.append(raw)+ else:+ glob_patterns.extend(p for p in raw.split(",") if p)+ for gp in glob_patterns:+ args.extend(["--glob", gp])++ try:+ results = await self._run_ripgrep(args, search_path)+ except RipgrepTimeoutError as e:+ return ToolChunk(+ content=[TextBlock(text=str(e))],+ state="error",+ is_last=True,+ )+ except RuntimeError as e:+ return ToolChunk(+ content=[TextBlock(text=str(e))],+ state="error",+ is_last=True,+ )++ if not results:+ return ToolChunk(+ content=[+ TextBlock(text=f"No matches found for pattern: {pattern}"),+ ],+ state="running",+ is_last=True,+ )++ limited, applied_limit = self._apply_head_limit(+ results,+ head_limit,+ offset,+ )++ suffix = ""+ if applied_limit is not None:+ suffix = (+ f"\n\n[Showing results with pagination = "+ f"limit: {applied_limit}"+ )+ if offset:+ suffix += f", offset: {offset}"+ suffix += "]"++ return ToolChunk(+ content=[TextBlock(text="\n".join(limited) + suffix)],+ state="running",+ is_last=True,+ )diff --git a/src/agentscope/tool/_builtin/_meta.py b/src/agentscope/tool/_builtin/_meta.pyindex 33630491f..fb39cc042 100644--- a/src/agentscope/tool/_builtin/_meta.py+++ b/src/agentscope/tool/_builtin/_meta.py@@ -13,13 +13,14 @@ from .._permission import (from .._response import ToolChunkfrom .._base import ToolBasefrom .._types import ToolGroup+from ...exception import DeveloperOrientedExceptionfrom ...message import TextBlockif TYPE_CHECKING:from ...agent import AgentStateelse:- AgentState = "AgentState"+ AgentState = Anyclass ResetTools(ToolBase):@@ -87,11 +88,20 @@ class ResetTools(ToolBase):message="The meta tool is always allowed to be called.",)- async def __call__(self, state: AgentState, **kwargs: Any) -> ToolChunk:+ async def __call__(+ self,+ _agent_state: AgentState,+ **kwargs: Any,+ ) -> ToolChunk:"""Activate or deactivate tool groups based on the input arguments,and return their usage instructions."""+ if _agent_state is None:+ raise DeveloperOrientedException(+ "Error: ResetTools requires state to be provided.",+ )+# Deactivate all tool groups first- state.activated_groups.clear()+ _agent_state.tool_context.activated_groups.clear()to_activate = []for key, value in kwargs.items():@@ -108,7 +118,7 @@ class ResetTools(ToolBase):if value:to_activate.append(key)- state.activated_groups.extend(to_activate)+ _agent_state.tool_context.activated_groups.extend(to_activate)template = Template(self.response_template)activated_groups = [diff --git a/src/agentscope/tool/_builtin/_read.py b/src/agentscope/tool/_builtin/_read.pynew file mode 100644index 000000000..243ec6440--- /dev/null+++ b/src/agentscope/tool/_builtin/_read.py@@ -0,0 +1,277 @@+# -*- coding: utf-8 -*-+"""The read tool in agentscope."""+import fnmatch+import os+from typing import Any, List, TYPE_CHECKING++import aiofiles++from .._base import ToolBase+from .._permission import (+ PermissionContext,+ PermissionDecision,+ PermissionBehavior,+ PermissionRule,+)+from .._response import ToolChunk+from ...message import TextBlock++if TYPE_CHECKING:+ from ...agent import AgentState+else:+ AgentState = Any+++class Read(ToolBase):+ """The read tool."""++ name: str = "Read"+ """The tool name presented to the agent."""++ # pylint: disable=line-too-long+ description: str = """Reads a file from the local filesystem. You can access any file directly by using this tool.+Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.++Usage:+- The file_path parameter must be an absolute path, not a relative path+- By default, it reads up to 2000 lines starting from the beginning of the file+- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters+- Results are returned using cat -n format, with line numbers starting at 1+- This tool allows you to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Claude Code is a multimodal LLM.+- This tool can read PDF files (.pdf). For large PDFs (more than 10 pages), you MUST provide the pages parameter to read specific pages.""" # noqa: E501+ """The description presented to the agent."""++ input_schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string",+ "description": "The absolute path to the file to read.",+ },+ "offset": {+ "type": "integer",+ "description": "Optional 1-based line number to start reading "+ "from (default: 1)",+ "default": 1,+ "minimum": 1,+ },+ "limit": {+ "type": "integer",+ "description": "Optional maximum number of lines to read "+ "(default: 2000, max: 2000)",+ "default": 2000,+ "maximum": 2000,+ "minimum": 1,+ },+ },+ "required": ["file_path"],+ }++ is_mcp: bool = False+ is_read_only: bool = True+ is_concurrency_safe: bool = True++ def __init__(+ self,+ max_line_characters: int = 2000,+ ) -> None:+ """Initialize the read tool.++ Args:+ max_line_characters (`int`, defaults to 2000):+ The maximum number of characters to include for each line when+ reading files. Lines longer than this will be truncated with+ a "[truncated]" suffix. This prevents overwhelming the agent+ with excessively long lines while still providing useful+ content.+ """++ self._max_line_characters = max_line_characters++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Check permissions for file reading.++ Read is a read-only tool. In EXPLORE mode the engine already handles+ the ALLOW via _check_explore_mode, so here we just return PASSTHROUGH+ to let the engine continue with rule matching.+ """+ return PermissionDecision(+ behavior=PermissionBehavior.PASSTHROUGH,+ message="File reading is read-only.",+ )++ def match_rule(+ self,+ rule_content: str | None,+ tool_input: dict[str, Any],+ ) -> bool:+ """Check if a permission rule matches the file path.++ Matches rule_content as a glob pattern against the "file_path"+ parameter using fnmatch. If rule_content is None, matches all+ invocations (tool-name-level rule).++ Args:+ rule_content (`str | None`):+ Glob pattern to match against the file path (e.g., "src/**"),+ or None to match all invocations+ tool_input (`dict[str, Any]`):+ The tool input data containing "file_path" key++ Returns:+ `bool`:+ True if the glob pattern matches the file path, False otherwise+ """+ # None = tool-name-level rule, matches everything+ if rule_content is None:+ return True++ file_path = tool_input.get("file_path", "")+ if not file_path:+ return False+ return fnmatch.fnmatch(file_path, rule_content)++ def generate_suggestions(+ self,+ tool_input: dict[str, Any],+ ) -> List[PermissionRule]:+ """Generate suggested permission rules for the file path.++ Suggests a glob pattern covering the parent directory of the file,+ allowing the user to grant permission for the entire directory at once.++ Args:+ tool_input (`dict[str, Any]`):+ The tool input data containing "file_path" key++ Returns:+ `List[PermissionRule]`:+ A single suggested rule covering the parent directory+ (e.g., file "/src/main.py" -> rule "src/**")+ """+ file_path = tool_input.get("file_path", "")+ if not file_path:+ return []++ parent = os.path.dirname(file_path)+ pattern = (parent.rstrip("/") + "/**") if parent else "**"++ return [+ PermissionRule(+ tool_name=self.name,+ rule_content=pattern,+ behavior=PermissionBehavior.ALLOW,+ source="suggested",+ ),+ ]++ async def __call__( # type: ignore[override]+ self,+ file_path: str,+ offset: int = 1,+ limit: int = 2000,+ _agent_state: AgentState | None = None,+ ) -> ToolChunk:+ """Read the file and return the content with line numbers."""++ # Validate file_path is absolute+ if not os.path.isabs(file_path):+ return ToolChunk(+ content=[+ TextBlock(+ text=f"Error: file_path must be an absolute path, "+ f"got: {file_path}",+ ),+ ],+ state="error",+ is_last=True,+ )++ # Check file exists+ if not os.path.exists(file_path):+ return ToolChunk(+ content=[+ TextBlock(text=f"Error: File does not exist: {file_path}"),+ ],+ state="error",+ is_last=True,+ )++ # Check it's not a directory+ if os.path.isdir(file_path):+ return ToolChunk(+ content=[+ TextBlock(+ text=f"Error: Path is a directory, not a file: "+ f"{file_path}",+ ),+ ],+ state="error",+ is_last=True,+ )++ try:+ # Read file content with aiofiles+ lines = None+ if _agent_state is not None:+ cache = await _agent_state.tool_context.get_cache(file_path)+ if cache is not None:+ lines = cache.lines++ if lines is None:+ async with aiofiles.open(+ file_path,+ mode="r",+ encoding="utf-8",+ errors="replace",+ ) as f:+ lines = await f.readlines()++ # Cache file if state is provided+ if _agent_state is not None:+ await _agent_state.tool_context.cache_file(+ file_path=file_path,+ lines=lines,+ )++ # Apply offset and limit (offset is 1-based)+ start_idx = offset - 1+ end_idx = start_idx + limit+ selected_lines = lines[start_idx:end_idx]++ # Format with line numbers (6-char padded + tab + content)+ formatted_lines = []+ for i, line in enumerate(selected_lines, start=offset):+ # Remove trailing newline if present+ line_content = line.rstrip("\n\r")++ # Truncate lines longer than 2000 chars+ if len(line_content) > self._max_line_characters:+ line_content = (+ line_content[: self._max_line_characters]+ + "[truncated]"+ )++ # Format: 6-char padded line number + tab + content+ formatted_line = f"{i:6d}\t{line_content}"+ formatted_lines.append(formatted_line)++ # Join all lines+ result = "\n".join(formatted_lines)++ return ToolChunk(+ content=[TextBlock(text=result)],+ state="running",+ is_last=True,+ )++ except Exception as e:+ return ToolChunk(+ content=[TextBlock(text=f"Error reading file: {str(e)}")],+ state="error",+ is_last=True,+ )diff --git a/src/agentscope/tool/_builtin/_write.py b/src/agentscope/tool/_builtin/_write.pynew file mode 100644index 000000000..6cf5b5396--- /dev/null+++ b/src/agentscope/tool/_builtin/_write.py@@ -0,0 +1,314 @@+# -*- coding: utf-8 -*-+"""The write tool in agentscope."""+import fnmatch+import os+from pathlib import Path+from typing import Any, List, TYPE_CHECKING++import aiofiles++from .._base import ToolBase+from .._permission import (+ PermissionContext,+ PermissionDecision,+ PermissionBehavior,+ PermissionMode,+ PermissionRule,+)+from .._response import ToolChunk+from ...message import TextBlock++if TYPE_CHECKING:+ from ...agent import AgentState+else:+ AgentState = Any+++class Write(ToolBase):+ """The write tool."""++ name: str = "Write"+ """The tool name presented to the agent."""++ # pylint: disable=line-too-long+ description: str = """Writes a file to the local filesystem.++Usage:+- This tool will overwrite the existing file if there is one at the provided path.+- If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.+- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.+- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.+- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.""" # noqa: E501+ """The description presented to the agent."""++ input_schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string",+ "description": "The absolute path to the file to write "+ "(must be absolute, not relative)",+ },+ "content": {+ "type": "string",+ "description": "The content to write to the file",+ },+ },+ "required": ["file_path", "content"],+ }++ is_mcp: bool = False+ is_read_only: bool = False+ is_concurrency_safe: bool = False++ def __init__(+ self,+ additional_dangerous_files: list[str] | None = None,+ additional_dangerous_directories: list[str] | None = None,+ ) -> None:+ """Initialize the write tool.++ Args:+ additional_dangerous_files (`list[str] | None`, optional):+ Additional dangerous files to check (added to built-in+ defaults). Use this to add project-specific sensitive files+ like '.env' or '.secrets'.+ additional_dangerous_directories (`list[str] | None`, optional):+ Additional dangerous directories to check (added to built-in+ defaults). Use this to add project-specific sensitive+ directories.+ """+ # Merge class-level dangerous paths with additional ones+ self.dangerous_files = self.__class__.dangerous_files.copy()+ if additional_dangerous_files:+ self.dangerous_files.extend(additional_dangerous_files)++ self.dangerous_directories = (+ self.__class__.dangerous_directories.copy()+ )+ if additional_dangerous_directories:+ self.dangerous_directories.extend(additional_dangerous_directories)++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Check permissions for file writing.++ This method implements Write-specific permission checks:+ 1. Dangerous path check (safety check, bypass-immune)+ 2. ACCEPT_EDITS mode check for files in working directories++ Args:+ tool_input (`dict[str, Any]`):+ The tool input containing "file_path" key+ context (`PermissionContext`):+ The permission context with mode and rules++ Returns:+ `PermissionDecision`:+ ASK for dangerous paths, ALLOW for safe operations in+ ACCEPT_EDITS mode, PASSTHROUGH otherwise+ """++ file_path = tool_input.get("file_path")+ if not file_path:+ return PermissionDecision(+ behavior=PermissionBehavior.PASSTHROUGH,+ message="No file path provided",+ )++ # 1. Check for dangerous paths (safety check, bypass-immune)+ if self._is_dangerous_path(file_path):+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message=f"Permission required: Write operation on "+ f"sensitive file {file_path}",+ decision_reason="Safety check: dangerous file or directory",+ )++ # 2. Check ACCEPT_EDITS mode for files in working directories+ if context.mode == PermissionMode.ACCEPT_EDITS:+ if self._path_in_allowed_working_path(file_path, context):+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"Permission granted for writing {file_path} "+ f"(accept edits mode - in working directory)",+ decision_reason="File is in working directory and not "+ "a dangerous path",+ )++ # 3. Return PASSTHROUGH to let PermissionEngine check allow rules+ # This ensures allow rules can grant Write permissions+ return PermissionDecision(+ behavior=PermissionBehavior.PASSTHROUGH,+ message="",+ )++ def _path_in_allowed_working_path(+ self,+ file_path: str,+ context: PermissionContext,+ ) -> bool:+ """Check if a file path is within any allowed working directory.++ Args:+ file_path (`str`):+ The file path to check+ context (`PermissionContext`):+ The permission context containing working directories++ Returns:+ `bool`:+ True if the path is within any allowed working directory+ """++ # Get all working directories (current directory + additional)+ current_dir = os.getcwd()+ additional_dirs = list(context.working_directories.keys())+ all_working_dirs = [current_dir] + additional_dirs++ # Normalize paths+ abs_file_path = os.path.abspath(os.path.expanduser(file_path))++ # Check if file path is in any working directory+ for working_dir in all_working_dirs:+ abs_working_dir = os.path.abspath(os.path.expanduser(working_dir))+ try:+ # Check if file_path is inside working_dir+ os.path.relpath(abs_file_path, abs_working_dir)+ if (+ abs_file_path.startswith(abs_working_dir + os.sep)+ or abs_file_path == abs_working_dir+ ):+ return True+ except ValueError:+ # On Windows, relpath raises ValueError if paths are on+ # different drives+ continue++ return False++ def match_rule(+ self,+ rule_content: str | None,+ tool_input: dict[str, Any],+ ) -> bool:+ """Check if a permission rule matches the file path.++ Matches rule_content as a glob pattern against the "file_path"+ parameter using fnmatch. If rule_content is None, matches all+ invocations (tool-name-level rule).++ Args:+ rule_content (`str | None`):+ Glob pattern to match against the file path (e.g., "src/**"),+ or None to match all invocations+ tool_input (`dict[str, Any]`):+ The tool input data containing "file_path" key++ Returns:+ `bool`:+ True if the glob pattern matches the file path, False otherwise+ """+ if rule_content is None:+ return True++ file_path = tool_input.get("file_path", "")+ if not file_path:+ return False+ return fnmatch.fnmatch(file_path, rule_content)++ def generate_suggestions(+ self,+ tool_input: dict[str, Any],+ ) -> List[PermissionRule]:+ """Generate suggested permission rules for the file path.++ Suggests a glob pattern covering the parent directory of the file,+ allowing the user to grant permission for the entire directory at once.++ Args:+ tool_input (`dict[str, Any]`):+ The tool input data containing "file_path" key++ Returns:+ `List[PermissionRule]`:+ A single suggested rule covering the parent directory+ (e.g., file "/src/main.py" -> rule "src/**")+ """+ file_path = tool_input.get("file_path", "")+ if not file_path:+ return []++ parent = os.path.dirname(file_path)+ pattern = (parent.rstrip("/") + "/**") if parent else "**"++ return [+ PermissionRule(+ tool_name=self.name,+ rule_content=pattern,+ behavior=PermissionBehavior.ALLOW,+ source="suggested",+ ),+ ]++ async def __call__( # type: ignore[override]+ self,+ file_path: str,+ content: str,+ _agent_state: AgentState | None = None,+ ) -> ToolChunk:+ """Write content to a file and return the result."""+ # Validate that file_path is absolute+ if not os.path.isabs(file_path):+ return ToolChunk(+ content=[+ TextBlock(+ text=f"Error: file_path must be an absolute path, "+ f"got: {file_path}",+ ),+ ],+ state="error",+ is_last=True,+ )++ # Check if file exists, it must be read first if it exists+ if os.path.exists(file_path) and _agent_state is not None:+ cache = await _agent_state.tool_context.get_cache(file_path)+ if cache is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=f"Error: File {file_path} exists but has not "+ f"been read yet. You must read the file first "+ f"before writing to it.",+ ),+ ],+ state="error",+ is_last=True,+ )++ # Create parent directories if they don't exist+ parent_dir = Path(file_path).parent+ os.makedirs(parent_dir, exist_ok=True)++ # Write content to file+ async with aiofiles.open(file_path, mode="w", encoding="utf-8") as f:+ await f.write(content)++ # Count lines in content+ line_count = len(content.split("\n"))++ # Return success message+ return ToolChunk(+ content=[+ TextBlock(+ text=f"The file {file_path} has been written successfully "+ f"({line_count} lines).",+ ),+ ],+ state="running",+ is_last=True,+ )diff --git a/src/agentscope/tool/_constants.py b/src/agentscope/tool/_constants.pynew file mode 100644index 000000000..a99d3255c--- /dev/null+++ b/src/agentscope/tool/_constants.py@@ -0,0 +1,98 @@+# -*- coding: utf-8 -*-+"""Constants for tool permission system."""++DEFAULT_DANGEROUS_FILES = [+ ".gitconfig",+ ".gitmodules",+ ".bashrc",+ ".bash_profile",+ ".zshrc",+ ".zprofile",+ ".profile",+ ".ssh/config",+ ".ssh/authorized_keys",+ ".netrc",+ ".npmrc",+ ".pypirc",+]+# Built-in list of dangerous files that should be protected from auto-editing.+#+# These files can be used for code execution, credential storage, or data+# exfiltration:+# - Shell configuration files: .bashrc, .zshrc, .profile, etc.+# - Git configuration: .gitconfig, .gitmodules+# - SSH configuration: .ssh/config, .ssh/authorized_keys+# - Credential files: .netrc, .npmrc, .pypirc+++DEFAULT_DANGEROUS_DIRECTORIES = [+ ".git",+ ".vscode",+ ".idea",+ ".ssh",+]+# Built-in list of dangerous directories that should be protected from+# auto-editing.+#+# These directories contain sensitive configuration or executable files:+# - .git: Git repository metadata+# - .vscode: VS Code configuration+# - .idea: JetBrains IDE configuration+# - .ssh: SSH keys and configuration+++DANGEROUS_COMMANDS = [+ "rm -rf",+ "sudo rm",+ "dd",+ "mkfs",+ "fdisk",+ "format",+ "chmod 777",+ "chmod -R 777",+ "chown -R",+ "kill -9",+ "> /dev/",+]+# Built-in list of dangerous command patterns that require explicit+# user approval.+#+# These commands can cause data loss, system damage, or security issues:+# - rm -rf: Recursive force deletion+# - sudo rm: Deletion with elevated privileges+# - dd: Direct disk operations+# - mkfs: Format filesystem+# - fdisk: Disk partitioning+# - format: Format disk+# - chmod 777: Overly permissive file permissions+# - chown -R: Recursive ownership changes+# - kill -9: Force kill processes+# - > /dev/: Writing to device files+++DANGEROUS_NODE_TYPES = {+ "command_substitution", # $(...) or `...`+ "process_substitution", # <(...)+ "expansion", # ${VAR:-default} complex expansion+ "subshell", # (...)+ "for_statement", # for loops+ "while_statement", # while loops+ "until_statement", # until loops+ "if_statement", # if conditionals+ "case_statement", # case statements+ "function_definition", # function definitions+ "test_command", # [[ ... ]] test commands+}+# Node types that indicate commands cannot be statically analyzed.+# These either execute arbitrary code or expand to values we can't+# determine statically.+#+# When these are detected, the command requires user review because:+# - Command substitution $(cmd) executes arbitrary commands+# - Process substitution <(cmd) creates dynamic file descriptors+# - Complex expansions ${VAR:-default} have runtime-dependent values+# - Control flow (if/while/for) has conditional execution paths+# - Subshells (...) create new execution contexts+#+# Note: simple_expansion ($VAR) is handled separately with allowlist+# for known-safe environment variables ($HOME, $PWD, etc.)diff --git a/src/agentscope/tool/_permission/_engine.py b/src/agentscope/tool/_permission/_engine.pyindex a255505ba..2b4aa2008 100644--- a/src/agentscope/tool/_permission/_engine.py+++ b/src/agentscope/tool/_permission/_engine.py@@ -1,60 +1,18 @@# -*- coding: utf-8 -*-"""The permission engine for checking and enforcing permission rules."""-import fnmatch-import osimport json-from pathlib import Path-from typing import Any, List+from typing import Any, List, TYPE_CHECKING-from ._bash_parser import BashCommandParserfrom ._context import PermissionContextfrom ._rule import PermissionRulefrom ._decision import PermissionDecision, PermissionBehaviorfrom ._types import PermissionModefrom ...message import ToolCallBlock-# ============================================================================-# Built-in Dangerous Paths-# ============================================================================--DEFAULT_DANGEROUS_FILES = [- ".gitconfig",- ".gitmodules",- ".bashrc",- ".bash_profile",- ".zshrc",- ".zprofile",- ".profile",- ".ssh/config",- ".ssh/authorized_keys",- ".netrc",- ".npmrc",- ".pypirc",-]-# Built-in list of dangerous files that should be protected from auto-editing.-#-# These files can be used for code execution, credential storage, or data-# exfiltration:-# - Shell configuration files: .bashrc, .zshrc, .profile, etc.-# - Git configuration: .gitconfig, .gitmodules-# - SSH configuration: .ssh/config, .ssh/authorized_keys-# - Credential files: .netrc, .npmrc, .pypirc---DEFAULT_DANGEROUS_DIRECTORIES = [- ".git",- ".vscode",- ".idea",- ".ssh",-]-# Built-in list of dangerous directories that should be protected from-# auto-editing.-#-# These directories contain sensitive configuration or executable files:-# - .git: Git repository metadata-# - .vscode: VS Code configuration-# - .idea: JetBrains IDE configuration-# - .ssh: SSH keys and configuration+if TYPE_CHECKING:+ from .._base import ToolBase+else:+ ToolBase = "ToolBase"class PermissionEngine:@@ -70,54 +28,30 @@ class PermissionEngine:The evaluation order is:1. Check deny rules (highest priority)- 2. Check mode-specific logic (EXPLORE, ACCEPT_EDITS, dangerous paths)- 3. Check ask rules+ 2. Check ask rules+ 3. Tool-specific checks (EXPLORE/ACCEPT_EDITS modes, dangerous paths,+ read-only commands, etc.) - bypass-immune4. Check allow rules- 5. Apply default behavior based on permission mode+ 5. BYPASS mode check+ 6. Default behavior (ask)"""def __init__(self,context: PermissionContext,- additional_dangerous_files: list[str] | None = None,- additional_dangerous_directories: list[str] | None = None,- ):+ ) -> None:"""Initialize the permission engine.Args:context (`PermissionContext`):The permission context containing rules and mode- additional_dangerous_files (`list[str] | None`, optional):- Additional dangerous files to check- (added to built-in defaults). Use this to add project-specific- sensitive files like '.env' or '.secrets'.- additional_dangerous_directories (`list[str] | None`, optional):- Additional dangerous directories- to check (added to built-in defaults). Use this to add- project-specific sensitive directories.Example:>>> context = PermissionContext(mode=PermissionMode.ACCEPT_EDITS)- >>> engine = PermissionEngine(- ... context,- ... additional_dangerous_files=['.env', '.secrets'],- ... additional_dangerous_directories=['secrets/']- ... )+ >>> engine = PermissionEngine(context)"""self.context = context- # Merge built-in and additional dangerous paths- self.dangerous_files = DEFAULT_DANGEROUS_FILES.copy()- if additional_dangerous_files:- self.dangerous_files.extend(additional_dangerous_files)-- self.dangerous_directories = DEFAULT_DANGEROUS_DIRECTORIES.copy()- if additional_dangerous_directories:- self.dangerous_directories.extend(additional_dangerous_directories)-- # Initialize bash parser- self._bash_parser = BashCommandParser()-def add_rule(self, rule: PermissionRule) -> None:"""Add a permission rule to the context.@@ -149,22 +83,28 @@ class PermissionEngine:async def check_permission(self,tool_call: ToolCallBlock,+ tool: ToolBase,) -> PermissionDecision:"""Check permission for a tool execution request.The evaluation order:1. Tool-level deny rules (highest priority)2. Tool-level ask rules- 3. Tool-specific checks (dangerous paths, content rules), bypass-immune- 4. Allow rules (exact + content-specific)- 5. Mode-specific logic (ACCEPT_EDITS auto-allow)- 6. Read-only check (for Bash commands)- 7. BYPASS mode check- 8. Default behavior (passthrough → ask)+ 3. Tool-specific checks (bypass-immune):+ - EXPLORE mode logic (read-only tools auto-allowed)+ - ACCEPT_EDITS mode logic (file edits in working dir auto-allowed)+ - Dangerous path checks (safety checks)+ - Read-only command checks (for Bash)+ - Other tool-specific permission logic+ 4. Allow rules+ 5. BYPASS mode check+ 6. Default behavior (ask)Args:tool_call (`ToolCallBlock`):The tool call block containing tool name and input+ tool (`ToolBase`):+ The tool instance being called (used for tool-specific checks)Returns:`PermissionDecision`:@@ -175,22 +115,26 @@ class PermissionEngine:input_data = json.loads(tool_call.input)# 1. Check tool-level deny rules (highest priority)- deny_decision = self._check_deny_rules(tool_name, input_data)+ deny_decision = self._check_deny_rules(tool, input_data)if deny_decision:return deny_decision# 2. Check tool-level ask rules- ask_decision = self._check_ask_rules(tool_name, input_data)+ ask_decision = self._check_ask_rules(tool, input_data)if ask_decision:# Generate suggestions for ASK decisionsask_decision.suggested_rules = self._generate_suggestions(tool_call,+ tool,)return ask_decision# 3. Tool-specific permission checks (dangerous paths, etc.)# These are bypass-immune- tool_decision = self._tool_check_permissions(tool_name, input_data)+ tool_decision = await self._tool_check_permissions(+ input_data,+ tool,+ )# 3a. Tool denied permission (bypass-immune)if tool_decision and tool_decision.behavior == PermissionBehavior.DENY:@@ -212,34 +156,16 @@ class PermissionEngine:):tool_decision.suggested_rules = self._generate_suggestions(tool_call,+ tool,)return tool_decision# 4. Check allow rules- allow_decision = self._check_allow_rules(tool_name, input_data)+ allow_decision = self._check_allow_rules(tool, input_data)if allow_decision:return allow_decision- # 5. Mode-specific auto-allow (ACCEPT_EDITS)- if self.context.mode == PermissionMode.ACCEPT_EDITS:- mode_decision = self._check_accept_edits_mode(- tool_name,- input_data,- )- if mode_decision:- return mode_decision-- # 6. Read-only check (for Bash commands)- if tool_name == "Bash":- command = input_data.get("command", "")- if self._bash_parser.is_read_only_command(command):- return PermissionDecision(- behavior=PermissionBehavior.ALLOW,- message="Permission granted for read-only command",- decision_reason="Read-only command is allowed",- )-- # 7. BYPASS mode check+ # 5. BYPASS mode checkif self.context.mode == PermissionMode.BYPASS:return PermissionDecision(behavior=PermissionBehavior.ALLOW,@@ -247,402 +173,124 @@ class PermissionEngine:decision_reason="Bypass mode allows all operations",)- # 8. Default behavior (passthrough → ask)+ # 7. Default behavior (passthrough → ask)default_decision = self._default_decision_ask(tool_name)default_decision.suggested_rules = self._generate_suggestions(tool_call,+ tool,)return default_decision- def _tool_check_permissions(+ async def _tool_check_permissions(self,- tool_name: str,input_data: dict[str, Any],+ tool: ToolBase,) -> PermissionDecision | None:"""Tool-specific permission checks.This includes:- EXPLORE mode logic (read-only tools only)- - Dangerous path checks (safety checks) - bypass-immune-- Note: ACCEPT_EDITS mode logic is handled separately after allow rules.+ - Tool's own check_permissions() methodArgs:- tool_name (`str`):- The name of the toolinput_data (`dict[str, Any]`):The tool input data+ tool (`ToolBase`):+ The tool instance being called (used for tool-specific checks)Returns:`PermissionDecision | None`:PermissionDecision if tool has specific logic, None forpassthrough"""- # EXPLORE mode: read-only tools only- if self.context.mode == PermissionMode.EXPLORE:- explore_decision = self._check_explore_mode(tool_name)- if explore_decision:- return explore_decision-- # Check dangerous paths for file operations and bash commands- # This is a safety check that is bypass-immune- dangerous_path_decision = self._check_dangerous_paths(- tool_name,+ # EXPLORE and ACCEPT_EDITS modes: check read-only tool handling+ if self.context.mode in (+ PermissionMode.EXPLORE,+ PermissionMode.ACCEPT_EDITS,+ ):+ mode_decision = self._check_explore_mode(tool)+ if mode_decision:+ return mode_decision++ # Call tool's own check_permissions method if available+ decision = await tool.check_permissions(input_data,+ self.context,)- if dangerous_path_decision:- return dangerous_path_decision+ # If tool returns PASSTHROUGH, continue with Engine's logic+ if decision.behavior != PermissionBehavior.PASSTHROUGH:+ return decision# No specific tool logic, passthroughreturn None- def _check_dangerous_paths(- self,- tool_name: str,- input_data: dict[str, Any],- ) -> PermissionDecision | None:- """Check for dangerous paths in file operations and bash commands.-- This is a safety check that is bypass-immune.- Uses tree-sitter to extract file paths from bash commands.-- Args:- tool_name (`str`):- The name of the tool- input_data (`dict[str, Any]`):- The tool input data-- Returns:- `PermissionDecision | None`:- ASK decision if dangerous path detected, None otherwise- """- # Check Write/Edit tools- if tool_name in ["Write", "Edit"]:- file_path = input_data.get("file_path")- if file_path and self._is_dangerous_path(file_path):- return PermissionDecision(- behavior=PermissionBehavior.ASK,- message=f"Permission required: {tool_name} operation on "- f"sensitive file {file_path}",- decision_reason="Safety check: dangerous file or "- "directory",- )-- # Check Bash tool for dangerous paths in commands- if tool_name == "Bash":- command = input_data.get("command", "")- dangerous_paths = self._extract_dangerous_paths_from_bash(command)- if dangerous_paths:- paths_str = ", ".join(dangerous_paths)- return PermissionDecision(- behavior=PermissionBehavior.ASK,- message=f"Permission required: Bash command operates on "- f"sensitive paths: {paths_str}",- decision_reason="Safety check: dangerous file or "- "directory in bash command",- )-- return None-- def _extract_dangerous_paths_from_bash(- self,- command: str,- ) -> list[str]:- """Extract dangerous paths from a bash command using tree-sitter.-- Checks for dangerous paths in:- - File-manipulating commands (rm, mv, cp, chmod, chown, sed, touch)- - Output redirections (>, >>)-- Args:- command (`str`):- The bash command string-- Returns:- `list[str]`:- List of dangerous paths found in the command- """- dangerous_paths = []-- # Use tree-sitter to extract file paths- file_paths = self._bash_parser.extract_file_paths(command)-- for _cmd_name, path in file_paths:- if self._is_dangerous_path(path):- dangerous_paths.append(path)-- return dangerous_paths-- def _check_explore_mode(self, tool_name: str) -> PermissionDecision | None:- """Check permissions in EXPLORE (read-only) mode.-- Args:- tool_name (`str`):- The name of the tool-- Returns:- `PermissionDecision | None`:- ALLOW for read-only tools, DENY for modification tools- """- # Read-only tools are allowed- read_only_tools = ["Read", "Grep", "Glob"]- if tool_name in read_only_tools:- return PermissionDecision(- behavior=PermissionBehavior.ALLOW,- message=(- f"Permission granted for {tool_name} (explore mode - "- f"read-only tool)"- ),- decision_reason="Explore mode allows read-only operations",- )-- # Modification tools are denied- modification_tools = ["Write", "Edit", "Bash", "PowerShell"]- if tool_name in modification_tools:- return PermissionDecision(- behavior=PermissionBehavior.DENY,- message=(- f"Permission denied for {tool_name} (explore mode is "- f"read-only)"- ),- decision_reason="Explore mode does not allow modifications",- )-- # Other tools: no special handling- return None-- def _check_accept_edits_mode(+ def _check_explore_mode(self,- tool_name: str,- input_data: dict[str, Any],+ tool: ToolBase,) -> PermissionDecision | None:- """Check permissions in ACCEPT_EDITS mode.+ """Check permissions for read-only tools in EXPLORE and+ ACCEPT_EDITS modes.- In ACCEPT_EDITS mode:- - Dangerous paths are NOT auto-allowed- (handled by _check_dangerous_paths)- - File writes in working directories are auto-allowed- - File reads in working directories are auto-allowed- - Common filesystem commands (mkdir, rm, mv, cp) are auto-allowed+ EXPLORE mode: only allows read-only tools, denies modifications+ ACCEPT_EDITS mode: allows read-only tools (no restrictions)Args:- tool_name (`str`):- The name of the tool- input_data (`dict[str, Any]`):- The tool input data+ tool (`ToolBase`):+ The tool instance being called (used to check is_read_only)Returns:`PermissionDecision | None`:- ALLOW if operation is safe and in working directory,+ ALLOW for read-only tools in EXPLORE/ACCEPT_EDITS modes,+ DENY for modification tools in EXPLORE mode,None otherwise"""- # Handle Write tool- if tool_name == "Write":- file_path = input_data.get("file_path")- if not file_path:- return None-- # Dangerous paths are already checked in _check_dangerous_paths- # Here we only check if in working directory- if self._path_in_allowed_working_path(file_path):- return PermissionDecision(- behavior=PermissionBehavior.ALLOW,- message=f"Permission granted for writing {file_path} "- f"(accept edits mode - in working directory)",- decision_reason="File is in working directory and not "- "a dangerous path",- updated_input=input_data,- )-- # Handle Read tool- if tool_name == "Read":- file_path = input_data.get("file_path")- if file_path and self._path_in_allowed_working_path(file_path):+ # EXPLORE mode: allow read-only, deny modifications+ if self.context.mode == PermissionMode.EXPLORE:+ if tool.is_read_only:return PermissionDecision(behavior=PermissionBehavior.ALLOW,- message=f"Permission granted for reading {file_path} "- f"(accept edits mode - in working directory)",- decision_reason="File is in working directory",- updated_input=input_data,+ message=(+ f"Permission granted for {tool.name} "+ f"(explore mode - read-only tool)"+ ),+ decision_reason="Explore mode allows read-only operations",)-- # Handle Edit tool- if tool_name == "Edit":- file_path = input_data.get("file_path")- if not file_path:- return None-- # Dangerous paths are already checked in _check_dangerous_paths- # Here we only check if in working directory- if self._path_in_allowed_working_path(file_path):+ else:return PermissionDecision(- behavior=PermissionBehavior.ALLOW,- message=f"Permission granted for editing {file_path} "- f"(accept edits mode - in working directory)",- decision_reason="File is in working directory and not "- "a dangerous path",- updated_input=input_data,+ behavior=PermissionBehavior.DENY,+ message=(+ f"Permission denied for {tool.name} "+ f"(explore mode is read-only)"+ ),+ decision_reason="Explore mode does not allow "+ "modifications",)- # Handle Bash tool - auto-allow common filesystem commands- if tool_name == "Bash":- command = input_data.get("command", "")- filesystem_commands = [- "mkdir",- "touch",- "rm",- "rmdir",- "mv",- "cp",- "sed",- ]- base_command = (- command.strip().split()[0] if command.strip() else ""- )-- if base_command in filesystem_commands:+ # ACCEPT_EDITS mode: allow read-only tools+ if self.context.mode == PermissionMode.ACCEPT_EDITS:+ if tool.is_read_only:return PermissionDecision(behavior=PermissionBehavior.ALLOW,- message=f"Permission granted for '{base_command}' "- f"command (accept edits mode - filesystem command)",- decision_reason=f"Filesystem command '{base_command}' "- f"is auto-allowed in accept edits mode",- updated_input=input_data,+ message=(+ f"Permission granted for {tool.name} "+ f"(accept edits mode - read-only tool)"+ ),+ decision_reason="Accept edits mode allows read-only "+ "operations",)return None- def _is_dangerous_path(self, file_path: str) -> bool:- """Check if a file path is dangerous (sensitive file or directory).-- A path is considered dangerous if:- 1. The filename matches a dangerous file (e.g., .bashrc, .gitconfig)- 2. Any path segment matches a dangerous directory (e.g., .git, .ssh)-- Case-insensitive matching is used to prevent bypasses on- case-insensitive filesystems (macOS, Windows).-- Args:- file_path (`str`):- The file path to check-- Returns:- `bool`:- True if the path is dangerous and should require explicit- permission-- Example:- >>> self._is_dangerous_path("/home/user/.bashrc")- True- >>> self._is_dangerous_path("/home/user/.git/config")- True- >>> self._is_dangerous_path("/home/user/project/main.py")- False- """- # Normalize path- abs_path = os.path.abspath(os.path.expanduser(file_path))-- # Split path into segments- path_parts = Path(abs_path).parts- path_parts_lower = [p.lower() for p in path_parts]-- # Check if filename matches dangerous files (case-insensitive)- filename = os.path.basename(abs_path)- filename_lower = filename.lower()- for dangerous_file in self.dangerous_files:- if filename_lower == dangerous_file.lower():- return True-- # Check if any path segment matches dangerous directories- # (case-insensitive)- for dangerous_dir in self.dangerous_directories:- dangerous_dir_lower = dangerous_dir.lower()- if dangerous_dir_lower in path_parts_lower:- return True-- return False-- def _path_in_allowed_working_path(self, file_path: str) -> bool:- """Check if a file path is within any allowed working directory.-- Args:- file_path (`str`):- The file path to check-- Returns:- `bool`:- True if the path is within any allowed working directory- """- # Get all working directories (current directory + additional)- all_working_dirs = self._get_all_working_directories()-- # Check if file path is in any working directory- for working_dir in all_working_dirs:- if self._path_in_working_path(file_path, working_dir):- return True-- return False-- def _get_all_working_directories(self) -> list[str]:- """Get all allowed working directories.-- Returns:- `list[str]`:- List of absolute directory paths- """- # Current working directory (always included)- current_dir = os.getcwd()-- # Additional working directories- additional_dirs = list(self.context.working_directories.keys())-- return [current_dir] + additional_dirs-- def _path_in_working_path(self, file_path: str, working_dir: str) -> bool:- """Check if a file path is within a specific working directory.-- Args:- file_path (`str`):- The file path to check- working_dir (`str`):- The working directory path-- Returns:- `bool`:- True if file_path is inside working_dir- """-- # Convert to absolute paths- abs_file_path = os.path.abspath(file_path)- abs_working_dir = os.path.abspath(working_dir)-- # Calculate relative path- try:- rel_path = os.path.relpath(abs_file_path, abs_working_dir)- except ValueError:- # Different drives on Windows- return False-- # Check if path traversal is present (..)- if rel_path.startswith(".."):- return False-- # Check if it's an absolute path (means not in working directory)- if os.path.isabs(rel_path):- return False-- return True-def _check_deny_rules(self,- tool_name: str,+ tool: ToolBase,input_data: dict[str, Any],) -> PermissionDecision | None:"""Check if any deny rules match the request.Args:- tool_name (`str`):- The name of the tool+ tool (`ToolBase`):+ The tool instance being calledinput_data (`dict[str, Any]`):The tool input data@@ -650,26 +298,26 @@ class PermissionEngine:`PermissionDecision | None`:DENY decision if a rule matches, None otherwise"""- rules = self.context.deny_rules.get(tool_name, [])+ rules = self.context.deny_rules.get(tool.name, [])for rule in rules:- if self._rule_matches(rule, input_data):+ if self._rule_matches(tool, rule, input_data):return PermissionDecision(behavior=PermissionBehavior.DENY,- message=f"Permission to use {tool_name} has been denied",+ message=f"Permission to use {tool.name} has been denied",decision_reason=f"Rule: {rule.rule_content}",)return Nonedef _check_ask_rules(self,- tool_name: str,+ tool: ToolBase,input_data: dict[str, Any],) -> PermissionDecision | None:"""Check if any ask rules match the request.Args:- tool_name (`str`):- The name of the tool+ tool (`ToolBase`):+ The tool instance being called (used for tool-specific checks)input_data (`dict[str, Any]`):The tool input data@@ -677,26 +325,26 @@ class PermissionEngine:`PermissionDecision | None`:ASK decision if a rule matches, None otherwise"""- rules = self.context.ask_rules.get(tool_name, [])+ rules = self.context.ask_rules.get(tool.name, [])for rule in rules:- if self._rule_matches(rule, input_data):+ if self._rule_matches(tool, rule, input_data):return PermissionDecision(behavior=PermissionBehavior.ASK,- message=f"Permission required for {tool_name}",+ message=f"Permission required for {tool.name}",decision_reason=f"Rule: {rule.rule_content}",)return Nonedef _check_allow_rules(self,- tool_name: str,+ tool: ToolBase,input_data: dict[str, Any],) -> PermissionDecision | None:"""Check if any allow rules match the request.Args:- tool_name (`str`):- The name of the tool+ tool (`ToolBase`):+ The tool instance being called (used for tool-specific checks)input_data (`dict[str, Any]`):The tool input data@@ -704,18 +352,19 @@ class PermissionEngine:`PermissionDecision | None`:ALLOW decision if a rule matches, None otherwise"""- rules = self.context.allow_rules.get(tool_name, [])+ rules = self.context.allow_rules.get(tool.name, [])for rule in rules:- if self._rule_matches(rule, input_data):+ if self._rule_matches(tool, rule, input_data):return PermissionDecision(behavior=PermissionBehavior.ALLOW,- message=f"Permission granted for {tool_name}",+ message=f"Permission granted for {tool.name}",updated_input=input_data,)return Nonedef _rule_matches(self,+ tool: ToolBase,rule: PermissionRule,input_data: dict[str, Any],) -> bool:@@ -740,119 +389,8 @@ class PermissionEngine:if not rule.rule_content:return True- # Route to appropriate matching logic based on tool type- if rule.tool_name == "Bash":- return self._match_bash_rule(rule.rule_content, input_data)-- if rule.tool_name in ["Write", "Read"]:- return self._match_filesystem_rule(rule.rule_content, input_data)-- return self._match_generic_rule(rule.rule_content, input_data)-- def _match_bash_rule(- self,- pattern: str,- input_data: dict[str, Any],- ) -> bool:- """Match Bash command using substring or prefix matching.-- Supports two matching modes:- 1. Prefix pattern (e.g., "git:*"): matches commands starting- with "git "- 2. Substring pattern (e.g., "npm install"): matches if pattern is- in command-- Args:- pattern (`str`):- The command pattern to match- input_data (`dict[str, Any]`):- Must contain a "command" key with the command string-- Returns:- `bool`:- True if pattern matches the command-- Examples:- pattern="git:*" matches "git status", "git add .", etc.- pattern="npm install" matches "npm install express"- """- command = input_data.get("command", "")-- # Check if pattern is a prefix pattern (ends with :*)- if pattern.endswith(":*"):- # Extract prefix (remove :*)- prefix = pattern[:-2].strip()- # Match if command starts with prefix followed by space or is- # exactly the prefix- return command.startswith(prefix + " ") or command == prefix-- # Otherwise, use substring matching- return pattern in command-- def _match_filesystem_rule(- self,- pattern: str,- input_data: dict[str, Any],- ) -> bool:- """Match file path using glob pattern matching.-- Args:- pattern (`str`):- The glob pattern to match (e.g., "src/**", "*.py")- input_data (`dict[str, Any]`):- Must contain a "file_path" key with the file path-- Returns:- `bool`:- True if the file path matches the glob pattern-- Example:- pattern="src/**" matches file_path="src/main.py"- pattern="**/.bashrc" matches file_path="/home/user/.bashrc"- """- file_path = input_data.get("file_path", "")- if not file_path:- return False-- # Try both fnmatch and pathlib matching for compatibility- try:- # fnmatch for simple patterns- if fnmatch.fnmatch(file_path, pattern):- return True-- # pathlib for more complex glob patterns- path_obj = Path(file_path)- if path_obj.match(pattern):- return True- except (ValueError, Exception):- # If pattern is invalid, fall back to substring matching- return pattern in file_path-- return False-- def _match_generic_rule(- self,- pattern: str,- input_data: dict[str, Any],- ) -> bool:- """Generic pattern matching for other tools.-- Performs substring matching against all string values in input_data.-- Args:- pattern (`str`):- The pattern to match- input_data (`dict[str, Any]`):- The tool input data-- Returns:- `bool`:- True if pattern is found in any string value- """- for value in input_data.values():- if isinstance(value, str) and pattern in value:- return True- return False+ # Try to use tool's match_rule method if available+ return tool.match_rule(rule.rule_content, input_data)def _default_decision_ask(self, tool_name: str) -> PermissionDecision:"""Return default ASK decision.@@ -885,6 +423,7 @@ class PermissionEngine:def _generate_suggestions(self,tool_call: ToolCallBlock,+ tool: ToolBase,) -> List[PermissionRule]:"""Generate suggested permission rules from a tool call.@@ -900,127 +439,16 @@ class PermissionEngine:Args:tool_call (`ToolCallBlock`):The tool call block containing name and parameters+ tool (`ToolBase`):+ The tool instance being called (used for tool-specific+ suggestions)Returns:`List[PermissionRule]`:List of suggested permission rules (usually 1, max 5 forcompound commands)"""- tool_name = tool_call.name-- if tool_name == "Bash":- return self._generate_bash_suggestions(tool_call)-- if tool_name in ["Read", "Write", "Edit"]:- return self._generate_file_suggestions(tool_call)-- return self._generate_exact_suggestions(tool_call)-- def _generate_bash_suggestions(- self,- tool_call: "ToolCallBlock",- ) -> List[PermissionRule]:- """Generate suggestions for Bash commands.-- Generates prefix rules based on command + subcommand (two words).- For example, "git commit -m 'xxx'" generates "git commit:*".-- Args:- tool_call (`ToolCallBlock`):- The tool call block containing name and input-- Returns:- `List[PermissionRule]`:- List of suggested permission rules based on command prefixes- """- input_data = json.loads(tool_call.input)- command = input_data.get("command", "")- if not command:- return []-- # Use bash parser to extract command prefixes- prefixes = self._bash_parser.extract_command_prefixes(- command,- max_prefixes=5,- )-- if not prefixes:- # Cannot extract any prefix, return empty- return []-- # Generate rules for each prefix- rules = []- for prefix in prefixes:- rules.append(- PermissionRule(- tool_name="Bash",- rule_content=f"{prefix}:*",- behavior=PermissionBehavior.ALLOW,- source="suggested",- ),- )-- return rules-- def _generate_file_suggestions(- self,- tool_call: ToolCallBlock,- ) -> List[PermissionRule]:- """Generate suggestions for file operations.-- Suggests allowing the entire directory containing the file.-- Args:- tool_call (`ToolCallBlock`):- The tool call block containing name and input-- Returns:- `List[PermissionRule]`:- List of suggested permission rules based on file directory- """input_data = json.loads(tool_call.input)- file_path = input_data.get("file_path", "")- if not file_path:- return []-- # Extract directory- directory = os.path.dirname(file_path)- if directory:- return [- PermissionRule(- tool_name=tool_call.name,- rule_content=f"{directory}/**",- behavior=PermissionBehavior.ALLOW,- source="suggested",- ),- ]-- return []- def _generate_exact_suggestions(- self,- tool_call: ToolCallBlock,- ) -> List[PermissionRule]:- """Generate exact match rule (fallback strategy).-- Used when no specific suggestion strategy is available.-- Args:- tool_call (`ToolCallBlock`):- The tool call block containing name and input-- Returns:- `List[PermissionRule]`:- List containing a single exact-match permission rule- """- input_data = json.loads(tool_call.input)- rule_content = json.dumps(input_data, sort_keys=True)-- return [- PermissionRule(- tool_name=tool_call.name,- rule_content=rule_content,- behavior=PermissionBehavior.ALLOW,- source="suggested",- ),- ]+ # Try to use tool's generate_suggestions method if available+ return tool.generate_suggestions(input_data)diff --git a/src/agentscope/tool/_permission/_types.py b/src/agentscope/tool/_permission/_types.pyindex 76ca32afe..6561f1e06 100644--- a/src/agentscope/tool/_permission/_types.py+++ b/src/agentscope/tool/_permission/_types.py@@ -59,8 +59,17 @@ class PermissionMode(Enum):class PermissionBehavior(Enum):- """The behavior of permission."""+ """The behavior of permission.++ Attributes:+ ALLOW: Allow the operation+ DENY: Deny the operation+ ASK: Ask the user for permission+ PASSTHROUGH: Let the permission engine continue with rule matching+ (used by tools to defer decision to the engine)+ """ALLOW = "allow"DENY = "deny"ASK = "ask"+ PASSTHROUGH = "passthrough"diff --git a/src/agentscope/tool/_toolkit.py b/src/agentscope/tool/_toolkit.pyindex 59ffaca82..c15ff5758 100644--- a/src/agentscope/tool/_toolkit.py+++ b/src/agentscope/tool/_toolkit.py@@ -23,7 +23,7 @@ from pydantic import (create_model,)-from ._builtin import ResetTools+from ._builtin import ResetTools, Edit, Write, Readfrom ._base import ToolBasefrom ._adapters import _FunctionToolfrom ._response import ToolResponse, ToolChunk@@ -192,6 +192,7 @@ Check "{dir}/SKILL.md" for how to use this skill"""super().__init__()self.tools: dict[str, RegisteredTool] = OrderedDict()+if tools:for tool in tools:# TODO: handle the name conflict here@@ -516,7 +517,9 @@ Check "{dir}/SKILL.md" for how to use this skill"""tool_response = ToolResponse(id=tool_call.id)# Check- available_tools = self._get_available_tools(state.activated_groups)+ available_tools = self._get_available_tools(+ state.tool_context.activated_groups,+ )if tool_call.name not in available_tools:# Not activate@@ -561,9 +564,9 @@ Check "{dir}/SKILL.md" for how to use this skill"""kwargs = _json_loads_with_repair(tool_call.input)# TODO: we should be build a mechanism to support state injection in- # the future instead of hard coding here.- if tool_call.name == self.builtin_meta_tool.tool.name:- kwargs["state"] = state+ # the future instead of hard coding here.+ if isinstance(tool_func, (ResetTools, Read, Write, Edit)):+ kwargs["_agent_state"] = state# Async functiontry:diff --git a/tests/builtin_bash_test.py b/tests/builtin_bash_test.pynew file mode 100644index 000000000..861f393ea--- /dev/null+++ b/tests/builtin_bash_test.py@@ -0,0 +1,477 @@+# -*- coding: utf-8 -*-+"""Bash tool test case."""+import sys+import unittest+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.tool import ToolChunk, PermissionContext, Bash+from agentscope.message import TextBlock+++ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)+class BashToolTest(IsolatedAsyncioTestCase):+ """The bash tool test case."""++ async def asyncSetUp(self) -> None:+ """The async setup method."""+ self.bash_tool = Bash()++ async def test_tool_properties(self) -> None:+ """Test bash tool properties."""+ self.assertEqual(self.bash_tool.name, "Bash")+ self.assertIsInstance(self.bash_tool.description, str)+ self.assertIsInstance(self.bash_tool.input_schema, dict)+ self.assertFalse(self.bash_tool.is_mcp)+ self.assertFalse(self.bash_tool.is_read_only)+ self.assertFalse(self.bash_tool.is_concurrency_safe)++ async def test_check_permissions(self) -> None:+ """Test bash tool permission checking."""+ from agentscope.tool import PermissionBehavior++ context = PermissionContext()+ tool_input = {"command": "echo hello"}+ decision = await self.bash_tool.check_permissions(tool_input, context)++ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ async def test_simple_command(self) -> None:+ """Test executing a simple bash command."""+ chunks = []+ async for chunk in self.bash_tool(command="echo 'Hello World'"):+ chunks.append(chunk)++ self.assertEqual(len(chunks), 1)+ self.assertIsInstance(chunks[0], ToolChunk)+ self.assertEqual(chunks[0].state, "running")+ self.assertTrue(chunks[0].is_last)+ self.assertEqual(len(chunks[0].content), 1)+ self.assertIsInstance(chunks[0].content[0], TextBlock)+ self.assertIn("Hello World", chunks[0].content[0].text)++ async def test_command_with_error(self) -> None:+ """Test executing a command that fails."""+ chunks = []+ async for chunk in self.bash_tool(command="exit 1"):+ chunks.append(chunk)++ self.assertEqual(len(chunks), 1)+ self.assertEqual(chunks[0].state, "error")+ self.assertTrue(chunks[0].is_last)++ @unittest.skipIf(+ sys.platform == "win32",+ "sleep command not available on Windows",+ )+ async def test_command_timeout(self) -> None:+ """Test command timeout."""+ chunks = []+ async for chunk in self.bash_tool(+ command="sleep 10",+ timeout=100, # 100ms timeout+ ):+ chunks.append(chunk)++ self.assertEqual(len(chunks), 1)+ self.assertEqual(chunks[0].state, "error")+ self.assertIn("timed out", chunks[0].content[0].text.lower())+++ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)+class BashToolInjectionCheckTest(IsolatedAsyncioTestCase):+ """Test injection detection in Bash tool permission checks."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.bash_tool = Bash()+ self.context = PermissionContext()++ async def test_command_substitution_blocked(self) -> None:+ """Test that command substitution is blocked."""+ from agentscope.tool import PermissionBehavior++ test_cases = [+ "ls $(pwd)",+ "rm $(find . -name '*.tmp')",+ "cat `which python`",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ decision = await self.bash_tool.check_permissions(+ {"command": cmd},+ self.context,+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("command_substitution", decision.message)++ async def test_control_flow_blocked(self) -> None:+ """Test that control flow structures are blocked."""+ from agentscope.tool import PermissionBehavior++ test_cases = [+ "for f in *.txt; do cat $f; done",+ "while read line; do echo $line; done < file.txt",+ "if [ -f file.txt ]; then cat file.txt; fi",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ decision = await self.bash_tool.check_permissions(+ {"command": cmd},+ self.context,+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn(+ "cannot be statically analyzed",+ decision.message,+ )++ async def test_subshell_blocked(self) -> None:+ """Test that subshells are blocked."""+ from agentscope.tool import PermissionBehavior++ cmd = "(cd /tmp && ls)"+ decision = await self.bash_tool.check_permissions(+ {"command": cmd},+ self.context,+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("subshell", decision.message)++ async def test_injection_check_before_readonly(self) -> None:+ """Test that injection check runs before read-only check."""+ from agentscope.tool import PermissionBehavior++ # ls is read-only, but $(rm -rf /) is dangerous+ cmd = "ls $(rm -rf /)"+ decision = await self.bash_tool.check_permissions(+ {"command": cmd},+ self.context,+ )+ # Should be blocked by injection check, not allowed as read-only+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("command_substitution", decision.message)++ async def test_safe_commands_pass(self) -> None:+ """Test that safe commands pass injection check."""+ from agentscope.tool import PermissionBehavior++ safe_commands = [+ "ls -la",+ "cat file.txt",+ "git status",+ "echo 'hello world'",+ ]+ for cmd in safe_commands:+ with self.subTest(cmd=cmd):+ decision = await self.bash_tool.check_permissions(+ {"command": cmd},+ self.context,+ )+ # Should pass injection check (either ALLOW or PASSTHROUGH)+ self.assertNotEqual(decision.behavior, PermissionBehavior.ASK)+ if decision.behavior == PermissionBehavior.ASK:+ self.assertNotIn(+ "cannot be statically analyzed",+ decision.message,+ )++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.bash_tool = None+ self.context = None+++ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)+class BashToolMatchRuleTest(IsolatedAsyncioTestCase):+ """Test cases for Bash tool match_rule and generate_suggestions."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.bash_tool = Bash()++ async def test_match_rule_prefix_pattern(self) -> None:+ """Test match_rule with prefix patterns (e.g., git:*)."""+ # Test exact command match+ self.assertTrue(+ self.bash_tool.match_rule(+ "git:*",+ {"command": "git"},+ ),+ )++ # Test command with arguments+ self.assertTrue(+ self.bash_tool.match_rule(+ "git:*",+ {"command": "git status"},+ ),+ )++ # Test non-matching command+ self.assertFalse(+ self.bash_tool.match_rule(+ "git:*",+ {"command": "npm install"},+ ),+ )++ async def test_match_rule_wildcard_pattern(self) -> None:+ """Test match_rule with wildcard patterns."""+ # Test wildcard matching+ self.assertTrue(+ self.bash_tool.match_rule(+ "git * -m *",+ {"command": "git commit -m 'test'"},+ ),+ )++ # Test non-matching wildcard+ self.assertFalse(+ self.bash_tool.match_rule(+ "git * -m *",+ {"command": "git status"},+ ),+ )++ async def test_match_rule_substring_pattern(self) -> None:+ """Test match_rule with substring patterns."""+ # Test substring matching+ self.assertTrue(+ self.bash_tool.match_rule(+ "install",+ {"command": "npm install package"},+ ),+ )++ # Test non-matching substring+ self.assertFalse(+ self.bash_tool.match_rule(+ "install",+ {"command": "npm run build"},+ ),+ )++ async def test_match_rule_escaped_characters(self) -> None:+ """Test match_rule with escaped characters."""+ # Test escaped asterisk+ self.assertTrue(+ self.bash_tool.match_rule(+ r"echo \*",+ {"command": "echo *"},+ ),+ )++ # Test escaped backslash+ self.assertTrue(+ self.bash_tool.match_rule(+ r"echo \\",+ {"command": "echo \\"},+ ),+ )++ async def test_generate_suggestions(self) -> None:+ """Test generate_suggestions for bash commands."""+ from agentscope.tool import PermissionRule++ # Test two-word command+ suggestions = self.bash_tool.generate_suggestions(+ {"command": "git commit -m 'test'"},+ )++ self.assertIsInstance(suggestions, list)+ self.assertGreater(len(suggestions), 0)+ self.assertIsInstance(suggestions[0], PermissionRule)++ # Should suggest "git commit:*"+ suggestion_contents = [s.rule_content for s in suggestions]+ self.assertIn("git commit:*", suggestion_contents)++ async def test_generate_suggestions_single_word(self) -> None:+ """Test generate_suggestions for single-word commands."""+ suggestions = self.bash_tool.generate_suggestions(+ {"command": "npm install"},+ )++ self.assertGreater(len(suggestions), 0)++ # Should suggest "npm install:*"+ suggestion_contents = [s.rule_content for s in suggestions]+ self.assertIn("npm install:*", suggestion_contents)++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.bash_tool = None+++ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)+class BashToolDangerousRemovalTest(IsolatedAsyncioTestCase):+ """Test dangerous removal path detection in Bash tool."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.bash_tool = Bash()+ self.context = PermissionContext()++ async def test_rm_root_blocked(self) -> None:+ """Test that rm -rf / is blocked."""+ from agentscope.tool import PermissionBehavior++ cmd = "rm -rf /"+ decision = await self.bash_tool.check_permissions(+ {"command": cmd},+ self.context,+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ # Can be blocked by either dangerous command pattern or dangerous+ # removal path check+ self.assertTrue(+ "Dangerous removal operation" in decision.message+ or "dangerous pattern" in decision.message,+ )++ async def test_rm_root_children_blocked(self) -> None:+ """Test that rm -rf /usr, /etc, etc. are blocked."""+ from agentscope.tool import PermissionBehavior++ test_cases = [+ "rm -rf /usr",+ "rm -rf /etc",+ "rm -rf /tmp",+ "rm -rf /var",+ "rm -rf /bin",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ decision = await self.bash_tool.check_permissions(+ {"command": cmd},+ self.context,+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ # Can be blocked by either dangerous command pattern or+ # dangerous removal path check+ self.assertTrue(+ "Dangerous removal operation" in decision.message+ or "dangerous pattern" in decision.message,+ )++ async def test_rm_home_blocked(self) -> None:+ """Test that rm -rf ~ is blocked."""+ from agentscope.tool import PermissionBehavior++ cmd = "rm -rf ~"+ decision = await self.bash_tool.check_permissions(+ {"command": cmd},+ self.context,+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ # Can be blocked by either dangerous command pattern or dangerous+ # removal path check+ self.assertTrue(+ "Dangerous removal operation" in decision.message+ or "dangerous pattern" in decision.message,+ )++ async def test_rm_wildcard_blocked(self) -> None:+ """Test that rm -rf * and rm -rf /* are blocked."""+ from agentscope.tool import PermissionBehavior++ test_cases = [+ "rm -rf *",+ "rm -rf /*",+ "rm -rf /tmp/*",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ decision = await self.bash_tool.check_permissions(+ {"command": cmd},+ self.context,+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ # Can be blocked by either dangerous command pattern or+ # dangerous removal path check+ self.assertTrue(+ "Dangerous removal operation" in decision.message+ or "dangerous pattern" in decision.message,+ )++ async def test_rmdir_dangerous_paths_blocked(self) -> None:+ """Test that rmdir on dangerous paths is blocked."""+ from agentscope.tool import PermissionBehavior++ test_cases = [+ "rmdir /",+ "rmdir /usr",+ "rmdir ~",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ decision = await self.bash_tool.check_permissions(+ {"command": cmd},+ self.context,+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("Dangerous removal operation", decision.message)++ async def test_safe_rm_commands_pass(self) -> None:+ """Test that safe rm commands pass dangerous removal check."""+ from agentscope.tool import PermissionBehavior++ safe_commands = [+ "rm file.txt",+ "rm -f temp.log",+ "rm -rf /tmp/my_project/build",+ "rm -rf ./node_modules",+ ]+ for cmd in safe_commands:+ with self.subTest(cmd=cmd):+ decision = await self.bash_tool.check_permissions(+ {"command": cmd},+ self.context,+ )+ # Should not be blocked by dangerous removal check+ # (may still be blocked by other checks)+ if decision.behavior == PermissionBehavior.ASK:+ self.assertNotIn(+ "Dangerous removal operation",+ decision.message,+ )++ async def test_compound_commands_with_dangerous_removal(self) -> None:+ """Test compound commands containing dangerous removal."""+ from agentscope.tool import PermissionBehavior++ test_cases = [+ "ls && rm -rf /",+ "cd /tmp && rm -rf /usr",+ "echo start; rm -rf ~; echo end",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ decision = await self.bash_tool.check_permissions(+ {"command": cmd},+ self.context,+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ # Can be blocked by either dangerous command pattern or+ # dangerous removal path check+ self.assertTrue(+ "Dangerous removal operation" in decision.message+ or "dangerous pattern" in decision.message,+ )++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.bash_tool = None+ self.context = Nonediff --git a/tests/builtin_edit_test.py b/tests/builtin_edit_test.pynew file mode 100644index 000000000..529350272--- /dev/null+++ b/tests/builtin_edit_test.py@@ -0,0 +1,178 @@+# -*- coding: utf-8 -*-+"""Edit tool test case."""+import os+import tempfile+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.tool import PermissionContext, PermissionBehavior, Edit+++class EditToolTest(IsolatedAsyncioTestCase):+ """The edit tool test case."""++ async def asyncSetUp(self) -> None:+ """The async setup method."""+ self.edit_tool = Edit()+ # Create a temporary file for testing+ self.temp_file = tempfile.NamedTemporaryFile(+ mode="w",+ delete=False,+ suffix=".txt",+ )+ self.temp_file.write("Hello World\nThis is a test\n")+ self.temp_file.close()++ async def asyncTearDown(self) -> None:+ """Clean up temporary files."""+ if os.path.exists(self.temp_file.name):+ os.unlink(self.temp_file.name)++ async def test_tool_properties(self) -> None:+ """Test edit tool properties."""+ self.assertEqual(self.edit_tool.name, "Edit")+ self.assertIsInstance(self.edit_tool.description, str)+ self.assertIsInstance(self.edit_tool.input_schema, dict)+ self.assertFalse(self.edit_tool.is_mcp)+ self.assertFalse(self.edit_tool.is_read_only)+ self.assertFalse(self.edit_tool.is_concurrency_safe)++ async def test_check_permissions(self) -> None:+ """Test edit tool permission checking.++ Edit tool should return PASSTHROUGH for non-dangerous paths,+ allowing PermissionEngine to check allow rules.+ """+ context = PermissionContext()+ tool_input = {"file_path": "/tmp/test.txt"}+ decision = await self.edit_tool.check_permissions(tool_input, context)++ self.assertEqual(decision.behavior, PermissionBehavior.PASSTHROUGH)++ async def test_simple_edit(self) -> None:+ """Test simple file editing."""+ chunk = await self.edit_tool(+ file_path=self.temp_file.name,+ old_string="Hello World",+ new_string="Hello Python",+ )++ self.assertEqual(chunk.state, "running")+ self.assertTrue(chunk.is_last)++ # Verify file content+ with open(self.temp_file.name, "r", encoding="utf-8") as f:+ content = f.read()+ self.assertIn("Hello Python", content)+ self.assertNotIn("Hello World", content)++ async def test_edit_not_found(self) -> None:+ """Test editing with string not found."""+ chunk = await self.edit_tool(+ file_path=self.temp_file.name,+ old_string="NonExistent",+ new_string="Something",+ )++ self.assertEqual(chunk.state, "error")+ self.assertIn("not found", chunk.content[0].text)++ async def test_edit_multiple_occurrences(self) -> None:+ """Test editing with multiple occurrences."""+ # Write file with duplicate content+ with open(self.temp_file.name, "w", encoding="utf-8") as f:+ f.write("test\ntest\ntest\n")++ chunk = await self.edit_tool(+ file_path=self.temp_file.name,+ old_string="test",+ new_string="replaced",+ )++ # Should fail without replace_all+ self.assertEqual(chunk.state, "error")++ async def test_edit_replace_all(self) -> None:+ """Test editing with replace_all flag."""+ # Write file with duplicate content+ with open(self.temp_file.name, "w", encoding="utf-8") as f:+ f.write("test\ntest\ntest\n")++ chunk = await self.edit_tool(+ file_path=self.temp_file.name,+ old_string="test",+ new_string="replaced",+ replace_all=True,+ )++ self.assertEqual(chunk.state, "running")++ # Verify all occurrences replaced+ with open(self.temp_file.name, "r", encoding="utf-8") as f:+ content = f.read()+ self.assertEqual(content.count("replaced"), 3)+ self.assertEqual(content.count("test"), 0)++ async def test_match_rule_glob_pattern(self) -> None:+ """Test match_rule with glob patterns."""+ # Test exact match+ self.assertTrue(+ self.edit_tool.match_rule(+ "test.py",+ {"file_path": "test.py"},+ ),+ )++ # Test wildcard pattern+ self.assertTrue(+ self.edit_tool.match_rule(+ "*.py",+ {"file_path": "test.py"},+ ),+ )++ # Test directory pattern+ self.assertTrue(+ self.edit_tool.match_rule(+ "/tmp/**",+ {"file_path": "/tmp/test.py"},+ ),+ )++ # Test non-matching pattern+ self.assertFalse(+ self.edit_tool.match_rule(+ "*.txt",+ {"file_path": "test.py"},+ ),+ )++ # Test empty file_path+ self.assertFalse(+ self.edit_tool.match_rule(+ "*.py",+ {"file_path": ""},+ ),+ )++ async def test_generate_suggestions(self) -> None:+ """Test generate_suggestions for file operations."""+ from agentscope.tool import PermissionRule++ # Test suggestion for file in subdirectory+ suggestions = self.edit_tool.generate_suggestions(+ {"file_path": "/tmp/project/src/main.py"},+ )++ self.assertIsInstance(suggestions, list)+ self.assertGreater(len(suggestions), 0)+ self.assertIsInstance(suggestions[0], PermissionRule)++ # Should suggest parent directory pattern+ suggestion_contents = [s.rule_content for s in suggestions]+ self.assertIn("/tmp/project/src/**", suggestion_contents)++ # Test suggestion for file in root+ suggestions = self.edit_tool.generate_suggestions(+ {"file_path": "/test.py"},+ )+ self.assertGreater(len(suggestions), 0)diff --git a/tests/builtin_file_cache_test.py b/tests/builtin_file_cache_test.pynew file mode 100644index 000000000..069c3c3f5--- /dev/null+++ b/tests/builtin_file_cache_test.py@@ -0,0 +1,432 @@+# -*- coding: utf-8 -*-+"""File cache test case for Read/Write/Edit tools."""+import os+import tempfile+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.agent import AgentState+from agentscope.tool import Read, Write, Edit+++class FileCacheTest(IsolatedAsyncioTestCase):+ """Test file cache functionality for Read/Write/Edit tools."""++ async def asyncSetUp(self) -> None:+ """The async setup method."""+ self.read_tool = Read()+ self.write_tool = Write()+ self.edit_tool = Edit()+ self.state = AgentState()++ # Create a temporary directory+ self.temp_dir = tempfile.mkdtemp()+ self.test_file = os.path.join(self.temp_dir, "test.txt")++ async def asyncTearDown(self) -> None:+ """Clean up temporary files."""+ import shutil++ if os.path.exists(self.temp_dir):+ shutil.rmtree(self.temp_dir)++ async def test_edit_without_read(self) -> None:+ """Test Edit fails when file not read first."""+ # Create a file+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("Hello World\n")++ # Try to edit without reading first+ chunk = await self.edit_tool(+ file_path=self.test_file,+ old_string="Hello",+ new_string="Hi",+ _agent_state=self.state,+ )++ # Should fail with error+ self.assertEqual(chunk.state, "error")+ self.assertIn("must first read", chunk.content[0].text)++ async def test_write_without_read(self) -> None:+ """Test Write fails when existing file not read first."""+ # Create a file+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("Existing content\n")++ # Try to write without reading first+ chunk = await self.write_tool(+ file_path=self.test_file,+ content="New content\n",+ _agent_state=self.state,+ )++ # Should fail with error+ self.assertEqual(chunk.state, "error")+ self.assertIn("has not been read yet", chunk.content[0].text)++ async def test_write_new_file_without_read(self) -> None:+ """Test Write succeeds for new file without reading."""+ new_file = os.path.join(self.temp_dir, "new_file.txt")++ # Write to a new file (doesn't exist yet)+ chunk = await self.write_tool(+ file_path=new_file,+ content="New file content\n",+ _agent_state=self.state,+ )++ # Should succeed+ self.assertEqual(chunk.state, "running")+ self.assertTrue(os.path.exists(new_file))++ with open(new_file, "r", encoding="utf-8") as f:+ content = f.read()+ self.assertEqual(content, "New file content\n")++ async def test_edit_after_read(self) -> None:+ """Test Edit succeeds after reading file."""+ # Create a file+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("Hello World\n")++ # Read the file first+ read_chunk = await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )+ self.assertEqual(read_chunk.state, "running")++ # Now edit should succeed+ edit_chunk = await self.edit_tool(+ file_path=self.test_file,+ old_string="Hello",+ new_string="Hi",+ _agent_state=self.state,+ )++ self.assertEqual(edit_chunk.state, "running")++ # Verify file was edited+ with open(self.test_file, "r", encoding="utf-8") as f:+ content = f.read()+ self.assertEqual(content, "Hi World\n")++ async def test_write_after_read(self) -> None:+ """Test Write succeeds after reading file."""+ # Create a file+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("Old content\n")++ # Read the file first+ read_chunk = await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )+ self.assertEqual(read_chunk.state, "running")++ # Now write should succeed+ write_chunk = await self.write_tool(+ file_path=self.test_file,+ content="New content\n",+ _agent_state=self.state,+ )++ self.assertEqual(write_chunk.state, "running")++ # Verify file was overwritten+ with open(self.test_file, "r", encoding="utf-8") as f:+ content = f.read()+ self.assertEqual(content, "New content\n")++ async def test_cache_invalidation_after_file_deletion(self) -> None:+ """Test cache handles file deletion gracefully."""+ # Create a file+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("Test content\n")++ # Read the file to cache it+ read_chunk = await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )+ self.assertEqual(read_chunk.state, "running")++ # Verify cache exists+ self.assertEqual(len(self.state.tool_context.read_file_cache), 1)+ self.assertEqual(+ self.state.tool_context.read_file_cache[0].file_path,+ self.test_file,+ )++ # Delete the file+ os.unlink(self.test_file)++ # Try to edit - should fail with "File not found" error+ edit_chunk = await self.edit_tool(+ file_path=self.test_file,+ old_string="Test",+ new_string="New",+ _agent_state=self.state,+ )++ # Should fail with "File not found" error+ self.assertEqual(edit_chunk.state, "error")+ self.assertIn("not found", edit_chunk.content[0].text.lower())++ # Try to read again - should also fail+ read_chunk2 = await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )+ self.assertEqual(read_chunk2.state, "error")+ self.assertIn("does not exist", read_chunk2.content[0].text)++ async def test_cache_invalidation_after_file_modification(self) -> None:+ """Test cache detects file modification."""+ # Create a file+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("Original content\n")++ # Read the file to cache it+ read_chunk = await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )+ self.assertEqual(read_chunk.state, "running")++ # Modify the file externally+ import time++ time.sleep(0.1) # Ensure mtime changes+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("Modified content\n")++ # Try to edit - should fail because cache is stale+ edit_chunk = await self.edit_tool(+ file_path=self.test_file,+ old_string="Original",+ new_string="New",+ _agent_state=self.state,+ )++ # Should fail with error+ self.assertEqual(edit_chunk.state, "error")+ self.assertIn("must first read", edit_chunk.content[0].text)++ async def test_cache_lru_eviction(self) -> None:+ """Test LRU cache eviction when max_cache_files is exceeded."""+ # Set a small cache limit+ self.state.tool_context.max_cache_files = 3++ # Create and read 4 files+ files = []+ for i in range(4):+ file_path = os.path.join(self.temp_dir, f"file{i}.txt")+ with open(file_path, "w", encoding="utf-8") as f:+ f.write(f"Content {i}\n")+ files.append(file_path)++ # Read each file+ await self.read_tool(+ file_path=file_path,+ _agent_state=self.state,+ )++ # Cache should only have 3 files (oldest evicted)+ self.assertEqual(len(self.state.tool_context.read_file_cache), 3)++ # The first file should have been evicted+ cached_paths = [+ entry.file_path+ for entry in self.state.tool_context.read_file_cache+ ]+ self.assertNotIn(files[0], cached_paths)+ self.assertIn(files[1], cached_paths)+ self.assertIn(files[2], cached_paths)+ self.assertIn(files[3], cached_paths)++ async def test_cache_without_state(self) -> None:+ """Test tools work without state (fallback mode)."""+ # Create a file+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("Hello World\n")++ # Edit without state should work (fallback to reading from disk)+ edit_chunk = await self.edit_tool(+ file_path=self.test_file,+ old_string="Hello",+ new_string="Hi",+ _agent_state=None,+ )++ self.assertEqual(edit_chunk.state, "running")++ # Verify file was edited+ with open(self.test_file, "r", encoding="utf-8") as f:+ content = f.read()+ self.assertEqual(content, "Hi World\n")++ async def test_multiple_reads_update_cache(self) -> None:+ """Test reading same file multiple times updates cache."""+ # Create a file+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("Content v1\n")++ # Read the file+ await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )+ self.assertEqual(len(self.state.tool_context.read_file_cache), 1)++ # Read again - should update cache, not add duplicate+ await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )+ self.assertEqual(len(self.state.tool_context.read_file_cache), 1)++ async def test_read_cache_lines_contain_newlines(self) -> None:+ """Test that cached lines from Read retain trailing newlines.++ readlines() includes the newline character in each line. The cache+ must store them as-is so that "".join(lines) reconstructs the exact+ original file content.+ """+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("line1\nline2\nline3\n")++ await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )++ cache = await self.state.tool_context.get_cache(self.test_file)+ self.assertIsNotNone(cache)+ # Each line from readlines() ends with \n+ self.assertEqual(cache.lines, ["line1\n", "line2\n", "line3\n"])+ # "".join reconstructs the exact original content+ self.assertEqual("".join(cache.lines), "line1\nline2\nline3\n")++ async def test_edit_multiline_match_from_cache(self) -> None:+ """Test Edit correctly matches multi-line old_string from+ cached content.++ Regression test for the bug where "\n".join(cache.lines) doubled the+ newlines (e.g. "line1\n\nline2\n" instead of "line1\nline2\n"),+ making multi-line old_string matching fail.+ """+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("line1\nline2\nline3\n")++ await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )++ # This multi-line old_string must match exactly in the reconstructed+ # content; with the bug it would not be found.+ chunk = await self.edit_tool(+ file_path=self.test_file,+ old_string="line1\nline2",+ new_string="replaced",+ _agent_state=self.state,+ )++ self.assertEqual(chunk.state, "running")++ with open(self.test_file, "r", encoding="utf-8") as f:+ content = f.read()+ self.assertEqual(content, "replaced\nline3\n")++ async def test_edit_single_line_match_from_cache(self) -> None:+ """Test Edit correctly matches single-line old_string from cache."""+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("Hello World\nThis is a test\n")++ await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )++ chunk = await self.edit_tool(+ file_path=self.test_file,+ old_string="Hello World",+ new_string="Hello Python",+ _agent_state=self.state,+ )++ self.assertEqual(chunk.state, "running")++ with open(self.test_file, "r", encoding="utf-8") as f:+ content = f.read()+ self.assertEqual(content, "Hello Python\nThis is a test\n")++ async def test_write_invalidates_cache(self) -> None:+ """Test that Write updates the cache so Edit can use it afterwards."""+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("original content\n")++ # Read to populate cache+ await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )++ # Overwrite with Write (mtime changes, old cache becomes stale)+ write_chunk = await self.write_tool(+ file_path=self.test_file,+ content="new content\n",+ _agent_state=self.state,+ )+ self.assertEqual(write_chunk.state, "running")++ # The old cache entry is now stale; Edit should require a new Read+ edit_chunk = await self.edit_tool(+ file_path=self.test_file,+ old_string="new content",+ new_string="updated content",+ _agent_state=self.state,+ )+ self.assertEqual(edit_chunk.state, "error")+ self.assertIn("must first read", edit_chunk.content[0].text)++ async def test_write_cache_stale_then_reread(self) -> None:+ """Test workflow: Read -> Write -> Read -> Edit works correctly."""+ with open(self.test_file, "w", encoding="utf-8") as f:+ f.write("original\n")++ # First read+ await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )++ # Overwrite+ import time++ time.sleep(0.01) # ensure mtime changes+ await self.write_tool(+ file_path=self.test_file,+ content="rewritten\n",+ _agent_state=self.state,+ )++ # Re-read to refresh cache+ await self.read_tool(+ file_path=self.test_file,+ _agent_state=self.state,+ )++ # Now Edit should succeed against the new content+ edit_chunk = await self.edit_tool(+ file_path=self.test_file,+ old_string="rewritten",+ new_string="final",+ _agent_state=self.state,+ )+ self.assertEqual(edit_chunk.state, "running")++ with open(self.test_file, "r", encoding="utf-8") as f:+ content = f.read()+ self.assertEqual(content, "final\n")diff --git a/tests/builtin_glob_test.py b/tests/builtin_glob_test.pynew file mode 100644index 000000000..c3069dd9e--- /dev/null+++ b/tests/builtin_glob_test.py@@ -0,0 +1,203 @@+# -*- coding: utf-8 -*-+"""Glob tool test case."""+import os+import tempfile+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.tool import PermissionContext, PermissionBehavior, Glob+++class GlobToolTest(IsolatedAsyncioTestCase):+ """The glob tool test case."""++ async def asyncSetUp(self) -> None:+ """The async setup method."""+ self.glob_tool = Glob()+ # Create a temporary directory with test files+ self.temp_dir = tempfile.mkdtemp()++ # Create test files+ with open(+ os.path.join(self.temp_dir, "test1.py"),+ "w",+ encoding="utf-8",+ ):+ pass+ with open(+ os.path.join(self.temp_dir, "test2.py"),+ "w",+ encoding="utf-8",+ ):+ pass+ with open(+ os.path.join(self.temp_dir, "test.txt"),+ "w",+ encoding="utf-8",+ ):+ pass++ # Create subdirectory+ sub_dir = os.path.join(self.temp_dir, "subdir")+ os.makedirs(sub_dir)+ with open(os.path.join(sub_dir, "test3.py"), "w", encoding="utf-8"):+ pass++ async def asyncTearDown(self) -> None:+ """Clean up temporary files."""+ import shutil++ if os.path.exists(self.temp_dir):+ shutil.rmtree(self.temp_dir)++ async def test_tool_properties(self) -> None:+ """Test glob tool properties."""+ self.assertEqual(self.glob_tool.name, "Glob")+ self.assertIsInstance(self.glob_tool.description, str)+ self.assertIsInstance(self.glob_tool.input_schema, dict)+ self.assertFalse(self.glob_tool.is_mcp)+ self.assertTrue(self.glob_tool.is_read_only)+ self.assertTrue(self.glob_tool.is_concurrency_safe)++ async def test_check_permissions(self) -> None:+ """Test glob tool permission checking."""+ context = PermissionContext()+ tool_input = {"pattern": "*.py"}+ decision = await self.glob_tool.check_permissions(tool_input, context)++ # Read/Glob/Grep are read-only, return PASSTHROUGH+ self.assertEqual(decision.behavior, PermissionBehavior.PASSTHROUGH)++ async def test_simple_pattern(self) -> None:+ """Test simple glob pattern."""+ chunk = await self.glob_tool(+ pattern="*.py",+ path=self.temp_dir,+ )++ self.assertEqual(chunk.state, "running")++ # Should find test1.py and test2.py+ content = chunk.content[0].text+ self.assertIn("test1.py", content)+ self.assertIn("test2.py", content)+ self.assertNotIn("test.txt", content)++ async def test_recursive_pattern(self) -> None:+ """Test recursive glob pattern."""+ chunk = await self.glob_tool(+ pattern="**/*.py",+ path=self.temp_dir,+ )++ content = chunk.content[0].text++ # Should find all .py files including in subdirectory+ self.assertIn("test1.py", content)+ self.assertIn("test2.py", content)+ self.assertIn("test3.py", content)++ async def test_no_matches(self) -> None:+ """Test pattern with no matches."""+ chunk = await self.glob_tool(+ pattern="*.nonexistent",+ path=self.temp_dir,+ )++ self.assertEqual(chunk.state, "running")+ self.assertIn("No files found", chunk.content[0].text)++ async def test_match_rule_path(self) -> None:+ """Test match_rule with path patterns."""+ # Test matching explicit path+ self.assertTrue(+ self.glob_tool.match_rule(+ self.temp_dir,+ {"path": self.temp_dir, "pattern": "*.py"},+ ),+ )++ # Test wildcard pattern matching path+ parent_dir = os.path.dirname(self.temp_dir)+ self.assertTrue(+ self.glob_tool.match_rule(+ parent_dir + "/**",+ {"path": self.temp_dir, "pattern": "*.py"},+ ),+ )++ # Test non-matching path+ self.assertFalse(+ self.glob_tool.match_rule(+ "/some/other/path/**",+ {"path": self.temp_dir, "pattern": "*.py"},+ ),+ )++ async def test_match_rule_pattern(self) -> None:+ """Test match_rule with pattern matching."""+ # Test matching against the pattern itself+ self.assertTrue(+ self.glob_tool.match_rule(+ "*.py",+ {"pattern": "*.py"},+ ),+ )++ # Test wildcard pattern matching+ self.assertTrue(+ self.glob_tool.match_rule(+ "**/*.py",+ {"pattern": "src/**/*.py"},+ ),+ )++ # Test non-matching pattern+ self.assertFalse(+ self.glob_tool.match_rule(+ "*.txt",+ {"pattern": "*.py"},+ ),+ )++ async def test_match_rule_path_priority(self) -> None:+ """Test that path matching takes priority over pattern matching."""+ # If path matches, should return True even if pattern doesn't+ self.assertTrue(+ self.glob_tool.match_rule(+ self.temp_dir,+ {"path": self.temp_dir, "pattern": "*.txt"},+ ),+ )++ async def test_generate_suggestions_with_path(self) -> None:+ """Test generate_suggestions for glob with explicit path."""+ from agentscope.tool import PermissionRule++ suggestions = self.glob_tool.generate_suggestions(+ {"path": self.temp_dir, "pattern": "*.py"},+ )++ self.assertIsInstance(suggestions, list)+ self.assertGreater(len(suggestions), 0)+ self.assertIsInstance(suggestions[0], PermissionRule)++ # Should suggest directory pattern+ abs_path = os.path.abspath(self.temp_dir)+ expected_pattern = abs_path.rstrip("/") + "/**"+ suggestion_contents = [s.rule_content for s in suggestions]+ self.assertIn(expected_pattern, suggestion_contents)++ async def test_generate_suggestions_defaults_to_cwd(self) -> None:+ """Test generate_suggestions defaults to cwd when no path provided."""++ suggestions = self.glob_tool.generate_suggestions(+ {"pattern": "*.py"},+ )++ self.assertIsInstance(suggestions, list)+ self.assertGreater(len(suggestions), 0)++ cwd = os.getcwd()+ expected_pattern = os.path.abspath(cwd).rstrip("/") + "/**"+ suggestion_contents = [s.rule_content for s in suggestions]+ self.assertIn(expected_pattern, suggestion_contents)diff --git a/tests/builtin_grep_test.py b/tests/builtin_grep_test.pynew file mode 100644index 000000000..a8f2627c8--- /dev/null+++ b/tests/builtin_grep_test.py@@ -0,0 +1,249 @@+# -*- coding: utf-8 -*-+"""Grep tool test case."""+import os+import tempfile+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.tool import PermissionContext, PermissionBehavior, Grep+++class GrepToolTest(IsolatedAsyncioTestCase):+ """The grep tool test case."""++ async def asyncSetUp(self) -> None:+ """The async setup method."""+ self.grep_tool = Grep()+ # Create a temporary directory with test files+ self.temp_dir = tempfile.mkdtemp()++ # Create test files+ with open(+ os.path.join(self.temp_dir, "test1.py"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write("def hello():\n print('Hello World')\n")++ with open(+ os.path.join(self.temp_dir, "test2.py"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write("def goodbye():\n print('Goodbye')\n")++ with open(+ os.path.join(self.temp_dir, "test.txt"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write("This is a text file\nHello from text\n")++ # Create subdirectory with files for glob pattern testing+ subdir = os.path.join(self.temp_dir, "subdir")+ os.makedirs(subdir)+ with open(+ os.path.join(subdir, "nested.py"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write("def nested():\n print('Nested')\n")++ async def asyncTearDown(self) -> None:+ """Clean up temporary files."""+ import shutil++ if os.path.exists(self.temp_dir):+ shutil.rmtree(self.temp_dir)++ async def test_tool_properties(self) -> None:+ """Test grep tool properties."""+ self.assertEqual(self.grep_tool.name, "Grep")+ self.assertIsInstance(self.grep_tool.description, str)+ self.assertIsInstance(self.grep_tool.input_schema, dict)+ self.assertFalse(self.grep_tool.is_mcp)+ self.assertTrue(self.grep_tool.is_read_only)+ self.assertTrue(self.grep_tool.is_concurrency_safe)++ async def test_check_permissions(self) -> None:+ """Test grep tool permission checking."""+ context = PermissionContext()+ tool_input = {"pattern": "hello"}+ decision = await self.grep_tool.check_permissions(tool_input, context)++ # Read/Glob/Grep are read-only, return PASSTHROUGH+ self.assertEqual(decision.behavior, PermissionBehavior.PASSTHROUGH)++ async def test_simple_search(self) -> None:+ """Test simple grep search."""+ chunk = await self.grep_tool(+ pattern="Hello",+ path=self.temp_dir,+ output_mode="files_with_matches",+ )++ self.assertEqual(chunk.state, "running")++ content = chunk.content[0].text+ # Should find files containing "Hello"+ self.assertIn("test1.py", content)+ self.assertIn("test.txt", content)++ async def test_content_mode(self) -> None:+ """Test grep with content output mode."""+ chunk = await self.grep_tool(+ pattern="def",+ path=self.temp_dir,+ output_mode="content",+ type="py",+ )++ content = chunk.content[0].text++ # Should show matching lines+ self.assertIn("def hello", content)+ self.assertIn("def goodbye", content)++ async def test_case_insensitive(self) -> None:+ """Test case-insensitive search."""+ chunk = await self.grep_tool(+ pattern="HELLO",+ path=self.temp_dir,+ case_insensitive=True,+ output_mode="files_with_matches",+ )++ content = chunk.content[0].text+ self.assertIn("test1.py", content)++ async def test_no_matches(self) -> None:+ """Test search with no matches."""+ chunk = await self.grep_tool(+ pattern="NonExistentPattern",+ path=self.temp_dir,+ )++ self.assertIn("No matches found", chunk.content[0].text)++ async def test_type_filter(self) -> None:+ """Test filtering by file type."""+ chunk = await self.grep_tool(+ pattern="Hello",+ path=self.temp_dir,+ type="py",+ output_mode="files_with_matches",+ )++ content = chunk.content[0].text++ # Should only find .py files+ self.assertIn("test1.py", content)+ self.assertNotIn("test.txt", content)++ async def test_invalid_regex(self) -> None:+ """Test grep with invalid regex pattern."""+ chunk = await self.grep_tool(+ pattern="[invalid(regex",+ path=self.temp_dir,+ )++ self.assertEqual(chunk.state, "error")+ # ripgrep returns its own error message for regex parse errors+ self.assertIn("regex parse error", chunk.content[0].text)++ async def test_glob_pattern_with_subdirs(self) -> None:+ """Test glob pattern matching with subdirectories like **/*.py."""+ chunk = await self.grep_tool(+ pattern="def",+ path=self.temp_dir,+ glob="**/*.py",+ output_mode="files_with_matches",+ )++ content = chunk.content[0].text++ # Should find all .py files including in subdirectories+ self.assertIn("test1.py", content)+ self.assertIn("test2.py", content)+ self.assertIn("nested.py", content)+ # Should not find .txt files+ self.assertNotIn("test.txt", content)++ async def test_match_rule_path(self) -> None:+ """Test match_rule with search path patterns."""+ # Test matching explicit path+ self.assertTrue(+ self.grep_tool.match_rule(+ self.temp_dir,+ {"path": self.temp_dir},+ ),+ )++ # Test wildcard pattern matching path+ parent_dir = os.path.dirname(self.temp_dir)+ self.assertTrue(+ self.grep_tool.match_rule(+ parent_dir + "/**",+ {"path": self.temp_dir},+ ),+ )++ # Test non-matching path+ self.assertFalse(+ self.grep_tool.match_rule(+ "/some/other/path/**",+ {"path": self.temp_dir},+ ),+ )++ async def test_match_rule_defaults_to_cwd(self) -> None:+ """Test match_rule defaults to cwd when no path is provided."""+ cwd = os.getcwd()++ # When no path provided, should match against cwd+ self.assertTrue(+ self.grep_tool.match_rule(+ cwd,+ {"pattern": "hello"},+ ),+ )++ # Should not match a different path+ self.assertFalse(+ self.grep_tool.match_rule(+ "/some/other/path",+ {"pattern": "hello"},+ ),+ )++ async def test_generate_suggestions_with_path(self) -> None:+ """Test generate_suggestions for grep with explicit path."""+ from agentscope.tool import PermissionRule++ suggestions = self.grep_tool.generate_suggestions(+ {"path": self.temp_dir, "pattern": "hello"},+ )++ self.assertIsInstance(suggestions, list)+ self.assertGreater(len(suggestions), 0)+ self.assertIsInstance(suggestions[0], PermissionRule)++ # Should suggest directory pattern+ abs_path = os.path.abspath(self.temp_dir)+ expected_pattern = abs_path.rstrip("/") + "/**"+ suggestion_contents = [s.rule_content for s in suggestions]+ self.assertIn(expected_pattern, suggestion_contents)++ async def test_generate_suggestions_defaults_to_cwd(self) -> None:+ """Test generate_suggestions defaults to cwd when no path provided."""++ suggestions = self.grep_tool.generate_suggestions(+ {"pattern": "hello"},+ )++ self.assertIsInstance(suggestions, list)+ self.assertGreater(len(suggestions), 0)++ cwd = os.getcwd()+ expected_pattern = os.path.abspath(cwd).rstrip("/") + "/**"+ suggestion_contents = [s.rule_content for s in suggestions]+ self.assertIn(expected_pattern, suggestion_contents)diff --git a/tests/builtin_read_test.py b/tests/builtin_read_test.pynew file mode 100644index 000000000..4ea058af9--- /dev/null+++ b/tests/builtin_read_test.py@@ -0,0 +1,189 @@+# -*- coding: utf-8 -*-+"""Read tool test case."""+import os+import tempfile+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.tool import (+ ToolChunk,+ PermissionContext,+ PermissionBehavior,+ Read,+)+from agentscope.message import TextBlock+++class ReadToolTest(IsolatedAsyncioTestCase):+ """The read tool test case."""++ async def asyncSetUp(self) -> None:+ """The async setup method."""+ self.read_tool = Read()+ # Create a temporary file for testing+ self.temp_file = tempfile.NamedTemporaryFile(+ mode="w",+ delete=False,+ suffix=".txt",+ )+ # Write multiple lines+ for i in range(1, 11):+ self.temp_file.write(f"Line {i}\n")+ self.temp_file.close()++ async def asyncTearDown(self) -> None:+ """Clean up temporary files."""+ if os.path.exists(self.temp_file.name):+ os.unlink(self.temp_file.name)++ async def test_tool_properties(self) -> None:+ """Test read tool properties."""+ self.assertEqual(self.read_tool.name, "Read")+ self.assertIsInstance(self.read_tool.description, str)+ self.assertIsInstance(self.read_tool.input_schema, dict)+ self.assertFalse(self.read_tool.is_mcp)+ self.assertTrue(self.read_tool.is_read_only)+ self.assertTrue(self.read_tool.is_concurrency_safe)++ async def test_check_permissions(self) -> None:+ """Test read tool permission checking."""+ context = PermissionContext()+ tool_input = {"file_path": "/tmp/test.txt"}+ decision = await self.read_tool.check_permissions(tool_input, context)++ # Read/Glob/Grep are read-only, return PASSTHROUGH+ self.assertEqual(decision.behavior, PermissionBehavior.PASSTHROUGH)++ async def test_simple_read(self) -> None:+ """Test simple file reading."""+ chunk = await self.read_tool(file_path=self.temp_file.name)++ self.assertIsInstance(chunk, ToolChunk)+ self.assertEqual(chunk.state, "running")+ self.assertEqual(len(chunk.content), 1)+ self.assertIsInstance(chunk.content[0], TextBlock)++ content = chunk.content[0].text+ # Should contain all lines with line numbers+ self.assertIn("Line 1", content)+ self.assertIn("Line 10", content)++ async def test_read_with_offset(self) -> None:+ """Test reading with offset."""+ chunk = await self.read_tool(+ file_path=self.temp_file.name,+ offset=5,+ )++ self.assertEqual(chunk.state, "running")+ content = chunk.content[0].text++ # Should start from line 5+ self.assertIn("Line 5", content)+ # Line 1 should not appear (but Line 10 contains "1",+ # so check more specifically)+ lines = content.split("\n")+ line_numbers = [+ int(line.split("\t")[0].strip()) for line in lines if line.strip()+ ]+ self.assertNotIn(1, line_numbers)+ self.assertIn(5, line_numbers)++ async def test_read_with_limit(self) -> None:+ """Test reading with limit."""+ chunk = await self.read_tool(+ file_path=self.temp_file.name,+ offset=1,+ limit=3,+ )++ self.assertEqual(chunk.state, "running")+ content = chunk.content[0].text++ # Should only read 3 lines+ self.assertIn("Line 1", content)+ self.assertIn("Line 2", content)+ self.assertIn("Line 3", content)+ self.assertNotIn("Line 4", content)++ async def test_read_nonexistent_file(self) -> None:+ """Test reading a non-existent file."""+ chunk = await self.read_tool(file_path="/nonexistent/file.txt")++ self.assertEqual(chunk.state, "error")+ self.assertIn("does not exist", chunk.content[0].text)++ async def test_read_directory(self) -> None:+ """Test reading a directory (should fail)."""+ temp_dir = tempfile.mkdtemp()+ try:+ chunk = await self.read_tool(file_path=temp_dir)++ self.assertEqual(chunk.state, "error")+ self.assertIn("directory", chunk.content[0].text.lower())+ finally:+ os.rmdir(temp_dir)++ async def test_match_rule_glob_pattern(self) -> None:+ """Test match_rule with glob patterns."""+ # Test exact match+ self.assertTrue(+ self.read_tool.match_rule(+ "test.py",+ {"file_path": "test.py"},+ ),+ )++ # Test wildcard pattern+ self.assertTrue(+ self.read_tool.match_rule(+ "*.py",+ {"file_path": "test.py"},+ ),+ )++ # Test directory pattern+ self.assertTrue(+ self.read_tool.match_rule(+ "/tmp/**",+ {"file_path": "/tmp/test.py"},+ ),+ )++ # Test non-matching pattern+ self.assertFalse(+ self.read_tool.match_rule(+ "*.txt",+ {"file_path": "test.py"},+ ),+ )++ # Test empty file_path+ self.assertFalse(+ self.read_tool.match_rule(+ "*.py",+ {"file_path": ""},+ ),+ )++ async def test_generate_suggestions(self) -> None:+ """Test generate_suggestions for file operations."""+ from agentscope.tool import PermissionRule++ # Test suggestion for file in subdirectory+ suggestions = self.read_tool.generate_suggestions(+ {"file_path": "/tmp/project/src/main.py"},+ )++ self.assertIsInstance(suggestions, list)+ self.assertGreater(len(suggestions), 0)+ self.assertIsInstance(suggestions[0], PermissionRule)++ # Should suggest parent directory pattern+ suggestion_contents = [s.rule_content for s in suggestions]+ self.assertIn("/tmp/project/src/**", suggestion_contents)++ # Test suggestion for file in root+ suggestions = self.read_tool.generate_suggestions(+ {"file_path": "/test.py"},+ )+ self.assertGreater(len(suggestions), 0)diff --git a/tests/builtin_write_test.py b/tests/builtin_write_test.pynew file mode 100644index 000000000..f75a88310--- /dev/null+++ b/tests/builtin_write_test.py@@ -0,0 +1,185 @@+# -*- coding: utf-8 -*-+"""Write tool test case."""+import os+import tempfile+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.tool import PermissionContext, PermissionBehavior, Write+++class WriteToolTest(IsolatedAsyncioTestCase):+ """The write tool test case."""++ async def asyncSetUp(self) -> None:+ """The async setup method."""+ self.write_tool = Write()+ self.temp_dir = tempfile.mkdtemp()++ async def asyncTearDown(self) -> None:+ """Clean up temporary files."""+ import shutil++ if os.path.exists(self.temp_dir):+ shutil.rmtree(self.temp_dir)++ async def test_tool_properties(self) -> None:+ """Test write tool properties."""+ self.assertEqual(self.write_tool.name, "Write")+ self.assertIsInstance(self.write_tool.description, str)+ self.assertIsInstance(self.write_tool.input_schema, dict)+ self.assertFalse(self.write_tool.is_mcp)+ self.assertFalse(self.write_tool.is_read_only)+ self.assertFalse(self.write_tool.is_concurrency_safe)++ async def test_check_permissions(self) -> None:+ """Test write tool permission checking.++ Write tool should return PASSTHROUGH for non-dangerous paths,+ allowing PermissionEngine to check allow rules.+ """+ context = PermissionContext()+ tool_input = {"file_path": "/tmp/test.txt"}+ decision = await self.write_tool.check_permissions(tool_input, context)++ self.assertEqual(decision.behavior, PermissionBehavior.PASSTHROUGH)++ async def test_simple_write(self) -> None:+ """Test simple file writing."""+ file_path = os.path.join(self.temp_dir, "test.txt")+ content = "Hello World\nThis is a test\n"++ chunk = await self.write_tool(+ file_path=file_path,+ content=content,+ )++ self.assertEqual(chunk.state, "running")+ self.assertTrue(chunk.is_last)++ # Verify file was created and content is correct+ self.assertTrue(os.path.exists(file_path))+ with open(file_path, "r", encoding="utf-8") as f:+ written_content = f.read()+ self.assertEqual(written_content, content)++ async def test_write_creates_directory(self) -> None:+ """Test that write creates parent directories."""+ file_path = os.path.join(self.temp_dir, "subdir", "test.txt")+ content = "Test content"++ chunk = await self.write_tool(+ file_path=file_path,+ content=content,+ )++ self.assertEqual(chunk.state, "running")++ # Verify directory and file were created+ self.assertTrue(os.path.exists(file_path))+ with open(file_path, "r", encoding="utf-8") as f:+ written_content = f.read()+ self.assertEqual(written_content, content)++ async def test_write_overwrites_existing(self) -> None:+ """Test that write overwrites existing files."""+ file_path = os.path.join(self.temp_dir, "test.txt")++ # Write initial content+ with open(file_path, "w", encoding="utf-8") as f:+ f.write("Initial content")++ # Overwrite with new content+ new_content = "New content"+ chunk = await self.write_tool(+ file_path=file_path,+ content=new_content,+ )++ self.assertEqual(len([chunk]), 1)++ # Verify content was overwritten+ with open(file_path, "r", encoding="utf-8") as f:+ written_content = f.read()+ self.assertEqual(written_content, new_content)+ self.assertNotIn("Initial", written_content)++ async def test_write_empty_content(self) -> None:+ """Test writing empty content."""+ file_path = os.path.join(self.temp_dir, "empty.txt")++ chunk = await self.write_tool(+ file_path=file_path,+ content="",+ )++ self.assertEqual(len([chunk]), 1)+ self.assertTrue(os.path.exists(file_path))++ with open(file_path, "r", encoding="utf-8") as f:+ content = f.read()+ self.assertEqual(content, "")++ async def test_match_rule_glob_pattern(self) -> None:+ """Test match_rule with glob patterns."""+ # Test exact match+ self.assertTrue(+ self.write_tool.match_rule(+ "test.py",+ {"file_path": "test.py"},+ ),+ )++ # Test wildcard pattern+ self.assertTrue(+ self.write_tool.match_rule(+ "*.py",+ {"file_path": "test.py"},+ ),+ )++ # Test directory pattern+ self.assertTrue(+ self.write_tool.match_rule(+ "/tmp/**",+ {"file_path": "/tmp/test.py"},+ ),+ )++ # Test non-matching pattern+ self.assertFalse(+ self.write_tool.match_rule(+ "*.txt",+ {"file_path": "test.py"},+ ),+ )++ # Test empty file_path+ self.assertFalse(+ self.write_tool.match_rule(+ "*.py",+ {"file_path": ""},+ ),+ )++ async def test_generate_suggestions(self) -> None:+ """Test generate_suggestions for file operations."""+ from agentscope.tool import PermissionRule++ # Test suggestion for file in subdirectory+ suggestions = self.write_tool.generate_suggestions(+ {"file_path": "/tmp/project/src/main.py"},+ )++ self.assertIsInstance(suggestions, list)+ self.assertGreater(len(suggestions), 0)+ self.assertIsInstance(suggestions[0], PermissionRule)++ # Should suggest parent directory pattern+ suggestion_contents = [s.rule_content for s in suggestions]+ self.assertIn("/tmp/project/src/**", suggestion_contents)++ # Test suggestion for file in root+ suggestions = self.write_tool.generate_suggestions(+ {"file_path": "/test.py"},+ )+ self.assertGreater(len(suggestions), 0)diff --git a/tests/permission_bash_parser_test.py b/tests/permission_bash_parser_test.pyindex 652bb07d9..b41c2d044 100644--- a/tests/permission_bash_parser_test.py+++ b/tests/permission_bash_parser_test.py@@ -1,10 +1,17 @@# -*- coding: utf-8 -*-"""Test cases for BashCommandParser."""+import sys+import unittestfrom unittest.async_case import IsolatedAsyncioTestCase-from agentscope.tool._permission._bash_parser import BashCommandParser+from agentscope.tool._builtin._bash_parser import BashCommandParser+from agentscope.tool import Bash+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)class BashCommandParserTest(IsolatedAsyncioTestCase):"""Test cases for BashCommandParser."""@@ -198,6 +205,10 @@ class BashCommandParserTest(IsolatedAsyncioTestCase):self.parser = None+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)class BashParserReadOnlyTest(IsolatedAsyncioTestCase):"""Test is_read_only_command() method."""@@ -386,6 +397,10 @@ class BashParserReadOnlyTest(IsolatedAsyncioTestCase):self.parser = None+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)class BashParserFilePathsTest(IsolatedAsyncioTestCase):"""Test extract_file_paths() method."""@@ -609,6 +624,10 @@ class BashParserFilePathsTest(IsolatedAsyncioTestCase):self.parser = None+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)class BashParserRedirectionsTest(IsolatedAsyncioTestCase):"""Test extract_redirections() method."""@@ -776,3 +795,523 @@ class BashParserRedirectionsTest(IsolatedAsyncioTestCase):async def asyncTearDown(self) -> None:"""Clean up test fixtures."""self.parser = None+++ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)+class BashParserSedConstraintsTest(IsolatedAsyncioTestCase):+ """Test check_sed_constraints() with complex allowlist/denylist."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.parser = BashCommandParser()+ self.dangerous_files = [".env", "config.json", "secrets.yaml"]++ async def test_allowlist_line_printing(self) -> None:+ """Test allowlist Pattern 1: Line printing with -n flag."""+ test_cases = [+ ("sed -n '5p' file.txt", None),+ ("sed -n '10,20p' file.txt", None),+ ("sed -n '1p' data.log", None),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_sed_constraints(+ cmd,+ self.dangerous_files,+ )+ self.assertEqual(result, expected)++ async def test_allowlist_substitution(self) -> None:+ """Test allowlist Pattern 2: Substitution commands."""+ test_cases = [+ ("sed 's/old/new/' file.txt", None),+ ("sed 's/old/new/g' file.txt", None),+ ("sed 's|old|new|' file.txt", None),+ ("sed 's#pattern#replacement#' file.txt", None),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_sed_constraints(+ cmd,+ self.dangerous_files,+ )+ self.assertEqual(result, expected)++ async def test_denylist_write_operations(self) -> None:+ """Test denylist: write operations (w/W)."""+ test_cases = [+ ("sed 's/old/new/w output.txt' file.txt", "write operation"),+ ("sed 's/old/new/W output.txt' file.txt", "write operation"),+ ]+ for cmd, expected_substring in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_sed_constraints(+ cmd,+ self.dangerous_files,+ )+ self.assertIsNotNone(result)+ self.assertIn(expected_substring, result)++ async def test_denylist_execute_operations(self) -> None:+ """Test denylist: execute operations (e/E)."""+ test_cases = [+ ("sed 's/old/new/e' file.txt", "execute operation"),+ ("sed 's/old/new/E' file.txt", "execute operation"),+ ]+ for cmd, expected_substring in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_sed_constraints(+ cmd,+ self.dangerous_files,+ )+ self.assertIsNotNone(result)+ self.assertIn(expected_substring, result)++ async def test_denylist_dangerous_patterns(self) -> None:+ """Test denylist: dangerous patterns (curly braces, negation)."""+ test_cases = [+ ("sed '{s/old/new/}' file.txt", "curly braces"),+ ("sed '!s/old/new/' file.txt", "negation"),+ ]+ for cmd, expected_substring in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_sed_constraints(+ cmd,+ self.dangerous_files,+ )+ self.assertIsNotNone(result)+ self.assertIn(expected_substring, result)++ async def test_not_in_allowlist(self) -> None:+ """Test commands not in allowlist."""+ test_cases = [+ ("sed 'd' file.txt", "not in allowlist"),+ ("sed 'a\\text' file.txt", "not in allowlist"),+ ("sed 'i\\text' file.txt", "not in allowlist"),+ ]+ for cmd, expected_substring in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_sed_constraints(+ cmd,+ self.dangerous_files,+ )+ self.assertIsNotNone(result)+ self.assertIn(expected_substring, result)++ async def test_inplace_with_dangerous_files(self) -> None:+ """Test -i flag with dangerous files."""+ test_cases = [+ ("sed -i 's/old/new/' .env", "dangerous file"),+ ("sed -i 's/old/new/' config.json", "dangerous file"),+ ("sed --in-place 's/old/new/' secrets.yaml", "dangerous file"),+ ]+ for cmd, expected_substring in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_sed_constraints(+ cmd,+ self.dangerous_files,+ )+ self.assertIsNotNone(result)+ self.assertIn(expected_substring, result)++ async def test_invalid_flags(self) -> None:+ """Test invalid flags."""+ test_cases = [+ ("sed -r 's/old/new/' file.txt", "flag -r not allowed"),+ ("sed -u 's/old/new/' file.txt", "flag -u not allowed"),+ ]+ for cmd, expected_substring in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_sed_constraints(+ cmd,+ self.dangerous_files,+ )+ self.assertIsNotNone(result)+ self.assertIn(expected_substring, result)++ async def test_non_sed_commands(self) -> None:+ """Test non-sed commands return None."""+ test_cases = [+ "ls -la",+ "cat file.txt",+ "grep pattern file.txt",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_sed_constraints(+ cmd,+ self.dangerous_files,+ )+ self.assertIsNone(result)++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.parser = None+++ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)+class BashWildcardMatchingTest(IsolatedAsyncioTestCase):+ """Test match_rule() with complex regex-based wildcard matching."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.bash_tool = Bash()++ async def test_basic_wildcard_matching(self) -> None:+ """Test basic wildcard matching with *."""+ test_cases = [+ ("git *", "git status", True),+ ("git *", "git", True), # Special optimization+ ("git * push", "git origin push", True),+ ("npm run *", "npm run build", True),+ ("npm run *", "npm run test", True),+ ("docker * up", "docker compose up", True),+ ]+ for pattern, command, expected in test_cases:+ with self.subTest(pattern=pattern, command=command):+ result = self.bash_tool.match_rule(+ pattern,+ {"command": command},+ )+ self.assertEqual(result, expected)++ async def test_wildcard_no_match(self) -> None:+ """Test wildcard patterns that don't match."""+ test_cases = [+ ("git *", "github", False),+ ("npm run *", "yarn run build", False),+ ("docker * up", "docker ps", False),+ ]+ for pattern, command, expected in test_cases:+ with self.subTest(pattern=pattern, command=command):+ result = self.bash_tool.match_rule(+ pattern,+ {"command": command},+ )+ self.assertEqual(result, expected)++ async def test_escape_sequences(self) -> None:+ """Test escape sequences \\* and \\\\."""+ test_cases = [+ ("file\\*.txt", "file*.txt", True),+ ("file\\*.txt", "file123.txt", False),+ ("path\\\\to\\\\file", "path\\to\\file", True),+ ("path\\\\to\\\\file", "path/to/file", False),+ ]+ for pattern, command, expected in test_cases:+ with self.subTest(pattern=pattern, command=command):+ result = self.bash_tool.match_rule(+ pattern,+ {"command": command},+ )+ self.assertEqual(result, expected)++ async def test_prefix_pattern(self) -> None:+ """Test prefix pattern with :* suffix."""+ test_cases = [+ ("git:*", "git status", True),+ ("git:*", "git", True),+ ("git:*", "github", False),+ ("npm:*", "npm install", True),+ ("npm:*", "npm", True),+ ]+ for pattern, command, expected in test_cases:+ with self.subTest(pattern=pattern, command=command):+ result = self.bash_tool.match_rule(+ pattern,+ {"command": command},+ )+ self.assertEqual(result, expected)++ async def test_substring_matching(self) -> None:+ """Test substring matching (no wildcards)."""+ test_cases = [+ ("npm install", "npm install express", True),+ ("npm install", "yarn install", False),+ ("git commit", "git commit -m 'fix'", True),+ ("git commit", "git push", False),+ ]+ for pattern, command, expected in test_cases:+ with self.subTest(pattern=pattern, command=command):+ result = self.bash_tool.match_rule(+ pattern,+ {"command": command},+ )+ self.assertEqual(result, expected)++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.bash_tool = None+++ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)+class BashParserInjectionRiskTest(IsolatedAsyncioTestCase):+ """Test check_injection_risk() method for detecting dynamic shell+ structures."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.parser = BashCommandParser()++ async def test_command_substitution_dollar_paren(self) -> None:+ """Test detection of command substitution with $()."""+ test_cases = [+ "ls $(pwd)",+ "rm $(find . -name '*.tmp')",+ "echo $(date)",+ "cat $(which python)",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_injection_risk(cmd)+ self.assertIsNotNone(result)+ self.assertIn("command_substitution", result)++ async def test_command_substitution_backtick(self) -> None:+ """Test detection of command substitution with backticks."""+ test_cases = [+ "ls `pwd`",+ "rm `find . -name '*.tmp'`",+ "echo `date`",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_injection_risk(cmd)+ self.assertIsNotNone(result)+ self.assertIn("command_substitution", result)++ async def test_process_substitution(self) -> None:+ """Test detection of process substitution <()."""+ test_cases = [+ "diff <(ls dir1) <(ls dir2)",+ "cat <(echo hello)",+ "grep pattern <(curl http://example.com)",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_injection_risk(cmd)+ self.assertIsNotNone(result)+ self.assertIn("process_substitution", result)++ async def test_subshell(self) -> None:+ """Test detection of subshells ()."""+ test_cases = [+ "(cd /tmp && ls)",+ "(export VAR=value; echo $VAR)",+ "echo before && (cd /tmp; pwd) && echo after",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_injection_risk(cmd)+ self.assertIsNotNone(result)+ self.assertIn("subshell", result)++ async def test_for_loop(self) -> None:+ """Test detection of for loops."""+ test_cases = [+ "for f in *.txt; do cat $f; done",+ "for i in 1 2 3; do echo $i; done",+ "for file in $(ls); do rm $file; done",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_injection_risk(cmd)+ self.assertIsNotNone(result)+ self.assertIn("for_statement", result)++ async def test_while_loop(self) -> None:+ """Test detection of while loops."""+ test_cases = [+ "while read line; do echo $line; done < file.txt",+ "while true; do sleep 1; done",+ "while [ $i -lt 10 ]; do echo $i; i=$((i+1)); done",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_injection_risk(cmd)+ self.assertIsNotNone(result)+ self.assertIn("while_statement", result)++ async def test_if_statement(self) -> None:+ """Test detection of if statements."""+ test_cases = [+ "if [ -f file.txt ]; then cat file.txt; fi",+ "if test -d /tmp; then echo exists; fi",+ "if [ $? -eq 0 ]; then echo success; else echo fail; fi",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_injection_risk(cmd)+ self.assertIsNotNone(result)+ self.assertIn("if_statement", result)++ async def test_case_statement(self) -> None:+ """Test detection of case statements."""+ test_cases = [+ "case $1 in start) echo starting;; stop) echo stopping;; esac",+ "case $var in a) echo A;; b) echo B;; *) echo other;; esac",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_injection_risk(cmd)+ self.assertIsNotNone(result)+ self.assertIn("case_statement", result)++ async def test_function_definition(self) -> None:+ """Test detection of function definitions."""+ test_cases = [+ "function myfunc() { echo hello; }",+ "myfunc() { ls -la; }",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_injection_risk(cmd)+ self.assertIsNotNone(result)+ self.assertIn("function_definition", result)++ async def test_safe_commands(self) -> None:+ """Test that safe commands pass injection check."""+ safe_commands = [+ "ls -la",+ "cat file.txt",+ "git status",+ "npm install",+ "echo 'hello world'",+ "grep pattern file.txt",+ "find . -name '*.py'",+ "docker ps",+ "python script.py",+ ]+ for cmd in safe_commands:+ with self.subTest(cmd=cmd):+ result = self.parser.check_injection_risk(cmd)+ self.assertIsNone(result, f"Expected '{cmd}' to be safe")++ async def test_compound_commands_safe(self) -> None:+ """Test that compound commands without dynamic structures are safe."""+ safe_commands = [+ "ls -la && cat file.txt",+ "git add . && git commit -m 'fix'",+ "npm install || echo failed",+ "cd /tmp; ls; pwd",+ "cat file.txt | grep pattern",+ ]+ for cmd in safe_commands:+ with self.subTest(cmd=cmd):+ result = self.parser.check_injection_risk(cmd)+ self.assertIsNone(result, f"Expected '{cmd}' to be safe")++ async def test_mixed_safe_and_unsafe(self) -> None:+ """Test compound commands with both safe and unsafe parts."""+ test_cases = [+ ("ls && rm $(find . -name '*.tmp')", "command_substitution"),+ ("git status && (cd /tmp; ls)", "subshell"),+ (+ "echo start && for f in *.txt; do cat $f; done",+ "for_statement",+ ),+ ]+ for cmd, expected_type in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_injection_risk(cmd)+ self.assertIsNotNone(result)+ self.assertIn(expected_type, result)++ async def test_empty_command(self) -> None:+ """Test empty command."""+ result = self.parser.check_injection_risk("")+ # Empty command should be safe (no dangerous nodes)+ self.assertIsNone(result)++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.parser = None+++ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)+class BashParserDangerousCommandTest(IsolatedAsyncioTestCase):+ """Test check_dangerous_command() method."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.parser = BashCommandParser()++ async def test_rm_rf_pattern(self) -> None:+ """Test detection of rm -rf pattern."""+ test_cases = [+ "rm -rf /tmp/test",+ "rm -rf .",+ "sudo rm -rf /var/log",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_dangerous_command(cmd)+ self.assertIsNotNone(result)+ self.assertIn("rm -rf", result)++ async def test_sudo_rm_pattern(self) -> None:+ """Test detection of sudo rm pattern."""+ test_cases = [+ "sudo rm file.txt",+ "sudo rm -f /etc/config",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_dangerous_command(cmd)+ self.assertIsNotNone(result)+ self.assertIn("sudo rm", result)++ async def test_dd_command(self) -> None:+ """Test detection of dd command."""+ test_cases = [+ "dd if=/dev/zero of=/dev/sda",+ "dd if=file.iso of=/dev/sdb",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_dangerous_command(cmd)+ self.assertIsNotNone(result)+ self.assertEqual(result, "dd")++ async def test_chmod_777_pattern(self) -> None:+ """Test detection of chmod 777 pattern."""+ test_cases = [+ "chmod 777 file.txt",+ "chmod -R 777 /var/www",+ ]+ for cmd in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.check_dangerous_command(cmd)+ self.assertIsNotNone(result)+ self.assertIn("chmod", result)++ async def test_safe_commands(self) -> None:+ """Test that safe commands are not flagged."""+ safe_commands = [+ "rm file.txt",+ "rm -f temp.log",+ "chmod +x script.sh",+ "chmod 644 file.txt",+ "ls -la",+ "git status",+ ]+ for cmd in safe_commands:+ with self.subTest(cmd=cmd):+ result = self.parser.check_dangerous_command(cmd)+ self.assertIsNone(result, f"Expected '{cmd}' to be safe")++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.parser = Nonediff --git a/tests/permission_engine_test.py b/tests/permission_engine_test.pyindex 2c5bfbca6..ccbeb72c8 100644--- a/tests/permission_engine_test.py+++ b/tests/permission_engine_test.py@@ -1,6 +1,8 @@# -*- coding: utf-8 -*-"""Test cases for PermissionEngine."""import json+import sys+import unittestfrom unittest.async_case import IsolatedAsyncioTestCasefrom agentscope.tool import (@@ -10,53 +12,16 @@ from agentscope.tool import (PermissionRule,PermissionBehavior,AdditionalWorkingDirectory,+ Bash,+ Write,+ Read,+ Edit,)from agentscope.message import ToolCallBlock-class PermissionEngineInitializationTest(IsolatedAsyncioTestCase):- """Test cases for PermissionEngine initialization."""-- async def test_initialization_default(self) -> None:- """Test default initialization with built-in dangerous paths."""- context = PermissionContext(mode=PermissionMode.DEFAULT)- engine = PermissionEngine(context)-- # Check that built-in dangerous files are loaded- self.assertIn(".bashrc", engine.dangerous_files)- self.assertIn(".ssh/config", engine.dangerous_files)- self.assertIn(".gitconfig", engine.dangerous_files)-- # Check that built-in dangerous directories are loaded- self.assertIn(".git", engine.dangerous_directories)- self.assertIn(".ssh", engine.dangerous_directories)-- async def test_initialization_custom_dangerous_paths(self) -> None:- """Test initialization with custom dangerous paths."""- context = PermissionContext(mode=PermissionMode.DEFAULT)- engine = PermissionEngine(- context,- additional_dangerous_files=[".env", ".secrets"],- additional_dangerous_directories=["secrets/", "private/"],- )-- # Check that custom dangerous files are added- self.assertIn(".env", engine.dangerous_files)- self.assertIn(".secrets", engine.dangerous_files)-- # Check that built-in dangerous files are still present- self.assertIn(".bashrc", engine.dangerous_files)-- # Check that custom dangerous directories are added- self.assertIn("secrets/", engine.dangerous_directories)- self.assertIn("private/", engine.dangerous_directories)-- # Check that built-in dangerous directories are still present- self.assertIn(".git", engine.dangerous_directories)--class PermissionEngineRulePriorityTest(IsolatedAsyncioTestCase):- """Test cases for rule priority and decision making."""+ """Test cases for rule priority and decision-making."""async def asyncSetUp(self) -> None:"""Set up test fixtures."""@@ -64,7 +29,7 @@ class PermissionEngineRulePriorityTest(IsolatedAsyncioTestCase):self.engine = PermissionEngine(self.context)async def test_deny_rule_priority(self) -> None:- """Test that deny rules have highest priority."""+ """Test that deny rules have the highest priority."""# Add both allow and deny rules for the same toolself.engine.add_rule(PermissionRule(@@ -88,7 +53,7 @@ class PermissionEngineRulePriorityTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "git status"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Deny should take precedence over allowself.assertEqual(decision.behavior, PermissionBehavior.DENY)@@ -118,7 +83,7 @@ class PermissionEngineRulePriorityTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "npm install"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Ask should take precedence over allowself.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -156,7 +121,7 @@ class PermissionEngineRulePriorityTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "test command"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Deny should winself.assertEqual(decision.behavior, PermissionBehavior.DENY)@@ -181,7 +146,7 @@ class PermissionEngineModeTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "npm install"}),)- decision = await engine.check_permission(tool_call)+ decision = await engine.check_permission(tool_call, Bash())# BYPASS mode should allow by defaultself.assertEqual(decision.behavior, PermissionBehavior.ALLOW)@@ -207,9 +172,9 @@ class PermissionEngineModeTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "rm -rf /tmp"}),)- decision = await engine.check_permission(tool_call)+ decision = await engine.check_permission(tool_call, Bash())- # Deny rules have highest priority, even in BYPASS mode+ # Deny rules have the highest priority, even in BYPASS modeself.assertEqual(decision.behavior, PermissionBehavior.DENY)async def test_bypass_mode_with_dangerous_path(self) -> None:@@ -225,7 +190,7 @@ class PermissionEngineModeTest(IsolatedAsyncioTestCase):name="Write",input=json.dumps({"file_path": "/home/user/.bashrc"}),)- decision = await engine.check_permission(tool_call)+ decision = await engine.check_permission(tool_call, Write())# Safety checks are bypass-immuneself.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -241,7 +206,7 @@ class PermissionEngineModeTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "npm install"}),)- decision = await engine.check_permission(tool_call)+ decision = await engine.check_permission(tool_call, Bash())# DONT_ASK mode should deny instead of askself.assertEqual(decision.behavior, PermissionBehavior.DENY)@@ -266,7 +231,7 @@ class PermissionEngineModeTest(IsolatedAsyncioTestCase):name="Write",input=json.dumps({"file_path": "/tmp/project/file.txt"}),)- decision = await engine.check_permission(tool_call)+ decision = await engine.check_permission(tool_call, Write())self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)# Read tool within working directory@@ -275,7 +240,7 @@ class PermissionEngineModeTest(IsolatedAsyncioTestCase):name="Read",input=json.dumps({"file_path": "/tmp/project/file.txt"}),)- decision = await engine.check_permission(tool_call)+ decision = await engine.check_permission(tool_call, Read())self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)# Edit tool within working directory@@ -284,7 +249,7 @@ class PermissionEngineModeTest(IsolatedAsyncioTestCase):name="Edit",input=json.dumps({"file_path": "/tmp/project/file.txt"}),)- decision = await engine.check_permission(tool_call)+ decision = await engine.check_permission(tool_call, Edit())self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)async def test_accept_edits_mode_outside_working_directory(self) -> None:@@ -307,7 +272,7 @@ class PermissionEngineModeTest(IsolatedAsyncioTestCase):name="Edit",input=json.dumps({"file_path": "/home/user/file.txt"}),)- decision = await engine.check_permission(tool_call)+ decision = await engine.check_permission(tool_call, Edit())self.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -322,7 +287,7 @@ class PermissionEngineModeTest(IsolatedAsyncioTestCase):name="Read",input=json.dumps({"file_path": "/tmp/file.txt"}),)- decision = await engine.check_permission(tool_call)+ decision = await engine.check_permission(tool_call, Read())self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)@@ -337,11 +302,15 @@ class PermissionEngineModeTest(IsolatedAsyncioTestCase):name="Write",input=json.dumps({"file_path": "/tmp/file.txt"}),)- decision = await engine.check_permission(tool_call)+ decision = await engine.check_permission(tool_call, Write())self.assertEqual(decision.behavior, PermissionBehavior.DENY)+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)class PermissionEngineBashRuleTest(IsolatedAsyncioTestCase):"""Test cases for Bash command rule matching."""@@ -367,7 +336,7 @@ class PermissionEngineBashRuleTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "git"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)# Test command with arguments@@ -376,7 +345,7 @@ class PermissionEngineBashRuleTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "git status"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)# Test command with multiple arguments@@ -385,7 +354,7 @@ class PermissionEngineBashRuleTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "git add ."}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)# Test non-matching command@@ -394,7 +363,7 @@ class PermissionEngineBashRuleTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "npm install"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())self.assertEqual(decision.behavior, PermissionBehavior.ASK)async def test_bash_substring_pattern_matching(self) -> None:@@ -414,7 +383,7 @@ class PermissionEngineBashRuleTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "npm install package"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())self.assertEqual(decision.behavior, PermissionBehavior.DENY)# Test command containing substring in different position@@ -423,7 +392,7 @@ class PermissionEngineBashRuleTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "pip install requests"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())self.assertEqual(decision.behavior, PermissionBehavior.DENY)async def test_bash_multiple_rules(self) -> None:@@ -451,7 +420,7 @@ class PermissionEngineBashRuleTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "rm -rf /tmp"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())self.assertEqual(decision.behavior, PermissionBehavior.DENY)# Test allow rule@@ -460,7 +429,7 @@ class PermissionEngineBashRuleTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "git status"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)# Test no matching rule@@ -469,7 +438,7 @@ class PermissionEngineBashRuleTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "npm install"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())self.assertEqual(decision.behavior, PermissionBehavior.ASK)async def asyncTearDown(self) -> None:@@ -503,7 +472,7 @@ class PermissionEngineFileRuleTest(IsolatedAsyncioTestCase):name="Read",input=json.dumps({"file_path": "test.py"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Read())self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)# Test non-matching file@@ -512,7 +481,7 @@ class PermissionEngineFileRuleTest(IsolatedAsyncioTestCase):name="Read",input=json.dumps({"file_path": "test.txt"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Read())self.assertEqual(decision.behavior, PermissionBehavior.ASK)async def test_file_directory_pattern_matching(self) -> None:@@ -532,7 +501,7 @@ class PermissionEngineFileRuleTest(IsolatedAsyncioTestCase):name="Edit",input=json.dumps({"file_path": "/tmp/test.txt"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Edit())# Note: The current implementation uses fnmatch/pathlib matching# /tmp/** may not match /tmp/test.txt depending on implementation# This test verifies the actual behavior@@ -547,7 +516,7 @@ class PermissionEngineFileRuleTest(IsolatedAsyncioTestCase):name="Edit",input=json.dumps({"file_path": "/tmp/subdir/test.txt"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Edit())self.assertIn(decision.behavior,[PermissionBehavior.ALLOW, PermissionBehavior.ASK],@@ -559,7 +528,7 @@ class PermissionEngineFileRuleTest(IsolatedAsyncioTestCase):name="Edit",input=json.dumps({"file_path": "/home/user/test.txt"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Edit())self.assertEqual(decision.behavior, PermissionBehavior.ASK)async def asyncTearDown(self) -> None:@@ -568,6 +537,10 @@ class PermissionEngineFileRuleTest(IsolatedAsyncioTestCase):self.context = None+ sys.platform == "win32",+ "Unix-specific paths not supported on Windows",+)class PermissionEngineDangerousPathTest(IsolatedAsyncioTestCase):"""Test cases for dangerous path detection (bypass-immune safetychecks)."""@@ -586,11 +559,10 @@ class PermissionEngineDangerousPathTest(IsolatedAsyncioTestCase):name="Write",input=json.dumps({"file_path": "/home/user/.bashrc"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Write())# Should ask for confirmation (safety check)self.assertEqual(decision.behavior, PermissionBehavior.ASK)- self.assertIn("safety", decision.decision_reason.lower())async def test_dangerous_file_blocks_edit(self) -> None:"""Test that Edit operations on dangerous files require@@ -601,7 +573,7 @@ class PermissionEngineDangerousPathTest(IsolatedAsyncioTestCase):name="Edit",input=json.dumps({"file_path": "/home/user/.gitconfig"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Edit())# Should ask for confirmation (safety check)self.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -616,7 +588,7 @@ class PermissionEngineDangerousPathTest(IsolatedAsyncioTestCase):name="Write",input=json.dumps({"file_path": "/home/user/.ssh/config"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Write())# Should ask for confirmation (safety check)self.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -630,7 +602,7 @@ class PermissionEngineDangerousPathTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "rm /home/user/.bashrc"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Should ask for confirmation (safety check)self.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -648,7 +620,7 @@ class PermissionEngineDangerousPathTest(IsolatedAsyncioTestCase):name="Write",input=json.dumps({"file_path": "/home/user/.bashrc"}),)- decision = await engine.check_permission(tool_call)+ decision = await engine.check_permission(tool_call, Write())# Safety checks are bypass-immuneself.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -673,7 +645,7 @@ class PermissionEngineDangerousPathTest(IsolatedAsyncioTestCase):name="Write",input=json.dumps({"file_path": "/home/user/.bashrc"}),)- decision = await engine.check_permission(tool_call)+ decision = await engine.check_permission(tool_call, Write())# Should ask despite being in working directoryself.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -686,7 +658,7 @@ class PermissionEngineDangerousPathTest(IsolatedAsyncioTestCase):name="Write",input=json.dumps({"file_path": "/home/user/test.py"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Write())# Should ask (no allow rule, but not blocked by safety check)self.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -715,7 +687,7 @@ class PermissionEngineSuggestionTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "git commit -m 'test'"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Should ask (not read-only)self.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -738,7 +710,7 @@ class PermissionEngineSuggestionTest(IsolatedAsyncioTestCase):name="Read",input=json.dumps({"file_path": "/tmp/test.py"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Read())# Should have suggestionsself.assertGreater(len(decision.suggested_rules), 0)@@ -755,6 +727,10 @@ class PermissionEngineSuggestionTest(IsolatedAsyncioTestCase):self.context = None+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):"""Test cases for read-only command auto-allow."""@@ -770,7 +746,7 @@ class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "git status"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Should be allowed (read-only command)self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)@@ -783,7 +759,7 @@ class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "ls -la"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Should be allowed (read-only command)self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)@@ -795,7 +771,7 @@ class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "cat file.txt"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Should be allowed (read-only command)self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)@@ -807,7 +783,7 @@ class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "git commit -m 'test'"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Should ask (not read-only)self.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -821,7 +797,7 @@ class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "ls -la && rm ~/.bashrc"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Should ask because of dangerous path (safety check is bypass-immune)self.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -835,7 +811,7 @@ class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "ls -la && cat file.txt"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Should be allowed (all read-only)self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)@@ -848,7 +824,7 @@ class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "ls -la && git commit -m 'test'"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Should ask (contains non-read-only command)self.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -861,7 +837,7 @@ class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "cat file.txt > ~/.bashrc"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Should ask because of dangerous path in redirectionself.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -875,7 +851,7 @@ class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):name="Bash",input=json.dumps({"command": "cat file.txt > /tmp/output.txt"}),)- decision = await self.engine.check_permission(tool_call)+ decision = await self.engine.check_permission(tool_call, Bash())# Should ask (redirection is not considered read-only)self.assertEqual(decision.behavior, PermissionBehavior.ASK)@@ -884,3 +860,129 @@ class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):"""Clean up test fixtures."""self.engine = Noneself.context = None+++ sys.platform == "win32",+ "Bash tool is not supported on Windows",+)+class PermissionEngineSafetyCheckBypassImmuneTest(IsolatedAsyncioTestCase):+ """Test that all safety checks are bypass-immune (cannot be overridden+ by BYPASS mode or allow rules)."""++ async def test_injection_check_bypass_immune(self) -> None:+ """Test that injection detection is bypass-immune."""+ context = PermissionContext(mode=PermissionMode.BYPASS)+ engine = PermissionEngine(context)++ # Command substitution should be blocked even in BYPASS mode+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "ls $(rm -rf /)"}),+ )+ decision = await engine.check_permission(tool_call, Bash())+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("command_substitution", decision.message)++ async def test_injection_check_not_bypassed_by_allow_rule(self) -> None:+ """Test that allow rules cannot bypass injection detection."""+ context = PermissionContext(mode=PermissionMode.DEFAULT)+ engine = PermissionEngine(context)++ # Add a broad allow rule+ engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="ls:*",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )++ # ls $(rm -rf /) should still be blocked despite allow rule for ls:*+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "ls $(rm -rf /)"}),+ )+ decision = await engine.check_permission(tool_call, Bash())+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("command_substitution", decision.message)++ async def test_dangerous_removal_bypass_immune(self) -> None:+ """Test that dangerous removal path check is bypass-immune."""+ context = PermissionContext(mode=PermissionMode.BYPASS)+ engine = PermissionEngine(context)++ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "rm -rf /"}),+ )+ decision = await engine.check_permission(tool_call, Bash())+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ # Can be blocked by either dangerous command pattern or dangerous+ # removal path check+ self.assertTrue(+ "Dangerous removal operation" in decision.message+ or "dangerous pattern" in decision.message,+ )++ async def test_dangerous_removal_not_bypassed_by_allow_rule(self) -> None:+ """Test that allow rules cannot bypass dangerous removal check."""+ context = PermissionContext(mode=PermissionMode.DEFAULT)+ engine = PermissionEngine(context)++ # Add a broad allow rule for rm+ engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="rm:*",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )++ # rm -rf / should still be blocked despite allow rule for rm:*+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "rm -rf /"}),+ )+ decision = await engine.check_permission(tool_call, Bash())+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ # Can be blocked by either dangerous command pattern or dangerous+ # removal path check+ self.assertTrue(+ "Dangerous removal operation" in decision.message+ or "dangerous pattern" in decision.message,+ )++ async def test_sed_constraint_bypass_immune(self) -> None:+ """Test that sed constraint check is bypass-immune."""+ context = PermissionContext(mode=PermissionMode.BYPASS)+ engine = PermissionEngine(context)++ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "sed 's/old/new/e' file.txt"}),+ )+ decision = await engine.check_permission(tool_call, Bash())+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("safety", decision.decision_reason.lower())++ async def test_dangerous_config_path_bypass_immune(self) -> None:+ """Test that dangerous config file path check is bypass-immune."""+ context = PermissionContext(mode=PermissionMode.BYPASS)+ engine = PermissionEngine(context)++ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "rm ~/.bashrc"}),+ )+ decision = await engine.check_permission(tool_call, Bash())+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("safety", decision.decision_reason.lower())diff --git a/tests/toolkit_test.py b/tests/toolkit_test.pyindex 2ea398d1d..598febc20 100644--- a/tests/toolkit_test.py+++ b/tests/toolkit_test.py@@ -1,4 +1,5 @@# -*- coding: utf-8 -*-+# pylint: disable=unused-argument"""Toolkit test case."""import jsonfrom typing import Any, AsyncGenerator, Generator@@ -16,7 +17,6 @@ from agentscope.tool import (Toolkit,ToolBase,ToolChunk,- PermissionContext,PermissionDecision,PermissionBehavior,ToolResponse,@@ -38,8 +38,8 @@ class Tool1(ToolBase):async def check_permissions(self,- tool_input: dict[str, Any],- context: PermissionContext,+ *args: Any,+ **kwargs: Any,) -> PermissionDecision:"""Check permissions for the tool."""return PermissionDecision(@@ -69,8 +69,8 @@ class Tool2(ToolBase):async def check_permissions(self,- tool_input: dict[str, Any],- context: PermissionContext,+ *args: Any,+ **kwargs: Any,) -> PermissionDecision:"""Check permissions for the tool."""return PermissionDecision(@@ -850,6 +850,7 @@ class ToolGroupTest(IsolatedAsyncioTestCase):group_name="group_1",description="Group 1",)+ self.maxDiff = None# The group is created successfullyself.assertEqual(len(toolkit.groups), 1)