Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(permission): build the basic permission checking logic (#1486)
DavdGao35efec62f71c
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 5f34d4102..84b963f8b 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -102,6 +102,8 @@ repos:--max-branches=30,--max-nested-blocks=7,--max-statements=100,+ --max-returns=10,+ --max-module-lines=2000,]- repo: https://github.com/regebro/pyromarev: "5.0"diff --git a/pyproject.toml b/pyproject.tomlindex d3c7d7adf..c663875c4 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -39,6 +39,8 @@ dependencies = ["shortuuid","python-frontmatter","aiofiles",+ "tree_sitter",+ "tree_sitter_bash",][project.optional-dependencies]diff --git a/src/agentscope/tool/__init__.py b/src/agentscope/tool/__init__.pyindex bafcf15bc..74c17257f 100644--- a/src/agentscope/tool/__init__.py+++ b/src/agentscope/tool/__init__.py@@ -3,8 +3,25 @@from ._response import ToolResponsefrom ._toolkit import Toolkit+from ._permission import (+ PermissionContext,+ AdditionalWorkingDirectory,+ PermissionDecision,+ PermissionEngine,+ PermissionRule,+ PermissionMode,+ PermissionBehavior,+)+__all__ = ["Toolkit","ToolResponse",+ "PermissionContext",+ "AdditionalWorkingDirectory",+ "PermissionDecision",+ "PermissionEngine",+ "PermissionRule",+ "PermissionMode",+ "PermissionBehavior",]diff --git a/src/agentscope/tool/_permission/__init__.py b/src/agentscope/tool/_permission/__init__.pynew file mode 100644index 000000000..727144524--- /dev/null+++ b/src/agentscope/tool/_permission/__init__.py@@ -0,0 +1,18 @@+# -*- coding: utf-8 -*-+"""The tool permission related types and functions."""++from ._context import PermissionContext, AdditionalWorkingDirectory+from ._decision import PermissionDecision+from ._engine import PermissionEngine+from ._rule import PermissionRule+from ._types import PermissionMode, PermissionBehavior++__all__ = [+ "PermissionContext",+ "AdditionalWorkingDirectory",+ "PermissionDecision",+ "PermissionEngine",+ "PermissionRule",+ "PermissionMode",+ "PermissionBehavior",+]diff --git a/src/agentscope/tool/_permission/_bash_parser.py b/src/agentscope/tool/_permission/_bash_parser.pynew file mode 100644index 000000000..f495c0f3c--- /dev/null+++ b/src/agentscope/tool/_permission/_bash_parser.py@@ -0,0 +1,589 @@+# -*- coding: utf-8 -*-+"""Bash command parser using tree-sitter for precise syntax analysis.++This module provides utilities to parse Bash commands and extract meaningful+information for permission rule generation, including:+- Splitting compound commands (&&, ||, ;, |)+- Extracting command prefixes (e.g., "npm run" from "npm run build")+- Extracting file paths from commands for dangerous path detection+- Extracting output redirections+- Checking if commands are read-only+"""++from typing import List, Optional, Set, Tuple++import tree_sitter_bash as tsbash+from tree_sitter import Language, Parser, Node+++# Commands that are considered safe and don't require permission rules+SAFE_COMMANDS: Set[str] = {+ "echo",+ "cat",+ "ls",+ "pwd",+ "cd",+ "true",+ "false",+ "printf",+ "grep",+ "tee",+}++# Safe environment variables that can be skipped when extracting command prefix+SAFE_ENV_VARS = {+ "NODE_ENV",+ "PYTHONUNBUFFERED",+ "RUST_LOG",+ "LANG",+ "TERM",+ "NO_COLOR",+ "FORCE_COLOR",+ "DEBUG",+ "VERBOSE",+ "CI",+ "PATH",+ "HOME",+ "USER",+ "SHELL",+ "EDITOR",+ "PAGER",+ "TZ",+ "LC_ALL",+ "LC_CTYPE",+ "COLUMNS",+ "LINES",+ "CLICOLOR",+ "CLICOLOR_FORCE",+}++# Read-only git commands+GIT_READ_ONLY_COMMANDS = {+ "git status",+ "git log",+ "git diff",+ "git show",+ "git branch",+ "git tag",+ "git remote",+ "git ls-files",+ "git ls-tree",+ "git cat-file",+ "git rev-parse",+ "git rev-list",+ "git describe",+ "git shortlog",+ "git blame",+ "git grep",+ "git reflog",+ "git config --get",+ "git config --list",+}++# Read-only commands for various tools+READ_ONLY_COMMANDS = {+ # Basic file operations+ "ls",+ "cat",+ "head",+ "tail",+ "less",+ "more",+ "file",+ "stat",+ "wc",+ "grep",+ "rg",+ "ag",+ "ack",+ "find",+ "tree",+ "pwd",+ "which",+ "whereis",+ "type",+ # Git commands+ *GIT_READ_ONLY_COMMANDS,+ # Docker read-only+ "docker ps",+ "docker images",+ "docker inspect",+ "docker logs",+ "docker version",+ "docker info",+ # GitHub CLI read-only+ "gh repo view",+ "gh issue list",+ "gh pr list",+ "gh status",+ # Python/Node tools+ "python --version",+ "python -V",+ "node --version",+ "node -v",+ "npm list",+ "npm ls",+ "pip list",+ "pip show",+}+++class BashCommandParser:+ """Parse Bash commands using tree-sitter for accurate syntax analysis."""++ def __init__(self) -> None:+ """Initialize the parser with tree-sitter-bash language."""+ self.parser = Parser(Language(tsbash.language()))++ def is_read_only_command(self, command: str) -> bool:+ """Check if a command is read-only (safe to auto-allow).++ For compound commands (&&, ||, ;, |), ALL subcommands must be+ read-only for the entire command to be considered read-only.++ Commands with output redirections (>, >>) are NOT considered read-only.++ Args:+ command (`str`):+ The bash command string++ Returns:+ `bool`:+ True if the command (and all subcommands) are read-only,+ False otherwise+ """+ # Normalize command (strip leading/trailing whitespace)+ cmd = command.strip()++ # Check for output redirections - these are NOT read-only+ if ">" in cmd:+ return False++ # Check if it's a compound command+ if any(op in cmd for op in ["&&", "||", ";", "|"]):+ # Split into subcommands and check each one+ try:+ tree = self.parser.parse(bytes(cmd, "utf8"))+ root = tree.root_node+ subcommands = self._split_compound_command(root, cmd)++ # All subcommands must be read-only+ for subcmd in subcommands:+ if not self._is_single_command_read_only(subcmd.strip()):+ return False+ return True+ except Exception:+ # If parsing fails, be conservative+ return False++ # Single command - check directly+ return self._is_single_command_read_only(cmd)++ def _is_single_command_read_only(self, cmd: str) -> bool:+ """Check if a single (non-compound) command is read-only.++ Args:+ cmd (`str`):+ A single command string (no &&, ||, ;, |)++ Returns:+ `bool`:+ True if the command is read-only, False otherwise+ """+ # Check exact match in read-only commands+ if cmd in READ_ONLY_COMMANDS:+ return True++ # Check if it starts with a read-only prefix+ for readonly_cmd in READ_ONLY_COMMANDS:+ if cmd == readonly_cmd or cmd.startswith(readonly_cmd + " "):+ return True++ # Check base command for simple read-only operations+ tokens = cmd.split()+ if tokens:+ base_cmd = tokens[0]+ # Skip environment variables+ i = 0+ while i < len(tokens) and "=" in tokens[i]:+ i += 1+ if i < len(tokens):+ base_cmd = tokens[i]++ # Check if base command is in safe commands+ if base_cmd in SAFE_COMMANDS:+ return True++ return False++ def extract_file_paths(+ self,+ command: str,+ ) -> List[Tuple[str, str]]:+ """Extract file paths from a bash command using tree-sitter.++ Returns paths that are arguments to file-manipulating commands+ (rm, mv, cp, chmod, chown, etc.) and output redirection targets.++ Args:+ command (`str`):+ The bash command string++ Returns:+ `List[Tuple[str, str]]`:+ List of tuples (command_name, file_path)+ """+ paths = []++ try:+ # Parse command to AST+ tree = self.parser.parse(bytes(command, "utf8"))+ root = tree.root_node++ # Extract paths from commands+ self._extract_paths_from_node(root, command, paths)++ except Exception:+ # Fallback to simple token-based extraction+ paths = self._extract_paths_fallback(command)++ return paths++ def _extract_paths_from_node(+ self,+ node: Node,+ command: str,+ paths: List[Tuple[str, str]],+ ) -> None:+ """Recursively extract file paths from AST nodes.++ Args:+ node (`Node`):+ The AST node to process+ command (`str`):+ The original command string+ paths (`List[Tuple[str, str]]`):+ List to append (command_name, path) tuples to+ """+ # Check for redirections+ if node.type == "file_redirect":+ # Extract the target file+ for child in node.children:+ if child.type == "word":+ path = command[child.start_byte : child.end_byte]+ paths.append(("redirect", path.strip("'\"")))+ # Check for commands+ if node.type == "command":+ # Extract command name and arguments+ cmd_name = None+ args = []++ for child in node.children:+ if child.type == "command_name":+ cmd_name = command[child.start_byte : child.end_byte]+ elif child.type == "word" and cmd_name:+ arg = command[child.start_byte : child.end_byte]+ args.append(arg.strip("'\""))++ # Check if this is a file-manipulating command+ if cmd_name in [+ "rm",+ "mv",+ "cp",+ "chmod",+ "chown",+ "chgrp",+ "touch",+ "ln",+ "sed",+ ]:+ # Extract file arguments (skip flags)+ for arg in args:+ if not arg.startswith("-"):+ paths.append((cmd_name, arg))++ # Recursively process children+ for child in node.children:+ self._extract_paths_from_node(child, command, paths)++ def _extract_paths_fallback(+ self,+ command: str,+ ) -> List[Tuple[str, str]]:+ """Fallback path extraction using simple token parsing.++ Args:+ command (`str`):+ The bash command string++ Returns:+ `List[Tuple[str, str]]`:+ List of tuples (command_name, file_path)+ """+ paths = []+ tokens = command.split()+ i = 0++ while i < len(tokens):+ token = tokens[i]++ # Check for output redirections+ if token in [">", ">>", "2>", "&>"]:+ if i + 1 < len(tokens):+ path = tokens[i + 1].strip("'\"")+ paths.append(("redirect", path))+ i += 2+ continue++ # Check for file-manipulating commands+ if token in ["rm", "mv", "cp", "chmod", "chown", "sed", "touch"]:+ cmd_name = token+ # Look for file arguments after this command+ j = i + 1+ while j < len(tokens):+ arg = tokens[j].strip("'\"")+ # Skip flags+ if arg.startswith("-"):+ j += 1+ continue+ # This is a file argument+ paths.append((cmd_name, arg))+ j += 1+ break++ i += 1++ return paths++ def extract_redirections(self, command: str) -> List[str]:+ """Extract output redirection targets from a bash command.++ Args:+ command (`str`):+ The bash command string++ Returns:+ `List[str]`:+ List of file paths that are redirection targets+ """+ redirections = []++ try:+ # Parse command to AST+ tree = self.parser.parse(bytes(command, "utf8"))+ root = tree.root_node++ # Extract redirections+ self._extract_redirections_from_node(root, command, redirections)++ except Exception:+ # Fallback to simple extraction+ tokens = command.split()+ for i, token in enumerate(tokens):+ if token in [">", ">>", "2>", "&>"] and i + 1 < len(tokens):+ path = tokens[i + 1].strip("'\"")+ redirections.append(path)++ return redirections++ def _extract_redirections_from_node(+ self,+ node: Node,+ command: str,+ redirections: List[str],+ ) -> None:+ """Recursively extract redirections from AST nodes.++ Args:+ node (`Node`):+ The AST node to process+ command (`str`):+ The original command string+ redirections (`List[str]`):+ List to append redirection targets to+ """+ if node.type == "file_redirect":+ # Extract the target file+ for child in node.children:+ if child.type == "word":+ path = command[child.start_byte : child.end_byte]+ redirections.append(path.strip("'\""))++ # Recursively process children+ for child in node.children:+ self._extract_redirections_from_node(child, command, redirections)++ def extract_command_prefixes(+ self,+ command: str,+ max_prefixes: int = 5,+ ) -> List[str]:+ """Extract command prefixes from a bash command.++ Automatically handles compound commands (&&, ||, ;, |) and extracts+ prefixes from each subcommand. Returns deduplicated list of prefixes.++ Args:+ command (`str`):+ The bash command string (may be compound)+ max_prefixes (`int`):+ Maximum number of prefixes to return (default: 5)++ Returns:+ `List[str]`:+ List of command prefixes (deduplicated), e.g., ["npm run",+ "git commit"]++ Examples:+ >>> parser.extract_command_prefixes("git add . && git commit")+ ['git add', 'git commit']+ >>> parser.extract_command_prefixes("npm run build")+ ['npm run']+ >>> parser.extract_command_prefixes("ls -la")+ []+ """+ if not command or not command.strip():+ return []++ # Parse command to AST+ tree = self.parser.parse(bytes(command, "utf8"))+ root = tree.root_node++ # Split compound commands+ subcommands = self._split_compound_command(root, command)++ # Extract prefixes from each subcommand+ prefixes = []+ seen = set()++ for subcmd in subcommands[:max_prefixes]:+ prefix = self._extract_command_prefix(subcmd)+ if prefix and prefix not in seen:+ prefixes.append(prefix)+ seen.add(prefix)++ if len(prefixes) >= max_prefixes:+ break++ return prefixes++ def _split_compound_command(self, root: Node, command: str) -> List[str]:+ """Split compound commands using tree-sitter for precise parsing.++ Recognizes: &&, ||, ;, |++ Args:+ root (`Node`):+ The root AST node+ command (`str`):+ The original command string++ Returns:+ `List[str]`:+ List of individual subcommands+ """+ subcommands = []++ def extract_commands(node: Node) -> None:+ """Recursively extract commands from AST."""+ if node.type == "command":+ # Extract command text+ cmd_text = command[node.start_byte : node.end_byte]+ subcommands.append(cmd_text)+ elif node.type in ["list", "pipeline", "command_list"]:+ # Recursively process compound structures+ for child in node.children:+ if child.type not in ["&&", "||", ";", "|", "|&"]:+ extract_commands(child)+ else:+ # Continue traversing+ for child in node.children:+ extract_commands(child)++ extract_commands(root)+ return subcommands if subcommands else [command]++ def _extract_command_prefix(+ self,+ subcmd: str,+ ) -> Optional[str]:+ """Extract command prefix (first two words) from a subcommand.++ Logic:+ 1. Skip safe environment variable assignments+ 2. Extract command name and first subcommand+ 3. Verify the second word looks like a subcommand (not a flag)++ Args:+ subcmd (`str`):+ The subcommand string to extract prefix from++ Returns:+ `Optional[str]`:+ Command prefix (e.g., "npm run") or None if cannot extract+ """+ # Parse the subcommand+ tree = self.parser.parse(bytes(subcmd, "utf8"))+ root = tree.root_node++ # Find the first simple_command node+ simple_cmd = self._find_first_simple_command(root)+ if not simple_cmd:+ return None++ # Extract command parts+ parts = []+ env_vars = []++ for child in simple_cmd.children:+ if child.type == "variable_assignment":+ # Environment variable assignment+ var_name = subcmd[child.start_byte : child.end_byte].split(+ "=",+ )[0]+ env_vars.append(var_name)+ elif child.type == "command_name":+ # Command name+ parts.append(subcmd[child.start_byte : child.end_byte])+ elif child.type == "word" and len(parts) >= 1:+ # Argument (might be a flag or subcommand)+ word = subcmd[child.start_byte : child.end_byte]+ parts.append(word)+ # Stop after we have command + first argument+ if len(parts) >= 2:+ break++ # Check if environment variables are safe+ if env_vars and not all(v in SAFE_ENV_VARS for v in env_vars):+ return None++ # Check if the command is a safe command that doesn't need permission+ if parts and parts[0].lower() in SAFE_COMMANDS:+ return None++ # Return first two words+ if len(parts) >= 2:+ return " ".join(parts[:2])++ return None++ def _find_first_simple_command(self, node: Node) -> Optional[Node]:+ """Recursively find the first command node in AST.++ Args:+ node (`Node`):+ The AST node to search from++ Returns:+ `Optional[Node]`:+ The first command node found, or None+ """+ if node.type == "command":+ return node++ for child in node.children:+ result = self._find_first_simple_command(child)+ if result:+ return result++ return Nonediff --git a/src/agentscope/tool/_permission/_context.py b/src/agentscope/tool/_permission/_context.pynew file mode 100644index 000000000..9093c66da--- /dev/null+++ b/src/agentscope/tool/_permission/_context.py@@ -0,0 +1,46 @@+# -*- coding: utf-8 -*-+"""The permission context module."""+from pydantic import BaseModel, Field++from ._rule import PermissionRule+from ._types import PermissionMode+++class AdditionalWorkingDirectory(BaseModel):+ """An additional directory included in permission scope.++ Working directories are used to determine which file paths should be+ automatically allowed in ACCEPT_EDITS mode.+ """++ path: str+ """Absolute path to the directory."""++ source: str+ """Where this directory permission originated from+ (e.g., 'userSettings', 'session')."""+++class PermissionContext(BaseModel):+ """Context for permission checking.++ Contains the permission mode, working directories, and all configured+ permission rules organized by behavior type (allow, deny, ask).+ """++ mode: PermissionMode+ """The current permission mode."""++ working_directories: dict[str, AdditionalWorkingDirectory] = Field(+ default_factory=dict,+ )+ """Additional directories allowed for file operations, keyed by path."""++ allow_rules: dict[str, list[PermissionRule]] = Field(default_factory=dict)+ """Rules that allow tool execution, keyed by tool name."""++ deny_rules: dict[str, list[PermissionRule]] = Field(default_factory=dict)+ """Rules that deny tool execution, keyed by tool name."""++ ask_rules: dict[str, list[PermissionRule]] = Field(default_factory=dict)+ """Rules that require user confirmation, keyed by tool name."""diff --git a/src/agentscope/tool/_permission/_decision.py b/src/agentscope/tool/_permission/_decision.pynew file mode 100644index 000000000..674ad089b--- /dev/null+++ b/src/agentscope/tool/_permission/_decision.py@@ -0,0 +1,31 @@+# -*- coding: utf-8 -*-+"""The permission decision result."""+from dataclasses import dataclass+from typing import Any++from ._rule import PermissionRule+from ._types import PermissionBehavior+++@dataclass+class PermissionDecision:+ """Decision result from permission checking.++ Represents the outcome of a permission check, including whether+ the action should be allowed, denied, or require user confirmation.+ """++ behavior: PermissionBehavior+ """The permission behavior decision."""++ message: str+ """Human-readable message describing the decision."""++ decision_reason: str | None = None+ """Optional explanation for why this decision was made."""++ updated_input: dict[str, Any] | None = None+ """Optional modified input data (e.g., sanitized paths)."""++ suggested_rules: list[PermissionRule] | None = None+ """Optional list of suggested permission rules for user to apply."""diff --git a/src/agentscope/tool/_permission/_engine.py b/src/agentscope/tool/_permission/_engine.pynew file mode 100644index 000000000..a255505ba--- /dev/null+++ b/src/agentscope/tool/_permission/_engine.py@@ -0,0 +1,1026 @@+# -*- coding: utf-8 -*-+"""The permission engine for checking and enforcing permission rules."""+import fnmatch+import os+import json+from pathlib import Path+from typing import Any, List++from ._bash_parser import BashCommandParser+from ._context import PermissionContext+from ._rule import PermissionRule+from ._decision import PermissionDecision, PermissionBehavior+from ._types import PermissionMode+from ...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+++class PermissionEngine:+ """Engine for checking and enforcing permission rules.++ The PermissionEngine evaluates tool execution requests against configured+ permission rules. It supports different matching strategies based on+ tool type:++ - Bash tools: Matches command substrings+ - Write/Read tools: Matches file paths using glob patterns+ - Other tools: Uses generic pattern matching++ The evaluation order is:+ 1. Check deny rules (highest priority)+ 2. Check mode-specific logic (EXPLORE, ACCEPT_EDITS, dangerous paths)+ 3. Check ask rules+ 4. Check allow rules+ 5. Apply default behavior based on permission mode+ """++ def __init__(+ self,+ context: PermissionContext,+ additional_dangerous_files: list[str] | None = None,+ additional_dangerous_directories: list[str] | 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/']+ ... )+ """+ 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.++ Args:+ rule (`PermissionRule`):+ The permission rule to add++ Example:+ >>> engine.add_rule(PermissionRule(+ ... tool_name="Bash",+ ... rule_content="git:*",+ ... behavior=PermissionBehavior.ALLOW,+ ... ))+ """++ if rule.behavior == PermissionBehavior.ALLOW:+ if rule.tool_name not in self.context.allow_rules:+ self.context.allow_rules[rule.tool_name] = []+ self.context.allow_rules[rule.tool_name].append(rule)+ elif rule.behavior == PermissionBehavior.DENY:+ if rule.tool_name not in self.context.deny_rules:+ self.context.deny_rules[rule.tool_name] = []+ self.context.deny_rules[rule.tool_name].append(rule)+ elif rule.behavior == PermissionBehavior.ASK:+ if rule.tool_name not in self.context.ask_rules:+ self.context.ask_rules[rule.tool_name] = []+ self.context.ask_rules[rule.tool_name].append(rule)++ async def check_permission(+ self,+ tool_call: ToolCallBlock,+ ) -> 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)++ Args:+ tool_call (`ToolCallBlock`):+ The tool call block containing tool name and input++ Returns:+ `PermissionDecision`:+ Decision indicating whether to allow, deny, or ask+ """++ tool_name = tool_call.name+ 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)+ if deny_decision:+ return deny_decision++ # 2. Check tool-level ask rules+ ask_decision = self._check_ask_rules(tool_name, input_data)+ if ask_decision:+ # Generate suggestions for ASK decisions+ ask_decision.suggested_rules = self._generate_suggestions(+ tool_call,+ )+ 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)++ # 3a. Tool denied permission (bypass-immune)+ if tool_decision and tool_decision.behavior == PermissionBehavior.DENY:+ return tool_decision++ # 3b. Tool allowed permission (e.g., EXPLORE mode allows Read)+ if (+ tool_decision+ and tool_decision.behavior == PermissionBehavior.ALLOW+ ):+ return tool_decision++ # 3c. Safety checks (bypass-immune)+ if (+ tool_decision+ and tool_decision.behavior == PermissionBehavior.ASK+ and tool_decision.decision_reason+ and "safety" in tool_decision.decision_reason.lower()+ ):+ tool_decision.suggested_rules = self._generate_suggestions(+ tool_call,+ )+ return tool_decision++ # 4. Check allow rules+ allow_decision = self._check_allow_rules(tool_name, 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+ if self.context.mode == PermissionMode.BYPASS:+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"Permission granted for {tool_name} (bypass mode)",+ decision_reason="Bypass mode allows all operations",+ )++ # 8. Default behavior (passthrough → ask)+ default_decision = self._default_decision_ask(tool_name)+ default_decision.suggested_rules = self._generate_suggestions(+ tool_call,+ )+ return default_decision++ def _tool_check_permissions(+ self,+ tool_name: str,+ input_data: dict[str, Any],+ ) -> 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.++ Args:+ tool_name (`str`):+ The name of the tool+ input_data (`dict[str, Any]`):+ The tool input data++ Returns:+ `PermissionDecision | None`:+ PermissionDecision if tool has specific logic, None for+ passthrough+ """+ # 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,+ input_data,+ )+ if dangerous_path_decision:+ return dangerous_path_decision++ # No specific tool logic, passthrough+ return 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(+ self,+ tool_name: str,+ input_data: dict[str, Any],+ ) -> PermissionDecision | None:+ """Check permissions in ACCEPT_EDITS mode.++ 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++ Args:+ tool_name (`str`):+ The name of the tool+ input_data (`dict[str, Any]`):+ The tool input data++ Returns:+ `PermissionDecision | None`:+ ALLOW if operation is safe and in working directory,+ 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):+ 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,+ )++ # 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):+ 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,+ )++ # 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:+ 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,+ )++ 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,+ input_data: dict[str, Any],+ ) -> PermissionDecision | None:+ """Check if any deny rules match the request.++ Args:+ tool_name (`str`):+ The name of the tool+ input_data (`dict[str, Any]`):+ The tool input data++ Returns:+ `PermissionDecision | None`:+ DENY decision if a rule matches, None otherwise+ """+ rules = self.context.deny_rules.get(tool_name, [])+ for rule in rules:+ if self._rule_matches(rule, input_data):+ return PermissionDecision(+ behavior=PermissionBehavior.DENY,+ message=f"Permission to use {tool_name} has been denied",+ decision_reason=f"Rule: {rule.rule_content}",+ )+ return None++ def _check_ask_rules(+ self,+ tool_name: str,+ input_data: dict[str, Any],+ ) -> PermissionDecision | None:+ """Check if any ask rules match the request.++ Args:+ tool_name (`str`):+ The name of the tool+ input_data (`dict[str, Any]`):+ The tool input data++ Returns:+ `PermissionDecision | None`:+ ASK decision if a rule matches, None otherwise+ """+ rules = self.context.ask_rules.get(tool_name, [])+ for rule in rules:+ if self._rule_matches(rule, input_data):+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message=f"Permission required for {tool_name}",+ decision_reason=f"Rule: {rule.rule_content}",+ )+ return None++ def _check_allow_rules(+ self,+ tool_name: str,+ input_data: dict[str, Any],+ ) -> PermissionDecision | None:+ """Check if any allow rules match the request.++ Args:+ tool_name (`str`):+ The name of the tool+ input_data (`dict[str, Any]`):+ The tool input data++ Returns:+ `PermissionDecision | None`:+ ALLOW decision if a rule matches, None otherwise+ """+ rules = self.context.allow_rules.get(tool_name, [])+ for rule in rules:+ if self._rule_matches(rule, input_data):+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"Permission granted for {tool_name}",+ updated_input=input_data,+ )+ return None++ def _rule_matches(+ self,+ rule: PermissionRule,+ input_data: dict[str, Any],+ ) -> bool:+ """Check if a rule matches the input data.++ The matching strategy depends on the tool type:+ - Bash: Substring matching against the command+ - Write/Read: Glob pattern matching against file paths+ - Other: Generic pattern matching++ Args:+ rule (`PermissionRule`):+ The permission rule to check+ input_data (`dict[str, Any]`):+ The tool input data++ Returns:+ `bool`:+ True if the rule matches, False otherwise+ """+ # Empty rule_content matches everything+ 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++ def _default_decision_ask(self, tool_name: str) -> PermissionDecision:+ """Return default ASK decision.++ Args:+ tool_name (`str`):+ The name of the tool++ Returns:+ `PermissionDecision`:+ PermissionDecision with ASK behavior+ """+ # DONT_ASK: Convert ASK to DENY (user not available)+ if self.context.mode == PermissionMode.DONT_ASK:+ return PermissionDecision(+ behavior=PermissionBehavior.DENY,+ message=f"Permission denied for {tool_name} "+ f"(dont_ask mode - user not available)",+ decision_reason="User is not available to answer "+ "permission prompts",+ )++ # DEFAULT and other modes: Ask for permission+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message=f"Permission required for {tool_name}",+ decision_reason=f"Mode: {self.context.mode.value}",+ )++ def _generate_suggestions(+ self,+ tool_call: ToolCallBlock,+ ) -> List[PermissionRule]:+ """Generate suggested permission rules from a tool call.++ This method analyzes the tool call and generates broader permission+ suggestions that the user can apply to avoid future confirmations.++ Strategy:+ - For Bash: Extract command prefix (e.g., "npm run" -> "npm run:*")+ - For File operations: Extract directory (e.g.,+ "src/file.py" -> "src/**")+ - For other tools: Generate exact match rule++ Args:+ tool_call (`ToolCallBlock`):+ The tool call block containing name and parameters++ Returns:+ `List[PermissionRule]`:+ List of suggested permission rules (usually 1, max 5 for+ compound 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",+ ),+ ]diff --git a/src/agentscope/tool/_permission/_rule.py b/src/agentscope/tool/_permission/_rule.pynew file mode 100644index 000000000..7d4a07810--- /dev/null+++ b/src/agentscope/tool/_permission/_rule.py@@ -0,0 +1,36 @@+# -*- coding: utf-8 -*-+"""Permission rule model for tool usage."""+from pydantic import BaseModel++from ._types import PermissionBehavior+++class PermissionRule(BaseModel):+ """Permission rule for tool usage.++ A permission rule defines whether a specific tool or tool operation+ should be allowed, denied, or require user confirmation. The+ rule_content field has different semantics depending on the tool_name:++ - For "Bash": rule_content is a substring pattern matched against the+ command Example: rule_content="npm install" matches "npm install express"++ - For "Write"/"Read": rule_content is a glob pattern matched against file+ paths Example: rule_content="src/**" matches "src/main.py"++ - For other tools: rule_content is a tool-specific filter pattern+ """++ tool_name: str+ """The name of the tool this rule applies to (e.g., "Bash",+ "Write", "Read")."""++ rule_content: str | None+ """Optional filter pattern - semantics depend on tool_name."""++ behavior: PermissionBehavior+ """The permission behavior ("allow", "deny", or "ask")."""++ source: str+ """Where this rule originated from (e.g., "userSettings",+ "projectSettings")."""diff --git a/src/agentscope/tool/_permission/_types.py b/src/agentscope/tool/_permission/_types.pynew file mode 100644index 000000000..76ca32afe--- /dev/null+++ b/src/agentscope/tool/_permission/_types.py@@ -0,0 +1,66 @@+# -*- coding: utf-8 -*-+# pylint: disable=line-too-long+"""Permission system types and engine for tool usage control.++This module implements a permission system that controls tool execution based+on configurable rules. The permission system supports different matching+strategies depending on the tool type:++- For Bash tools: rule_content is a substring pattern matched against commands+- For Write/Read tools: rule_content is a glob pattern matched against file+ paths+- For other tools: rule_content uses generic matching logic+"""++from enum import Enum+++class PermissionMode(Enum):+ """The mode of permission.++ Permission modes control how the system handles tool execution requests.+ Different modes are suitable for different scenarios:++ +---------------+--------------------------------------------------+--------------------------------++ | Mode | Behavior | Use Case |+ +===============+==================================================+================================++ | DEFAULT | All operations require explicit permission | Default mode, most secure |+ | | (unless there are explicit allow rules) | |+ +---------------+--------------------------------------------------+--------------------------------++ | ACCEPT_EDITS | - Auto-allow file writes in working directories | User present, rapid iteration |+ | | - Auto-allow file reads in working directories | development |+ | | - Auto-allow filesystem commands (mkdir, rm, mv) | |+ | | - Other operations follow normal rules | |+ +---------------+--------------------------------------------------+--------------------------------++ | EXPLORE | Read-only mode: | Exploring codebase, planning |+ | | - Allow: Read, Grep, Glob (read-only tools) | implementation |+ | | - Deny: Write, Edit, Bash (modification tools) | |+ +---------------+--------------------------------------------------+--------------------------------++ | BYPASS | All operations automatically allowed | Testing environment, sandbox, |+ | | (no permission checks) | fully trusted scenarios |+ +---------------+--------------------------------------------------+--------------------------------++ | DONT_ASK | Convert all ASK decisions to DENY | Scheduled tasks, background |+ | | (user not available to answer prompts) | execution when user is away |+ +---------------+--------------------------------------------------+--------------------------------+++ Attributes:+ DEFAULT: Default mode - requires explicit permission for each action+ ACCEPT_EDITS: Accept edits mode - automatically allows file edits within working directories+ EXPLORE: Explore mode - read-only, no writes or command execution allowed+ BYPASS: Bypass mode - allows all actions without permission checks+ DONT_ASK: Don't ask mode - converts all ASK decisions to DENY (for unattended execution)+ """ # noqa: E501++ DEFAULT = "default"+ ACCEPT_EDITS = "accept_edits"+ EXPLORE = "explore"+ BYPASS = "bypass"+ DONT_ASK = "dont_ask"+++class PermissionBehavior(Enum):+ """The behavior of permission."""++ ALLOW = "allow"+ DENY = "deny"+ ASK = "ask"diff --git a/tests/permission_bash_parser_test.py b/tests/permission_bash_parser_test.pynew file mode 100644index 000000000..652bb07d9--- /dev/null+++ b/tests/permission_bash_parser_test.py@@ -0,0 +1,778 @@+# -*- coding: utf-8 -*-+"""Test cases for BashCommandParser."""+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.tool._permission._bash_parser import BashCommandParser+++class BashCommandParserTest(IsolatedAsyncioTestCase):+ """Test cases for BashCommandParser."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.parser = BashCommandParser()++ async def test_single_command_with_prefix(self) -> None:+ """Test single commands that can extract prefixes."""+ test_cases = [+ ("git commit -m 'fix'", ["git commit"]),+ ("npm run build", ["npm run"]),+ ("docker compose up", ["docker compose"]),+ ("cargo build --release", ["cargo build"]),+ ("python -m pytest", ["python -m"]),+ ]++ for command, expected in test_cases:+ with self.subTest(command=command):+ result = self.parser.extract_command_prefixes(command)+ self.assertEqual(result, expected)++ async def test_single_command_without_prefix(self) -> None:+ """Test single commands that cannot extract prefixes."""+ test_cases = [+ ("ls", []),+ ("ls -la", []),+ ("echo hello", []),+ ("cd /tmp", []),+ ("pwd", []),+ ("cat file.txt", []),+ ]++ for command, expected in test_cases:+ with self.subTest(command=command):+ result = self.parser.extract_command_prefixes(command)+ self.assertEqual(result, expected)++ async def test_environment_variables_safe(self) -> None:+ """Test commands with safe environment variables."""+ test_cases = [+ ("NODE_ENV=prod npm run build", ["npm run"]),+ ("DEBUG=1 npm test", ["npm test"]),+ ("PATH=/usr/bin npm run build", ["npm run"]),+ ("CI=true npm run test", ["npm run"]),+ ("PYTHONUNBUFFERED=1 python -m pytest", ["python -m"]),+ ]++ for command, expected in test_cases:+ with self.subTest(command=command):+ result = self.parser.extract_command_prefixes(command)+ self.assertEqual(result, expected)++ async def test_environment_variables_unsafe(self) -> None:+ """Test commands with unsafe environment variables."""+ test_cases = [+ ("CUSTOM_VAR=value npm run build", []),+ ("MY_SECRET=123 npm test", []),+ ("API_KEY=abc npm run deploy", []),+ ]++ for command, expected in test_cases:+ with self.subTest(command=command):+ result = self.parser.extract_command_prefixes(command)+ self.assertEqual(result, expected)++ async def test_compound_command_and_operator(self) -> None:+ """Test compound commands with && operator."""+ test_cases = [+ ("git add . && git commit", ["git add", "git commit"]),+ (+ "npm install && npm run build && npm test",+ ["npm install", "npm run", "npm test"],+ ),+ ("docker build . && docker push", ["docker build", "docker push"]),+ ]++ for command, expected in test_cases:+ with self.subTest(command=command):+ result = self.parser.extract_command_prefixes(command)+ self.assertEqual(result, expected)++ async def test_compound_command_or_operator(self) -> None:+ """Test compound commands with || operator."""+ test_cases = [+ ("npm run build || echo failed", ["npm run"]),+ ("git commit || git status", ["git commit", "git status"]),+ ]++ for command, expected in test_cases:+ with self.subTest(command=command):+ result = self.parser.extract_command_prefixes(command)+ self.assertEqual(result, expected)++ async def test_compound_command_semicolon(self) -> None:+ """Test compound commands with ; operator."""+ test_cases = [+ ("cd /tmp; ls -la; pwd", []),+ ("npm install; npm run build", ["npm install", "npm run"]),+ ]++ for command, expected in test_cases:+ with self.subTest(command=command):+ result = self.parser.extract_command_prefixes(command)+ self.assertEqual(result, expected)++ async def test_compound_command_pipe(self) -> None:+ """Test compound commands with | operator."""+ test_cases = [+ ("cat file.txt | grep error", []),+ ("docker ps | grep nginx", ["docker ps"]),+ ("npm run build | tee output.log", ["npm run"]),+ ]++ for command, expected in test_cases:+ with self.subTest(command=command):+ result = self.parser.extract_command_prefixes(command)+ self.assertEqual(result, expected)++ async def test_compound_command_mixed(self) -> None:+ """Test compound commands with mixed operators."""+ test_cases = [+ (+ "git add . && git commit -m 'fix' || echo failed",+ ["git add", "git commit"],+ ),+ (+ "npm install && npm run build | tee log.txt",+ ["npm install", "npm run"],+ ),+ ]++ for command, expected in test_cases:+ with self.subTest(command=command):+ result = self.parser.extract_command_prefixes(command)+ self.assertEqual(result, expected)++ async def test_edge_cases(self) -> None:+ """Test edge cases."""+ test_cases = [+ ("", []),+ (" ", []),+ ("npm", []),+ (" npm run build ", ["npm run"]),+ ]++ for command, expected in test_cases:+ with self.subTest(command=command):+ result = self.parser.extract_command_prefixes(command)+ self.assertEqual(result, expected)++ async def test_max_prefixes_limit(self) -> None:+ """Test that max_prefixes parameter limits the results."""+ command = (+ "npm install && npm run build && npm test && "+ "npm run lint && npm run format && npm run deploy"+ )++ # Default max is 5, but with deduplication we get 3 unique prefixes+ result = self.parser.extract_command_prefixes(command)+ self.assertEqual(len(result), 3)+ self.assertEqual(+ result,+ ["npm install", "npm run", "npm test"],+ )++ # Custom max+ result = self.parser.extract_command_prefixes(command, max_prefixes=3)+ self.assertEqual(len(result), 3)++ async def test_deduplication(self) -> None:+ """Test that duplicate prefixes are removed."""+ test_cases = [+ (+ "npm run build && npm run test && npm run lint",+ ["npm run"],+ ),+ (+ "git add . && git commit && git push && git status",+ ["git add", "git commit", "git push", "git status"],+ ),+ ]++ for command, expected in test_cases:+ with self.subTest(command=command):+ result = self.parser.extract_command_prefixes(command)+ self.assertEqual(result, expected)++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.parser = None+++class BashParserReadOnlyTest(IsolatedAsyncioTestCase):+ """Test is_read_only_command() method."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.parser = BashCommandParser()++ async def test_single_read_only_git_commands(self) -> None:+ """Test single read-only git commands."""+ read_only_commands = [+ "git status",+ "git log",+ "git diff",+ "git show",+ "git branch",+ "git remote -v",+ "git log --oneline",+ ]+ for cmd in read_only_commands:+ with self.subTest(cmd=cmd):+ self.assertTrue(+ self.parser.is_read_only_command(cmd),+ f"Expected '{cmd}' to be read-only",+ )++ async def test_single_read_only_file_commands(self) -> None:+ """Test single read-only file commands."""+ read_only_commands = [+ "ls",+ "ls -la",+ "cat file.txt",+ "head -n 10 file.txt",+ "tail -f log.txt",+ "grep pattern file.txt",+ "find . -name '*.py'",+ "tree",+ "pwd",+ "which python",+ ]+ for cmd in read_only_commands:+ with self.subTest(cmd=cmd):+ self.assertTrue(+ self.parser.is_read_only_command(cmd),+ f"Expected '{cmd}' to be read-only",+ )++ async def test_single_read_only_docker_commands(self) -> None:+ """Test single read-only docker commands."""+ read_only_commands = [+ "docker ps",+ "docker images",+ "docker inspect container_id",+ "docker logs container_id",+ ]+ for cmd in read_only_commands:+ with self.subTest(cmd=cmd):+ self.assertTrue(+ self.parser.is_read_only_command(cmd),+ f"Expected '{cmd}' to be read-only",+ )++ async def test_single_non_read_only_commands(self) -> None:+ """Test single non-read-only commands."""+ non_read_only_commands = [+ "git commit -m 'message'",+ "git push",+ "git pull",+ "rm file.txt",+ "mv file1.txt file2.txt",+ "cp file1.txt file2.txt",+ "chmod +x script.sh",+ "mkdir new_dir",+ "touch file.txt",+ ]+ for cmd in non_read_only_commands:+ with self.subTest(cmd=cmd):+ self.assertFalse(+ self.parser.is_read_only_command(cmd),+ f"Expected '{cmd}' to be non-read-only",+ )++ async def test_compound_command_all_read_only(self) -> None:+ """Test compound commands with all read-only subcommands."""+ compound_commands = [+ "ls -la && cat file.txt",+ "git status && git log",+ "pwd && ls",+ "cat file1.txt || cat file2.txt",+ "ls; pwd; cat file.txt",+ "git diff | grep pattern",+ ]+ for cmd in compound_commands:+ with self.subTest(cmd=cmd):+ self.assertTrue(+ self.parser.is_read_only_command(cmd),+ f"Expected '{cmd}' to be read-only "+ f"(all subcommands are read-only)",+ )++ async def test_compound_command_mixed(self) -> None:+ """Test compound commands with mixed read-only and non-read-only."""+ mixed_commands = [+ "ls -la && git commit -m 'message'",+ "cat file.txt && rm file.txt",+ "git status && git push",+ "pwd || mkdir new_dir",+ "ls; touch file.txt",+ ]+ for cmd in mixed_commands:+ with self.subTest(cmd=cmd):+ self.assertFalse(+ self.parser.is_read_only_command(cmd),+ f"Expected '{cmd}' to be non-read-only "+ f"(contains non-read-only subcommand)",+ )++ async def test_commands_with_output_redirection(self) -> None:+ """Test commands with output redirections are not read-only."""+ redirect_commands = [+ "cat file.txt > output.txt",+ "ls -la > list.txt",+ "git log >> history.txt",+ "echo 'hello' > file.txt",+ "cat file.txt 2> error.log",+ "ls &> output.log",+ ]+ for cmd in redirect_commands:+ with self.subTest(cmd=cmd):+ self.assertFalse(+ self.parser.is_read_only_command(cmd),+ f"Expected '{cmd}' to be non-read-only "+ f"(contains output redirection)",+ )++ async def test_commands_with_dangerous_paths(self) -> None:+ """Test commands with dangerous paths."""+ # Note: dangerous path check is separate from read-only check+ # These commands are still considered read-only if they don't+ # modify files+ dangerous_read_only = [+ "cat ~/.bashrc",+ "ls ~/.ssh",+ "cat .git/config",+ ]+ for cmd in dangerous_read_only:+ with self.subTest(cmd=cmd):+ self.assertTrue(+ self.parser.is_read_only_command(cmd),+ f"Expected '{cmd}' to be read-only "+ f"(dangerous path doesn't affect read-only status)",+ )++ # These are non-read-only because they modify files+ dangerous_non_read_only = [+ "rm ~/.bashrc",+ "chmod 600 ~/.ssh/config",+ "mv file.txt ~/.ssh/",+ ]+ for cmd in dangerous_non_read_only:+ with self.subTest(cmd=cmd):+ self.assertFalse(+ self.parser.is_read_only_command(cmd),+ f"Expected '{cmd}' to be non-read-only "+ f"(modifies files)",+ )++ async def test_empty_and_whitespace_commands(self) -> None:+ """Test empty and whitespace-only commands."""+ empty_commands = [+ "",+ " ",+ "\t",+ "\n",+ ]+ for cmd in empty_commands:+ with self.subTest(cmd=repr(cmd)):+ # Empty commands return False (not read-only, but+ # also not executable)+ self.assertFalse(+ self.parser.is_read_only_command(cmd),+ "Expected empty/whitespace command to return False",+ )++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.parser = None+++class BashParserFilePathsTest(IsolatedAsyncioTestCase):+ """Test extract_file_paths() method."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.parser = BashCommandParser()++ async def test_rm_command(self) -> None:+ """Test file path extraction from rm commands."""+ test_cases = [+ ("rm file.txt", [("rm", "file.txt")]),+ ("rm -rf /tmp/test", [("rm", "/tmp/test")]),+ (+ "rm file1.txt file2.txt",+ [("rm", "file1.txt"), ("rm", "file2.txt")],+ ),+ ("rm -f *.log", [("rm", "*.log")]),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_mv_command(self) -> None:+ """Test file path extraction from mv commands."""+ test_cases = [+ ("mv old.txt new.txt", [("mv", "old.txt"), ("mv", "new.txt")]),+ (+ "mv /tmp/file.txt /home/user/",+ [("mv", "/tmp/file.txt"), ("mv", "/home/user/")],+ ),+ (+ "mv -f file1.txt file2.txt",+ [("mv", "file1.txt"), ("mv", "file2.txt")],+ ),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_cp_command(self) -> None:+ """Test file path extraction from cp commands."""+ test_cases = [+ (+ "cp file.txt backup.txt",+ [("cp", "file.txt"), ("cp", "backup.txt")],+ ),+ ("cp -r /src /dest", [("cp", "/src"), ("cp", "/dest")]),+ (+ "cp file1.txt file2.txt /tmp/",+ [("cp", "file1.txt"), ("cp", "file2.txt"), ("cp", "/tmp/")],+ ),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_chmod_command(self) -> None:+ """Test file path extraction from chmod commands."""+ test_cases = [+ ("chmod +x script.sh", [("chmod", "+x"), ("chmod", "script.sh")]),+ ("chmod 755 /usr/bin/tool", [("chmod", "/usr/bin/tool")]),+ ("chmod -R 644 /tmp/files", [("chmod", "/tmp/files")]),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_chown_command(self) -> None:+ """Test file path extraction from chown commands."""+ test_cases = [+ (+ "chown user:group file.txt",+ [("chown", "user:group"), ("chown", "file.txt")],+ ),+ (+ "chown -R user /var/www",+ [("chown", "user"), ("chown", "/var/www")],+ ),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_touch_command(self) -> None:+ """Test file path extraction from touch commands."""+ test_cases = [+ ("touch file.txt", [("touch", "file.txt")]),+ (+ "touch file1.txt file2.txt",+ [("touch", "file1.txt"), ("touch", "file2.txt")],+ ),+ ("touch /tmp/newfile.log", [("touch", "/tmp/newfile.log")]),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_ln_command(self) -> None:+ """Test file path extraction from ln commands."""+ test_cases = [+ ("ln -s target link", [("ln", "target"), ("ln", "link")]),+ (+ "ln /src/file /dest/file",+ [("ln", "/src/file"), ("ln", "/dest/file")],+ ),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_sed_command(self) -> None:+ """Test file path extraction from sed commands."""+ test_cases = [+ ("sed -i 's/old/new/' file.txt", [("sed", "file.txt")]),+ ("sed 's/pattern/replacement/' input.txt", [("sed", "input.txt")]),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_output_redirections(self) -> None:+ """Test file path extraction from output redirections."""+ test_cases = [+ (+ "echo 'hello' > output.txt",+ [("redirect", "output.txt")],+ ),+ ("cat file.txt > backup.txt", [("redirect", "backup.txt")]),+ ("ls -la >> list.txt", [("redirect", "list.txt")]),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_compound_commands(self) -> None:+ """Test file path extraction from compound commands."""+ test_cases = [+ (+ "rm file1.txt && rm file2.txt",+ [("rm", "file1.txt"), ("rm", "file2.txt")],+ ),+ (+ "touch new.txt && chmod +x new.txt",+ [("touch", "new.txt"), ("chmod", "+x"), ("chmod", "new.txt")],+ ),+ (+ "cp src.txt dest.txt || mv src.txt dest.txt",+ [+ ("cp", "src.txt"),+ ("cp", "dest.txt"),+ ("mv", "src.txt"),+ ("mv", "dest.txt"),+ ],+ ),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_quoted_paths(self) -> None:+ """Test file path extraction with quoted paths."""+ test_cases = [+ ('rm "file with spaces.txt"', []), # Quoted paths not extracted+ ("rm 'file.txt'", []), # Quoted paths not extracted+ (+ 'mv "old file.txt" "new file.txt"',+ [], # Quoted paths not extracted+ ),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_dangerous_paths(self) -> None:+ """Test file path extraction with dangerous paths."""+ test_cases = [+ ("rm ~/.bashrc", [("rm", "~/.bashrc")]),+ ("chmod 600 ~/.ssh/config", [("chmod", "~/.ssh/config")]),+ (+ "mv file.txt .git/hooks/",+ [("mv", "file.txt"), ("mv", ".git/hooks/")],+ ),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_commands_without_file_operations(self) -> None:+ """Test commands that don't operate on files."""+ test_cases = [+ ("ls", []),+ ("pwd", []),+ ("echo 'hello'", []),+ ("git status", []),+ ("docker ps", []),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_file_paths(cmd)+ self.assertEqual(result, expected)++ async def test_empty_command(self) -> None:+ """Test empty command."""+ result = self.parser.extract_file_paths("")+ self.assertEqual(result, [])++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.parser = None+++class BashParserRedirectionsTest(IsolatedAsyncioTestCase):+ """Test extract_redirections() method."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.parser = BashCommandParser()++ async def test_simple_output_redirection(self) -> None:+ """Test simple output redirection (>)."""+ test_cases = [+ ("echo 'hello' > output.txt", ["output.txt"]),+ ("cat file.txt > backup.txt", ["backup.txt"]),+ ("ls -la > list.txt", ["list.txt"]),+ ("git log > history.txt", ["history.txt"]),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_redirections(cmd)+ self.assertEqual(result, expected)++ async def test_append_redirection(self) -> None:+ """Test append redirection (>>)."""+ test_cases = [+ ("echo 'line' >> log.txt", ["log.txt"]),+ ("cat file.txt >> combined.txt", ["combined.txt"]),+ ("ls >> list.txt", ["list.txt"]),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_redirections(cmd)+ self.assertEqual(result, expected)++ async def test_error_redirection(self) -> None:+ """Test error redirection (2>)."""+ test_cases = [+ ("command 2> error.log", ["error.log"]),+ ("python script.py 2> stderr.txt", ["stderr.txt"]),+ ("npm run build 2> build_errors.log", ["build_errors.log"]),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_redirections(cmd)+ self.assertEqual(result, expected)++ async def test_combined_redirection(self) -> None:+ """Test combined stdout/stderr redirection (&>)."""+ test_cases = [+ ("command &> output.log", ["output.log"]),+ ("python script.py &> all_output.txt", ["all_output.txt"]),+ ("npm test &> test_results.log", ["test_results.log"]),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_redirections(cmd)+ self.assertEqual(result, expected)++ async def test_multiple_redirections(self) -> None:+ """Test commands with multiple redirections."""+ test_cases = [+ ("command > output.txt 2> error.log", ["output.txt", "error.log"]),+ (+ "python script.py > stdout.txt 2> stderr.txt",+ ["stdout.txt", "stderr.txt"],+ ),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_redirections(cmd)+ self.assertEqual(result, expected)++ async def test_compound_commands_with_redirections(self) -> None:+ """Test compound commands with multiple redirections."""+ test_cases = [+ (+ "echo 'a' > file1.txt && echo 'b' > file2.txt",+ ["file1.txt", "file2.txt"],+ ),+ (+ "cat file.txt > backup.txt || cp file.txt backup.txt",+ ["backup.txt"],+ ),+ ("ls > list1.txt; pwd > list2.txt", ["list1.txt", "list2.txt"]),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_redirections(cmd)+ self.assertEqual(result, expected)++ async def test_redirections_with_quoted_paths(self) -> None:+ """Test redirections with quoted file paths."""+ test_cases = [+ (+ 'echo "hello" > "output file.txt"',+ [],+ ), # Quoted redirections not extracted+ (+ "cat file.txt > 'backup.txt'",+ [],+ ), # Quoted redirections not extracted+ (+ 'ls > "file with spaces.log"',+ [],+ ), # Quoted redirections not extracted+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_redirections(cmd)+ self.assertEqual(result, expected)++ async def test_redirections_to_dangerous_paths(self) -> None:+ """Test redirections to dangerous paths."""+ test_cases = [+ ("echo 'alias' >> ~/.bashrc", ["~/.bashrc"]),+ ("cat key > ~/.ssh/authorized_keys", ["~/.ssh/authorized_keys"]),+ ("echo 'config' > .git/config", [".git/config"]),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_redirections(cmd)+ self.assertEqual(result, expected)++ async def test_redirections_with_absolute_paths(self) -> None:+ """Test redirections with absolute paths."""+ test_cases = [+ ("echo 'data' > /tmp/output.txt", ["/tmp/output.txt"]),+ ("cat file.txt > /var/log/app.log", ["/var/log/app.log"]),+ ("ls > /home/user/list.txt", ["/home/user/list.txt"]),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_redirections(cmd)+ self.assertEqual(result, expected)++ async def test_commands_without_redirections(self) -> None:+ """Test commands without redirections."""+ test_cases = [+ ("ls -la", []),+ ("cat file.txt", []),+ ("echo 'hello'", []),+ ("git status", []),+ ("rm file.txt", []),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_redirections(cmd)+ self.assertEqual(result, expected)++ async def test_pipe_not_redirection(self) -> None:+ """Test that pipes (|) are not treated as redirections."""+ test_cases = [+ ("cat file.txt | grep pattern", []),+ ("ls | wc -l", []),+ ("git log | head -n 10", []),+ ]+ for cmd, expected in test_cases:+ with self.subTest(cmd=cmd):+ result = self.parser.extract_redirections(cmd)+ self.assertEqual(result, expected)++ async def test_empty_command(self) -> None:+ """Test empty command."""+ result = self.parser.extract_redirections("")+ self.assertEqual(result, [])++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.parser = Nonediff --git a/tests/permission_engine_test.py b/tests/permission_engine_test.pynew file mode 100644index 000000000..2c5bfbca6--- /dev/null+++ b/tests/permission_engine_test.py@@ -0,0 +1,886 @@+# -*- coding: utf-8 -*-+"""Test cases for PermissionEngine."""+import json+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.tool import (+ PermissionEngine,+ PermissionMode,+ PermissionContext,+ PermissionRule,+ PermissionBehavior,+ AdditionalWorkingDirectory,+)+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."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.context = PermissionContext(mode=PermissionMode.DEFAULT)+ self.engine = PermissionEngine(self.context)++ async def test_deny_rule_priority(self) -> None:+ """Test that deny rules have highest priority."""+ # Add both allow and deny rules for the same tool+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="git:*",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="git:*",+ behavior=PermissionBehavior.DENY,+ source="test",+ ),+ )++ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "git status"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Deny should take precedence over allow+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ async def test_ask_rule_priority(self) -> None:+ """Test that ask rules have priority over allow rules."""+ # Add both allow and ask rules for the same tool+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="npm:*",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="npm:*",+ behavior=PermissionBehavior.ASK,+ source="test",+ ),+ )++ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "npm install"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Ask should take precedence over allow+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_rule_priority_order(self) -> None:+ """Test complete rule priority: deny > ask > allow."""+ # Add all three types of rules+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="test:*",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="test:*",+ behavior=PermissionBehavior.ASK,+ source="test",+ ),+ )+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="test:*",+ behavior=PermissionBehavior.DENY,+ source="test",+ ),+ )++ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "test command"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Deny should win+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.engine = None+ self.context = None+++class PermissionEngineModeTest(IsolatedAsyncioTestCase):+ """Test cases for different permission modes."""++ async def test_bypass_mode(self) -> None:+ """Test BYPASS mode allows operations without explicit rules."""+ context = PermissionContext(mode=PermissionMode.BYPASS)+ engine = PermissionEngine(context)++ # No rules added - should default to ALLOW in BYPASS mode+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "npm install"}),+ )+ decision = await engine.check_permission(tool_call)++ # BYPASS mode should allow by default+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ async def test_bypass_mode_with_deny_rule(self) -> None:+ """Test that deny rules still work in BYPASS mode (deny has the+ highest priority)."""+ context = PermissionContext(mode=PermissionMode.BYPASS)+ engine = PermissionEngine(context)++ # Add a deny rule+ engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="rm:*",+ behavior=PermissionBehavior.DENY,+ source="test",+ ),+ )++ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "rm -rf /tmp"}),+ )+ decision = await engine.check_permission(tool_call)++ # Deny rules have highest priority, even in BYPASS mode+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ async def test_bypass_mode_with_dangerous_path(self) -> None:+ """Test that dangerous paths require confirmation even in+ BYPASS mode.+ """+ context = PermissionContext(mode=PermissionMode.BYPASS)+ engine = PermissionEngine(context)++ # Try to write to a dangerous file+ tool_call = ToolCallBlock(+ id="1",+ name="Write",+ input=json.dumps({"file_path": "/home/user/.bashrc"}),+ )+ decision = await engine.check_permission(tool_call)++ # Safety checks are bypass-immune+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_dont_ask_mode(self) -> None:+ """Test DONT_ASK mode denies operations that would normally ask."""+ context = PermissionContext(mode=PermissionMode.DONT_ASK)+ engine = PermissionEngine(context)++ # No rules added, should default to ASK in DEFAULT mode+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "npm install"}),+ )+ decision = await engine.check_permission(tool_call)++ # DONT_ASK mode should deny instead of ask+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ async def test_accept_edits_mode_within_working_directory(self) -> None:+ """Test ACCEPT_EDITS mode allows to Write/Read/Edit within working+ directories."""+ context = PermissionContext(+ mode=PermissionMode.ACCEPT_EDITS,+ working_directories={+ "/tmp/project": AdditionalWorkingDirectory(+ path="/tmp/project",+ source="test",+ ),+ },+ )+ engine = PermissionEngine(context)++ # Write tool within working directory+ tool_call = ToolCallBlock(+ id="1",+ name="Write",+ input=json.dumps({"file_path": "/tmp/project/file.txt"}),+ )+ decision = await engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ # Read tool within working directory+ tool_call = ToolCallBlock(+ id="2",+ name="Read",+ input=json.dumps({"file_path": "/tmp/project/file.txt"}),+ )+ decision = await engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ # Edit tool within working directory+ tool_call = ToolCallBlock(+ id="3",+ name="Edit",+ input=json.dumps({"file_path": "/tmp/project/file.txt"}),+ )+ decision = await engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ async def test_accept_edits_mode_outside_working_directory(self) -> None:+ """Test ACCEPT_EDITS mode asks for edits outside working+ directories."""+ context = PermissionContext(+ mode=PermissionMode.ACCEPT_EDITS,+ working_directories={+ "/tmp/project": AdditionalWorkingDirectory(+ path="/tmp/project",+ source="test",+ ),+ },+ )+ engine = PermissionEngine(context)++ # Edit tool outside working directory+ tool_call = ToolCallBlock(+ id="1",+ name="Edit",+ input=json.dumps({"file_path": "/home/user/file.txt"}),+ )+ decision = await engine.check_permission(tool_call)++ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_explore_mode_read_operations(self) -> None:+ """Test EXPLORE mode allows read operations."""+ context = PermissionContext(mode=PermissionMode.EXPLORE)+ engine = PermissionEngine(context)++ # Read operation+ tool_call = ToolCallBlock(+ id="1",+ name="Read",+ input=json.dumps({"file_path": "/tmp/file.txt"}),+ )+ decision = await engine.check_permission(tool_call)++ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ async def test_explore_mode_write_operations(self) -> None:+ """Test EXPLORE mode denies write operations."""+ context = PermissionContext(mode=PermissionMode.EXPLORE)+ engine = PermissionEngine(context)++ # Write operation+ tool_call = ToolCallBlock(+ id="1",+ name="Write",+ input=json.dumps({"file_path": "/tmp/file.txt"}),+ )+ decision = await engine.check_permission(tool_call)++ self.assertEqual(decision.behavior, PermissionBehavior.DENY)+++class PermissionEngineBashRuleTest(IsolatedAsyncioTestCase):+ """Test cases for Bash command rule matching."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.context = PermissionContext(mode=PermissionMode.DEFAULT)+ self.engine = PermissionEngine(self.context)++ async def test_bash_prefix_pattern_matching(self) -> None:+ """Test bash command prefix pattern matching with :* wildcard."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="git:*",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )++ # Test exact command+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "git"}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ # Test command with arguments+ tool_call = ToolCallBlock(+ id="2",+ name="Bash",+ input=json.dumps({"command": "git status"}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ # Test command with multiple arguments+ tool_call = ToolCallBlock(+ id="3",+ name="Bash",+ input=json.dumps({"command": "git add ."}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ # Test non-matching command+ tool_call = ToolCallBlock(+ id="4",+ name="Bash",+ input=json.dumps({"command": "npm install"}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_bash_substring_pattern_matching(self) -> None:+ """Test bash command substring pattern matching."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="install",+ behavior=PermissionBehavior.DENY,+ source="test",+ ),+ )++ # Test command containing substring+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "npm install package"}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ # Test command containing substring in different position+ tool_call = ToolCallBlock(+ id="2",+ name="Bash",+ input=json.dumps({"command": "pip install requests"}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ async def test_bash_multiple_rules(self) -> None:+ """Test bash command matching with multiple rules."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="rm:*",+ behavior=PermissionBehavior.DENY,+ source="test",+ ),+ )+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="git:*",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )++ # Test deny rule+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "rm -rf /tmp"}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ # Test allow rule+ tool_call = ToolCallBlock(+ id="2",+ name="Bash",+ input=json.dumps({"command": "git status"}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ # Test no matching rule+ tool_call = ToolCallBlock(+ id="3",+ name="Bash",+ input=json.dumps({"command": "npm install"}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.engine = None+ self.context = None+++class PermissionEngineFileRuleTest(IsolatedAsyncioTestCase):+ """Test cases for file operation rule matching."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.context = PermissionContext(mode=PermissionMode.DEFAULT)+ self.engine = PermissionEngine(self.context)++ async def test_file_glob_pattern_matching(self) -> None:+ """Test file path glob pattern matching."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Read",+ rule_content="*.py",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )++ # Test matching file+ tool_call = ToolCallBlock(+ id="1",+ name="Read",+ input=json.dumps({"file_path": "test.py"}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ # Test non-matching file+ tool_call = ToolCallBlock(+ id="2",+ name="Read",+ input=json.dumps({"file_path": "test.txt"}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_file_directory_pattern_matching(self) -> None:+ """Test file path directory pattern matching."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Edit",+ rule_content="/tmp/**",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )++ # Test file in directory - glob pattern /tmp/** should match+ tool_call = ToolCallBlock(+ id="1",+ name="Edit",+ input=json.dumps({"file_path": "/tmp/test.txt"}),+ )+ decision = await self.engine.check_permission(tool_call)+ # Note: The current implementation uses fnmatch/pathlib matching+ # /tmp/** may not match /tmp/test.txt depending on implementation+ # This test verifies the actual behavior+ self.assertIn(+ decision.behavior,+ [PermissionBehavior.ALLOW, PermissionBehavior.ASK],+ )++ # Test file in subdirectory+ tool_call = ToolCallBlock(+ id="2",+ name="Edit",+ input=json.dumps({"file_path": "/tmp/subdir/test.txt"}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertIn(+ decision.behavior,+ [PermissionBehavior.ALLOW, PermissionBehavior.ASK],+ )++ # Test file outside directory+ tool_call = ToolCallBlock(+ id="3",+ name="Edit",+ input=json.dumps({"file_path": "/home/user/test.txt"}),+ )+ decision = await self.engine.check_permission(tool_call)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.engine = None+ self.context = None+++class PermissionEngineDangerousPathTest(IsolatedAsyncioTestCase):+ """Test cases for dangerous path detection (bypass-immune safety+ checks)."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.context = PermissionContext(mode=PermissionMode.DEFAULT)+ self.engine = PermissionEngine(self.context)++ async def test_dangerous_file_blocks_write(self) -> None:+ """Test that Write operations on dangerous files require+ confirmation."""+ # Try to write a dangerous file+ tool_call = ToolCallBlock(+ id="1",+ name="Write",+ input=json.dumps({"file_path": "/home/user/.bashrc"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # 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+ confirmation."""+ # Try to edit a dangerous file+ tool_call = ToolCallBlock(+ id="1",+ name="Edit",+ input=json.dumps({"file_path": "/home/user/.gitconfig"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should ask for confirmation (safety check)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("safety", decision.decision_reason.lower())++ async def test_dangerous_directory_blocks_write(self) -> None:+ """Test that Write operations in dangerous directories require+ confirmation."""+ # Try to write in a dangerous directory+ tool_call = ToolCallBlock(+ id="1",+ name="Write",+ input=json.dumps({"file_path": "/home/user/.ssh/config"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should ask for confirmation (safety check)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("safety", decision.decision_reason.lower())++ async def test_dangerous_path_in_bash_command(self) -> None:+ """Test that Bash commands on dangerous paths require confirmation."""+ # Try to remove a dangerous file+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "rm /home/user/.bashrc"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should ask for confirmation (safety check)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("safety", decision.decision_reason.lower())++ async def test_dangerous_path_bypass_immune(self) -> None:+ """Test that dangerous paths require confirmation even in+ BYPASS mode."""+ context = PermissionContext(mode=PermissionMode.BYPASS)+ engine = PermissionEngine(context)++ # Try to write a dangerous file in BYPASS mode+ tool_call = ToolCallBlock(+ id="1",+ name="Write",+ input=json.dumps({"file_path": "/home/user/.bashrc"}),+ )+ decision = await engine.check_permission(tool_call)++ # Safety checks are bypass-immune+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_dangerous_path_in_accept_edits_mode(self) -> None:+ """Test that dangerous paths require confirmation even in+ ACCEPT_EDITS mode."""+ context = PermissionContext(+ mode=PermissionMode.ACCEPT_EDITS,+ working_directories={+ "/home/user": AdditionalWorkingDirectory(+ path="/home/user",+ source="test",+ ),+ },+ )+ engine = PermissionEngine(context)++ # Try to write a dangerous file in working directory+ tool_call = ToolCallBlock(+ id="1",+ name="Write",+ input=json.dumps({"file_path": "/home/user/.bashrc"}),+ )+ decision = await engine.check_permission(tool_call)++ # Should ask despite being in working directory+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_safe_file_allows_write(self) -> None:+ """Test that Write operations on safe files work normally."""+ # Try to write a safe file+ tool_call = ToolCallBlock(+ id="1",+ name="Write",+ input=json.dumps({"file_path": "/home/user/test.py"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should ask (no allow rule, but not blocked by safety check)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ # Should NOT be a safety check+ self.assertNotIn("safety", decision.decision_reason.lower())++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.engine = None+ self.context = None+++class PermissionEngineSuggestionTest(IsolatedAsyncioTestCase):+ """Test cases for permission rule suggestions."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.context = PermissionContext(mode=PermissionMode.DEFAULT)+ self.engine = PermissionEngine(self.context)++ async def test_bash_suggestions(self) -> None:+ """Test suggestion generation for bash commands."""+ # Use a non-read-only command to test suggestions+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "git commit -m 'test'"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should ask (not read-only)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ # Should have suggestions+ self.assertIsNotNone(decision.suggested_rules)+ self.assertGreater(len(decision.suggested_rules), 0)++ # Check suggestion content - should generate two-word prefix rule+ suggestion_contents = [+ s.rule_content for s in decision.suggested_rules+ ]+ # git commit should generate "git commit:*"+ self.assertIn("git commit:*", suggestion_contents)++ async def test_file_suggestions(self) -> None:+ """Test suggestion generation for file operations."""+ tool_call = ToolCallBlock(+ id="1",+ name="Read",+ input=json.dumps({"file_path": "/tmp/test.py"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should have suggestions+ self.assertGreater(len(decision.suggested_rules), 0)++ # Check suggestion content - should generate directory rule+ suggestion_contents = [+ s.rule_content for s in decision.suggested_rules+ ]+ self.assertIn("/tmp/**", suggestion_contents)++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.engine = None+ self.context = None+++class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):+ """Test cases for read-only command auto-allow."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.context = PermissionContext(mode=PermissionMode.DEFAULT)+ self.engine = PermissionEngine(self.context)++ async def test_git_status_is_read_only(self) -> None:+ """Test that git status is auto-allowed as read-only."""+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "git status"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should be allowed (read-only command)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)+ self.assertIn("read-only", decision.decision_reason.lower())++ async def test_ls_is_read_only(self) -> None:+ """Test that ls is auto-allowed as read-only."""+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "ls -la"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should be allowed (read-only command)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ async def test_cat_is_read_only(self) -> None:+ """Test that cat is auto-allowed as read-only."""+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "cat file.txt"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should be allowed (read-only command)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ async def test_git_commit_is_not_read_only(self) -> None:+ """Test that git commit is not auto-allowed (not read-only)."""+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "git commit -m 'test'"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should ask (not read-only)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_compound_command_with_dangerous_path(self) -> None:+ """Test compound command with read-only and dangerous path o+ perations."""+ # ls is read-only, but rm ~/.bashrc is dangerous+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "ls -la && rm ~/.bashrc"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should ask because of dangerous path (safety check is bypass-immune)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("safety", decision.decision_reason.lower())++ async def test_compound_command_all_read_only(self) -> None:+ """Test compound command with all read-only operations."""+ # Both ls and cat are read-only+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "ls -la && cat file.txt"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should be allowed (all read-only)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ async def test_compound_command_with_write_operation(self) -> None:+ """Test compound command with read-only and write operations."""+ # ls is read-only, but git commit is not+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "ls -la && git commit -m 'test'"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should ask (contains non-read-only command)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_output_redirection_to_dangerous_path(self) -> None:+ """Test output redirection to dangerous path."""+ # cat is read-only, but redirecting to ~/.bashrc is dangerous+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "cat file.txt > ~/.bashrc"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should ask because of dangerous path in redirection+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("safety", decision.decision_reason.lower())++ async def test_output_redirection_to_safe_path(self) -> None:+ """Test output redirection to safe path."""+ # cat is read-only, redirecting to safe path+ tool_call = ToolCallBlock(+ id="1",+ name="Bash",+ input=json.dumps({"command": "cat file.txt > /tmp/output.txt"}),+ )+ decision = await self.engine.check_permission(tool_call)++ # Should ask (redirection is not considered read-only)+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.engine = None+ self.context = None