Skip to content

Build and run agents you can see, understand and trust.

fix(permission): unify per-mode evaluation and propagate batch confirmation exemptions (#2117)

DavdGao30ca3ef33189
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.py
index 553cc4603..e6a61f075 100644
--- a/src/agentscope/agent/_agent.py
+++ b/src/agentscope/agent/_agent.py
@@ -20,7 +20,11 @@ from ._config import ContextConfig, ReActConfig, ModelConfig
from ..state import AgentState
from ._utils import _ToolCallBatch
from .._logging import logger
-from .._utils._common import _generate_id, _json_loads_with_repair
+from .._utils._common import (
+ _generate_id,
+ _json_loads_with_repair,
+ _execute_async_or_sync_func,
+)
from ..event import (
AgentEvent,
ModelCallEndEvent,
@@ -85,6 +89,7 @@ from ..permission import (
PermissionBehavior,
PermissionEngine,
PermissionDecision,
+ PermissionRule,
)
from ..workspace import Offloader, WorkspaceBase
@@ -1486,6 +1491,14 @@ class Agent:
# Create a queue to collect events from all concurrent workers.
queue: Queue = Queue()
+ # Batch-shared accumulator for confirmation de-duplication: the
+ # suggested rules of every confirmation surfaced by this batch are
+ # collected here so a later call already covered by an earlier
+ # call's rule is not prompted a second time. Mutated only from
+ # synchronous sections of the workers, so no lock is needed on the
+ # single-threaded event loop.
+ kept_rules: list[PermissionRule] = []
+
async def _run_all() -> list[BaseException | None]:
"""Run all tool calls concurrently and push the sentinel when done.
@@ -1497,7 +1510,10 @@ class Agent:
# return_exceptions=True keeps all tasks running even when some
# fail, and returns exceptions as values instead of re-raising.
results = await asyncio.gather(
- *[self._into_queue(tc, queue) for tc in tool_calls],
+ *[
+ self._into_queue(tc, queue, kept_rules)
+ for tc in tool_calls
+ ],
return_exceptions=True,
)
# The sentinel is placed AFTER gather returns, which guarantees
@@ -1550,6 +1566,7 @@ class Agent:
self,
tool_call: ToolCallBlock,
queue: Queue,
+ kept_rules: list[PermissionRule] | None = None,
) -> None:
"""Execute a single tool call and forward every event into *queue*.
@@ -1559,13 +1576,18 @@ class Agent:
queue (`Queue`):
The shared async queue that collects events from all
concurrent workers.
+ kept_rules (`list[PermissionRule] | None`, defaults to `None`):
+ The batch-shared accumulator of already-surfaced suggested
+ rules, forwarded to :meth:`_execute_tool_call` for
+ confirmation de-duplication within the concurrent batch.
"""
- async for evt in self._execute_tool_call(tool_call):
+ async for evt in self._execute_tool_call(tool_call, kept_rules):
await queue.put(evt)
async def _execute_tool_call(
self,
tool_call: ToolCallBlock,
+ kept_rules: list[PermissionRule] | None = None,
) -> AsyncGenerator[
RequireUserConfirmEvent
| RequireExternalExecutionEvent
@@ -1587,6 +1609,16 @@ class Agent:
Args:
tool_call (`ToolCallBlock`):
The tool call block to be executed.
+ kept_rules (`list[PermissionRule] | None`, defaults to `None`):
+ A batch-scoped, shared accumulator of the suggested rules
+ already surfaced by earlier confirmations in the same
+ concurrent batch. Passed only by
+ :meth:`_execute_concurrent_tool_calls`; when provided, a
+ non-safety ASK whose invocation is already covered by an
+ accumulated rule is de-duplicated (left ``PENDING`` and
+ not surfaced again). ``None`` disables de-duplication
+ (e.g. sequential execution, which already parks at the
+ first ASK).
Yields:
`RequireUserConfirmEvent \
@@ -1663,6 +1695,36 @@ class Agent:
PermissionBehavior.ASK,
PermissionBehavior.PASSTHROUGH,
]:
+ # Batch de-duplication (concurrent batches only): if an earlier
+ # confirmation in this same batch already suggested an allow rule
+ # that matches this invocation, do not surface a second prompt.
+ # Leave the call PENDING so the next reply run re-evaluates it
+ # against the engine once the user answers the first prompt (and
+ # its rule has been added). Safety ASKs (bypass-immune) are never
+ # de-duplicated — an allow rule cannot clear them, so each must
+ # surface its own prompt.
+ is_safety_ask = (
+ decision.behavior == PermissionBehavior.ASK
+ and decision.bypass_immune
+ )
+ if kept_rules is not None and not is_safety_ask:
+ for rule in kept_rules:
+ if rule.tool_name != tool.name:
+ continue
+ if await _execute_async_or_sync_func(
+ tool.match_rule,
+ rule.rule_content,
+ parsed_input,
+ ):
+ # Covered by an earlier call's rule; stay PENDING and
+ # do not yield — re-evaluated on the next reply run.
+ return
+
+ if kept_rules is not None:
+ # Register this prompt's suggested rules so later calls in the
+ # batch can be de-duplicated against them.
+ kept_rules.extend(decision.suggested_rules or [])
+
# Set the state of the tool call to "ask"
# **Note** the update must be done before yielding the event
self._update_tool_call_state(
diff --git a/src/agentscope/permission/_engine.py b/src/agentscope/permission/_engine.py
index 8487ae65f..434acfd10 100644
--- a/src/agentscope/permission/_engine.py
+++ b/src/agentscope/permission/_engine.py
@@ -121,20 +121,20 @@ class PermissionEngine:
) -> 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:
+ Every operation requires explicit permission unless it is a
+ read-only invocation, an allow rule matches, or the tool's own
+ ``check_permissions`` returns ALLOW. Evaluation order:
1. Deny rules → DENY
2. Ask rules → ASK (with suggestions)
- 3. ``tool.check_permissions``:
+ 3. Read-only fast path → ALLOW
+ 4. ``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)
+ 5. Allow rules → ALLOW
+ 6. Default → ASK (with suggestions)
Args:
tool (`ToolBase`):
@@ -146,12 +146,16 @@ class PermissionEngine:
`PermissionDecision`:
The final decision.
"""
- # step 1: deny rules — highest priority
+ # ================================================================
+ # Step 1: Deny rules — highest priority (all modes)
+ # ================================================================
deny = await self._check_deny_rules(tool, tool_input)
if deny:
return deny
- # step 2: ask rules
+ # ================================================================
+ # Step 2: Ask rules → ASK (with suggestions)
+ # ================================================================
ask = await self._check_ask_rules(tool, tool_input)
if ask:
ask.suggested_rules = await self._generate_suggestions(
@@ -160,15 +164,25 @@ class PermissionEngine:
)
return ask
- # step 3: tool's own check_permissions
+ # ================================================================
+ # Step 3: Read-only fast path → ALLOW
+ # ================================================================
+ read_only = await self._check_read_only_fast_path(tool, tool_input)
+ if read_only:
+ return read_only
+
+ # ================================================================
+ # Step 4: Tool's own check_permissions
+ # - ALLOW / DENY → returned as-is
+ # - safety ASK (bypass-immune) → returned; allow rules can't override
+ # - non-safety ASK / PASSTHROUGH → continue
+ # ================================================================
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 = await self._generate_suggestions(
tool,
@@ -176,12 +190,16 @@ class PermissionEngine:
)
return tool_decision
- # step 4: allow rules
+ # ================================================================
+ # Step 5: Allow rules → ALLOW
+ # ================================================================
allow = await self._check_allow_rules(tool, tool_input)
if allow:
return allow
- # step 5: default — ASK the user
+ # ================================================================
+ # Step 6: Mode fallback → ASK the user
+ # ================================================================
default = PermissionDecision(
behavior=PermissionBehavior.ASK,
message=f"Permission required for {tool.name}",
@@ -205,9 +223,10 @@ class PermissionEngine:
1. Deny rules → DENY
2. Ask rules → ASK (with suggestions)
- 3. :meth:`ToolBase.check_read_only` (input-aware):
- - True → ALLOW
- - False → DENY
+ 3. Read-only fast path → ALLOW
+ 4. ``tool.check_permissions`` → not applicable (see below)
+ 5. Allow rules → not applicable (see below)
+ 6. Mode fallback → DENY
``tool.check_permissions`` is not invoked: EXPLORE is fully
resolved by the read-only verdict, so safety ASK paths (e.g.
@@ -225,12 +244,16 @@ class PermissionEngine:
`PermissionDecision`:
ALLOW for read-only invocations, DENY otherwise.
"""
- # step 1: deny rules
+ # ================================================================
+ # Step 1: Deny rules — highest priority (all modes)
+ # ================================================================
deny = await self._check_deny_rules(tool, tool_input)
if deny:
return deny
- # step 2: ask rules
+ # ================================================================
+ # Step 2: Ask rules → ASK (with suggestions)
+ # ================================================================
ask = await self._check_ask_rules(tool, tool_input)
if ask:
ask.suggested_rules = await self._generate_suggestions(
@@ -239,16 +262,29 @@ class PermissionEngine:
)
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",
- )
+ # ================================================================
+ # Step 3: Read-only fast path → ALLOW
+ # ================================================================
+ read_only = await self._check_read_only_fast_path(tool, tool_input)
+ if read_only:
+ return read_only
+
+ # ================================================================
+ # Step 4: Tool's own check_permissions
+ # Not applicable in EXPLORE: any non-read-only op is denied below
+ # regardless of the tool's opinion, so the tool is never consulted
+ # (a safety ASK would only be subsumed into the broader DENY).
+ # ================================================================
+
+ # ================================================================
+ # Step 5: Allow rules
+ # Not applicable in EXPLORE: the read-only guarantee cannot be
+ # granted away by a user-configured allow rule.
+ # ================================================================
+
+ # ================================================================
+ # Step 6: Mode fallback → DENY (invocation is not read-only)
+ # ================================================================
return PermissionDecision(
behavior=PermissionBehavior.DENY,
message=(
@@ -290,12 +326,16 @@ class PermissionEngine:
`PermissionDecision`:
The final decision.
"""
- # step 1: deny rules
+ # ================================================================
+ # Step 1: Deny rules — highest priority (all modes)
+ # ================================================================
deny = await self._check_deny_rules(tool, tool_input)
if deny:
return deny
- # step 2: ask rules
+ # ================================================================
+ # Step 2: Ask rules → ASK (with suggestions)
+ # ================================================================
ask = await self._check_ask_rules(tool, tool_input)
if ask:
ask.suggested_rules = await self._generate_suggestions(
@@ -304,28 +344,26 @@ class PermissionEngine:
)
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",
- )
-
- # step 4: tool's own check_permissions (working-directory check
- # for Write/Edit, path-checked auto-allow for Bash, ...)
+ # ================================================================
+ # Step 3: Read-only fast path → ALLOW
+ # ================================================================
+ read_only = await self._check_read_only_fast_path(tool, tool_input)
+ if read_only:
+ return read_only
+
+ # ================================================================
+ # Step 4: Tool's own check_permissions (working-directory auto-allow
+ # for Write/Edit, path-checked auto-allow for Bash, ...)
+ # - ALLOW / DENY → returned as-is
+ # - safety ASK (bypass-immune) → returned; allow rules can't override
+ # - non-safety ASK / PASSTHROUGH → continue
+ # ================================================================
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 = await self._generate_suggestions(
tool,
@@ -333,12 +371,16 @@ class PermissionEngine:
)
return tool_decision
- # step 5: allow rules
+ # ================================================================
+ # Step 5: Allow rules → ALLOW
+ # ================================================================
allow = await self._check_allow_rules(tool, tool_input)
if allow:
return allow
- # step 6: default — ASK the user
+ # ================================================================
+ # Step 6: Mode fallback → ASK the user
+ # ================================================================
default = PermissionDecision(
behavior=PermissionBehavior.ASK,
message=f"Permission required for {tool.name}",
@@ -375,12 +417,13 @@ class PermissionEngine:
1. Deny rules → DENY
2. Ask rules → ASK (with suggestions; honors explicit user intent)
- 3. ``tool.check_permissions``:
+ 3. Read-only fast path → ALLOW
+ 4. ``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)
+ 5. Allow rules → ALLOW
+ 6. Fallback → ALLOW (BYPASS)
Args:
tool (`ToolBase`):
@@ -392,12 +435,16 @@ class PermissionEngine:
`PermissionDecision`:
The final decision.
"""
- # step 1: deny rules
+ # ================================================================
+ # Step 1: Deny rules — highest priority (all modes)
+ # ================================================================
deny = await self._check_deny_rules(tool, tool_input)
if deny:
return deny
- # step 2: ask rules (honor explicit user intent to be prompted)
+ # ================================================================
+ # Step 2: Ask rules → ASK (honor explicit user intent to be prompted)
+ # ================================================================
ask = await self._check_ask_rules(tool, tool_input)
if ask:
ask.suggested_rules = await self._generate_suggestions(
@@ -406,9 +453,18 @@ class PermissionEngine:
)
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.
+ # ================================================================
+ # Step 3: Read-only fast path → ALLOW
+ # ================================================================
+ read_only = await self._check_read_only_fast_path(tool, tool_input)
+ if read_only:
+ return read_only
+
+ # ================================================================
+ # Step 4: 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,
@@ -416,12 +472,16 @@ class PermissionEngine:
):
return tool_decision
- # step 4: allow rules
+ # ================================================================
+ # Step 5: Allow rules → ALLOW
+ # ================================================================
allow = await self._check_allow_rules(tool, tool_input)
if allow:
return allow
- # step 5: bypass fallback — ALLOW everything else
+ # ================================================================
+ # Step 6: Mode fallback → ALLOW everything else (BYPASS)
+ # ================================================================
return PermissionDecision(
behavior=PermissionBehavior.ALLOW,
message=f"Permission granted for {tool.name} (bypass mode)",
@@ -436,19 +496,25 @@ class PermissionEngine:
"""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
+ tasks, background runs). Behaves as the *unattended* counterpart
+ of :attr:`PermissionMode.ACCEPT_EDITS`: read-only invocations and
+ edits within a working directory are auto-allowed, while anything
+ that would otherwise prompt the (absent) user is refused.
+ 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
+ 3. Read-only fast path → ALLOW
+ 4. ``tool.check_permissions``:
+ - ALLOW (e.g. an edit within a working directory) / 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)
+ 5. Allow rules → ALLOW
+ 6. Default → DENY (user not available to answer)
Args:
tool (`ToolBase`):
@@ -460,12 +526,16 @@ class PermissionEngine:
`PermissionDecision`:
The final decision (never ASK).
"""
- # step 1: deny rules
+ # ================================================================
+ # Step 1: Deny rules — highest priority (all modes)
+ # ================================================================
deny = await self._check_deny_rules(tool, tool_input)
if deny:
return deny
- # step 2: ask rules — converted to DENY (no user available)
+ # ================================================================
+ # Step 2: Ask rules → DENY (converted; no user available to answer)
+ # ================================================================
ask = await self._check_ask_rules(tool, tool_input)
if ask:
ask.suggested_rules = await self._generate_suggestions(
@@ -474,15 +544,25 @@ class PermissionEngine:
)
return self._convert_ask_to_deny(tool, ask)
- # step 3: tool's own check_permissions
+ # ================================================================
+ # Step 3: Read-only fast path → ALLOW
+ # ================================================================
+ read_only = await self._check_read_only_fast_path(tool, tool_input)
+ if read_only:
+ return read_only
+
+ # ================================================================
+ # Step 4: Tool's own check_permissions
+ # - ALLOW (e.g. edit within a working directory) / DENY → as-is
+ # - safety ASK → DENY (converted; no user available)
+ # - non-safety ASK / PASSTHROUGH → continue
+ # ================================================================
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 = await self._generate_suggestions(
tool,
@@ -490,12 +570,16 @@ class PermissionEngine:
)
return self._convert_ask_to_deny(tool, tool_decision)
- # step 4: allow rules
+ # ================================================================
+ # Step 5: Allow rules → ALLOW
+ # ================================================================
allow = await self._check_allow_rules(tool, tool_input)
if allow:
return allow
- # step 5: default — DENY (no user available to confirm)
+ # ================================================================
+ # Step 6: Mode fallback → DENY (no user available to confirm)
+ # ================================================================
return PermissionDecision(
behavior=PermissionBehavior.DENY,
message=(
@@ -572,6 +656,41 @@ class PermissionEngine:
and decision.bypass_immune
)
+ async def _check_read_only_fast_path(
+ self,
+ tool: ToolBase,
+ tool_input: dict[str, Any],
+ ) -> PermissionDecision | None:
+ """Read-only fast path shared by every mode.
+
+ A read-only invocation has no side effects, so it is auto-allowed
+ in every :class:`PermissionMode`. Keeping this in a single helper
+ (rather than re-inlining it per mode) guarantees the modes cannot
+ drift apart on read-only handling — the exact divergence that
+ previously left ``DEFAULT`` and ``DONT_ASK`` without a read-only
+ fast path while ``ACCEPT_EDITS`` / ``EXPLORE`` had one.
+
+ Args:
+ tool (`ToolBase`):
+ The tool instance being called.
+ tool_input (`dict[str, Any]`):
+ The tool input data.
+
+ Returns:
+ `PermissionDecision | None`:
+ An ALLOW decision if this invocation is read-only, else None.
+ """
+ if await tool.check_read_only(tool_input):
+ return PermissionDecision(
+ behavior=PermissionBehavior.ALLOW,
+ message=(
+ f"Permission granted for {tool.name} "
+ f"(read-only invocation)"
+ ),
+ decision_reason="Read-only operations are auto-allowed",
+ )
+ return None
+
async def _check_deny_rules(
self,
tool: ToolBase,
diff --git a/src/agentscope/tool/_builtin/_bash.py b/src/agentscope/tool/_builtin/_bash.py
index 58952f6fc..6cec9091d 100644
--- a/src/agentscope/tool/_builtin/_bash.py
+++ b/src/agentscope/tool/_builtin/_bash.py
@@ -191,6 +191,14 @@ easier to review tool calls and give permission.
command = tool_input.get("command", "")
if not command:
return self.is_read_only
+ # A command with dynamic / unanalyzable structure (command
+ # substitution, control flow, ...) cannot be *proven* read-only —
+ # e.g. ``ls $(rm -rf /)`` looks read-only but embeds a mutation.
+ # Report it as non-read-only so the engine's read-only fast path
+ # does not short-circuit it; ``check_permissions`` then surfaces the
+ # bypass-immune injection safety ASK.
+ if self._bash_parser.check_injection_risk(command):
+ return False
return self._bash_parser.is_read_only_command(command)
async def check_permissions(
@@ -324,13 +332,17 @@ easier to review tool calls and give permission.
bypass_immune=True,
)
- # 6. ACCEPT_EDITS auto-allow for filesystem commands whose targets
- # all live inside a working directory. Mirrors Write/Edit's strict
+ # 6. Auto-allow filesystem commands whose targets all live inside a
+ # working directory. Applies to ACCEPT_EDITS (interactive) and
+ # DONT_ASK (its unattended counterpart). 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:
+ if context.mode in (
+ PermissionMode.ACCEPT_EDITS,
+ PermissionMode.DONT_ASK,
+ ):
filesystem_commands = {
"mkdir",
"touch",
@@ -366,13 +378,12 @@ easier to review tool calls and give permission.
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)",
+ f"command (filesystem command, all targets in "
+ f"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"
+ f"auto-allowed because all target paths are "
+ f"within a working directory"
),
)
diff --git a/src/agentscope/tool/_builtin/_edit.py b/src/agentscope/tool/_builtin/_edit.py
index 962b68078..d9765c240 100644
--- a/src/agentscope/tool/_builtin/_edit.py
+++ b/src/agentscope/tool/_builtin/_edit.py
@@ -160,13 +160,19 @@ Usage:
bypass_immune=True,
)
- # 2. Check ACCEPT_EDITS mode for files in working directories
- if context.mode == PermissionMode.ACCEPT_EDITS:
+ # 2. Auto-allow edits within a working directory. This applies to
+ # ACCEPT_EDITS (interactive) and DONT_ASK (its unattended
+ # counterpart), which trusts in-working-directory edits without a
+ # prompt because no user is available to grant one.
+ if context.mode in (
+ PermissionMode.ACCEPT_EDITS,
+ PermissionMode.DONT_ASK,
+ ):
if self._path_in_allowed_working_path(file_path, context):
return PermissionDecision(
behavior=PermissionBehavior.ALLOW,
message=f"Permission granted for editing {file_path} "
- f"(accept edits mode - in working directory)",
+ f"(in working directory)",
decision_reason="File is in working directory and not "
"a dangerous path",
)
diff --git a/src/agentscope/tool/_builtin/_write.py b/src/agentscope/tool/_builtin/_write.py
index a4fdd11ba..83e6b5cfb 100644
--- a/src/agentscope/tool/_builtin/_write.py
+++ b/src/agentscope/tool/_builtin/_write.py
@@ -139,13 +139,19 @@ Usage:
bypass_immune=True,
)
- # 2. Check ACCEPT_EDITS mode for files in working directories
- if context.mode == PermissionMode.ACCEPT_EDITS:
+ # 2. Auto-allow edits within a working directory. This applies to
+ # ACCEPT_EDITS (interactive) and DONT_ASK (its unattended
+ # counterpart), which trusts in-working-directory edits without a
+ # prompt because no user is available to grant one.
+ if context.mode in (
+ PermissionMode.ACCEPT_EDITS,
+ PermissionMode.DONT_ASK,
+ ):
if self._path_in_allowed_working_path(file_path, context):
return PermissionDecision(
behavior=PermissionBehavior.ALLOW,
message=f"Permission granted for writing {file_path} "
- f"(accept edits mode - in working directory)",
+ f"(in working directory)",
decision_reason="File is in working directory and not "
"a dangerous path",
)
diff --git a/tests/agent_interrupt_test.py b/tests/agent_interrupt_test.py
index 359110ba1..e44f41e9a 100644
--- a/tests/agent_interrupt_test.py
+++ b/tests/agent_interrupt_test.py
@@ -116,6 +116,10 @@ class _UserConfirmConcurrentTool(_TimeoutConcurrentTool):
"""Concurrent tool that always asks for user confirmation."""
name: str = "user_confirm_concurrent"
+ # A tool that requires confirmation is not read-only: the read-only
+ # fast path auto-allows read-only invocations in every mode (ahead of
+ # ``check_permissions``), which would otherwise bypass the ASK below.
+ is_read_only: bool = False
async def check_permissions(
self,
diff --git a/tests/hitl_user_confirmation_test.py b/tests/hitl_user_confirmation_test.py
index 7e27cf92e..35cea9aea 100644
--- a/tests/hitl_user_confirmation_test.py
+++ b/tests/hitl_user_confirmation_test.py
@@ -16,6 +16,7 @@ from agentscope.permission import (
PermissionDecision,
PermissionBehavior,
PermissionContext,
+ PermissionRule,
)
from agentscope.message import (
TextBlock,
@@ -101,6 +102,49 @@ class MockUserConfirmConcurrentTool(ToolBase):
)
+class MockUserConfirmConcurrentToolB(ToolBase):
+ """A second concurrent confirm tool with a distinct name.
+
+ Used to exercise concurrent confirmations that are NOT de-duplicated:
+ two calls to *different* tools never share a suggested rule, so both
+ surface their own confirmation prompt.
+ """
+
+ name: str = "mock_user_confirm_concurrent_tool_b"
+ description: str = "A second mock user confirm concurrent tool"
+ input_schema: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "input": {"type": "string", "description": "Input string"},
+ },
+ "required": ["input"],
+ }
+ is_concurrency_safe: bool = True
+ is_read_only: bool = False
+ is_external_tool: bool = False
+ is_mcp: bool = False
+
+ async def check_permissions(
+ self,
+ tool_input: dict[str, Any],
+ context: PermissionContext,
+ ) -> PermissionDecision:
+ """Check permissions for the tool usage."""
+ return PermissionDecision(
+ behavior=PermissionBehavior.ASK,
+ decision_reason="Mock tool requires user confirmation",
+ message="Mock tool requires user confirmation",
+ )
+
+ async def __call__(self, input: str, **kwargs: Any) -> ToolChunk:
+ """Execute the tool."""
+ return ToolChunk(
+ content=[
+ TextBlock(text=f"User confirm concurrent result B: {input}"),
+ ],
+ )
+
+
class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
"""Test the user confirmation events in the agent class."""
@@ -831,14 +875,19 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
self.assertListEqual(context_dicts, expected_context_final)
async def test_concurrent_user_confirmation(self) -> None:
- """Test multiple user confirmation tool calls in concurrent execution.
-
- The agent should:
- 1. Generate multiple tool calls that require user confirmation
- 2. All tools have is_concurrent_safe=True (concurrent)
- 3. Emit REQUIRE_USER_CONFIRM event and pause
- 4. Resume when UserConfirmResultEvent is provided
- 5. Execute the tools and continue
+ """Concurrent confirmations, first confirmed WITHOUT a rule.
+
+ Two concurrent calls to the same tool share one tool-name-level
+ suggested rule, so batch de-duplication surfaces only the first
+ confirmation and leaves the second PENDING. When the first is
+ confirmed WITHOUT an always-allow rule, the second is re-evaluated
+ on the next reply run and surfaces its own (deferred) prompt — it is
+ never silently skipped. The agent should:
+ 1. Generate two concurrent tool calls that require confirmation
+ 2. Emit ONE REQUIRE_USER_CONFIRM (for the first) and pause; the
+ second stays PENDING
+ 3. On confirming the first, execute it and surface the second prompt
+ 4. On confirming the second, execute it and continue
"""
# Register user confirm concurrent tool
confirm_tool = MockUserConfirmConcurrentTool()
@@ -907,6 +956,17 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
self.tool_input_2,
)
+ suggested_rules = [
+ {
+ "tool_name": self.concurrent_tool_name,
+ "rule_content": None,
+ "behavior": PermissionBehavior.ALLOW,
+ "source": "suggested",
+ },
+ ]
+
+ # Only the first call surfaces a confirmation; the second is deduped
+ # (left PENDING) because they share one tool-name-level rule.
expected_events = [
{
"type": "REPLY_START",
@@ -935,35 +995,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
"name": self.concurrent_tool_name,
"input": self.tool_input_1,
"state": "asking",
- "suggested_rules": [
- {
- "tool_name": self.concurrent_tool_name,
- "rule_content": None,
- "behavior": PermissionBehavior.ALLOW,
- "source": "suggested",
- },
- ],
- },
- ],
- },
- {
- "type": "REQUIRE_USER_CONFIRM",
- "reply_id": reply_id,
- "tool_calls": [
- {
- "type": "tool_call",
- "id": self.tool_call_id_2,
- "name": self.concurrent_tool_name,
- "input": self.tool_input_2,
- "state": "asking",
- "suggested_rules": [
- {
- "tool_name": self.concurrent_tool_name,
- "rule_content": None,
- "behavior": PermissionBehavior.ALLOW,
- "source": "suggested",
- },
- ],
+ "suggested_rules": suggested_rules,
},
],
},
@@ -975,7 +1007,8 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
[{**basic_dict, **_} for _ in expected_events],
)
- # Assert context after first call
+ # Assert context after first call: tool_call_1 asking, tool_call_2
+ # left PENDING with no suggested rules (never surfaced).
msg_base = self._get_msg_base()
expected_context = [
{
@@ -998,29 +1031,15 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
"name": self.concurrent_tool_name,
"input": self.tool_input_1,
"state": "asking",
- "suggested_rules": [
- {
- "tool_name": self.concurrent_tool_name,
- "rule_content": None,
- "behavior": PermissionBehavior.ALLOW,
- "source": "suggested",
- },
- ],
+ "suggested_rules": suggested_rules,
},
{
"type": "tool_call",
"id": self.tool_call_id_2,
"name": self.concurrent_tool_name,
"input": self.tool_input_2,
- "state": "asking",
- "suggested_rules": [
- {
- "tool_name": self.concurrent_tool_name,
- "rule_content": None,
- "behavior": PermissionBehavior.ALLOW,
- "source": "suggested",
- },
- ],
+ "state": "pending",
+ "suggested_rules": [],
},
],
},
@@ -1029,7 +1048,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
expected_context = [{**msg_base, **_} for _ in expected_context]
self.assertListEqual(context_dicts, expected_context)
- # Create user confirmation result event
+ # Confirm the first call WITHOUT an always-allow rule.
user_confirm_event = UserConfirmResultEvent(
reply_id=reply_id,
confirm_results=[
@@ -1049,13 +1068,28 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
async for event in self.agent.reply_stream(inputs=user_confirm_event):
events.append(event.model_dump())
- # Verify events for tool call 1 after resumption
+ # The first call executes; then the second (deferred) surfaces its
+ # own confirmation now that it is re-evaluated against the engine.
expected_events = [
*self._get_tool_result_events(
self.tool_call_id_1,
self.concurrent_tool_name,
self.concurrent_result_1,
),
+ {
+ "type": "REQUIRE_USER_CONFIRM",
+ "reply_id": reply_id,
+ "tool_calls": [
+ {
+ "type": "tool_call",
+ "id": self.tool_call_id_2,
+ "name": self.concurrent_tool_name,
+ "input": self.tool_input_2,
+ "state": "asking",
+ "suggested_rules": suggested_rules,
+ },
+ ],
+ },
]
self.assertListEqual(
events,
@@ -1121,14 +1155,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
"name": self.concurrent_tool_name,
"input": self.tool_input_1,
"state": "finished",
- "suggested_rules": [
- {
- "tool_name": self.concurrent_tool_name,
- "rule_content": None,
- "behavior": PermissionBehavior.ALLOW,
- "source": "suggested",
- },
- ],
+ "suggested_rules": suggested_rules,
},
{
"type": "tool_call",
@@ -1136,14 +1163,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
"name": self.concurrent_tool_name,
"input": self.tool_input_2,
"state": "finished",
- "suggested_rules": [
- {
- "tool_name": self.concurrent_tool_name,
- "rule_content": None,
- "behavior": PermissionBehavior.ALLOW,
- "source": "suggested",
- },
- ],
+ "suggested_rules": suggested_rules,
},
{
"type": "tool_result",
@@ -1187,21 +1207,20 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
]
self.assertListEqual(context_dicts, expected_context_final)
- async def test_concurrent_user_confirmation_in_single_event(self) -> None:
- """Test concurrent user confirmation when two approvals arrive
- together.
+ async def test_concurrent_user_confirmation_rule_dedup(self) -> None:
+ """Confirming the first deduped call WITH a rule auto-runs the second.
- The agent should:
- 1. Generate multiple tool calls that require user confirmation
- 2. Pause in concurrent mode with two asking tool calls
- 3. Resume when one UserConfirmResultEvent carries both confirmations
- 4. Execute both tools and continue reasoning after both complete
+ This is the core batch-exemption-propagation fix: two concurrent
+ calls to the same tool share one tool-name-level suggested rule, so
+ only the first surfaces a confirmation. Confirming it WITH the
+ suggested (always-allow) rule adds the rule to the engine, and the
+ second (PENDING) call is then allowed on the next reply run — with
+ no second prompt.
"""
confirm_tool = MockUserConfirmConcurrentTool()
self.agent.toolkit = Toolkit(
tools=[confirm_tool],
)
-
self.model.set_responses(
[
[
@@ -1218,18 +1237,135 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
input=self.tool_input_2,
),
],
+ is_last=True,
+ ),
+ ],
+ self.final_mock_responses,
+ ],
+ )
+
+ events = []
+ async for event in self.agent.reply_stream(
+ UserMsg(name="user", content=self.user_input_text),
+ ):
+ events.append(event.model_dump())
+
+ reply_id = self.agent.state.reply_id
+
+ # Run 1: exactly one confirmation, for the first call only.
+ confirm_events = [
+ _ for _ in events if _["type"] == "REQUIRE_USER_CONFIRM"
+ ]
+ self.assertEqual(len(confirm_events), 1)
+ self.assertEqual(
+ confirm_events[0]["tool_calls"][0]["id"],
+ self.tool_call_id_1,
+ )
+
+ # Confirm the first call WITH the always-allow rule it suggested.
+ user_confirm_event = UserConfirmResultEvent(
+ reply_id=reply_id,
+ confirm_results=[
+ ConfirmResult(
+ confirmed=True,
+ tool_call=ToolCallBlock(
+ id=self.tool_call_id_1,
+ name=self.concurrent_tool_name,
+ input=self.tool_input_1,
+ ),
+ rules=[
+ PermissionRule(
+ tool_name=self.concurrent_tool_name,
+ rule_content=None,
+ behavior=PermissionBehavior.ALLOW,
+ source="suggested",
+ ),
+ ],
+ ),
+ ],
+ )
+
+ events = []
+ async for event in self.agent.reply_stream(inputs=user_confirm_event):
+ events.append(event.model_dump())
+
+ # No further confirmation is required — the rule cleared the second.
+ self.assertNotIn(
+ "REQUIRE_USER_CONFIRM",
+ [_["type"] for _ in events],
+ )
+ # Both tool calls execute.
+ finished_ids = sorted(
+ _["tool_call_id"] for _ in events if _["type"] == "TOOL_RESULT_END"
+ )
+ self.assertEqual(
+ finished_ids,
+ [self.tool_call_id_1, self.tool_call_id_2],
+ )
+ self.assertEqual(events[-1]["type"], "REPLY_END")
+
+ # Both tool calls end up finished.
+ assistant_msg = self.agent.state.context[-1]
+ self.assertEqual(
+ [
+ _.model_dump()["state"]
+ for _ in assistant_msg.get_content_blocks("tool_call")
+ ],
+ ["finished", "finished"],
+ )
+
+ async def test_concurrent_user_confirmation_in_single_event(self) -> None:
+ """Two different-tool confirmations resolved by one event.
+
+ Two concurrent calls to *different* tools do not share a suggested
+ rule, so neither is de-duplicated and both surface a confirmation. A
+ single UserConfirmResultEvent then carries both approvals and both
+ tools execute on resume. The agent should:
+ 1. Generate two concurrent tool calls (distinct tools) that require
+ confirmation
+ 2. Emit two REQUIRE_USER_CONFIRM events and pause
+ 3. Resume when one UserConfirmResultEvent carries both confirmations
+ 4. Execute both tools and continue reasoning after both complete
+ """
+ name_a = self.concurrent_tool_name
+ name_b = "mock_user_confirm_concurrent_tool_b"
+ result_a = self.concurrent_result_1
+ result_b = "User confirm concurrent result B: test2"
+ self.agent.toolkit = Toolkit(
+ tools=[
+ MockUserConfirmConcurrentTool(),
+ MockUserConfirmConcurrentToolB(),
+ ],
+ )
+
+ self.model.set_responses(
+ [
+ [
+ ChatResponse(
+ content=[
+ ToolCallBlock(
+ id=self.tool_call_id_1,
+ name=name_a,
+ input=self.tool_input_1,
+ ),
+ ToolCallBlock(
+ id=self.tool_call_id_2,
+ name=name_b,
+ input=self.tool_input_2,
+ ),
+ ],
is_last=False,
),
ChatResponse(
content=[
ToolCallBlock(
id=self.tool_call_id_1,
- name=self.concurrent_tool_name,
+ name=name_a,
input=self.tool_input_1,
),
ToolCallBlock(
id=self.tool_call_id_2,
- name=self.concurrent_tool_name,
+ name=name_b,
input=self.tool_input_2,
),
],
@@ -1253,15 +1389,33 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
tool_call_1_events = self._get_tool_call_events(
self.tool_call_id_1,
- self.concurrent_tool_name,
+ name_a,
self.tool_input_1,
)
tool_call_2_events = self._get_tool_call_events(
self.tool_call_id_2,
- self.concurrent_tool_name,
+ name_b,
self.tool_input_2,
)
+ rule_a = [
+ {
+ "tool_name": name_a,
+ "rule_content": None,
+ "behavior": PermissionBehavior.ALLOW,
+ "source": "suggested",
+ },
+ ]
+ rule_b = [
+ {
+ "tool_name": name_b,
+ "rule_content": None,
+ "behavior": PermissionBehavior.ALLOW,
+ "source": "suggested",
+ },
+ ]
+
+ # Distinct tools do not de-duplicate: both surface a confirmation.
expected_events = [
{
"type": "REPLY_START",
@@ -1287,17 +1441,10 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
{
"type": "tool_call",
"id": self.tool_call_id_1,
- "name": self.concurrent_tool_name,
+ "name": name_a,
"input": self.tool_input_1,
"state": "asking",
- "suggested_rules": [
- {
- "tool_name": self.concurrent_tool_name,
- "rule_content": None,
- "behavior": PermissionBehavior.ALLOW,
- "source": "suggested",
- },
- ],
+ "suggested_rules": rule_a,
},
],
},
@@ -1308,17 +1455,10 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
{
"type": "tool_call",
"id": self.tool_call_id_2,
- "name": self.concurrent_tool_name,
+ "name": name_b,
"input": self.tool_input_2,
"state": "asking",
- "suggested_rules": [
- {
- "tool_name": self.concurrent_tool_name,
- "rule_content": None,
- "behavior": PermissionBehavior.ALLOW,
- "source": "suggested",
- },
- ],
+ "suggested_rules": rule_b,
},
],
},
@@ -1346,32 +1486,18 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
{
"type": "tool_call",
"id": self.tool_call_id_1,
- "name": self.concurrent_tool_name,
+ "name": name_a,
"input": self.tool_input_1,
"state": "asking",
- "suggested_rules": [
- {
- "tool_name": self.concurrent_tool_name,
- "rule_content": None,
- "behavior": PermissionBehavior.ALLOW,
- "source": "suggested",
- },
- ],
+ "suggested_rules": rule_a,
},
{
"type": "tool_call",
"id": self.tool_call_id_2,
- "name": self.concurrent_tool_name,
+ "name": name_b,
"input": self.tool_input_2,
"state": "asking",
- "suggested_rules": [
- {
- "tool_name": self.concurrent_tool_name,
- "rule_content": None,
- "behavior": PermissionBehavior.ALLOW,
- "source": "suggested",
- },
- ],
+ "suggested_rules": rule_b,
},
],
},
@@ -1380,6 +1506,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
expected_context = [{**msg_base, **_} for _ in expected_context]
self.assertListEqual(context_dicts, expected_context)
+ # A single confirmation event carrying BOTH approvals.
user_confirm_event = UserConfirmResultEvent(
reply_id=reply_id,
confirm_results=[
@@ -1387,7 +1514,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
confirmed=True,
tool_call=ToolCallBlock(
id=self.tool_call_id_1,
- name=self.concurrent_tool_name,
+ name=name_a,
input=self.tool_input_1,
),
),
@@ -1395,7 +1522,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
confirmed=True,
tool_call=ToolCallBlock(
id=self.tool_call_id_2,
- name=self.concurrent_tool_name,
+ name=name_b,
input=self.tool_input_2,
),
),
@@ -1415,16 +1542,16 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
{**basic_dict, **_}
for _ in self._get_tool_result_events(
self.tool_call_id_1,
- self.concurrent_tool_name,
- self.concurrent_result_1,
+ name_a,
+ result_a,
)
],
self.tool_call_id_2: [
{**basic_dict, **_}
for _ in self._get_tool_result_events(
self.tool_call_id_2,
- self.concurrent_tool_name,
- self.concurrent_result_2,
+ name_b,
+ result_b,
)
],
}
@@ -1497,16 +1624,8 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):
for _ in assistant_msg.get_content_blocks("tool_result")
},
{
- (
- self.concurrent_tool_name,
- "success",
- self.concurrent_result_1,
- ),
- (
- self.concurrent_tool_name,
- "success",
- self.concurrent_result_2,
- ),
+ (name_a, "success", result_a),
+ (name_b, "success", result_b),
},
)
self.assertEqual(
diff --git a/tests/permission_engine_test.py b/tests/permission_engine_test.py
index 4be95ddb5..ee71c1f96 100644
--- a/tests/permission_engine_test.py
+++ b/tests/permission_engine_test.py
@@ -22,7 +22,6 @@ from agentscope.permission import (
from agentscope.tool import (
Bash,
Write,
- Read,
Edit,
ToolBase,
)
@@ -265,10 +264,15 @@ class PermissionEngineFileRuleTest(IsolatedAsyncioTestCase):
self.engine = PermissionEngine(self.context)
async def test_file_glob_pattern_matching(self) -> None:
- """Test file path glob pattern matching."""
+ """Test file path glob pattern matching.
+
+ Uses ``Write`` (a mutating tool) rather than a read-only tool:
+ read-only invocations are auto-allowed before rule matching in
+ every mode, so they cannot exercise the allow-rule glob path.
+ """
self.engine.add_rule(
PermissionRule(
- tool_name="Read",
+ tool_name="Write",
rule_content="*.py",
behavior=PermissionBehavior.ALLOW,
source="test",
@@ -277,14 +281,14 @@ class PermissionEngineFileRuleTest(IsolatedAsyncioTestCase):
# Test matching file
decision = await self.engine.check_permission(
- Read(),
+ Write(),
{"file_path": "test.py"},
)
self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)
# Test non-matching file
decision = await self.engine.check_permission(
- Read(),
+ Write(),
{"file_path": "test.txt"},
)
self.assertEqual(decision.behavior, PermissionBehavior.ASK)
@@ -472,9 +476,14 @@ class PermissionEngineSuggestionTest(IsolatedAsyncioTestCase):
self.assertIn("git commit:*", suggestion_contents)
async def test_file_suggestions(self) -> None:
- """Test suggestion generation for file operations."""
+ """Test suggestion generation for file operations.
+
+ Uses ``Write`` (a mutating tool): read-only tools are auto-allowed
+ and an ALLOW decision carries no suggestions, so a mutating tool is
+ needed to reach the ASK path that generates them.
+ """
decision = await self.engine.check_permission(
- Read(),
+ Write(),
{"file_path": "/tmp/test.py"},
)
diff --git a/tests/permission_mode_test.py b/tests/permission_mode_test.py
index ef57478a8..6a619fb96 100644
--- a/tests/permission_mode_test.py
+++ b/tests/permission_mode_test.py
@@ -36,6 +36,8 @@ from agentscope.tool import (
Write,
Read,
Edit,
+ Glob,
+ Grep,
)
@@ -66,6 +68,27 @@ class PermissionEngineDefaultModeTest(IsolatedAsyncioTestCase):
)
self.assertEqual(decision.behavior, PermissionBehavior.ASK)
+ async def test_default_read_only_tools_auto_allow(self) -> None:
+ """Read / Glob / Grep are read-only and must be auto-allowed in
+ DEFAULT via the read-only fast path — no confirmation prompt.
+
+ Regression for the DEFAULT-mode gap where read-only tools fell
+ through to the default ASK because DEFAULT lacked the read-only
+ fast path that ACCEPT_EDITS / EXPLORE already had.
+ """
+ cases = [
+ (Read(), {"file_path": "/anywhere/file.txt"}),
+ (Glob(), {"pattern": "**/*.py"}),
+ (Grep(), {"pattern": "TODO"}),
+ ]
+ for tool, tool_input in cases:
+ decision = await self.engine.check_permission(tool, tool_input)
+ self.assertEqual(
+ decision.behavior,
+ PermissionBehavior.ALLOW,
+ f"Expected ALLOW for read-only tool {tool.name} in DEFAULT",
+ )
+
async def test_default_deny_rule_returns_deny(self) -> None:
"""Deny rule has the highest priority."""
self.engine.add_rule(
@@ -823,6 +846,99 @@ class PermissionEngineDontAskModeTest(IsolatedAsyncioTestCase):
)
self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)
+ async def test_dont_ask_read_only_tools_auto_allow(self) -> None:
+ """Read / Glob / Grep are auto-allowed in DONT_ASK: the read-only
+ fast path applies in every mode, so unattended runs can freely
+ inspect files without an (impossible) prompt."""
+ cases = [
+ (Read(), {"file_path": "/anywhere/file.txt"}),
+ (Glob(), {"pattern": "**/*.py"}),
+ (Grep(), {"pattern": "TODO"}),
+ ]
+ for tool, tool_input in cases:
+ decision = await self.engine.check_permission(tool, tool_input)
+ self.assertEqual(
+ decision.behavior,
+ PermissionBehavior.ALLOW,
+ f"Expected ALLOW for read-only tool {tool.name} in DONT_ASK",
+ )
+
+ async def test_dont_ask_edit_within_working_directory_allows(
+ self,
+ ) -> None:
+ """DONT_ASK is the unattended counterpart of ACCEPT_EDITS: edits
+ within a configured working directory are auto-allowed (no user is
+ available to grant them interactively)."""
+ context = PermissionContext(
+ mode=PermissionMode.DONT_ASK,
+ working_directories={
+ "/tmp/project": AdditionalWorkingDirectory(
+ path="/tmp/project",
+ source="test",
+ ),
+ },
+ )
+ engine = PermissionEngine(context)
+ for tool in (Write(), Edit()):
+ decision = await engine.check_permission(
+ tool,
+ {"file_path": "/tmp/project/file.txt"},
+ )
+ self.assertEqual(
+ decision.behavior,
+ PermissionBehavior.ALLOW,
+ f"Expected ALLOW for {tool.name} inside DONT_ASK working dir",
+ )
+
+ async def test_dont_ask_edit_outside_working_directory_denies(
+ self,
+ ) -> None:
+ """Edits outside the working directory cannot be granted without a
+ user to ask, so they are refused (DONT_ASK never returns ASK)."""
+ context = PermissionContext(
+ mode=PermissionMode.DONT_ASK,
+ working_directories={
+ "/tmp/project": AdditionalWorkingDirectory(
+ path="/tmp/project",
+ source="test",
+ ),
+ },
+ )
+ engine = PermissionEngine(context)
+ decision = await engine.check_permission(
+ Write(),
+ {"file_path": "/home/user/other.txt"},
+ )
+ self.assertEqual(decision.behavior, PermissionBehavior.DENY)
+
+ @unittest.skipIf(
+ sys.platform == "win32",
+ "Bash tool is not supported on Windows",
+ )
+ async def test_dont_ask_bash_filesystem_command_working_dir(self) -> None:
+ """DONT_ASK auto-allows filesystem commands whose targets are all
+ inside the working directory, and denies those that escape it."""
+ context = PermissionContext(
+ mode=PermissionMode.DONT_ASK,
+ working_directories={
+ "/tmp/project": AdditionalWorkingDirectory(
+ path="/tmp/project",
+ source="test",
+ ),
+ },
+ )
+ engine = PermissionEngine(context)
+ inside = await engine.check_permission(
+ Bash(),
+ {"command": "touch /tmp/project/new.txt"},
+ )
+ self.assertEqual(inside.behavior, PermissionBehavior.ALLOW)
+ outside = await engine.check_permission(
+ Bash(),
+ {"command": "touch /home/user/new.txt"},
+ )
+ self.assertEqual(outside.behavior, PermissionBehavior.DENY)
+
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
@@ -893,3 +1009,53 @@ class PermissionEngineDontAskModeTest(IsolatedAsyncioTestCase):
{"command": "rm -rf /"},
)
self.assertEqual(decision.behavior, PermissionBehavior.DENY)
+
+
+# ---------------------------------------------------------------------------
+# Cross-mode invariants
+# ---------------------------------------------------------------------------
+
+
+class PermissionEngineReadOnlyConsistencyTest(IsolatedAsyncioTestCase):
+ """A read-only invocation must be ALLOWed in *every* mode.
+
+ Read-only operations have no side effects, so every mode auto-allows
+ them via the shared read-only fast path. This test pins that invariant
+ across all modes at once — it is the guard against the modes drifting
+ apart on read-only handling (the divergence that once left DEFAULT and
+ DONT_ASK without a read-only fast path).
+ """
+
+ async def test_read_only_tool_allowed_in_every_mode(self) -> None:
+ """Read (a statically read-only tool) → ALLOW in all five modes."""
+ for mode in PermissionMode:
+ context = PermissionContext(mode=mode)
+ engine = PermissionEngine(context)
+ decision = await engine.check_permission(
+ Read(),
+ {"file_path": "/anywhere/file.txt"},
+ )
+ self.assertEqual(
+ decision.behavior,
+ PermissionBehavior.ALLOW,
+ f"Expected ALLOW for read-only Read in mode {mode.value}",
+ )
+
+ @unittest.skipIf(
+ sys.platform == "win32",
+ "Bash tool is not supported on Windows",
+ )
+ async def test_read_only_bash_command_allowed_in_every_mode(self) -> None:
+ """A statically read-only bash command → ALLOW in all five modes."""
+ for mode in PermissionMode:
+ context = PermissionContext(mode=mode)
+ engine = PermissionEngine(context)
+ decision = await engine.check_permission(
+ Bash(),
+ {"command": "git status"},
+ )
+ self.assertEqual(
+ decision.behavior,
+ PermissionBehavior.ALLOW,
+ f"Expected ALLOW for read-only bash in mode {mode.value}",
+ )
diff --git a/tests/tracing_test.py b/tests/tracing_test.py
index 762df421a..47ed5999e 100644
--- a/tests/tracing_test.py
+++ b/tests/tracing_test.py
@@ -84,7 +84,10 @@ class HitlWeatherTool(ToolBase):
"required": ["city"],
}
is_concurrency_safe: bool = True
- is_read_only: bool = True
+ # A tool requiring confirmation is not read-only: the read-only fast
+ # path auto-allows read-only invocations in every mode (ahead of
+ # ``check_permissions``), which would otherwise bypass the ASK below.
+ is_read_only: bool = False
is_external_tool: bool = False
is_mcp: bool = False