Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
perf(permission): improve the implementation of the current permission system (#1767)
DavdGao68f643db4d81
diff --git a/src/agentscope/permission/_decision.py b/src/agentscope/permission/_decision.pyindex 674ad089b..c85b9f87e 100644--- a/src/agentscope/permission/_decision.py+++ b/src/agentscope/permission/_decision.py@@ -29,3 +29,40 @@ class PermissionDecision:suggested_rules: list[PermissionRule] | None = None"""Optional list of suggested permission rules for user to apply."""++ bypass_immune: bool = False+ """Whether this decision is immune to being silenced by allow rules+ ("bypass-immune").++ Only meaningful when :attr:`behavior` is :attr:`PermissionBehavior.ASK`.+ A tool sets this to ``True`` to signal that the operation is+ dangerous enough that **no allow rule** may convert the ASK into an+ ALLOW — the user must explicitly confirm in-the-moment. In+ :attr:`PermissionMode.DONT_ASK` where no user is available, a+ bypass-immune ASK is converted to DENY rather than silently allowed.++ Per-mode handling of a ``bypass_immune=True`` ASK:++ - ``DEFAULT`` / ``ACCEPT_EDITS``: honored — allow rules cannot+ override.+ - ``EXPLORE``: not applicable (the engine resolves EXPLORE via+ :meth:`ToolBase.check_read_only` and does not invoke+ :meth:`ToolBase.check_permissions`).+ - ``BYPASS``: **intentionally ignored** — BYPASS's contract is+ "the user has opted out of safety prompts; only deny / ask+ rules remain as guardrails." Use deny rules in BYPASS to+ enforce specific protections.+ - ``DONT_ASK``: converted to DENY (no user available).++ Default is ``False``: a regular ASK that may be overridden by an+ allow rule in DEFAULT / ACCEPT_EDITS, and is silently allowed by+ BYPASS's fallback. Tools should set this only for genuine safety+ checks (e.g. writes to dangerous paths, ``rm -rf /``, command+ injection patterns) — not for "I'd prefer user input" cases.++ Note: this field is internal metadata for the permission engine.+ Callers handling the decision (agent loop, HITL backend, UI) treat+ a bypass-immune ASK the same as a regular ASK — both prompt the+ user. The distinction only governs whether engine-level rules /+ modes may override it before reaching the caller.+ """diff --git a/src/agentscope/permission/_engine.py b/src/agentscope/permission/_engine.pyindex 600e893c4..5f31c1f9c 100644--- a/src/agentscope/permission/_engine.py+++ b/src/agentscope/permission/_engine.py@@ -16,22 +16,17 @@ else: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 ask rules- 3. Tool-specific checks (EXPLORE/ACCEPT_EDITS modes, dangerous paths,- read-only commands, etc.) - bypass-immune- 4. Check allow rules- 5. BYPASS mode check- 6. Default behavior (ask)+ Evaluates tool execution requests against configured permission rules.+ Matching strategy is delegated to each tool's :meth:`ToolBase.match_rule`:++ - Bash tools: substring / prefix wildcard matching against the command+ - Write/Read/Edit tools: glob matching against file paths+ - Other tools: generic pattern matching (or tool-name-level only)++ Each :class:`PermissionMode` has its own ``_check_<mode>`` method so+ that mode policies are self-contained and readable in isolation. See+ :meth:`check_permission` for the dispatcher and the individual methods+ for per-mode evaluation order."""def __init__(@@ -85,197 +80,475 @@ class PermissionEngine:) -> 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 (bypass-immune):- - EXPLORE mode logic (read-only tools auto-allowed)- - ACCEPT_EDITS mode logic (file edits in working dir auto-allowed)- - Dangerous path checks (safety checks)- - Read-only command checks (for Bash)- - Other tool-specific permission logic- 4. Allow rules- 5. BYPASS mode check- 6. Default behavior (ask)+ Dispatches to a per-mode private method so each mode's policy+ is self-contained and readable in isolation:++ - DEFAULT → :meth:`_check_default`+ - EXPLORE → :meth:`_check_explore`+ - ACCEPT_EDITS → :meth:`_check_accept_edits`+ - BYPASS → :meth:`_check_bypass`+ - DONT_ASK → :meth:`_check_dont_ask`Args:tool (`ToolBase`):- The tool instance being called (used for tool-specific checks)- tool_input (`dict`):- The tool input data (used for rule matching and tool-specific- checks)+ The tool instance being called.+ tool_input (`dict[str, Any]`):+ The tool input data, used for rule matching and+ tool-specific checks.Returns:`PermissionDecision`:- Decision indicating whether to allow, deny, or ask+ Decision indicating whether to allow, deny, or ask."""+ mode = self.context.mode+ if mode == PermissionMode.DEFAULT:+ return await self._check_default(tool, tool_input)+ if mode == PermissionMode.EXPLORE:+ return await self._check_explore(tool, tool_input)+ if mode == PermissionMode.ACCEPT_EDITS:+ return await self._check_accept_edits(tool, tool_input)+ if mode == PermissionMode.BYPASS:+ return await self._check_bypass(tool, tool_input)+ if mode == PermissionMode.DONT_ASK:+ return await self._check_dont_ask(tool, tool_input)+ raise ValueError(f"Unknown permission mode: {mode}")++ async def _check_default(+ self,+ tool: ToolBase,+ tool_input: dict[str, Any],+ ) -> PermissionDecision:+ """Permission check for :attr:`PermissionMode.DEFAULT`.++ Every operation requires explicit permission unless either an+ allow rule matches or the tool's own ``check_permissions``+ explicitly returns ALLOW (e.g. ``Bash`` auto-allows recognized+ read-only commands like ``ls``/``git status``). Evaluation order:++ 1. Deny rules → DENY+ 2. Ask rules → ASK (with suggestions)+ 3. ``tool.check_permissions``:+ - ALLOW / DENY → returned as-is+ - Safety ASK (bypass-immune) → returned with suggestions; cannot+ be overridden by allow rules+ - Non-safety ASK / PASSTHROUGH → continue+ 4. Allow rules → ALLOW+ 5. Default → ASK (with suggestions)- # 1. Check tool-level deny rules (highest priority)- deny_decision = self._check_deny_rules(tool, tool_input)- if deny_decision:- return deny_decision+ Args:+ tool (`ToolBase`):+ The tool instance being called.+ tool_input (`dict[str, Any]`):+ The tool input data.- # 2. Check tool-level ask rules- ask_decision = self._check_ask_rules(tool, tool_input)- if ask_decision:- # Generate suggestions for ASK decisions- ask_decision.suggested_rules = self._generate_suggestions(+ Returns:+ `PermissionDecision`:+ The final decision.+ """+ # step 1: deny rules — highest priority+ deny = self._check_deny_rules(tool, tool_input)+ if deny:+ return deny++ # step 2: ask rules+ ask = self._check_ask_rules(tool, tool_input)+ if ask:+ ask.suggested_rules = self._generate_suggestions(tool, tool_input)+ return ask++ # step 3: tool's own check_permissions+ tool_decision = await tool.check_permissions(tool_input, self.context)+ # step 3a: tool ALLOW / DENY returned as-is+ if tool_decision.behavior in (+ PermissionBehavior.ALLOW,+ PermissionBehavior.DENY,+ ):+ return tool_decision+ # step 3b: safety ASK is bypass-immune — allow rules can't override+ if self._is_safety_ask(tool_decision):+ tool_decision.suggested_rules = self._generate_suggestions(tool,tool_input,)- return ask_decision+ return tool_decision++ # step 4: allow rules+ allow = self._check_allow_rules(tool, tool_input)+ if allow:+ return allow- # 3. Tool-specific permission checks (dangerous paths, etc.)- # These are bypass-immune- tool_decision = await self._tool_check_permissions(- tool_input,- tool,+ # step 5: default — ASK the user+ default = PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message=f"Permission required for {tool.name}",+ decision_reason=f"Mode: {self.context.mode.value}",)+ default.suggested_rules = self._generate_suggestions(tool, tool_input)+ return default- # 3a. Tool denied permission (bypass-immune)- if tool_decision and tool_decision.behavior == PermissionBehavior.DENY:- return tool_decision+ async def _check_explore(+ self,+ tool: ToolBase,+ tool_input: dict[str, Any],+ ) -> PermissionDecision:+ """Permission check for :attr:`PermissionMode.EXPLORE`.- # 3b. Tool allowed permission (e.g., EXPLORE mode allows Read)- if (- tool_decision- and tool_decision.behavior == PermissionBehavior.ALLOW- ):- return tool_decision+ Read-only mode — modifications are categorically denied. Evaluation+ order:++ 1. Deny rules → DENY+ 2. Ask rules → ASK (with suggestions)+ 3. :meth:`ToolBase.check_read_only` (input-aware):+ - True → ALLOW+ - False → DENY++ ``tool.check_permissions`` is not invoked: EXPLORE is fully+ resolved by the read-only verdict, so safety ASK paths (e.g.+ ``rm -rf /``) are subsumed into the broader DENY. Allow rules are+ intentionally not consulted — EXPLORE's read-only guarantee+ cannot be granted away by a user-configured rule.++ Args:+ tool (`ToolBase`):+ The tool instance being called.+ tool_input (`dict[str, Any]`):+ The tool input data.++ Returns:+ `PermissionDecision`:+ ALLOW for read-only invocations, DENY otherwise.+ """+ # step 1: deny rules+ deny = self._check_deny_rules(tool, tool_input)+ if deny:+ return deny++ # step 2: ask rules+ ask = self._check_ask_rules(tool, tool_input)+ if ask:+ ask.suggested_rules = self._generate_suggestions(tool, tool_input)+ return ask++ # step 3: read-only verdict decides everything (ALLOW or DENY)+ if await tool.check_read_only(tool_input):+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=(+ f"Permission granted for {tool.name} "+ f"(explore mode - read-only invocation)"+ ),+ decision_reason="Explore mode allows read-only operations",+ )+ return PermissionDecision(+ behavior=PermissionBehavior.DENY,+ message=(+ f"Permission denied for {tool.name} "+ f"(explore mode is read-only)"+ ),+ decision_reason="Explore mode does not allow modifications",+ )++ async def _check_accept_edits(+ self,+ tool: ToolBase,+ tool_input: dict[str, Any],+ ) -> PermissionDecision:+ """Permission check for :attr:`PermissionMode.ACCEPT_EDITS`.++ Edits within working directories are auto-allowed by each tool's+ own ``check_permissions``; other operations follow the normal+ flow. Evaluation order:++ 1. Deny rules → DENY+ 2. Ask rules → ASK (with suggestions)+ 3. :meth:`ToolBase.check_read_only` → True → ALLOW (fast path)+ 4. ``tool.check_permissions``:+ - ALLOW (e.g. ``Write`` to a file in the working directory) /+ DENY → returned as-is+ - Safety ASK (bypass-immune) → returned with suggestions+ - Non-safety ASK / PASSTHROUGH → continue+ 5. Allow rules → ALLOW+ 6. Default → ASK (with suggestions)++ Args:+ tool (`ToolBase`):+ The tool instance being called.+ tool_input (`dict[str, Any]`):+ The tool input data.++ Returns:+ `PermissionDecision`:+ The final decision.+ """+ # step 1: deny rules+ deny = self._check_deny_rules(tool, tool_input)+ if deny:+ return deny++ # step 2: ask rules+ ask = self._check_ask_rules(tool, tool_input)+ if ask:+ ask.suggested_rules = self._generate_suggestions(tool, tool_input)+ return ask++ # step 3: read-only fast path — ALLOW without invoking the tool+ if await tool.check_read_only(tool_input):+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=(+ f"Permission granted for {tool.name} "+ f"(accept edits mode - read-only invocation)"+ ),+ decision_reason="Accept edits mode allows read-only "+ "operations",+ )- # 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()+ # step 4: tool's own check_permissions (working-directory check+ # for Write/Edit, path-checked auto-allow for Bash, ...)+ tool_decision = await tool.check_permissions(tool_input, self.context)+ # step 4a: tool ALLOW / DENY returned as-is+ if tool_decision.behavior in (+ PermissionBehavior.ALLOW,+ PermissionBehavior.DENY,):+ return tool_decision+ # step 4b: safety ASK is bypass-immune+ if self._is_safety_ask(tool_decision):tool_decision.suggested_rules = self._generate_suggestions(tool,tool_input,)return tool_decision- # 4. Check allow rules- allow_decision = self._check_allow_rules(tool, tool_input)- if allow_decision:- return allow_decision-- # 5. 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",- )+ # step 5: allow rules+ allow = self._check_allow_rules(tool, tool_input)+ if allow:+ return allow- # 7. Default behavior (passthrough → ask)- default_decision = self._default_decision_ask(tool.name)- default_decision.suggested_rules = self._generate_suggestions(- tool,- tool_input,+ # step 6: default — ASK the user+ default = PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message=f"Permission required for {tool.name}",+ decision_reason=f"Mode: {self.context.mode.value}",)- return default_decision+ default.suggested_rules = self._generate_suggestions(tool, tool_input)+ return default- async def _tool_check_permissions(+ async def _check_bypass(self,- input_data: dict[str, Any],tool: ToolBase,- ) -> PermissionDecision | None:- """Tool-specific permission checks.-- This includes:- - EXPLORE mode logic (read-only tools only)- - Tool's own check_permissions() method+ tool_input: dict[str, Any],+ ) -> PermissionDecision:+ """Permission check for :attr:`PermissionMode.BYPASS`.++ BYPASS is the "fully trusted" mode: the user has explicitly+ opted out of safety prompts. All tool-emitted safety ASKs+ (``rm -rf /``, write to ``~/.bashrc``, command-injection+ patterns, dangerous sed, etc.) are **skipped** — only+ user-configured deny / ask rules and tool-emitted DENY remain+ as guardrails. The :attr:`PermissionDecision.bypass_immune`+ field has no effect in BYPASS by design.++ Use BYPASS only for sandboxed / containerized environments or+ when you fully trust the agent's behavior. For unattended+ execution where safety still matters, use+ :attr:`PermissionMode.DONT_ASK` instead — it converts safety+ ASKs to DENY rather than skipping them.++ Evaluation order:++ 1. Deny rules → DENY+ 2. Ask rules → ASK (with suggestions; honors explicit user intent)+ 3. ``tool.check_permissions``:+ - ALLOW / DENY → returned as-is+ - ASK (including bypass-immune safety ASKs) → falls through+ - PASSTHROUGH → falls through+ 4. Allow rules → ALLOW+ 5. Fallback → ALLOW (BYPASS)Args:- input_data (`dict[str, Any]`):- The tool input datatool (`ToolBase`):- The tool instance being called (used for tool-specific checks)+ The tool instance being called.+ tool_input (`dict[str, Any]`):+ The tool input data.Returns:- `PermissionDecision | None`:- PermissionDecision if tool has specific logic, None for- passthrough+ `PermissionDecision`:+ The final decision."""- # EXPLORE and ACCEPT_EDITS modes: check read-only tool handling- if self.context.mode in (- PermissionMode.EXPLORE,- PermissionMode.ACCEPT_EDITS,+ # step 1: deny rules+ deny = self._check_deny_rules(tool, tool_input)+ if deny:+ return deny++ # step 2: ask rules (honor explicit user intent to be prompted)+ ask = self._check_ask_rules(tool, tool_input)+ if ask:+ ask.suggested_rules = self._generate_suggestions(tool, tool_input)+ return ask++ # step 3: tool's own check_permissions — ALLOW / DENY returned;+ # any ASK (including bypass-immune safety ASK) is intentionally+ # NOT honored here, per BYPASS's "skip safety prompts" contract.+ tool_decision = await tool.check_permissions(tool_input, self.context)+ if tool_decision.behavior in (+ PermissionBehavior.ALLOW,+ PermissionBehavior.DENY,):- mode_decision = self._check_explore_mode(tool)- if mode_decision:- return mode_decision-- # Call tool's own check_permissions method if available- decision = await tool.check_permissions(- input_data,- self.context,- )- # If tool returns PASSTHROUGH, continue with Engine's logic- if decision.behavior != PermissionBehavior.PASSTHROUGH:- return decision+ return tool_decision- # No specific tool logic, passthrough- return None+ # step 4: allow rules+ allow = self._check_allow_rules(tool, tool_input)+ if allow:+ return allow- def _check_explore_mode(+ # step 5: bypass fallback — ALLOW everything else+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"Permission granted for {tool.name} (bypass mode)",+ decision_reason="Bypass mode allows all operations",+ )++ async def _check_dont_ask(self,tool: ToolBase,- ) -> PermissionDecision | None:- """Check permissions for read-only tools in EXPLORE and- ACCEPT_EDITS modes.+ tool_input: dict[str, Any],+ ) -> PermissionDecision:+ """Permission check for :attr:`PermissionMode.DONT_ASK`.++ Used when no user is available to answer prompts (scheduled+ tasks, background runs). Invariant: this method must never+ return :attr:`PermissionBehavior.ASK` — every code path that+ would otherwise ASK is converted to DENY via+ :meth:`_convert_ask_to_deny`. Evaluation order:++ 1. Deny rules → DENY+ 2. Ask rules → DENY (converted, with suggestions preserved)+ 3. ``tool.check_permissions``:+ - ALLOW / DENY → returned as-is+ - Safety ASK → DENY (converted, with suggestions preserved)+ - Non-safety ASK / PASSTHROUGH → continue+ 4. Allow rules → ALLOW+ 5. Default → DENY (user not available to answer)++ Args:+ tool (`ToolBase`):+ The tool instance being called.+ tool_input (`dict[str, Any]`):+ The tool input data.++ Returns:+ `PermissionDecision`:+ The final decision (never ASK).+ """+ # step 1: deny rules+ deny = self._check_deny_rules(tool, tool_input)+ if deny:+ return deny++ # step 2: ask rules — converted to DENY (no user available)+ ask = self._check_ask_rules(tool, tool_input)+ if ask:+ ask.suggested_rules = self._generate_suggestions(tool, tool_input)+ return self._convert_ask_to_deny(tool, ask)++ # step 3: tool's own check_permissions+ tool_decision = await tool.check_permissions(tool_input, self.context)+ # step 3a: tool ALLOW / DENY returned as-is+ if tool_decision.behavior in (+ PermissionBehavior.ALLOW,+ PermissionBehavior.DENY,+ ):+ return tool_decision+ # step 3b: safety ASK converted to DENY (no user available)+ if self._is_safety_ask(tool_decision):+ tool_decision.suggested_rules = self._generate_suggestions(+ tool,+ tool_input,+ )+ return self._convert_ask_to_deny(tool, tool_decision)++ # step 4: allow rules+ allow = self._check_allow_rules(tool, tool_input)+ if allow:+ return allow++ # step 5: default — DENY (no user available to confirm)+ 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",+ )++ @staticmethod+ def _convert_ask_to_deny(+ tool: ToolBase,+ ask_decision: PermissionDecision,+ ) -> PermissionDecision:+ """Convert an ASK decision into a DENY for DONT_ASK mode.- EXPLORE mode: only allows read-only tools, denies modifications- ACCEPT_EDITS mode: allows read-only tools (no restrictions)+ DONT_ASK's invariant is "never return ASK" — the user is not+ available to answer prompts. This helper turns whatever produced+ the ASK (an ASK rule, a safety check) into a DENY while+ preserving traceability by carrying the original reason and+ ``suggested_rules`` forward; callers (e.g. a UI surfacing the+ scheduled-task failure) can still show the user what rule they+ could add to unblock the operation in the future.Args:tool (`ToolBase`):- The tool instance being called (used to check is_read_only)+ The tool whose invocation is being denied.+ ask_decision (`PermissionDecision`):+ The original ASK decision to convert.Returns:- `PermissionDecision | None`:- ALLOW for read-only tools in EXPLORE/ACCEPT_EDITS modes,- DENY for modification tools in EXPLORE mode,- None otherwise+ `PermissionDecision`:+ A DENY decision with the original ASK's reason and+ suggestions attached."""- # EXPLORE mode: allow read-only, deny modifications- if self.context.mode == PermissionMode.EXPLORE:- if tool.is_read_only:- return PermissionDecision(- behavior=PermissionBehavior.ALLOW,- message=(- f"Permission granted for {tool.name} "- f"(explore mode - read-only tool)"- ),- decision_reason="Explore mode allows read-only operations",- )- else:- return PermissionDecision(- behavior=PermissionBehavior.DENY,- message=(- f"Permission denied for {tool.name} "- f"(explore mode is read-only)"- ),- decision_reason="Explore mode does not allow "- "modifications",- )+ return PermissionDecision(+ behavior=PermissionBehavior.DENY,+ message=(+ f"Permission denied for {tool.name} "+ f"(dont_ask mode - ASK converted to DENY, "+ f"user not available)"+ ),+ decision_reason=(+ f"DONT_ASK mode converted ASK to DENY. "+ f"Original reason: {ask_decision.decision_reason}"+ ),+ suggested_rules=ask_decision.suggested_rules,+ )- # ACCEPT_EDITS mode: allow read-only tools- if self.context.mode == PermissionMode.ACCEPT_EDITS:- if tool.is_read_only:- return PermissionDecision(- behavior=PermissionBehavior.ALLOW,- message=(- f"Permission granted for {tool.name} "- f"(accept edits mode - read-only tool)"- ),- decision_reason="Accept edits mode allows read-only "- "operations",- )+ @staticmethod+ def _is_safety_ask(decision: PermissionDecision) -> bool:+ """Whether a decision is a bypass-immune safety ASK.- return None+ A safety ASK is an ASK that a tool has explicitly marked with+ :attr:`PermissionDecision.bypass_immune` ``= True``. Tools emit+ these for dangerous operations (e.g. write to ``~/.bashrc``,+ ``rm -rf /``, command-injection patterns) that must be surfaced+ to the user regardless of allow rules in+ ``DEFAULT``/``ACCEPT_EDITS``. ``BYPASS`` mode intentionally+ skips this check (see :meth:`_check_bypass`); ``DONT_ASK``+ converts the ASK to DENY (see :meth:`_check_dont_ask`).++ Args:+ decision (`PermissionDecision`):+ The decision returned by a tool's ``check_permissions``.++ Returns:+ `bool`:+ True iff ``behavior == ASK`` and ``bypass_immune`` is set.+ """+ return (+ decision.behavior == PermissionBehavior.ASK+ and decision.bypass_immune+ )def _check_deny_rules(self,@@ -388,34 +661,6 @@ class PermissionEngine:# Try to use tool's match_rule method if availablereturn tool.match_rule(rule.rule_content, input_data)- 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: ToolBase,diff --git a/src/agentscope/permission/_types.py b/src/agentscope/permission/_types.pyindex 6561f1e06..fc7b88a0f 100644--- a/src/agentscope/permission/_types.py+++ b/src/agentscope/permission/_types.py@@ -24,31 +24,58 @@ class PermissionMode(Enum):+---------------+--------------------------------------------------+--------------------------------+| Mode | Behavior | Use Case |+===============+==================================================+================================+- | DEFAULT | All operations require explicit permission | Default mode, most secure |- | | (unless there are explicit allow rules) | |+ | DEFAULT | Every operation asks for permission unless: | Default mode, most secure |+ | | - an allow rule matches, OR | |+ | | - the tool's ``check_permissions`` explicitly | |+ | | returns ALLOW for the invocation (currently | |+ | | only ``Bash`` auto-allows recognized | |+ | | read-only commands such as ``ls``/``git | |+ | | status``). Read/Glob/Grep return PASSTHROUGH | |+ | | and fall through to the default ASK unless | |+ | | an allow rule matches. | |+---------------+--------------------------------------------------+--------------------------------+| 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) | |+ | | - Auto-allow filesystem commands (mkdir, rm, | |+ | | mv, cp, ...) **only when all target paths** | |+ | | **resolve inside a working directory** | || | - 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) | |+ | | - Allow: read-only tools (``Read``/``Grep``/ | implementation |+ | | ``Glob``) and read-only bash commands | |+ | | (e.g. ``ls``, ``git status``) | |+ | | - Deny: any modification tool / command | |+ | | - User-configured DENY or ASK rules take | |+ | | precedence over the read-only auto-allow | |+---------------+--------------------------------------------------+--------------------------------+- | BYPASS | All operations automatically allowed | Testing environment, sandbox, |- | | (no permission checks) | fully trusted scenarios |+ | BYPASS | Skip all permission checks except explicit | Sandboxed environments |+ | | user-configured deny / ask rules and tool | (container, VM), unattended |+ | | DENY. **Safety ASKs from tools are NOT** | runs where you fully trust |+ | | **enforced** — including ``rm -rf /``, writes | the agent |+ | | to ``~/.bashrc``, command-injection patterns, | |+ | | etc. Use deny rules to protect specific paths. | |+ | | For unattended runs that still need safety, | |+ | | prefer DONT_ASK. | |+---------------+--------------------------------------------------+--------------------------------+- | DONT_ASK | Convert all ASK decisions to DENY | Scheduled tasks, background |- | | (user not available to answer prompts) | execution when user is away |+ | DONT_ASK | Convert every ASK (including safety ASKs and | Scheduled tasks, background |+ | | ASK-rule hits) to DENY. Safe-by-default for | execution when user is away |+ | | unattended execution. | |+---------------+--------------------------------------------------+--------------------------------+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)+ DEFAULT: Default mode - explicit permission per action. The+ only auto-allow path is the tool's own ``check_permissions``+ returning ALLOW (currently just ``Bash`` for recognized+ read-only commands like ``ls``/``git status``).+ ACCEPT_EDITS: Accept edits mode - automatically allows file+ edits within working directories (including filesystem+ bash commands whose every target is in a working dir).+ EXPLORE: Explore mode - read-only; modifications are denied.+ BYPASS: Bypass mode - skips safety checks; relies on user+ deny / ask rules as the only guardrail.+ DONT_ASK: Don't ask mode - converts all ASK decisions to DENY+ (for unattended execution).""" # noqa: E501DEFAULT = "default"diff --git a/src/agentscope/tool/_base.py b/src/agentscope/tool/_base.pyindex a56437b1c..60e30e655 100644--- a/src/agentscope/tool/_base.py+++ b/src/agentscope/tool/_base.py@@ -75,6 +75,30 @@ class ToolBase(ABC):) -> PermissionDecision:"""Check permissions for the tool usage."""+ async def check_read_only(+ self,+ tool_input: dict[str, Any],+ ) -> bool:+ """Decide whether this specific invocation is read-only.++ Returns the static :attr:`is_read_only` attribute by default.+ Subclasses with input-dependent semantics (e.g. ``Bash``) should+ override this to inspect ``tool_input`` — for example, ``Bash`` is+ statically marked as not read-only but ``ls -a`` is in fact read-only.++ Should be cheap — the permission engine may call this before the+ full :meth:`check_permissions` flow.++ Args:+ tool_input (`dict[str, Any]`):+ The tool input data for this invocation.++ Returns:+ `bool`:+ ``True`` if this invocation is read-only, ``False`` otherwise.+ """+ return self.is_read_only+def match_rule(self,rule_content: str | None,@@ -143,6 +167,58 @@ class ToolBase(ABC):),]+ def _path_in_allowed_working_path(+ self,+ file_path: str,+ context: PermissionContext,+ ) -> bool:+ """Check if a file path is within any allowed working directory.++ A "working directory" is the process's current directory plus any+ entries in :attr:`PermissionContext.working_directories`. Paths+ are compared via :func:`os.path.realpath` so that aliases like+ macOS's ``/tmp`` → ``/private/tmp`` and symlinked working+ directories compare equal on both sides.++ Used by tools that conditionally auto-allow file operations in+ :attr:`PermissionMode.ACCEPT_EDITS` (e.g. Write, Edit, and the+ filesystem-command branch of Bash).++ Args:+ file_path (`str`):+ The file path to check.+ context (`PermissionContext`):+ The permission context containing the working directories.++ Returns:+ `bool`:+ True if ``file_path`` is within any allowed working+ directory.+ """+ current_dir = os.getcwd()+ additional_dirs = list(context.working_directories.keys())+ all_working_dirs = [current_dir] + additional_dirs++ abs_file_path = os.path.realpath(os.path.expanduser(file_path))++ for working_dir in all_working_dirs:+ abs_working_dir = os.path.realpath(+ os.path.expanduser(working_dir),+ )+ try:+ os.path.relpath(abs_file_path, abs_working_dir)+ if (+ abs_file_path.startswith(abs_working_dir + os.sep)+ or abs_file_path == abs_working_dir+ ):+ return True+ except ValueError:+ # On Windows, relpath raises ValueError if paths are on+ # different drives.+ continue++ return False+def _is_dangerous_path(self, file_path: str) -> bool:"""Check if a file path is dangerous (sensitive file or directory).diff --git a/src/agentscope/tool/_builtin/_bash.py b/src/agentscope/tool/_builtin/_bash.pyindex fc058a20f..0697a347d 100644--- a/src/agentscope/tool/_builtin/_bash.py+++ b/src/agentscope/tool/_builtin/_bash.py@@ -178,6 +178,23 @@ easier to review tool calls and give permission.self.dangerous_files = list(dangerous_files)self.dangerous_directories = list(dangerous_directories)+ async def check_read_only(+ self,+ tool_input: dict[str, Any],+ ) -> bool:+ """Decide whether this specific bash invocation is read-only.++ Inspects the command and returns ``True`` for known-safe read-only+ commands (e.g. ``ls``, ``cat``, ``grep``, ``git status``). The+ static :attr:`is_read_only` class attribute is ``False`` because+ Bash can execute arbitrary commands; this method overrides that+ with a per-invocation answer.+ """+ command = tool_input.get("command", "")+ if not command:+ return self.is_read_only+ return self._bash_parser.is_read_only_command(command)+async def check_permissions(self,tool_input: dict[str, Any],@@ -186,13 +203,29 @@ easier to review tool calls and give permission."""Check permissions for bash command execution.This method implements Bash-specific permission checks:- 0. Injection risk check (detect dynamic shell structures)- 1. Read-only command check (auto-allow safe commands)- 2. Dangerous command pattern check (safety check, bypass-immune)- 3. Sed constraint check (safety check, bypass-immune)- 4. Dangerous path check for config files (safety check, bypass-immune)- 5. Dangerous removal path check for system dirs (bypass-immune)- 6. ACCEPT_EDITS mode filesystem command check++ 0. Injection risk check (bypass-immune safety ASK if command+ contains dynamic expansion like ``$(...)`` or ``<(...)``)+ 1. Read-only command check — auto-ALLOW in **every mode**+ (including DEFAULT) for known-safe read-only commands+ (``ls``, ``pwd``, ``git status``, ``cat``, etc.). This is+ the static counterpart to :meth:`check_read_only`.+ 2. Dangerous command pattern check (bypass-immune safety ASK)+ 3. Sed in-place constraint check (bypass-immune safety ASK)+ 4. Dangerous path check for config files (bypass-immune safety+ ASK)+ 5. Dangerous removal path check for system dirs (bypass-immune+ safety ASK)+ 6. ACCEPT_EDITS auto-allow for ``mkdir``/``touch``/``rm``/+ ``rmdir``/``mv``/``cp``/``sed`` — only when **every**+ target path resolves inside a working directory+ 7. PASSTHROUGH (engine continues with rule matching)++ "Bypass-immune" decisions set+ :attr:`PermissionDecision.bypass_immune` so they cannot be+ silenced by allow rules in DEFAULT mode. In BYPASS mode all+ bypass-immune ASKs are intentionally skipped — see+ :attr:`PermissionMode.BYPASS`.Args:tool_input (`dict[str, Any]`):@@ -224,6 +257,7 @@ easier to review tool calls and give permission.message=f"Permission required: {injection_reason}",decision_reason="Safety check: command contains dynamic ""expansion that cannot be statically analyzed",+ bypass_immune=True,)# 1. Check if command is read-only (auto-allow)@@ -243,6 +277,7 @@ easier to review tool calls and give permission.f"pattern: {dangerous_pattern}",decision_reason="Safety check: dangerous command pattern ""detected",+ bypass_immune=True,)# 3. Check for sed constraints (safety check, bypass-immune)@@ -256,6 +291,7 @@ easier to review tool calls and give permission.message=f"Permission required: {sed_error}",decision_reason="Safety check: sed in-place modification ""of dangerous file",+ bypass_immune=True,)# 4. Check for dangerous paths in sensitive config files/dirs@@ -269,6 +305,7 @@ easier to review tool calls and give permission.f"sensitive paths: {paths_str}",decision_reason="Safety check: dangerous file or ""directory in bash command",+ bypass_immune=True,)# 5. Check for dangerous removal paths: rm/rmdir targeting system@@ -286,11 +323,17 @@ easier to review tool calls and give permission.f"cannot be auto-allowed by permission rules.",decision_reason="Safety check: dangerous removal of ""critical system path",+ bypass_immune=True,)- # 6. Check ACCEPT_EDITS mode for filesystem commands+ # 6. ACCEPT_EDITS auto-allow for filesystem commands whose targets+ # all live inside a working directory. Mirrors Write/Edit's strict+ # working-directory check — we never auto-allow a bash command that+ # would touch a path outside the configured working set (e.g.+ # ``cp /etc/hosts /tmp/x`` must not pass even though ``cp`` is in+ # the auto-allow list).if context.mode == PermissionMode.ACCEPT_EDITS:- filesystem_commands = [+ filesystem_commands = {"mkdir","touch","rm",@@ -298,21 +341,44 @@ easier to review tool calls and give permission."mv","cp","sed",- ]+ }base_command = (command.strip().split()[0] if command.strip() else "")if base_command in filesystem_commands:- return PermissionDecision(- behavior=PermissionBehavior.ALLOW,- message=f"Permission granted for '{base_command}' "- f"command (accept edits mode - filesystem command)",- decision_reason=f"Filesystem command '{base_command}' "- f"is auto-allowed in accept edits mode",- )-- # 6. Passthrough to let Engine continue with rule matching+ # Collect every target path: file arguments AND output+ # redirections. ``extract_file_paths`` includes both.+ target_paths = [+ path+ for _cmd, path in self._bash_parser.extract_file_paths(+ command,+ )+ ]+ # Conservative: only auto-allow when we extracted at least+ # one target AND every target resolves inside a working+ # directory. An empty list means the parser found nothing+ # actionable (or the command has no args) — in that case+ # we fall through to PASSTHROUGH rather than blindly+ # allowing.+ if target_paths and all(+ self._path_in_allowed_working_path(path, context)+ for path in target_paths+ ):+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"Permission granted for '{base_command}' "+ f"command (accept edits mode - filesystem command, "+ f"all targets in working directory)",+ decision_reason=(+ f"Filesystem command '{base_command}' is "+ f"auto-allowed in accept edits mode because "+ f"all target paths are within a working "+ f"directory"+ ),+ )++ # 7. Passthrough to let Engine continue with rule matchingreturn PermissionDecision(behavior=PermissionBehavior.PASSTHROUGH,message=f"Execute bash command: {command}",diff --git a/src/agentscope/tool/_builtin/_bash_parser.py b/src/agentscope/tool/_builtin/_bash_parser.pyindex 013297e83..62d6f1a81 100644--- a/src/agentscope/tool/_builtin/_bash_parser.py+++ b/src/agentscope/tool/_builtin/_bash_parser.py@@ -301,6 +301,8 @@ class BashCommandParser:"touch","ln","sed",+ "mkdir",+ "rmdir",]:# Extract file arguments (skip flags)for arg in args:@@ -341,7 +343,17 @@ class BashCommandParser:continue# Check for file-manipulating commands- if token in ["rm", "mv", "cp", "chmod", "chown", "sed", "touch"]:+ if token in [+ "rm",+ "mv",+ "cp",+ "chmod",+ "chown",+ "sed",+ "touch",+ "mkdir",+ "rmdir",+ ]:cmd_name = token# Look for file arguments after this commandj = i + 1diff --git a/src/agentscope/tool/_builtin/_edit.py b/src/agentscope/tool/_builtin/_edit.pyindex d5d651a10..eb5bc4387 100644--- a/src/agentscope/tool/_builtin/_edit.py+++ b/src/agentscope/tool/_builtin/_edit.py@@ -147,6 +147,7 @@ Usage:message=f"Permission required: Edit operation on "f"sensitive file {file_path}",decision_reason="Safety check: dangerous file or directory",+ bypass_immune=True,)# 2. Check ACCEPT_EDITS mode for files in working directories@@ -167,53 +168,6 @@ Usage:message="",)- def _path_in_allowed_working_path(- self,- file_path: str,- context: PermissionContext,- ) -> bool:- """Check if a file path is within any allowed working directory.-- Args:- file_path (`str`):- The file path to check- context (`PermissionContext`):- The permission context containing working directories-- Returns:- `bool`:- True if the path is within any allowed working directory- """-- # Get all working directories (current directory + additional)- current_dir = os.getcwd()- additional_dirs = list(context.working_directories.keys())- all_working_dirs = [current_dir] + additional_dirs-- # Normalize paths, resolving symlinks so that aliases like- # macOS's /tmp -> /private/tmp compare equal on both sides.- abs_file_path = os.path.realpath(os.path.expanduser(file_path))-- # Check if file path is in any working directory- for working_dir in all_working_dirs:- abs_working_dir = os.path.realpath(- os.path.expanduser(working_dir),- )- try:- # Check if file_path is inside working_dir- os.path.relpath(abs_file_path, abs_working_dir)- if (- abs_file_path.startswith(abs_working_dir + os.sep)- or abs_file_path == abs_working_dir- ):- return True- except ValueError:- # On Windows, relpath raises ValueError if paths are on- # different drives- continue-- return False-def match_rule(self,rule_content: str | None,diff --git a/src/agentscope/tool/_builtin/_write.py b/src/agentscope/tool/_builtin/_write.pyindex 58a6584f7..64a6f05f3 100644--- a/src/agentscope/tool/_builtin/_write.py+++ b/src/agentscope/tool/_builtin/_write.py@@ -125,6 +125,7 @@ Usage:message=f"Permission required: Write operation on "f"sensitive file {file_path}",decision_reason="Safety check: dangerous file or directory",+ bypass_immune=True,)# 2. Check ACCEPT_EDITS mode for files in working directories@@ -145,53 +146,6 @@ Usage:message="",)- def _path_in_allowed_working_path(- self,- file_path: str,- context: PermissionContext,- ) -> bool:- """Check if a file path is within any allowed working directory.-- Args:- file_path (`str`):- The file path to check- context (`PermissionContext`):- The permission context containing working directories-- Returns:- `bool`:- True if the path is within any allowed working directory- """-- # Get all working directories (current directory + additional)- current_dir = os.getcwd()- additional_dirs = list(context.working_directories.keys())- all_working_dirs = [current_dir] + additional_dirs-- # Normalize paths, resolving symlinks so that aliases like- # macOS's /tmp -> /private/tmp compare equal on both sides.- abs_file_path = os.path.realpath(os.path.expanduser(file_path))-- # Check if file path is in any working directory- for working_dir in all_working_dirs:- abs_working_dir = os.path.realpath(- os.path.expanduser(working_dir),- )- try:- # Check if file_path is inside working_dir- os.path.relpath(abs_file_path, abs_working_dir)- if (- abs_file_path.startswith(abs_working_dir + os.sep)- or abs_file_path == abs_working_dir- ):- return True- except ValueError:- # On Windows, relpath raises ValueError if paths are on- # different drives- continue-- return False-def match_rule(self,rule_content: str | None,diff --git a/tests/permission_engine_test.py b/tests/permission_engine_test.pyindex 8a3278e29..4be95ddb5 100644--- a/tests/permission_engine_test.py+++ b/tests/permission_engine_test.py@@ -1,8 +1,12 @@# -*- coding: utf-8 -*--"""Test cases for PermissionEngine."""-import os+"""Test cases for PermissionEngine.++Mode-specific tests live in :mod:`tests.permission_mode_test`. This file+covers rule priority, rule pattern matching (Bash / file glob), dangerous+path detection, suggestion generation, Bash read-only command analysis,+and bypass-immune safety checks.+"""import sys-import tempfileimport unittestfrom unittest.async_case import IsolatedAsyncioTestCase@@ -12,6 +16,7 @@ from agentscope.permission import (PermissionContext,PermissionRule,PermissionBehavior,+ PermissionDecision,AdditionalWorkingDirectory,)from agentscope.tool import (@@ -19,6 +24,7 @@ from agentscope.tool import (Write,Read,Edit,+ ToolBase,)@@ -128,218 +134,6 @@ class PermissionEngineRulePriorityTest(IsolatedAsyncioTestCase):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- decision = await engine.check_permission(- Bash(),- {"command": "npm install"},- )-- # 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",- ),- )-- decision = await engine.check_permission(- Bash(),- {"command": "rm -rf /tmp"},- )-- # Deny rules have the 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- decision = await engine.check_permission(- Write(),- {"file_path": "/home/user/.bashrc"},- )-- # 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- decision = await engine.check_permission(- Bash(),- {"command": "npm install"},- )-- # 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- decision = await engine.check_permission(- Write(),- {"file_path": "/tmp/project/file.txt"},- )- self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)-- # Read tool within working directory- decision = await engine.check_permission(- Read(),- {"file_path": "/tmp/project/file.txt"},- )- self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)-- # Edit tool within working directory- decision = await engine.check_permission(- Edit(),- {"file_path": "/tmp/project/file.txt"},- )- self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)-- @unittest.skipIf(- os.name == "nt",- "os.symlink typically requires admin privileges on Windows",- )- async def test_accept_edits_mode_resolves_symlinked_working_directory(- self,- ) -> None:- """ACCEPT_EDITS must recognize a working directory and a file path- as equivalent even when one side reaches it through a symlink- (e.g. macOS's /tmp -> /private/tmp). Regression for the- abspath -> realpath fix in `_path_in_allowed_working_path`.- """- parent = tempfile.mkdtemp()- try:- real_dir = os.path.join(parent, "real")- os.makedirs(real_dir)- link_dir = os.path.join(parent, "link")- os.symlink(real_dir, link_dir)-- # Case 1: working_dir given as real path, file accessed via link- context = PermissionContext(- mode=PermissionMode.ACCEPT_EDITS,- working_directories={- real_dir: AdditionalWorkingDirectory(- path=real_dir,- source="test",- ),- },- )- engine = PermissionEngine(context)- decision = await engine.check_permission(- Write(),- {"file_path": os.path.join(link_dir, "file.txt")},- )- self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)-- # Case 2: working_dir given as link path, file accessed via real- context = PermissionContext(- mode=PermissionMode.ACCEPT_EDITS,- working_directories={- link_dir: AdditionalWorkingDirectory(- path=link_dir,- source="test",- ),- },- )- engine = PermissionEngine(context)- decision = await engine.check_permission(- Edit(),- {"file_path": os.path.join(real_dir, "file.txt")},- )- self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)- finally:- import shutil-- shutil.rmtree(parent, ignore_errors=True)-- 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- decision = await engine.check_permission(- Edit(),- {"file_path": "/home/user/file.txt"},- )-- 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- decision = await engine.check_permission(- Read(),- {"file_path": "/tmp/file.txt"},- )-- 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- decision = await engine.check_permission(- Write(),- {"file_path": "/tmp/file.txt"},- )-- self.assertEqual(decision.behavior, PermissionBehavior.DENY)--@unittest.skipIf(sys.platform == "win32","Bash tool is not supported on Windows",@@ -605,21 +399,6 @@ class PermissionEngineDangerousPathTest(IsolatedAsyncioTestCase):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- decision = await engine.check_permission(- Write(),- {"file_path": "/home/user/.bashrc"},- )-- # 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 inACCEPT_EDITS mode."""@@ -835,29 +614,26 @@ class PermissionEngineReadOnlyTest(IsolatedAsyncioTestCase):sys.platform == "win32","Bash tool is not supported on Windows",)-class PermissionEngineSafetyCheckBypassImmuneTest(IsolatedAsyncioTestCase):- """Test that all safety checks are bypass-immune (cannot be overridden- by BYPASS mode or allow rules)."""-- async def test_injection_check_bypass_immune(self) -> None:- """Test that injection detection is bypass-immune."""- context = PermissionContext(mode=PermissionMode.BYPASS)- engine = PermissionEngine(context)-- # Command substitution should be blocked even in BYPASS mode- decision = await engine.check_permission(- Bash(),- {"command": "ls $(rm -rf /)"},- )- self.assertEqual(decision.behavior, PermissionBehavior.ASK)- self.assertIn("command_substitution", decision.message)+class PermissionEngineSafetyCheckAllowRuleImmuneTest(+ IsolatedAsyncioTestCase,+):+ """Safety checks are immune to allow rules in DEFAULT mode.++ A user-configured allow rule cannot grant permission for an+ operation that the tool has flagged as a safety concern+ (``bypass_immune=True``). This guarantees that broad rules like+ ``Bash:rm:*`` don't accidentally authorize ``rm -rf /``.++ Note: in BYPASS mode the user has explicitly opted out of safety+ enforcement, so these tools' safety ASKs are NOT honored — that+ behavior is covered by+ :class:`tests.permission_mode_test.PermissionEngineBypassModeTest`.+ """async def test_injection_check_not_bypassed_by_allow_rule(self) -> None:- """Test that allow rules cannot bypass injection detection."""+ """Allow rule for ``ls:*`` does not authorize ``ls $(rm -rf /)``."""context = PermissionContext(mode=PermissionMode.DEFAULT)engine = PermissionEngine(context)-- # Add a broad allow ruleengine.add_rule(PermissionRule(tool_name="Bash",@@ -867,7 +643,6 @@ class PermissionEngineSafetyCheckBypassImmuneTest(IsolatedAsyncioTestCase):),)- # ls $(rm -rf /) should still be blocked despite allow rule for ls:*decision = await engine.check_permission(Bash(),{"command": "ls $(rm -rf /)"},@@ -875,71 +650,164 @@ class PermissionEngineSafetyCheckBypassImmuneTest(IsolatedAsyncioTestCase):self.assertEqual(decision.behavior, PermissionBehavior.ASK)self.assertIn("command_substitution", decision.message)- async def test_dangerous_removal_bypass_immune(self) -> None:- """Test that dangerous removal path check is bypass-immune."""- context = PermissionContext(mode=PermissionMode.BYPASS)+ async def test_dangerous_removal_not_bypassed_by_allow_rule(self) -> None:+ """Allow rule for ``rm:*`` does not authorize ``rm -rf /``."""+ context = PermissionContext(mode=PermissionMode.DEFAULT)engine = PermissionEngine(context)+ engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="rm:*",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )decision = await engine.check_permission(Bash(),{"command": "rm -rf /"},)self.assertEqual(decision.behavior, PermissionBehavior.ASK)- # Can be blocked by either dangerous command pattern or dangerous- # removal path check+ # Either dangerous removal path or dangerous command pattern firesself.assertTrue("Dangerous removal operation" in decision.messageor "dangerous pattern" in decision.message,)- async def test_dangerous_removal_not_bypassed_by_allow_rule(self) -> None:- """Test that allow rules cannot bypass dangerous removal check."""++# ---------------------------------------------------------------------------+# bypass_immune field mechanism+# ---------------------------------------------------------------------------+++class _FakeToolReturningAsk(ToolBase):+ """Minimal tool used to test the ``bypass_immune`` field mechanism.++ Returns a single configurable ASK decision from ``check_permissions``+ so we can verify the engine routes bypass-immune vs regular ASKs+ correctly regardless of the specific safety trigger.+ """++ name = "FakeAskTool"+ description = "Test-only tool"+ input_schema = {"type": "object", "properties": {}}+ is_concurrency_safe = True+ is_read_only = False+ is_external_tool = False+ is_state_injected = False+ is_mcp = False++ def __init__(self, bypass_immune: bool) -> None:+ self._bypass_immune = bypass_immune++ async def check_permissions(+ self,+ tool_input: dict,+ context: PermissionContext,+ ) -> PermissionDecision:+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message="fake tool requires confirmation",+ decision_reason="test-only reason without the s-word",+ bypass_immune=self._bypass_immune,+ )+++class PermissionEngineBypassImmuneFieldTest(IsolatedAsyncioTestCase):+ """Tests for the :attr:`PermissionDecision.bypass_immune` field.++ These tests use a minimal fake tool that returns ASK with a+ configurable ``bypass_immune`` value — independent of any specific+ safety trigger — to verify the engine's mechanism for honoring the+ field. Together with+ :class:`PermissionEngineSafetyCheckAllowRuleImmuneTest` (which tests+ that Bash/Write/Edit's individual safety checks correctly set the+ field), this fully covers the bypass-immune contract.+ """++ async def test_bypass_immune_ask_not_overridden_by_allow_rule(+ self,+ ) -> None:+ """An ASK with ``bypass_immune=True`` survives a matching allow+ rule that would otherwise grant the operation."""context = PermissionContext(mode=PermissionMode.DEFAULT)engine = PermissionEngine(context)-- # Add a broad allow rule for rmengine.add_rule(PermissionRule(- tool_name="Bash",- rule_content="rm:*",+ tool_name="FakeAskTool",+ rule_content=None,behavior=PermissionBehavior.ALLOW,source="test",),)- # rm -rf / should still be blocked despite allow rule for rm:*decision = await engine.check_permission(- Bash(),- {"command": "rm -rf /"},+ _FakeToolReturningAsk(bypass_immune=True),+ {},)self.assertEqual(decision.behavior, PermissionBehavior.ASK)- # Can be blocked by either dangerous command pattern or dangerous- # removal path check- self.assertTrue(- "Dangerous removal operation" in decision.message- or "dangerous pattern" in decision.message,++ async def test_non_bypass_immune_ask_overridden_by_allow_rule(+ self,+ ) -> None:+ """A regular ASK (``bypass_immune=False``) yields to a matching+ allow rule — proving the field, not the ``decision_reason``+ text, governs immunity."""+ context = PermissionContext(mode=PermissionMode.DEFAULT)+ engine = PermissionEngine(context)+ engine.add_rule(+ PermissionRule(+ tool_name="FakeAskTool",+ rule_content=None,+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )++ decision = await engine.check_permission(+ _FakeToolReturningAsk(bypass_immune=False),+ {},)+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)- async def test_sed_constraint_bypass_immune(self) -> None:- """Test that sed constraint check is bypass-immune."""+ async def test_bypass_mode_ignores_bypass_immune_field(self) -> None:+ """BYPASS is intentionally permissive: even an ASK with+ ``bypass_immune=True`` is allowed through. The user has opted+ out of safety prompts; ``bypass_immune`` only governs allow+ rules (in DEFAULT) and DONT_ASK conversion.+ """context = PermissionContext(mode=PermissionMode.BYPASS)engine = PermissionEngine(context)decision = await engine.check_permission(- Bash(),- {"command": "sed 's/old/new/e' file.txt"},+ _FakeToolReturningAsk(bypass_immune=True),+ {},)- self.assertEqual(decision.behavior, PermissionBehavior.ASK)- self.assertIn("safety", decision.decision_reason.lower())+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)- async def test_dangerous_config_path_bypass_immune(self) -> None:- """Test that dangerous config file path check is bypass-immune."""+ async def test_bypass_mode_allows_non_bypass_immune_ask(self) -> None:+ """For completeness: a non-bypass-immune ASK is also allowed+ through in BYPASS — same outcome, different path."""context = PermissionContext(mode=PermissionMode.BYPASS)engine = PermissionEngine(context)decision = await engine.check_permission(- Bash(),- {"command": "rm ~/.bashrc"},+ _FakeToolReturningAsk(bypass_immune=False),+ {},)- self.assertEqual(decision.behavior, PermissionBehavior.ASK)- self.assertIn("safety", decision.decision_reason.lower())+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ async def test_bypass_immune_ask_converted_to_deny_in_dont_ask(+ self,+ ) -> None:+ """Under DONT_ASK, even a bypass-immune ASK is converted to+ DENY (issue #3 contract): no user is available to confirm,+ so the only safe action is to refuse."""+ context = PermissionContext(mode=PermissionMode.DONT_ASK)+ engine = PermissionEngine(context)++ decision = await engine.check_permission(+ _FakeToolReturningAsk(bypass_immune=True),+ {},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)diff --git a/tests/permission_mode_test.py b/tests/permission_mode_test.pynew file mode 100644index 000000000..ef57478a8--- /dev/null+++ b/tests/permission_mode_test.py@@ -0,0 +1,895 @@+# -*- coding: utf-8 -*-+"""Per-mode test cases for ``PermissionEngine``.++Each :class:`PermissionMode` has its own test class so the policy of+that mode can be verified in isolation. Tests cover:++- the three rule layers (deny / ask / allow) for that mode+- the ``tool.check_permissions`` return paths (ALLOW / DENY / safety-ASK+ / PASSTHROUGH)+- mode-specific behavior (e.g. EXPLORE's read-only resolution,+ ACCEPT_EDITS's working-directory auto-allow, BYPASS's safety-ASK+ immunity, DONT_ASK's default DENY)+- Bash dynamic read-only / non-read-only / dangerous commands where+ relevant++Specific safety-check triggers (injection, dangerous removal, sed+constraints, dangerous config paths) are tested separately in+``permission_engine_test.py::PermissionEngineSafetyCheckAllowRuleImmuneTest``.+"""+import os+import sys+import tempfile+import unittest+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.permission import (+ PermissionEngine,+ PermissionMode,+ PermissionContext,+ PermissionRule,+ PermissionBehavior,+ AdditionalWorkingDirectory,+)+from agentscope.tool import (+ Bash,+ Write,+ Read,+ Edit,+)+++# ---------------------------------------------------------------------------+# DEFAULT mode+# ---------------------------------------------------------------------------+++class PermissionEngineDefaultModeTest(IsolatedAsyncioTestCase):+ """Tests for :attr:`PermissionMode.DEFAULT`.++ DEFAULT is the most restrictive non-DONT_ASK mode: every operation+ requires explicit permission unless an allow rule matches or the+ tool itself returns ALLOW (e.g. Bash auto-allows known read-only+ commands).+ """++ async def asyncSetUp(self) -> None:+ self.context = PermissionContext(mode=PermissionMode.DEFAULT)+ self.engine = PermissionEngine(self.context)++ async def test_default_write_with_no_rules_returns_ask(self) -> None:+ """Write to a safe path with no matching rules falls to the+ engine's default ASK."""+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/tmp/file.txt"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_default_deny_rule_returns_deny(self) -> None:+ """Deny rule has the highest priority."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Write",+ rule_content="*.env",+ behavior=PermissionBehavior.DENY,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/tmp/secret.env"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ async def test_default_ask_rule_returns_ask_with_suggestions(+ self,+ ) -> None:+ """Ask rule short-circuits before the tool's own check and+ attaches ``suggested_rules``."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Write",+ rule_content="*.py",+ behavior=PermissionBehavior.ASK,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/tmp/main.py"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIsNotNone(decision.suggested_rules)+ self.assertGreater(len(decision.suggested_rules), 0)++ async def test_default_allow_rule_returns_allow(self) -> None:+ """Allow rule grants permission when no deny/ask rule and no+ safety ASK applies."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Write",+ rule_content="/tmp/**",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/tmp/file.txt"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_default_bash_read_only_command_auto_allows(self) -> None:+ """Bash returns ALLOW for known read-only commands, which the+ engine surfaces directly in DEFAULT mode."""+ for command in ("ls -a", "pwd", "git status", "cat README.md"):+ decision = await self.engine.check_permission(+ Bash(),+ {"command": command},+ )+ self.assertEqual(+ decision.behavior,+ PermissionBehavior.ALLOW,+ f"Expected ALLOW for read-only bash command: {command}",+ )++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_default_bash_modification_command_returns_ask(+ self,+ ) -> None:+ """Bash modification commands (no matching rule) fall through to+ the engine's default ASK."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "npm install"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_default_dangerous_path_safety_ask(self) -> None:+ """Write to a dangerous path produces a safety ASK from the tool+ itself (bypass-immune)."""+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/home/user/.bashrc"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("safety", (decision.decision_reason or "").lower())++ async def test_default_safety_ask_not_overridden_by_allow_rule(+ self,+ ) -> None:+ """A user-configured allow rule must not override a tool's+ safety ASK (bypass-immune)."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Write",+ rule_content="**",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/home/user/.bashrc"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+++# ---------------------------------------------------------------------------+# EXPLORE mode+# ---------------------------------------------------------------------------+++class PermissionEngineExploreModeTest(IsolatedAsyncioTestCase):+ """Tests for :attr:`PermissionMode.EXPLORE`.++ EXPLORE is the read-only mode: an invocation is ALLOWed iff+ :meth:`ToolBase.check_read_only` returns True; everything else is+ DENIed outright. ``tool.check_permissions`` is intentionally not+ consulted (the read-only verdict is final), and allow rules cannot+ grant write access — EXPLORE's read-only invariant is non-negotiable.+ """++ async def asyncSetUp(self) -> None:+ self.context = PermissionContext(mode=PermissionMode.EXPLORE)+ self.engine = PermissionEngine(self.context)++ async def test_explore_read_tool_allows(self) -> None:+ """Statically read-only tools (Read/Glob/Grep) → ALLOW."""+ decision = await self.engine.check_permission(+ Read(),+ {"file_path": "/tmp/file.txt"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ async def test_explore_write_tool_denies(self) -> None:+ """Statically non-read-only tools (Write/Edit) → DENY."""+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/tmp/file.txt"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ async def test_explore_deny_rule_returns_deny(self) -> None:+ """Deny rule still has top priority in EXPLORE."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Read",+ rule_content="/secret/**",+ behavior=PermissionBehavior.DENY,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Read(),+ {"file_path": "/secret/key.txt"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ async def test_explore_ask_rule_on_read_only_tool_returns_ask(+ self,+ ) -> None:+ """Ask rules apply before the read-only fast-path, so a read-only+ tool with a matching ask rule still surfaces as ASK.++ Documents current behavior — this is the design point tracked+ as issue #7.+ """+ self.engine.add_rule(+ PermissionRule(+ tool_name="Read",+ rule_content="**/*.env",+ behavior=PermissionBehavior.ASK,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Read(),+ {"file_path": "/tmp/secret.env"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_explore_allow_rule_does_not_override_deny(self) -> None:+ """EXPLORE's deny on non-read-only tools is the invariant; an+ allow rule must not be able to grant write access."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Write",+ rule_content="**",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/tmp/file.txt"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ async def test_explore_dangerous_path_returns_deny_not_safety_ask(+ self,+ ) -> None:+ """EXPLORE never invokes ``tool.check_permissions``, so a dangerous+ path on a write tool surfaces as DENY (the read-only verdict)+ rather than a safety ASK. DENY is strictly stronger than ASK, so+ this is consistent with EXPLORE's "no writes" guarantee.+ """+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/home/user/.bashrc"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_explore_bash_read_only_command_allows(self) -> None:+ """EXPLORE allows read-only bash commands via+ :meth:`Bash.check_read_only` (regression for issue #1)."""+ for command in ("ls -a", "pwd", "git status", "cat README.md"):+ decision = await self.engine.check_permission(+ Bash(),+ {"command": command},+ )+ self.assertEqual(+ decision.behavior,+ PermissionBehavior.ALLOW,+ f"Expected ALLOW for read-only bash command: {command}",+ )++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_explore_bash_modification_command_denies(self) -> None:+ """EXPLORE denies bash commands that are not statically+ recognized as read-only."""+ for command in ("cp a b", "mv a b", "touch /tmp/x"):+ decision = await self.engine.check_permission(+ Bash(),+ {"command": command},+ )+ self.assertEqual(+ decision.behavior,+ PermissionBehavior.DENY,+ f"Expected DENY for non-read-only bash command: {command}",+ )++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_explore_bash_dangerous_command_denies(self) -> None:+ """EXPLORE denies dangerous commands directly — in DEFAULT mode+ the same command would surface as a safety ASK, but EXPLORE is+ stricter."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "rm -rf /"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)+++# ---------------------------------------------------------------------------+# ACCEPT_EDITS mode+# ---------------------------------------------------------------------------+++class PermissionEngineAcceptEditsModeTest(IsolatedAsyncioTestCase):+ """Tests for :attr:`PermissionMode.ACCEPT_EDITS`.++ ACCEPT_EDITS auto-allows file edits within configured working+ directories; reads are auto-allowed unconditionally; other+ operations follow the normal DEFAULT-like flow.+ """++ async def asyncSetUp(self) -> None:+ self.context = PermissionContext(+ mode=PermissionMode.ACCEPT_EDITS,+ working_directories={+ "/tmp/project": AdditionalWorkingDirectory(+ path="/tmp/project",+ source="test",+ ),+ },+ )+ self.engine = PermissionEngine(self.context)++ async def test_accept_edits_within_working_directory(self) -> None:+ """Write / Read / Edit within a working directory → ALLOW."""+ for tool in (Write(), Read(), Edit()):+ decision = await self.engine.check_permission(+ tool,+ {"file_path": "/tmp/project/file.txt"},+ )+ self.assertEqual(+ decision.behavior,+ PermissionBehavior.ALLOW,+ f"Expected ALLOW for {tool.name} in working directory",+ )++ @unittest.skipIf(+ os.name == "nt",+ "os.symlink typically requires admin privileges on Windows",+ )+ async def test_accept_edits_resolves_symlinked_working_directory(+ self,+ ) -> None:+ """Working directory comparison must use ``realpath`` so a path+ reached through a symlink (e.g. macOS's ``/tmp`` ->+ ``/private/tmp``) is recognized. Regression test for the+ ``abspath`` → ``realpath`` fix in+ :meth:`_path_in_allowed_working_path`.+ """+ parent = tempfile.mkdtemp()+ try:+ real_dir = os.path.join(parent, "real")+ os.makedirs(real_dir)+ link_dir = os.path.join(parent, "link")+ os.symlink(real_dir, link_dir)++ # Case 1: working_dir given as real path, file via link+ context = PermissionContext(+ mode=PermissionMode.ACCEPT_EDITS,+ working_directories={+ real_dir: AdditionalWorkingDirectory(+ path=real_dir,+ source="test",+ ),+ },+ )+ engine = PermissionEngine(context)+ decision = await engine.check_permission(+ Write(),+ {"file_path": os.path.join(link_dir, "file.txt")},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ # Case 2: working_dir given as link, file via real path+ context = PermissionContext(+ mode=PermissionMode.ACCEPT_EDITS,+ working_directories={+ link_dir: AdditionalWorkingDirectory(+ path=link_dir,+ source="test",+ ),+ },+ )+ engine = PermissionEngine(context)+ decision = await engine.check_permission(+ Edit(),+ {"file_path": os.path.join(real_dir, "file.txt")},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)+ finally:+ import shutil++ shutil.rmtree(parent, ignore_errors=True)++ async def test_accept_edits_outside_working_directory(self) -> None:+ """Edit outside a working directory falls to the default ASK."""+ decision = await self.engine.check_permission(+ Edit(),+ {"file_path": "/home/user/file.txt"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_accept_edits_read_operation_auto_allowed(self) -> None:+ """Read tool is auto-allowed regardless of path (read-only fast+ path)."""+ decision = await self.engine.check_permission(+ Read(),+ {"file_path": "/anywhere/file.txt"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ async def test_accept_edits_deny_rule_returns_deny(self) -> None:+ """Deny rule overrides ACCEPT_EDITS's working-directory+ auto-allow."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Write",+ rule_content="**/*.lock",+ behavior=PermissionBehavior.DENY,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/tmp/project/poetry.lock"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ async def test_accept_edits_ask_rule_returns_ask(self) -> None:+ """Ask rule short-circuits before the working-directory check."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Edit",+ rule_content="**/*.py",+ behavior=PermissionBehavior.ASK,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Edit(),+ {"file_path": "/tmp/project/main.py"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_accept_edits_dangerous_path_safety_ask(self) -> None:+ """Safety ASK from a dangerous path is bypass-immune even when+ the path is inside a working directory.+ """+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/home/user/.bashrc"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+ self.assertIn("safety", (decision.decision_reason or "").lower())++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_accept_edits_bash_read_only_command_allows(self) -> None:+ """Read-only bash commands ALLOW via the read-only fast path."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "ls -a"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_accept_edits_bash_filesystem_command_inside_working_dir(+ self,+ ) -> None:+ """ACCEPT_EDITS auto-allows recognized filesystem commands+ (``mkdir``, ``touch``, ``rm``, ``cp``, ``mv``, ``sed``,+ ``rmdir``) when **all** target paths are inside the configured+ working directories."""+ cases = [+ "touch /tmp/project/new.txt",+ "mkdir /tmp/project/newdir",+ "rm /tmp/project/old.txt",+ "rmdir /tmp/project/olddir",+ "cp /tmp/project/a /tmp/project/b",+ "mv /tmp/project/a /tmp/project/b",+ "sed -i 's/x/y/g' /tmp/project/foo.txt",+ ]+ for command in cases:+ decision = await self.engine.check_permission(+ Bash(),+ {"command": command},+ )+ self.assertEqual(+ decision.behavior,+ PermissionBehavior.ALLOW,+ f"Expected ALLOW for in-working-dir command: {command}",+ )++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_accept_edits_bash_filesystem_command_outside_working_dir(+ self,+ ) -> None:+ """Regression for issue #4: filesystem commands whose targets+ escape the working directory must NOT be auto-allowed.++ Without this guard ``cp /etc/hosts /Users/me/other-project/x``+ would silently succeed in ACCEPT_EDITS even though the+ equivalent ``Write`` call is correctly denied. The asserted+ behavior is ASK (the PASSTHROUGH from Bash + the engine's+ default ASK in ACCEPT_EDITS).+ """+ cases = [+ # Target entirely outside the working directory+ "rm /Users/someone/other/foo",+ "touch /Users/someone/other/foo",+ "mkdir /Users/someone/other/newdir",+ # cp / mv: at least one of (src, dst) outside+ "cp /tmp/project/a /Users/someone/other/b",+ "cp /Users/someone/other/a /tmp/project/b",+ "mv /tmp/project/a /Users/someone/other/b",+ # sed in-place modifying a file outside+ "sed -i 's/x/y/g' /Users/someone/other/foo.txt",+ ]+ for command in cases:+ decision = await self.engine.check_permission(+ Bash(),+ {"command": command},+ )+ self.assertEqual(+ decision.behavior,+ PermissionBehavior.ASK,+ f"Expected ASK for outside-working-dir command: {command}",+ )++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_accept_edits_bash_filesystem_command_no_args_not_allowed(+ self,+ ) -> None:+ """Conservative behavior: if the parser extracts no target paths+ (e.g. a bare ``mkdir`` with no arguments), we do not auto-allow.+ The command itself will fail at execution, but it should not+ silently pass the permission check."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "mkdir"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)+++# ---------------------------------------------------------------------------+# BYPASS mode+# ---------------------------------------------------------------------------+++class PermissionEngineBypassModeTest(IsolatedAsyncioTestCase):+ """Tests for :attr:`PermissionMode.BYPASS`.++ BYPASS is the "fully trusted" mode: the user has opted out of all+ safety prompts. The only guardrails left are user-configured deny+ / ask rules and tool-emitted DENY. Every bypass-immune safety ASK+ (dangerous removal, dangerous paths, sed in-place on sensitive+ files, command injection, ...) is intentionally **skipped**.+ Use BYPASS only in sandboxed environments or when you fully trust+ the agent.+ """++ async def asyncSetUp(self) -> None:+ self.context = PermissionContext(mode=PermissionMode.BYPASS)+ self.engine = PermissionEngine(self.context)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_bypass_no_rules_allows(self) -> None:+ """No rules → ALLOW (BYPASS's default fallback)."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "npm install"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_bypass_deny_rule_returns_deny(self) -> None:+ """Deny rules are bypass-immune."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="rm:*",+ behavior=PermissionBehavior.DENY,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "rm -rf /tmp/foo"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_bypass_ask_rule_returns_ask(self) -> None:+ """A user-configured ask rule represents explicit intent to be+ prompted; BYPASS must not override it."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="git push:*",+ behavior=PermissionBehavior.ASK,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "git push origin main"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ASK)++ async def test_bypass_skips_dangerous_path_safety(self) -> None:+ """BYPASS skips the Write tool's dangerous-path safety check —+ writing to ``~/.bashrc`` is allowed through."""+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/home/user/.bashrc"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_bypass_skips_dangerous_removal(self) -> None:+ """BYPASS skips Bash's dangerous-removal safety check —+ ``rm -rf /`` is allowed through."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "rm -rf /"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_bypass_skips_command_injection(self) -> None:+ """BYPASS skips Bash's command-injection safety check —+ dynamic expansion is allowed through."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "ls $(date +%s)"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_bypass_skips_sed_dangerous_file(self) -> None:+ """BYPASS skips Bash's sed-on-dangerous-file safety check."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "sed 's/old/new/e' file.txt"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_bypass_skips_dangerous_config_path_in_bash(self) -> None:+ """BYPASS skips Bash's dangerous-config-path safety check —+ operating on ``~/.bashrc`` via bash is allowed through."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "rm ~/.bashrc"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_bypass_tool_allow_returns_allow(self) -> None:+ """Tool's own ALLOW (e.g. Bash read-only command) is returned+ as-is in BYPASS as in any mode."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "ls -a"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)+++# ---------------------------------------------------------------------------+# DONT_ASK mode+# ---------------------------------------------------------------------------+++class PermissionEngineDontAskModeTest(IsolatedAsyncioTestCase):+ """Tests for :attr:`PermissionMode.DONT_ASK`.++ DONT_ASK is used when no user is available to answer prompts+ (scheduled tasks, background runs). The invariant is "never return+ ASK" — every ASK-producing code path (default, ASK rule, safety+ ASK) is converted to DENY.+ """++ async def asyncSetUp(self) -> None:+ self.context = PermissionContext(mode=PermissionMode.DONT_ASK)+ self.engine = PermissionEngine(self.context)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_dont_ask_no_rules_returns_deny(self) -> None:+ """No rules → DENY (DONT_ASK's default)."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "npm install"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_dont_ask_deny_rule_returns_deny(self) -> None:+ """Deny rules apply normally."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Bash",+ rule_content="rm:*",+ behavior=PermissionBehavior.DENY,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "rm -rf /tmp/foo"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ async def test_dont_ask_allow_rule_returns_allow(self) -> None:+ """An explicit allow rule still grants permission in DONT_ASK."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Write",+ rule_content="/tmp/**",+ behavior=PermissionBehavior.ALLOW,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/tmp/file.txt"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_dont_ask_bash_read_only_command_allows(self) -> None:+ """Tool's own ALLOW (Bash read-only command) is still ALLOW+ under DONT_ASK — no user prompt is needed."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "ls -a"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)++ async def test_dont_ask_ask_rule_returns_deny(self) -> None:+ """An ASK rule hit is converted to DENY (issue #3): the user is+ not available to answer the prompt, so the operation cannot+ proceed."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Write",+ rule_content="**/*.py",+ behavior=PermissionBehavior.ASK,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/tmp/main.py"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)++ async def test_dont_ask_ask_rule_conversion_preserves_suggestions(+ self,+ ) -> None:+ """Converted DENY decisions keep the original ASK's+ ``suggested_rules`` so callers can surface them to the user+ out-of-band (e.g. in a scheduled-task failure report)."""+ self.engine.add_rule(+ PermissionRule(+ tool_name="Write",+ rule_content="**/*.py",+ behavior=PermissionBehavior.ASK,+ source="test",+ ),+ )+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/tmp/main.py"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)+ self.assertIsNotNone(decision.suggested_rules)+ self.assertGreater(len(decision.suggested_rules), 0)++ async def test_dont_ask_safety_ask_returns_deny(self) -> None:+ """A safety ASK from ``tool.check_permissions`` (e.g. Write to a+ dangerous path) is converted to DENY (issue #3) — DONT_ASK+ respects the safety verdict but cannot ask the user, so the+ only safe action is to refuse."""+ decision = await self.engine.check_permission(+ Write(),+ {"file_path": "/home/user/.bashrc"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)+ # Conversion records both the original safety reason and the+ # DONT_ASK conversion in the decision_reason.+ reason = (decision.decision_reason or "").lower()+ self.assertIn("dont_ask", reason)+ self.assertIn("safety", reason)++ @unittest.skipIf(+ sys.platform == "win32",+ "Bash tool is not supported on Windows",+ )+ async def test_dont_ask_bash_dangerous_command_returns_deny(+ self,+ ) -> None:+ """``rm -rf /`` triggers a safety ASK from Bash, which DONT_ASK+ converts to DENY (issue #3)."""+ decision = await self.engine.check_permission(+ Bash(),+ {"command": "rm -rf /"},+ )+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)