Skip to content

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

feat(middleware): add file-based long-term memory middleware (#1927)

y1y5615524c68880
diff --git a/docs/NEWS.md b/docs/NEWS.md
index 847a01e4a..33a32f44d 100644
--- a/docs/NEWS.md
+++ b/docs/NEWS.md
@@ -2,6 +2,7 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-06] `FEAT`:** Agentic Memory supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/agentic_memory) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/long-term-memory)
- **[2026-06] `FEAT`:** Distributed & Multi-Tenancy & Multi-Session RAG service supported. [Docs](https://docs.agentscope.io/latest/en/deploy/agent-team)
- **[2026-06] `FEAT`:** RAG supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/rag)
- **[2026-06] `INTE`:** Mem0 supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/latest/en)
diff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.md
index 6b6c6f1bd..83a0ea686 100644
--- a/docs/NEWS_zh.md
+++ b/docs/NEWS_zh.md
@@ -2,6 +2,7 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-06] `功能`:** 支持 Agentic Memory。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/agentic_memory) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/long-term-memory)
- **[2026-06] `功能`:** 支持分布式 & 多租户 & 多会话 RAG 服务。 [文档](https://docs.agentscope.io/latest/en/deploy/agent-team)
- **[2026-06] `功能`:** 支持多模态 RAG。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [文档](https://docs.agentscope.io/latest/en/building-blocks/rag)
- **[2026-06] `集成`:** 集成 Mem0 长期记忆。 [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/latest/zh)
diff --git a/examples/long_term_memory/agentic_memory/README.md b/examples/long_term_memory/agentic_memory/README.md
new file mode 100644
index 000000000..cdf2daf9b
--- /dev/null
+++ b/examples/long_term_memory/agentic_memory/README.md
@@ -0,0 +1,83 @@
+# Agentic Memory Middleware
+
+This example demonstrates `AgenticMemoryMiddleware`, a long-term memory middleware backed by human-readable Markdown files.
+
+No vector database or embedding model is required.
+
+## What the demo shows
+
+`main.py` runs a single Agent against one workspace directory for two turns:
+
+1. **Turn 1 — persist**
+ - Receives mock user input containing durable user information.
+ - Is explicitly asked to remember that information.
+ - Uses the built-in `Read` / `Write` tools to create or update files under `demo_workspace/Memory`.
+
+2. **Turn 2 — recall**
+ - The same Agent instance is asked about the earlier user information.
+ - Answers from the Markdown memory files persisted on disk by the middleware.
+
+After the first turn, the script prints the generated Markdown files so you can inspect exactly what was persisted.
+
+## Quickstart
+
+Install the dependencies by the following commands:
+
+```bash
+git clone -b main https://github.com/agentscope-ai/agentscope
+
+uv pip install agentscope
+# or from source
+# uv pip install -e .
+```
+
+Run the example with the commands:
+
+```bash
+cd agentscope/examples/long_term_memory/agentic_memory
+export DASHSCOPE_API_KEY=sk-...; python main.py
+```
+
+The demo workspace is created at:
+
+```text
+examples/long_term_memory/agentic_memory/demo_workspace/
+```
+
+## Markdown layout
+
+The middleware creates this directory automatically:
+
+```text
+<workdir>/Memory/
+`-- MEMORY.md
+```
+
+The Agent should write each durable memory into its own Markdown file with frontmatter, then add a short pointer to `MEMORY.md`:
+
+```markdown
+---
+name: User profile
+description: User lives in Hangzhou and prefers concise Chinese answers
+type: user
+---
+
+Alice Chen lives in Hangzhou and prefers concise Chinese answers.
+```
+
+`MEMORY.md` is an index, not the memory body:
+
+```markdown
+- [User profile](user_profile.md) — User location and answer-style preference.
+```
+
+On future turns, `MEMORY.md` is always included in the system prompt. The middleware can then select relevant topic files by filename and frontmatter description and inject their contents as a hint.
+
+## Notes
+
+- Memory is workspace-scoped: reuse the same `workdir` to reuse the same Markdown memory.
+- A fresh Agent instance can still recall previous facts because they are stored on disk, not in `Agent.state`.
+- The Agent is responsible for deciding what to save when the user asks it to remember something.
+- `MEMORY.md` should stay concise because it is included in every system prompt.
+- Topic files are ordinary Markdown and can be inspected, edited, committed, copied, or deleted with normal filesystem tools.
+
diff --git a/examples/long_term_memory/agentic_memory/main.py b/examples/long_term_memory/agentic_memory/main.py
new file mode 100644
index 000000000..f16310f37
--- /dev/null
+++ b/examples/long_term_memory/agentic_memory/main.py
@@ -0,0 +1,238 @@
+# -*- coding: utf-8 -*-
+"""AgenticMemoryMiddleware end-to-end demo.
+
+The demo uses a single Agent with the filesystem-backed long-term memory
+middleware and the built-in ``Read`` / ``Write`` tools across two turns:
+
+1. The Agent receives mock user input that explicitly asks it to remember
+ durable user information. The middleware injects memory instructions and the
+ Agent writes Markdown files under ``demo_workspace/Memory``.
+2. The same Agent is then asked to recall the earlier user information. The
+ answer is grounded by the Markdown files persisted on disk by the
+ middleware.
+
+Requires:
+ pip install agentscope
+ export DASHSCOPE_API_KEY=sk-...
+"""
+import asyncio
+import os
+import shutil
+from pathlib import Path
+
+from pydantic import SecretStr
+
+from agentscope.agent import Agent
+from agentscope.credential import DashScopeCredential
+from agentscope.event import (
+ TextBlockDeltaEvent,
+ ToolCallDeltaEvent,
+ ToolCallStartEvent,
+ ToolResultEndEvent,
+ ToolResultTextDeltaEvent,
+)
+from agentscope.message import UserMsg
+from agentscope.middleware import AgenticMemoryMiddleware
+from agentscope.model import DashScopeChatModel
+from agentscope.permission import AdditionalWorkingDirectory, PermissionMode
+from agentscope.tool import Read, Toolkit, Write
+
+
+RESET_DEMO_WORKSPACE = True
+DEMO_ROOT = Path(__file__).with_name("demo_workspace")
+
+FIRST_USER_MESSAGE = """
+Please remember these durable facts for future conversations in this
+workspace:
+
+- My name is Alice Chen.
+- I live in Hangzhou.
+- I prefer concise Chinese answers.
+- When evaluating examples, I like seeing a fresh Agent instance prove that
+ long-term memory was persisted outside the current conversation state.
+
+Use the filesystem memory instructions in your system prompt: create or update
+a topic Markdown memory file with frontmatter, and update MEMORY.md with a
+short pointer to that file. Read MEMORY.md first if you need to update it.
+""".strip()
+
+SECOND_USER_MESSAGE = """
+What do you remember about my name, location, answer style, and how I like
+examples to demonstrate long-term memory? Read the relevant memory files if
+you need details before answering.
+""".strip()
+
+
+def _configure_demo_permissions(agent: Agent, workspace_root: Path) -> None:
+ """Allow the demo Agent to read and write inside the demo workspace.
+
+ Args:
+ agent (`Agent`):
+ The Agent whose permission context should be configured.
+ workspace_root (`Path`):
+ The directory containing the demo memory files.
+ """
+ agent.state.permission_context.mode = PermissionMode.ACCEPT_EDITS
+ agent.state.permission_context.working_directories[
+ str(workspace_root)
+ ] = AdditionalWorkingDirectory(
+ path=str(workspace_root),
+ source="file-system-memory-demo",
+ )
+
+
+def _build_agent(model: DashScopeChatModel, workspace_root: Path) -> Agent:
+ """Build a fresh Agent attached to one filesystem memory workspace.
+
+ Args:
+ model (`DashScopeChatModel`):
+ The chat model used by both the Agent and memory relevance
+ selection.
+ workspace_root (`Path`):
+ The directory that stores ``Memory/MEMORY.md`` and topic files.
+
+ Returns:
+ `Agent`:
+ A newly initialized Agent instance.
+ """
+ memory = AgenticMemoryMiddleware(workdir=str(workspace_root))
+ agent = Agent(
+ name="memory_assistant",
+ system_prompt=(
+ "You are a concise assistant. When the user asks you to remember "
+ "durable preferences or profile facts, persist them using the "
+ "filesystem memory instructions. Use the Read and Write tools for "
+ "memory files."
+ ),
+ model=model,
+ toolkit=Toolkit(tools=[Read(), Write()]),
+ middlewares=[memory],
+ )
+ _configure_demo_permissions(agent, workspace_root)
+ return agent
+
+
+async def _run_turn(agent: Agent, text: str) -> str:
+ """Run one streamed turn and print tool activity.
+
+ Args:
+ agent (`Agent`):
+ The Agent to run.
+ text (`str`):
+ The user message.
+
+ Returns:
+ `str`:
+ The concatenated assistant text response.
+ """
+ tool_names: dict[str, str] = {}
+ tool_args: dict[str, str] = {}
+ tool_results: dict[str, str] = {}
+ reply_parts: list[str] = []
+
+ async for event in agent.reply_stream(UserMsg("alice", text)):
+ if isinstance(event, ToolCallStartEvent):
+ tool_names[event.tool_call_id] = event.tool_call_name
+ tool_args[event.tool_call_id] = ""
+ tool_results[event.tool_call_id] = ""
+ elif isinstance(event, ToolCallDeltaEvent):
+ tool_args[event.tool_call_id] += event.delta
+ elif isinstance(event, ToolResultTextDeltaEvent):
+ tool_results[event.tool_call_id] += event.delta
+ elif isinstance(event, ToolResultEndEvent):
+ tool_id = event.tool_call_id
+ name = tool_names.pop(tool_id, "<unknown>")
+ arguments = tool_args.pop(tool_id, "")
+ result = tool_results.pop(tool_id, "")
+ print(f"[tool] {name}({arguments}) -> {event.state}")
+ for line in result.splitlines():
+ print(f" {line}")
+ elif isinstance(event, TextBlockDeltaEvent):
+ reply_parts.append(event.delta)
+
+ return "".join(reply_parts)
+
+
+def _print_memory_files(workspace_root: Path) -> None:
+ """Print the Markdown files persisted by the memory middleware.
+
+ Args:
+ workspace_root (`Path`):
+ The demo workspace root.
+ """
+ memory_root = workspace_root / "Memory"
+ print(f"\n[Markdown memory files] {memory_root}")
+ if not memory_root.exists():
+ print(" The Memory directory has not been created yet.")
+ return
+
+ for path in sorted(memory_root.rglob("*.md")):
+ relative = path.relative_to(workspace_root)
+ print(f"\n--- {relative} ---")
+ print(path.read_text(encoding="utf-8").strip())
+
+
+def _print_soft_verification(workspace_root: Path) -> None:
+ """Print a lightweight check that expected memory keywords were saved.
+
+ Args:
+ workspace_root (`Path`):
+ The demo workspace root.
+ """
+ memory_root = workspace_root / "Memory"
+ combined = (
+ "\n".join(
+ path.read_text(encoding="utf-8", errors="replace")
+ for path in sorted(memory_root.rglob("*.md"))
+ )
+ if memory_root.exists()
+ else ""
+ )
+ checks = {
+ "MEMORY.md exists": (memory_root / "MEMORY.md").exists(),
+ "mentions Alice Chen": "Alice Chen" in combined,
+ "mentions Hangzhou": "Hangzhou" in combined,
+ "mentions concise Chinese answers": (
+ "concise Chinese" in combined or "Chinese answers" in combined
+ ),
+ }
+
+ print("\n[Soft verification]")
+ for label, ok in checks.items():
+ print(f" {'PASS' if ok else 'WARN'} - {label}")
+
+
+async def main() -> None:
+ """Run the agentic memory demo."""
+ api_key = os.environ["DASHSCOPE_API_KEY"]
+
+ if RESET_DEMO_WORKSPACE:
+ print(f"=== resetting demo workspace: {DEMO_ROOT} ===")
+ shutil.rmtree(DEMO_ROOT, ignore_errors=True)
+ else:
+ print(f"=== reusing demo workspace: {DEMO_ROOT} ===")
+ DEMO_ROOT.mkdir(parents=True, exist_ok=True)
+
+ model = DashScopeChatModel(
+ credential=DashScopeCredential(api_key=SecretStr(api_key)),
+ model="qwen3.7-max",
+ stream=False,
+ )
+
+ print("\n=== Turn 1: ask the Agent to persist user memory ===")
+ agent = _build_agent(model, DEMO_ROOT)
+ print(f"[user]\n{FIRST_USER_MESSAGE}\n")
+ first_reply = await _run_turn(agent, FIRST_USER_MESSAGE)
+ print(f"\n[assistant]\n{first_reply}")
+
+ _print_memory_files(DEMO_ROOT)
+ _print_soft_verification(DEMO_ROOT)
+
+ print("\n=== Turn 2: ask the same Agent to recall memory ===")
+ print(f"[user]\n{SECOND_USER_MESSAGE}\n")
+ second_reply = await _run_turn(agent, SECOND_USER_MESSAGE)
+ print(f"\n[assistant]\n{second_reply}")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/src/agentscope/_utils/_common.py b/src/agentscope/_utils/_common.py
index 6aaac28af..41c585db1 100644
--- a/src/agentscope/_utils/_common.py
+++ b/src/agentscope/_utils/_common.py
@@ -327,3 +327,15 @@ def _flatten_json_schema(schema: dict) -> dict:
return result
return _resolve_ref(schema)
+
+
+def _estimate_tokens(text: str) -> int:
+ """Estimate the number of tokens in a given text."""
+
+ return int(len(text.encode("utf-8")) / 4 + 0.5)
+
+
+def _estimate_bytes(tokens: int) -> int:
+ """Estimate the number of bytes with given tokens."""
+
+ return int(tokens * 4)
diff --git a/src/agentscope/_version.py b/src/agentscope/_version.py
index 5d06d2323..72c989501 100644
--- a/src/agentscope/_version.py
+++ b/src/agentscope/_version.py
@@ -1,4 +1,4 @@
# -*- coding: utf-8 -*-
"""The version of agentscope."""
-__version__ = "2.0.3"
+__version__ = "2.0.4dev"
diff --git a/src/agentscope/middleware/__init__.py b/src/agentscope/middleware/__init__.py
index 57edf90eb..38f888648 100644
--- a/src/agentscope/middleware/__init__.py
+++ b/src/agentscope/middleware/__init__.py
@@ -4,12 +4,13 @@
from ._base import MiddlewareBase
from ._rag import RAGMiddleware
from ._budget import ReplyBudgetControlMiddleware
-from ._longterm_memory import Mem0Middleware
+from ._longterm_memory import AgenticMemoryMiddleware, Mem0Middleware
from ._tracing import TracingMiddleware
from ._tts_middleware import TTSMiddleware
__all__ = [
"MiddlewareBase",
+ "AgenticMemoryMiddleware",
"Mem0Middleware",
"RAGMiddleware",
"TracingMiddleware",
diff --git a/src/agentscope/middleware/_longterm_memory/__init__.py b/src/agentscope/middleware/_longterm_memory/__init__.py
index d7d379e4b..f59668850 100644
--- a/src/agentscope/middleware/_longterm_memory/__init__.py
+++ b/src/agentscope/middleware/_longterm_memory/__init__.py
@@ -1,16 +1,7 @@
# -*- coding: utf-8 -*-
-"""Long-term memory middlewares for AgentScope agents.
-
-Currently only the mem0 backend is implemented. Import the public class
-from the middleware package::
-
- from agentscope.middleware import Mem0Middleware
-
-Future backends (e.g. dedicated vector stores, custom user-profile
-services) can sit alongside ``_mem0/`` under this package and be
-re-exported here.
-"""
+"""Long-term memory middlewares for AgentScope agents."""
+from ._agentic_memory import AgenticMemoryMiddleware
from ._mem0 import Mem0Middleware
-__all__ = ["Mem0Middleware"]
+__all__ = ["AgenticMemoryMiddleware", "Mem0Middleware"]
diff --git a/src/agentscope/middleware/_longterm_memory/_agentic_memory/__init__.py b/src/agentscope/middleware/_longterm_memory/_agentic_memory/__init__.py
new file mode 100644
index 000000000..6c0a8cfd1
--- /dev/null
+++ b/src/agentscope/middleware/_longterm_memory/_agentic_memory/__init__.py
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+"""File-backed long-term memory middleware."""
+
+from ._middleware import AgenticMemoryMiddleware
+
+__all__ = ["AgenticMemoryMiddleware"]
diff --git a/src/agentscope/middleware/_longterm_memory/_agentic_memory/_middleware.py b/src/agentscope/middleware/_longterm_memory/_agentic_memory/_middleware.py
new file mode 100644
index 000000000..255b22b05
--- /dev/null
+++ b/src/agentscope/middleware/_longterm_memory/_agentic_memory/_middleware.py
@@ -0,0 +1,802 @@
+# -*- coding: utf-8 -*-
+"""Filesystem-backed long-term memory middleware.
+
+The middleware keeps a workspace-local Markdown memory store, injects a
+bounded ``MEMORY.md`` index into the system prompt, and can asynchronously
+surface relevant topic files as hint blocks during the reasoning loop.
+"""
+from __future__ import annotations
+
+import asyncio
+import re
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, AsyncGenerator, Callable
+
+from pydantic import BaseModel, Field
+
+from ..._base import MiddlewareBase
+from ...._logging import logger
+from ...._utils._common import _estimate_tokens, _estimate_bytes
+from ....message import Msg, SystemMsg, UserMsg, HintBlock
+from ....model import ChatModelBase
+from ....tool import BackendBase, LocalBackend
+
+if TYPE_CHECKING:
+ from ....agent import Agent
+
+
+@dataclass(slots=True)
+class _MemoryFileHeader:
+ """Lightweight header for one memory file, read from frontmatter only."""
+
+ filename: str
+ """Relative path under the memory directory (e.g. ``user_role.md``)."""
+ path: str
+ """Absolute path inside the backend."""
+ description: str | None
+ """One-line description from frontmatter; ``None`` when absent."""
+ type: str | None
+ """Memory type tag from frontmatter (user/feedback/project/reference)."""
+ mtime: float | None
+ """Modification time as a Unix timestamp; ``None`` when unavailable."""
+
+
+DEFAULT_MEMORY_INSTRUCTIONS = """# Auto Memory
+
+You have a persistent, file-based memory system at `{memory_dir}`. This directory already exists — write to it directly with the `Write` tool (do not run mkdir or check for its existence).
+
+You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.
+
+If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.
+
+## Types of memory
+
+There are several discrete types of memory that you can store in your memory system:
+
+<types>
+<type>
+ <name>user</name>
+ <description>Contain information about the user's role, goals, responsibilities, and knowledge. Great user memories help you tailor your future behavior to the user's preferences and perspective. Your goal in reading and writing these memories is to build up an understanding of who the user is and how you can be most helpful to them specifically. For example, you should collaborate with a senior software engineer differently than a student who is coding for the very first time. Keep in mind, that the aim here is to be helpful to the user. Avoid writing memories about the user that could be viewed as a negative judgement or that are not relevant to the work you're trying to accomplish together.</description>
+ <when_to_save>When you learn any details about the user's role, preferences, responsibilities, or knowledge</when_to_save>
+ <how_to_use>When your work should be informed by the user's profile or perspective. For example, if the user is asking you to explain a part of the code, you should answer that question in a way that is tailored to the specific details that they will find most valuable or that helps them build their mental model in relation to domain knowledge they already have.</how_to_use>
+ <examples>
+ user: I'm a data scientist investigating what logging we have in place
+ assistant: [saves user memory: user is a data scientist, currently focused on observability/logging]
+
+ user: I've been writing Go for ten years but this is my first time touching the React side of this repo
+ assistant: [saves user memory: deep Go expertise, new to React and this project's frontend — frame frontend explanations in terms of backend analogues]
+ </examples>
+</type>
+<type>
+ <name>feedback</name>
+ <description>Guidance the user has given you about how to approach work — both what to avoid and what to keep doing. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious.</description>
+ <when_to_save>Any time the user corrects your approach ("no not that", "don't", "stop doing X") OR confirms a non-obvious approach worked ("yes exactly", "perfect, keep doing that", accepting an unusual choice without pushback). Corrections are easy to notice; confirmations are quieter — watch for them. In both cases, save what is applicable to future conversations, especially if surprising or not obvious from the code. Include *why* so you can judge edge cases later.</when_to_save>
+ <how_to_use>Let these memories guide your behavior so that the user does not need to offer the same guidance twice.</how_to_use>
+ <body_structure>Lead with the rule itself, then a **Why:** line (the reason the user gave — often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule.</body_structure>
+ <examples>
+ user: don't mock the database in these tests — we got burned last quarter when mocked tests passed but the prod migration failed
+ assistant: [saves feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration]
+
+ user: stop summarizing what you just did at the end of every response, I can read the diff
+ assistant: [saves feedback memory: this user wants terse responses with no trailing summaries]
+
+ user: yeah the single bundled PR was the right call here, splitting this one would've just been churn
+ assistant: [saves feedback memory: for refactors in this area, user prefers one bundled PR over many small ones. Confirmed after I chose this approach — a validated judgment call, not a correction]
+ </examples>
+</type>
+<type>
+ <name>project</name>
+ <description>Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work the user is doing within this working directory.</description>
+ <when_to_save>When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., "Thursday" → "2026-03-05"), so the memory remains interpretable after time passes.</when_to_save>
+ <how_to_use>Use these memories to more fully understand the details and nuance behind the user's request and make better informed suggestions.</how_to_use>
+ <body_structure>Lead with the fact or decision, then a **Why:** line (the motivation — often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing.</body_structure>
+ <examples>
+ user: we're freezing all non-critical merges after Thursday — mobile team is cutting a release branch
+ assistant: [saves project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date]
+
+ user: the reason we're ripping out the old auth middleware is that legal flagged it for storing session tokens in a way that doesn't meet the new compliance requirements
+ assistant: [saves project memory: auth middleware rewrite is driven by legal/compliance requirements around session token storage, not tech-debt cleanup — scope decisions should favor compliance over ergonomics]
+ </examples>
+</type>
+<type>
+ <name>reference</name>
+ <description>Stores pointers to where information can be found in external systems. These memories allow you to remember where to look to find up-to-date information outside of the project directory.</description>
+ <when_to_save>When you learn about resources in external systems and their purpose. For example, that bugs are tracked in a specific project in Linear or that feedback can be found in a specific Slack channel.</when_to_save>
+ <how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>
+ <examples>
+ user: check the Linear project "INGEST" if you want context on these tickets, that's where we track all pipeline bugs
+ assistant: [saves reference memory: pipeline bugs are tracked in Linear project "INGEST"]
+
+ user: the Grafana board at grafana.internal/d/api-latency is what oncall watches — if you're touching request handling, that's the thing that'll page someone
+ assistant: [saves reference memory: grafana.internal/d/api-latency is the oncall latency dashboard — check it when editing request-path code]
+ </examples>
+</type>
+</types>
+
+## What NOT to save in memory
+
+- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state.
+- Git history, recent changes, or who-changed-what — `git log` / `git blame` are authoritative.
+- Debugging solutions or fix recipes — the fix is in the code; the commit message has the context.
+- Anything already documented in CLAUDE.md files.
+- Ephemeral task details: in-progress work, temporary state, current conversation context.
+
+These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it — that is the part worth keeping.
+
+## How to save memories
+
+Saving a memory is a two-step process:
+
+**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:
+
+```markdown
+---
+name: {{memory name}}
+description: {{one-line description — used to decide relevance in future conversations, so be specific}}
+type: {{user, feedback, project, reference}}
+---
+
+{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}
+```
+
+**Step 2** — add a pointer to that file in `MEMORY.md`. `MEMORY.md` is an index, not a memory — each entry should be one line, under ~150 characters: - [Title](file.md) — one-line hook. It has no frontmatter. Never write memory content directly into MEMORY.md.
+
+- MEMORY.md is always loaded into your conversation context — lines after 200 will be truncated, so keep the index concise
+- Keep the name, description, and type fields in memory files up-to-date with the content
+- Organize memory semantically by topic, not chronologically
+- Update or remove memories that turn out to be wrong or outdated
+- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.
+
+## When to access memories
+- When memories seem relevant, or the user references prior-conversation work.
+- You MUST access memory when the user explicitly asks you to check, recall, or remember.
+- If the user says to ignore or not use memory: proceed as if MEMORY.md were empty. Do not apply remembered facts, cite, compare against, or mention memory content.
+- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now — and update or remove the stale memory rather than acting on it.
+
+## Before recommending from memory
+
+A memory that names a specific function, file, or flag is a claim that it existed *when the memory was written*. It may have been renamed, removed, or never merged. Before recommending it:
+- If the memory names a file path: check the file exists.
+- If the memory names a function or flag: grep for it.
+- If the user is about to act on your recommendation (not just asking about history), verify first.
+
+"The memory says X exists" is not the same as "X exists now."
+
+A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot.
+
+## Memory and other forms of persistence
+Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.
+- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.
+- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.
+
+## Searching past context
+
+When looking for past context:
+1. Search topic files in your memory directory:
+```
+Grep with pattern="<search>" path="{memory_dir}" glob="*.md"</search>
+# or Bash command:
+grep -rn "<search term>" {memory_dir} --include="*.md"
+```
+Use narrow search terms (error messages, file paths, function names) rather than broad keywords.
+""" # noqa:
+
+DEFAULT_RETRIEVAL_INSTRUCTIONS = (
+ "You are selecting memory files that will be useful as context for "
+ "processing a user's query. You will be given the user's query and a "
+ "list of available memory files with their filenames and descriptions.\n\n"
+ "Return a list of filenames for the memories that will clearly be "
+ "useful (up to 5). Only include memories that you are certain will be "
+ "helpful based on their name and description.\n"
+ "- If you are unsure whether a memory will be useful, do not include "
+ "it. Be selective and discerning.\n"
+ "- If no memories would clearly be useful, return an empty list."
+)
+
+
+class _MemorySelection(BaseModel):
+ """Structured output schema for the memory relevance selector."""
+
+ selected_files: list[str] = Field(
+ description=(
+ "Filenames of the memory files to surface, relative to the "
+ "memory directory (e.g. 'user_role.md'). Up to 5 entries."
+ ),
+ )
+
+
+class AgenticMemoryMiddleware(MiddlewareBase):
+ """The agentic memory, where the LLM decides when and what to save,
+ together with an asyncio retrieval task in each reply. The memory is
+ stored and retrieval based on the Markdown files.
+
+ The `AgenticMemoryMiddleware` supports different backends via the
+ `backend` argument in its constructor.
+ """
+
+ FILENAME_MEMORY_MD: str = "MEMORY.md"
+
+ class Parameters(BaseModel):
+ """The user-tunable filesystem parameters."""
+
+ model_config = {"arbitrary_types_allowed": True}
+
+ memory_max_tokens: int = Field(
+ default=4_000,
+ title="MEMORY.md Max Length",
+ description=(
+ "The maximum tokens of the MEMORY.md inserted into the system "
+ "prompt."
+ ),
+ )
+
+ memory_instructions: str = Field(
+ default=DEFAULT_MEMORY_INSTRUCTIONS,
+ title="Memory Instructions",
+ description=(
+ "The default instructions appended to the system prompt "
+ "before the MEMORY.md snapshots."
+ ),
+ )
+
+ retrieval_async: bool = Field(
+ default=True,
+ title="Async Retrieval",
+ description=(
+ "Whether to retrieve relevant memory files asynchronously "
+ "during the agent reply. If `True`, an async retrieval task "
+ "will be started."
+ ),
+ )
+
+ retrieval_model: ChatModelBase | None = Field(
+ default=None,
+ title="Retrieval Model",
+ description=(
+ "The LLM used to retrieve relevant memory files "
+ "asynchronously during the agent reply. If `None`, the "
+ "agent's model will be used."
+ ),
+ )
+
+ retrieval_max_tokens_per_md: int = Field(
+ default=2_000,
+ title="Retrieval Max Tokens Per File",
+ description=(
+ "Maximum tokens read from each memory file that is surfaced "
+ "by the relevance retrieval step. Keeps individual files from "
+ "flooding the context window."
+ ),
+ )
+
+ retrieval_max_files: int = Field(
+ default=200,
+ title="Retrieval Max Files",
+ description=(
+ "The maximum number of Markdown memory files to consider "
+ "during relevance selection."
+ ),
+ )
+
+ retrieval_max_tokens_per_frontmatter: int = Field(
+ default=256,
+ title="Retrieval Max Tokens per Frontmatter",
+ description=(
+ "The maximum number of tokens to read from the beginning of "
+ "each Markdown file when parsing frontmatter."
+ ),
+ )
+
+ retrieval_instructions: str = Field(
+ default=DEFAULT_RETRIEVAL_INSTRUCTIONS,
+ title="Retrieval Instructions",
+ description=(
+ "The instructions used to select relevant memory files for a "
+ "given user query in the asynchronous retrieval task."
+ ),
+ )
+
+ def __init__(
+ self,
+ *,
+ workdir: str,
+ memory_dir: str = "Memory",
+ parameters: Parameters | None = None,
+ backend: BackendBase | None = None,
+ ) -> None:
+ """Initialize filesystem-backed long-term memory behavior.
+
+ Args:
+ workdir (`str`):
+ The working directory of this agent, used to store the agentic
+ searchable memory files.
+ memory_dir (`str`, defaults to ``"Memory"``):
+ The directory to store the long-term memory files, including
+ ``MEMORY.md``.
+ parameters (`AgenticMemoryMiddleware.Parameters | None`, \
+ defaults to ``None``):
+ User-tunable parameters. When ``None``, defaults are used.
+ backend (`BackendBase | None`, optional):
+ The backend to switch between local and remote storage.
+ When ``None``, a local filesystem is used.
+ """
+ self._workdir = workdir
+ self._memory_dir = memory_dir
+ self._parameters = parameters or self.Parameters()
+ self._backend = backend or LocalBackend()
+
+ self._cached_input: str | None = None
+ # The in-flight asynchronous retrieval task started in ``on_reply``
+ # and consumed in ``on_reasoning``. Kept on the instance so the
+ # reasoning hook can poll for completion across iterations.
+ self._retrieval_task: asyncio.Task | None = None
+
+ @staticmethod
+ def _truncate_if_needed(content: str, max_length: int) -> str:
+ """Return ``content`` truncated to at most ``max_length`` tokens.
+
+ Args:
+ content (`str`):
+ The content to truncate.
+ max_length (`int`):
+ The maximum estimated token count to keep.
+
+ Returns:
+ `str`:
+ The original content when it already fits; otherwise a prefix
+ that fits within the requested token budget.
+ """
+ if max_length <= 0:
+ return ""
+
+ n_tokens = _estimate_tokens(content)
+ if n_tokens <= max_length:
+ return content
+
+ index = int((max_length / n_tokens) * len(content))
+ while index > 0 and _estimate_tokens(content[:index]) > max_length:
+ index = max(0, index - 10)
+
+ return content[:index]
+
+ async def on_system_prompt(
+ self,
+ agent: "Agent",
+ current_prompt: str,
+ ) -> str:
+ """Append memory instructions and a bounded ``MEMORY.md`` snapshot.
+
+ Args:
+ agent (`Agent`):
+ The executing agent. Unused, but part of the middleware
+ contract.
+ current_prompt (`str`):
+ The system prompt produced by previous middleware.
+
+ Returns:
+ `str`:
+ The prompt with filesystem memory instructions appended.
+ """
+ await self._ensure_layout()
+ memory_md_content = await self._get_memory_md_content() or ""
+
+ # Truncated by config
+ memory_md_truncated = self._truncate_if_needed(
+ memory_md_content,
+ self._parameters.memory_max_tokens,
+ )
+
+ if len(memory_md_truncated) != len(memory_md_content):
+ memory_md_path = self._get_memory_md_path()
+ remain_lines = len(memory_md_truncated.split("\n"))
+ omitted_lines = len(memory_md_content.split("\n")) - remain_lines
+ memory_md_truncated += (
+ "\n<<<TRUNCATED>>>\n<system-reminder>The remaining "
+ f"{omitted_lines} lines have been omitted due to context "
+ "length limits. Use the `Read` tool with offset "
+ f"`{remain_lines}` to access the rest of '{memory_md_path}'."
+ f"</system-reminder>"
+ )
+
+ if not memory_md_truncated:
+ memory_md_truncated = (
+ "Your MEMORY.md is currently empty. When you save new "
+ "memories, they will appear here."
+ )
+
+ memory_instructions = self._parameters.memory_instructions.replace(
+ "{memory_dir}",
+ self._get_memory_dir(),
+ )
+ content = (
+ f"{memory_instructions}\n" f"## MEMORY.md\n{memory_md_truncated}"
+ )
+
+ return f"{current_prompt}\n\n{content}"
+
+ async def on_reply(
+ self,
+ agent: "Agent",
+ input_kwargs: dict,
+ next_handler: Callable[..., AsyncGenerator],
+ ) -> AsyncGenerator:
+ """Cache the user input and kick off an asynchronous retrieval task
+ that runs concurrently with the agent reply.
+
+ Args:
+ agent (`Agent`):
+ The executing agent whose model may be used for retrieval.
+ input_kwargs (`dict`):
+ Reply input kwargs forwarded unchanged.
+ next_handler (`Callable[..., AsyncGenerator]`):
+ The downstream middleware or core reply logic.
+
+ Yields:
+ `Any`:
+ Items yielded by ``next_handler``.
+ """
+
+ if self._parameters.retrieval_async:
+ inputs = input_kwargs.get("inputs")
+
+ msgs = None
+ if isinstance(inputs, list) and all(
+ isinstance(_, Msg) for _ in inputs
+ ):
+ msgs = inputs
+ elif isinstance(inputs, Msg):
+ msgs = [inputs]
+
+ if msgs is not None:
+ self._cached_input = "\n".join(
+ [
+ f"{_.name}: " + _.get_text_content()
+ for _ in msgs
+ if _.get_text_content() is not None
+ ],
+ )
+
+ # Start an asynchronous retrieval task that uses an LLM to decide
+ # which memory files are relevant to the current user input. The
+ # result is consumed by ``on_reasoning``.
+ if self._cached_input:
+ self._retrieval_task = asyncio.create_task(
+ self._retrieve_relevant_files(agent, self._cached_input),
+ )
+
+ try:
+ async for _ in next_handler(**input_kwargs):
+ yield _
+ finally:
+ # Ensure the retrieval task does not outlive the reply.
+ if (
+ self._retrieval_task is not None
+ and not self._retrieval_task.done()
+ ):
+ self._retrieval_task.cancel()
+ try:
+ await self._retrieval_task
+ except (asyncio.CancelledError, Exception): # noqa: BLE001
+ pass
+ self._retrieval_task = None
+ self._cached_input = None
+
+ async def on_reasoning(
+ self,
+ agent: "Agent",
+ input_kwargs: dict,
+ next_handler: Callable[..., AsyncGenerator],
+ ) -> AsyncGenerator:
+ """Check if the retrieval finished and if yes, insert a hint block to
+ the content.
+
+ Args:
+ agent (`Agent`):
+ The executing agent whose context may receive a hint block.
+ input_kwargs (`dict`):
+ Reasoning input kwargs forwarded unchanged.
+ next_handler (`Callable[..., AsyncGenerator]`):
+ The downstream middleware or core reasoning logic.
+
+ Yields:
+ `Any`:
+ Items yielded by ``next_handler``.
+ """
+ # Poll the in-flight retrieval task; if it has finished, consume its
+ # result and inject it into the agent context exactly once.
+ if self._retrieval_task is not None and self._retrieval_task.done():
+ task = self._retrieval_task
+ self._retrieval_task = None
+ try:
+ retrieval_result = task.result()
+ except (asyncio.CancelledError, Exception):
+ retrieval_result = None
+
+ if retrieval_result:
+ agent.state.append_context(
+ agent.name,
+ [
+ HintBlock(
+ hint=retrieval_result,
+ ),
+ ],
+ )
+
+ async for event in next_handler(**input_kwargs):
+ yield event
+
+ # ========================================================================
+ # Helper functions
+ # ========================================================================
+
+ @staticmethod
+ def _format_manifest(headers: list[_MemoryFileHeader]) -> str:
+ """Format a list of memory file headers into a one-line-per-file
+ manifest string suitable for the selector prompt.
+
+ Args:
+ headers (`list[_MemoryFileHeader]`):
+ The memory file headers to format.
+
+ Returns:
+ `str`:
+ The formatted manifest.
+ """
+ lines = []
+ for h in headers:
+ tag = f"[{h.type}] " if h.type else ""
+ if h.mtime is not None:
+ from datetime import datetime
+
+ ts = datetime.fromtimestamp(h.mtime).strftime("%Y-%m-%d")
+ else:
+ ts = "unknown"
+ desc = f": {h.description}" if h.description else ""
+ lines.append(f"- {tag}{h.filename} ({ts}){desc}")
+ return "\n".join(lines)
+
+ async def _retrieve_relevant_files(
+ self,
+ agent: "Agent",
+ query: str,
+ ) -> str | None:
+ """Use an LLM to identify memory files relevant to ``query`` and
+ return their content as an injectable string.
+
+ Args:
+ agent (`Agent`):
+ The agent whose model / memory store should be consulted.
+ query (`str`):
+ The cached user input used as the retrieval query.
+
+ Returns:
+ `str | None`:
+ The formatted retrieval result ready to be injected into the
+ context, or ``None`` when nothing relevant was found.
+ """
+ await self._ensure_layout()
+
+ # 1. Scan available memory files (frontmatter only, cheap).
+ headers = await self._list_md_files()
+ if not headers:
+ return None
+
+ valid_filenames = {h.filename for h in headers}
+ manifest = self._format_manifest(headers)
+
+ # 2. Ask the model to select relevant files.
+ model = self._parameters.retrieval_model or agent.model
+ res = await model.generate_structured_output(
+ [
+ SystemMsg(
+ name="system",
+ content=self._parameters.retrieval_instructions,
+ ),
+ UserMsg(
+ name="user",
+ content=(
+ f"Query: {query}\n\n"
+ f"Available memories:\n{manifest}"
+ ),
+ ),
+ ],
+ structured_model=_MemorySelection,
+ )
+
+ # 3. Validate: discard hallucinated filenames.
+ raw_selected: list[str] = res.content.get("selected_files", [])
+ selected = [f for f in raw_selected if f in valid_filenames][:5]
+ if not selected:
+ return None
+
+ # 4. Read each selected file and format as an injectable string.
+ # Cap each file to avoid flooding the context window.
+ header_by_filename = {h.filename: h for h in headers}
+ parts: list[str] = []
+ for filename in selected:
+ h = header_by_filename[filename]
+ try:
+ content = (await self._backend.read_file(h.path)).decode(
+ "utf-8",
+ errors="replace",
+ )
+ except Exception:
+ continue
+
+ # Truncate large files to avoid flooding the context window.
+ content = self._truncate_if_needed(
+ content,
+ self._parameters.retrieval_max_tokens_per_md,
+ )
+ if h.mtime is not None:
+ import time
+
+ days = max(0, int((time.time() - h.mtime) / 86_400))
+ if days == 0:
+ age = "today"
+ elif days == 1:
+ age = "yesterday"
+ else:
+ age = f"{days} days ago"
+ header = f"Memory (saved {age}): {h.path}:"
+ else:
+ header = f"Memory: {h.path}:"
+
+ parts.append(f"{header}\n\n{content}")
+
+ if not parts:
+ return None
+
+ return "\n\n---\n\n".join(parts)
+
+ async def _ensure_layout(self) -> None:
+ """Create the memory directory and initial files idempotently.
+
+ Existing human-edited documents are never replaced. The index file is
+ created only when absent so manual edits survive restarts. The memory
+ directory itself is materialized as a side effect of writing
+ ``MEMORY.md`` — :meth:`BackendBase.write_file` creates parent
+ directories — which avoids a platform-specific ``mkdir -p`` shell
+ invocation that is not portable on Windows.
+ """
+ if not await self._backend.file_exists(self._get_memory_md_path()):
+ logger.info(
+ "Creating 'MEMORY.md' file in '%s'",
+ self._workdir,
+ )
+ await self._backend.write_file(
+ self._get_memory_md_path(),
+ b"",
+ )
+
+ def _get_memory_dir(self) -> str:
+ """Get the memory directory.
+
+ Returns:
+ `str`:
+ The backend path of the memory directory.
+ """
+ return self._backend.join_path(self._workdir, self._memory_dir)
+
+ def _get_memory_md_path(self) -> str:
+ """Get the ``MEMORY.md`` path.
+
+ Returns:
+ `str`:
+ The backend path of the ``MEMORY.md`` index file.
+ """
+ return self._backend.join_path(
+ self._get_memory_dir(),
+ self.FILENAME_MEMORY_MD,
+ )
+
+ async def _get_memory_md_content(self) -> str | None:
+ """Get the content of the ``MEMORY.md`` file.
+
+ Returns:
+ `str | None`:
+ The decoded index file content, or ``None`` when the file does
+ not exist.
+ """
+ if not await self._backend.file_exists(self._get_memory_md_path()):
+ return None
+
+ return (
+ await self._backend.read_file(self._get_memory_md_path())
+ ).decode(
+ "utf-8",
+ errors="replace",
+ )
+
+ _FRONTMATTER_RE = re.compile(
+ r"^\s*---\s*\n(?P<body>.*?)\n---\s*\n",
+ re.DOTALL,
+ )
+ _FIELD_RE = re.compile(r"^(?P<key>\w+)\s*:\s*(?P<value>.+)$", re.MULTILINE)
+
+ @classmethod
+ def _parse_frontmatter_fields(cls, content: str) -> dict[str, str]:
+ """Return a dict of YAML-like key/value pairs from the first
+ frontmatter block. Only scalar ``key: value`` lines are parsed;
+ nested structures are intentionally ignored.
+
+ Args:
+ content (`str`):
+ The Markdown content prefix to inspect.
+
+ Returns:
+ `dict[str, str]`:
+ Parsed frontmatter fields, or an empty dict when no leading
+ frontmatter block is present.
+ """
+ m = cls._FRONTMATTER_RE.match(content)
+ if not m:
+ return {}
+ return {
+ fm.group("key"): fm.group("value").strip()
+ for fm in cls._FIELD_RE.finditer(m.group("body"))
+ }
+
+ async def _list_md_files(self) -> list[_MemoryFileHeader]:
+ """Scan the memory directory for individual memory files.
+
+ Returns:
+ `list[_MemoryFileHeader]`:
+ Memory file headers sorted newest-first and capped by
+ ``retrieval_max_files``. The system index file
+ (``MEMORY.md``) is excluded so only topic files are returned.
+ """
+ memory_dir = self._get_memory_dir()
+ system_files = {self.FILENAME_MEMORY_MD}
+
+ try:
+ all_entries = await self._backend.list_dir(
+ memory_dir,
+ recursive=True,
+ )
+ except Exception:
+ return []
+
+ headers: list[_MemoryFileHeader] = []
+ memory_dir_norm = self._backend.normpath(memory_dir)
+ memory_dir_prefix = self._backend.join_path(memory_dir_norm, "")
+ for entry in all_entries:
+ entry_path = self._backend.normpath(entry)
+ if self._backend.isabs(entry_path):
+ if not entry_path.startswith(memory_dir_prefix):
+ continue
+ filename = entry_path[len(memory_dir_prefix) :]
+ full_path = entry_path
+ else:
+ filename = entry_path
+ full_path = self._backend.join_path(memory_dir, filename)
+
+ if not filename.endswith(".md") or filename in system_files:
+ continue
+
+ try:
+ raw = await self._backend.read_file(full_path)
+ # Only parse the leading bytes to keep this cheap.
+ max_frontmatter_bytes = _estimate_bytes(
+ self._parameters.retrieval_max_tokens_per_frontmatter,
+ )
+ snippet = raw[:max_frontmatter_bytes].decode(
+ "utf-8",
+ errors="replace",
+ )
+ fields = self._parse_frontmatter_fields(snippet)
+ mtime = await self._backend.stat_mtime(full_path)
+ headers.append(
+ _MemoryFileHeader(
+ filename=filename,
+ path=full_path,
+ description=fields.get("description") or None,
+ type=fields.get("type") or None,
+ mtime=mtime,
+ ),
+ )
+ except Exception:
+ continue
+
+ headers.sort(key=lambda h: h.mtime or 0.0, reverse=True)
+ return headers[: self._parameters.retrieval_max_files]
diff --git a/src/agentscope/permission/_engine.py b/src/agentscope/permission/_engine.py
index 5f31c1f9c..8487ae65f 100644
--- a/src/agentscope/permission/_engine.py
+++ b/src/agentscope/permission/_engine.py
@@ -6,6 +6,7 @@ from ._context import PermissionContext
from ._rule import PermissionRule
from ._decision import PermissionDecision, PermissionBehavior
from ._types import PermissionMode
+from .._utils._common import _execute_async_or_sync_func
if TYPE_CHECKING:
from ..tool import ToolBase
@@ -146,14 +147,17 @@ class PermissionEngine:
The final decision.
"""
# step 1: deny rules — highest priority
- deny = self._check_deny_rules(tool, tool_input)
+ deny = await self._check_deny_rules(tool, tool_input)
if deny:
return deny
# step 2: ask rules
- ask = self._check_ask_rules(tool, tool_input)
+ ask = await self._check_ask_rules(tool, tool_input)
if ask:
- ask.suggested_rules = self._generate_suggestions(tool, tool_input)
+ ask.suggested_rules = await self._generate_suggestions(
+ tool,
+ tool_input,
+ )
return ask
# step 3: tool's own check_permissions
@@ -166,14 +170,14 @@ class PermissionEngine:
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_decision.suggested_rules = await self._generate_suggestions(
tool,
tool_input,
)
return tool_decision
# step 4: allow rules
- allow = self._check_allow_rules(tool, tool_input)
+ allow = await self._check_allow_rules(tool, tool_input)
if allow:
return allow
@@ -183,7 +187,10 @@ class PermissionEngine:
message=f"Permission required for {tool.name}",
decision_reason=f"Mode: {self.context.mode.value}",
)
- default.suggested_rules = self._generate_suggestions(tool, tool_input)
+ default.suggested_rules = await self._generate_suggestions(
+ tool,
+ tool_input,
+ )
return default
async def _check_explore(
@@ -219,14 +226,17 @@ class PermissionEngine:
ALLOW for read-only invocations, DENY otherwise.
"""
# step 1: deny rules
- deny = self._check_deny_rules(tool, tool_input)
+ deny = await self._check_deny_rules(tool, tool_input)
if deny:
return deny
# step 2: ask rules
- ask = self._check_ask_rules(tool, tool_input)
+ ask = await self._check_ask_rules(tool, tool_input)
if ask:
- ask.suggested_rules = self._generate_suggestions(tool, tool_input)
+ ask.suggested_rules = await self._generate_suggestions(
+ tool,
+ tool_input,
+ )
return ask
# step 3: read-only verdict decides everything (ALLOW or DENY)
@@ -281,14 +291,17 @@ class PermissionEngine:
The final decision.
"""
# step 1: deny rules
- deny = self._check_deny_rules(tool, tool_input)
+ deny = await self._check_deny_rules(tool, tool_input)
if deny:
return deny
# step 2: ask rules
- ask = self._check_ask_rules(tool, tool_input)
+ ask = await self._check_ask_rules(tool, tool_input)
if ask:
- ask.suggested_rules = self._generate_suggestions(tool, tool_input)
+ ask.suggested_rules = await self._generate_suggestions(
+ tool,
+ tool_input,
+ )
return ask
# step 3: read-only fast path — ALLOW without invoking the tool
@@ -314,14 +327,14 @@ class PermissionEngine:
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_decision.suggested_rules = await self._generate_suggestions(
tool,
tool_input,
)
return tool_decision
# step 5: allow rules
- allow = self._check_allow_rules(tool, tool_input)
+ allow = await self._check_allow_rules(tool, tool_input)
if allow:
return allow
@@ -331,7 +344,10 @@ class PermissionEngine:
message=f"Permission required for {tool.name}",
decision_reason=f"Mode: {self.context.mode.value}",
)
- default.suggested_rules = self._generate_suggestions(tool, tool_input)
+ default.suggested_rules = await self._generate_suggestions(
+ tool,
+ tool_input,
+ )
return default
async def _check_bypass(
@@ -377,14 +393,17 @@ class PermissionEngine:
The final decision.
"""
# step 1: deny rules
- deny = self._check_deny_rules(tool, tool_input)
+ deny = await 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)
+ ask = await self._check_ask_rules(tool, tool_input)
if ask:
- ask.suggested_rules = self._generate_suggestions(tool, tool_input)
+ ask.suggested_rules = await self._generate_suggestions(
+ tool,
+ tool_input,
+ )
return ask
# step 3: tool's own check_permissions — ALLOW / DENY returned;
@@ -398,7 +417,7 @@ class PermissionEngine:
return tool_decision
# step 4: allow rules
- allow = self._check_allow_rules(tool, tool_input)
+ allow = await self._check_allow_rules(tool, tool_input)
if allow:
return allow
@@ -442,14 +461,17 @@ class PermissionEngine:
The final decision (never ASK).
"""
# step 1: deny rules
- deny = self._check_deny_rules(tool, tool_input)
+ deny = await 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)
+ ask = await self._check_ask_rules(tool, tool_input)
if ask:
- ask.suggested_rules = self._generate_suggestions(tool, tool_input)
+ ask.suggested_rules = await self._generate_suggestions(
+ tool,
+ tool_input,
+ )
return self._convert_ask_to_deny(tool, ask)
# step 3: tool's own check_permissions
@@ -462,14 +484,14 @@ class PermissionEngine:
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_decision.suggested_rules = await 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)
+ allow = await self._check_allow_rules(tool, tool_input)
if allow:
return allow
@@ -550,7 +572,7 @@ class PermissionEngine:
and decision.bypass_immune
)
- def _check_deny_rules(
+ async def _check_deny_rules(
self,
tool: ToolBase,
input_data: dict[str, Any],
@@ -569,7 +591,7 @@ class PermissionEngine:
"""
rules = self.context.deny_rules.get(tool.name, [])
for rule in rules:
- if self._rule_matches(tool, rule, input_data):
+ if await self._rule_matches(tool, rule, input_data):
return PermissionDecision(
behavior=PermissionBehavior.DENY,
message=f"Permission to use {tool.name} has been denied",
@@ -577,7 +599,7 @@ class PermissionEngine:
)
return None
- def _check_ask_rules(
+ async def _check_ask_rules(
self,
tool: ToolBase,
input_data: dict[str, Any],
@@ -596,7 +618,7 @@ class PermissionEngine:
"""
rules = self.context.ask_rules.get(tool.name, [])
for rule in rules:
- if self._rule_matches(tool, rule, input_data):
+ if await self._rule_matches(tool, rule, input_data):
return PermissionDecision(
behavior=PermissionBehavior.ASK,
message=f"Permission required for {tool.name}",
@@ -604,7 +626,7 @@ class PermissionEngine:
)
return None
- def _check_allow_rules(
+ async def _check_allow_rules(
self,
tool: ToolBase,
input_data: dict[str, Any],
@@ -623,7 +645,7 @@ class PermissionEngine:
"""
rules = self.context.allow_rules.get(tool.name, [])
for rule in rules:
- if self._rule_matches(tool, rule, input_data):
+ if await self._rule_matches(tool, rule, input_data):
return PermissionDecision(
behavior=PermissionBehavior.ALLOW,
message=f"Permission granted for {tool.name}",
@@ -631,7 +653,7 @@ class PermissionEngine:
)
return None
- def _rule_matches(
+ async def _rule_matches(
self,
tool: ToolBase,
rule: PermissionRule,
@@ -658,10 +680,17 @@ class PermissionEngine:
if not rule.rule_content:
return True
- # Try to use tool's match_rule method if available
- return tool.match_rule(rule.rule_content, input_data)
+ # Try to use tool's match_rule method if available.
+ # ``_execute_async_or_sync_func`` keeps backward compatibility
+ # with third-party tools that still override match_rule with a
+ # sync ``def`` (the framework's signature is now ``async def``).
+ return await _execute_async_or_sync_func(
+ tool.match_rule,
+ rule.rule_content,
+ input_data,
+ )
- def _generate_suggestions(
+ async def _generate_suggestions(
self,
tool: ToolBase,
tool_input: dict[str, Any],
@@ -690,5 +719,11 @@ class PermissionEngine:
compound commands)
"""
- # Try to use tool's generate_suggestions method if available
- return tool.generate_suggestions(tool_input)
+ # Try to use tool's generate_suggestions method if available.
+ # ``_execute_async_or_sync_func`` keeps backward compatibility
+ # with third-party tools that still override this method with
+ # a sync ``def`` (the framework's signature is now ``async def``).
+ return await _execute_async_or_sync_func(
+ tool.generate_suggestions,
+ tool_input,
+ )
diff --git a/src/agentscope/tool/_base.py b/src/agentscope/tool/_base.py
index 93a80f304..33cc11ba5 100644
--- a/src/agentscope/tool/_base.py
+++ b/src/agentscope/tool/_base.py
@@ -279,7 +279,7 @@ class ToolBase(ABC):
"""
return self.is_read_only
- def match_rule(
+ async def match_rule(
self,
rule_content: str | None,
tool_input: dict[str, Any],
@@ -312,7 +312,7 @@ class ToolBase(ABC):
# None rule_content = tool-name-level rule, matches everything
return rule_content is None
- def generate_suggestions(
+ async def generate_suggestions(
self,
tool_input: dict[str, Any],
) -> List[PermissionRule]:
diff --git a/src/agentscope/tool/_builtin/_backend.py b/src/agentscope/tool/_builtin/_backend.py
index f291b85c5..fbac19dfd 100644
--- a/src/agentscope/tool/_builtin/_backend.py
+++ b/src/agentscope/tool/_builtin/_backend.py
@@ -36,10 +36,12 @@ from __future__ import annotations
import asyncio
import os
+import posixpath
import shlex
import shutil
from abc import ABC, abstractmethod
from dataclasses import dataclass
+from types import ModuleType
from typing import Any
import aiofiles
@@ -110,6 +112,125 @@ class BackendBase(ABC):
cheaper native path may override them (see :class:`LocalBackend`).
"""
+ #: Path-manipulation module whose semantics match the backend's
+ #: environment. Used by :meth:`join_path`, :meth:`dirname`,
+ #: :meth:`isabs`, :meth:`normpath`, and :meth:`abspath` to ensure
+ #: correct behavior when the host OS and the backend OS differ
+ #: (e.g. a Windows host driving a Linux Docker container).
+ #:
+ #: Defaults to :mod:`posixpath`, which is correct for any backend
+ #: whose environment is Linux/macOS (Docker, E2B, …). Subclasses
+ #: targeting a different environment override this attribute, e.g.
+ #: :class:`LocalBackend` sets it to :mod:`os.path`, and a future
+ #: Windows-container backend would set it to :mod:`ntpath`.
+ #:
+ #: .. important::
+ #:
+ #: Only **pure string operations** on this module are safe to
+ #: call (``join``, ``split``, ``dirname``, ``basename``,
+ #: ``normpath``, ``isabs``, ``splitext``, ``splitdrive``, …).
+ #:
+ #: Do **not** call functions that touch the filesystem or
+ #: environment variables — ``exists``, ``isfile``, ``isdir``,
+ #: ``getmtime``, ``realpath``, ``expanduser``, ``expandvars``,
+ #: and parameterless ``abspath`` — because those read the
+ #: **host** process's filesystem / ``$HOME`` / ``cwd``, which
+ #: is meaningless (and a silent bug) for remote backends. Use
+ #: the async I/O methods on the backend instead
+ #: (:meth:`file_exists`, :meth:`is_dir`, :meth:`stat_mtime`,
+ #: …) or the :meth:`abspath` wrapper below, which requires an
+ #: explicit ``cwd`` argument.
+ _path_module: ModuleType = posixpath
+
+ # ── path manipulation helpers (pure string ops) ────────────────
+
+ def join_path(self, path: str, *paths: str) -> str:
+ """Join one or more path components using the backend's separator.
+
+ Args:
+ path (`str`):
+ The first path component.
+ *paths (`str`):
+ Additional components to join onto ``path``.
+
+ Returns:
+ `str`:
+ The joined path, using the backend environment's path
+ separator.
+ """
+ return self._path_module.join(path, *paths)
+
+ def dirname(self, path: str) -> str:
+ """Return the directory component of ``path``.
+
+ Args:
+ path (`str`):
+ A path inside the backend's environment.
+
+ Returns:
+ `str`:
+ Everything up to (but not including) the last path
+ separator. Empty string if ``path`` has no separator.
+ """
+ return self._path_module.dirname(path)
+
+ def isabs(self, path: str) -> bool:
+ """Return ``True`` if ``path`` is absolute in the backend.
+
+ Args:
+ path (`str`):
+ A path inside the backend's environment.
+
+ Returns:
+ `bool`:
+ ``True`` iff ``path`` is absolute under the backend
+ environment's path semantics.
+ """
+ return self._path_module.isabs(path)
+
+ def normpath(self, path: str) -> str:
+ """Normalize ``path`` (collapse ``..``, ``.``, duplicate seps).
+
+ Pure string operation — does not touch the filesystem.
+
+ Args:
+ path (`str`):
+ A path inside the backend's environment.
+
+ Returns:
+ `str`:
+ The normalized path.
+ """
+ return self._path_module.normpath(path)
+
+ def abspath(self, path: str, *, cwd: str) -> str:
+ """Return an absolute, normalized version of ``path``.
+
+ Unlike :func:`os.path.abspath`, this helper **never** reads
+ the host process's working directory: when ``path`` is
+ relative it is joined with the explicitly supplied ``cwd``,
+ which must itself be a path that is meaningful inside the
+ backend's environment. This avoids the silent bug where the
+ host's ``os.getcwd()`` leaks into paths that will actually be
+ used on a remote backend.
+
+ Args:
+ path (`str`):
+ A path inside the backend's environment.
+ cwd (`str`):
+ Directory to resolve a relative ``path`` against.
+ Ignored when ``path`` is already absolute.
+
+ Returns:
+ `str`:
+ An absolute, normalized path.
+ """
+ if self._path_module.isabs(path):
+ return self._path_module.normpath(path)
+ return self._path_module.normpath(
+ self._path_module.join(cwd, path),
+ )
+
# ── abstract primitives ────────────────────────────────────────
@abstractmethod
@@ -175,6 +296,64 @@ class BackendBase(ABC):
# ── derived filesystem ops (shell-based defaults) ──────────────
+ async def getcwd(self) -> str:
+ """Return the backend environment's current working directory.
+
+ This is the directory that bare ``exec_shell`` invocations
+ (those with ``cwd=None``) execute in. Tools should call this
+ — instead of :func:`os.getcwd` — whenever they need a default
+ path that is meaningful inside the backend, because the host
+ process's cwd is meaningless for remote backends
+ (Docker / E2B).
+
+ The default implementation runs ``pwd`` via :meth:`exec_shell`,
+ which works for any POSIX-like backend. Backends with cheaper
+ native access (e.g. :class:`LocalBackend`, or remote backends
+ that already track their workdir) should override it.
+
+ Returns:
+ `str`:
+ The backend's current working directory.
+ """
+ result = await self.exec_shell(["pwd"])
+ return result.stdout.decode("utf-8", errors="replace").strip()
+
+ async def expanduser(self, path: str) -> str:
+ """Expand a leading ``~`` / ``~/`` to the backend's home directory.
+
+ Tools should call this — instead of :func:`os.path.expanduser`
+ — whenever they need to expand ``~`` in a path that lives
+ inside the backend's environment, because the host process's
+ ``$HOME`` is meaningless for remote backends.
+
+ The default implementation queries ``$HOME`` via
+ :meth:`exec_shell` (POSIX-only). Only the leading ``~`` /
+ ``~/foo`` form is expanded; ``~user/...`` is not supported by
+ the default and is returned unchanged. Backends with cheaper
+ native access should override (e.g. :class:`LocalBackend`).
+
+ Args:
+ path (`str`):
+ A path inside the backend's environment, possibly
+ starting with ``~``.
+
+ Returns:
+ `str`:
+ ``path`` with a leading ``~`` / ``~/`` expanded. If
+ ``path`` does not start with ``~``, or starts with
+ ``~user`` (unsupported), it is returned unchanged.
+ """
+ if not path or path[0] != "~":
+ return path
+ # ``~user/...`` form — not supported by the default impl.
+ if len(path) > 1 and path[1] not in ("/", self._path_module.sep):
+ return path
+ result = await self.exec_shell(["printenv", "HOME"])
+ home = result.stdout.decode("utf-8", errors="replace").strip()
+ if not home:
+ return path
+ return home + path[1:]
+
async def file_exists(self, path: str) -> bool:
"""Return ``True`` if ``path`` exists (file or directory).
@@ -339,6 +518,11 @@ class LocalBackend(BackendBase):
unavailable.
"""
+ # Use the host OS's path semantics (Windows or POSIX) instead of
+ # the base class default (``posixpath``), so path helpers behave
+ # correctly when running on a Windows host.
+ _path_module = os.path
+
async def exec_shell(
self,
command: list[str],
@@ -436,6 +620,29 @@ class LocalBackend(BackendBase):
async with aiofiles.open(path, mode="wb") as f:
await f.write(data)
+ async def getcwd(self) -> str:
+ """Return the host process's current working directory.
+
+ Returns:
+ `str`:
+ ``os.getcwd()`` — avoids spawning a ``pwd`` subprocess.
+ """
+ return os.getcwd()
+
+ async def expanduser(self, path: str) -> str:
+ """Expand ``~`` using the host process's ``$HOME``.
+
+ Args:
+ path (`str`):
+ A local path, possibly starting with ``~``.
+
+ Returns:
+ `str`:
+ ``os.path.expanduser(path)`` — avoids spawning a
+ subprocess.
+ """
+ return os.path.expanduser(path)
+
async def file_exists(self, path: str) -> bool:
"""Check if a local path exists.
diff --git a/src/agentscope/tool/_builtin/_bash.py b/src/agentscope/tool/_builtin/_bash.py
index 8e04dfed0..58952f6fc 100644
--- a/src/agentscope/tool/_builtin/_bash.py
+++ b/src/agentscope/tool/_builtin/_bash.py
@@ -311,7 +311,7 @@ easier to review tool calls and give permission.
# Checked separately from step 4 because these paths are not in the
# dangerous_files/directories lists — they are system-level paths
# that should never be removed regardless of user configuration.
- removal_path = self._check_dangerous_removal_path(command)
+ removal_path = await self._check_dangerous_removal_path(command)
if removal_path:
return PermissionDecision(
behavior=PermissionBehavior.ASK,
@@ -382,7 +382,7 @@ easier to review tool calls and give permission.
message=f"Execute bash command: {command}",
)
- def match_rule(
+ async def match_rule(
self,
rule_content: str | None,
tool_input: dict[str, Any],
@@ -479,7 +479,7 @@ easier to review tool calls and give permission.
# Invalid regex, fall back to substring matching
return rule_content.replace("*", "") in command
- def generate_suggestions(
+ async def generate_suggestions(
self,
tool_input: dict[str, Any],
) -> List["PermissionRule"]:
@@ -554,8 +554,8 @@ easier to review tool calls and give permission.
return dangerous_paths
- def _check_dangerous_removal_path(self, command: str) -> str | None:
- """Check if an rm/rmdir command targets a critical system path.
+ async def _check_dangerous_removal_path(self, command: str) -> str | None:
+ """Check if a rm/rmdir command targets a critical system path.
Detects commands like `rm -rf /`, `rm -rf /usr`, `rmdir ~` that
would destroy critical system directories. Unlike _is_dangerous_path
@@ -609,16 +609,20 @@ easier to review tool calls and give permission.
i += 1
continue
path = tok.strip("'\"")
- if self._is_dangerous_removal_path(path):
+ if await self._is_dangerous_removal_path(path):
return path
i += 1
return None
- def _is_dangerous_removal_path(self, path: str) -> bool:
+ async def _is_dangerous_removal_path(self, path: str) -> bool:
"""Check if a path is a critical system directory that must not be
removed.
+ All path resolution is performed via the backend so that the
+ check operates on the **backend environment's** ``$HOME`` /
+ ``cwd`` / path semantics, not the host process's.
+
Args:
path (`str`):
The path to check (may be relative, absolute, or contain ~)
@@ -635,24 +639,30 @@ easier to review tool calls and give permission.
if path.endswith("/*") or path.endswith("\\*"):
return True
- # Expand tilde and resolve to absolute path
- expanded = os.path.expanduser(path)
- # Don't resolve symlinks — /tmp is a symlink on macOS but is
- # still a root-child and should be flagged
- abs_path = os.path.normpath(os.path.abspath(expanded))
+ # Expand tilde and resolve to an absolute path inside the
+ # backend environment. Don't resolve symlinks — ``/tmp`` is a
+ # symlink on macOS but is still a root-child and should be
+ # flagged.
+ expanded = await self._backend.expanduser(path)
+ backend_cwd = await self._backend.getcwd()
+ abs_path = self._backend.abspath(expanded, cwd=backend_cwd)
# Home directory
- home = os.path.expanduser("~")
+ home = await self._backend.expanduser("~")
if abs_path == home:
return True
- # Root itself
- if abs_path == "/":
+ # Root itself: ``dirname(root) == root`` on both POSIX
+ # (``"/"``) and Windows (``"C:\\"``), so this check is
+ # path-flavor agnostic.
+ parent = self._backend.dirname(abs_path)
+ if abs_path == parent:
return True
- # Direct children of root: /usr, /etc, /tmp, /var, /bin, etc.
- parent = os.path.dirname(abs_path)
- if parent == "/":
+ # Direct children of root (e.g. ``/usr``, ``/etc``, ``/tmp``):
+ # the *parent* of these is the root, where
+ # ``dirname(parent) == parent``.
+ if self._backend.dirname(parent) == parent:
return True
return False
diff --git a/src/agentscope/tool/_builtin/_edit.py b/src/agentscope/tool/_builtin/_edit.py
index f57f12f98..962b68078 100644
--- a/src/agentscope/tool/_builtin/_edit.py
+++ b/src/agentscope/tool/_builtin/_edit.py
@@ -2,7 +2,6 @@
"""The edit tool in agentscope."""
import difflib
import fnmatch
-import os
from typing import Any, List
from .._base import ToolBase, ToolMiddlewareBase
@@ -179,7 +178,7 @@ Usage:
message="",
)
- def match_rule(
+ async def match_rule(
self,
rule_content: str | None,
tool_input: dict[str, Any],
@@ -209,7 +208,7 @@ Usage:
return False
return fnmatch.fnmatch(file_path, rule_content)
- def generate_suggestions(
+ async def generate_suggestions(
self,
tool_input: dict[str, Any],
) -> List[PermissionRule]:
@@ -231,8 +230,10 @@ Usage:
if not file_path:
return []
- parent = os.path.dirname(file_path)
- pattern = (parent.rstrip("/") + "/**") if parent else "**"
+ parent = self._backend.dirname(file_path)
+ # Glob patterns are POSIX-style strings (matched by fnmatch),
+ # not real filesystem paths — do NOT use backend.join_path here.
+ pattern = (parent.rstrip("/\\") + "/**") if parent else "**"
return [
PermissionRule(
@@ -253,7 +254,7 @@ Usage:
) -> ToolChunk:
"""Execute the edit and return the result."""
# Validate file_path is absolute
- if not os.path.isabs(file_path):
+ if not self._backend.isabs(file_path):
return ToolChunk(
content=[
TextBlock(
diff --git a/src/agentscope/tool/_builtin/_glob.py b/src/agentscope/tool/_builtin/_glob.py
index 563c56374..f5261c195 100644
--- a/src/agentscope/tool/_builtin/_glob.py
+++ b/src/agentscope/tool/_builtin/_glob.py
@@ -5,7 +5,6 @@ from __future__ import annotations
import fnmatch
import json
-import os
import sys
from typing import TYPE_CHECKING, Any, List
@@ -130,7 +129,7 @@ codebase.""" # ignore: E501
message="Glob pattern matching is read-only.",
)
- def match_rule(
+ async def match_rule(
self,
rule_content: str | None,
tool_input: dict[str, Any],
@@ -169,7 +168,7 @@ codebase.""" # ignore: E501
return False
- def generate_suggestions(
+ async def generate_suggestions(
self,
tool_input: dict[str, Any],
) -> List[PermissionRule]:
@@ -186,13 +185,14 @@ codebase.""" # ignore: E501
`List[PermissionRule]`:
A single suggested rule covering the search directory
"""
- path = tool_input.get("path", "")
- if not path:
- path = os.getcwd()
+ backend_cwd = await self._backend.getcwd()
+ path = tool_input.get("path") or backend_cwd
- # Normalize path and create pattern
- abs_path = os.path.abspath(path)
- pattern = abs_path.rstrip("/") + "/**"
+ # Normalize path and build a glob pattern. Glob patterns are
+ # POSIX-style strings (matched by fnmatch), not real filesystem
+ # paths — do NOT use backend.join_path here.
+ abs_path = self._backend.abspath(path, cwd=backend_cwd)
+ pattern = abs_path.rstrip("/\\") + "/**"
return [
PermissionRule(
@@ -232,7 +232,7 @@ codebase.""" # ignore: E501
is missing or the helper fails, an error chunk with
``ToolResultState.ERROR``.
"""
- base_dir = path if path else os.getcwd()
+ base_dir = path if path else await self._backend.getcwd()
# The base must be an existing directory; a regular file would
# otherwise be accepted here and fail later with a confusing
diff --git a/src/agentscope/tool/_builtin/_grep.py b/src/agentscope/tool/_builtin/_grep.py
index a7f31eadd..e0c798790 100644
--- a/src/agentscope/tool/_builtin/_grep.py
+++ b/src/agentscope/tool/_builtin/_grep.py
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
"""The grep tool in agentscope."""
import fnmatch
-import os
from typing import Any, List, Literal
from .._base import ToolBase, ToolMiddlewareBase
@@ -190,7 +189,7 @@ class Grep(ToolBase):
message="Grep search is read-only.",
)
- def match_rule(
+ async def match_rule(
self,
rule_content: str | None,
tool_input: dict[str, Any],
@@ -220,10 +219,10 @@ class Grep(ToolBase):
path = tool_input.get("path", "")
if not path:
- path = os.getcwd()
+ path = await self._backend.getcwd()
return fnmatch.fnmatch(path, rule_content)
- def generate_suggestions(
+ async def generate_suggestions(
self,
tool_input: dict[str, Any],
) -> List[PermissionRule]:
@@ -240,12 +239,13 @@ class Grep(ToolBase):
`List[PermissionRule]`:
A single suggested rule covering the search directory
"""
- path = tool_input.get("path", "")
- if not path:
- path = os.getcwd()
+ backend_cwd = await self._backend.getcwd()
+ path = tool_input.get("path") or backend_cwd
- abs_path = os.path.abspath(path)
- pattern = abs_path.rstrip("/") + "/**"
+ abs_path = self._backend.abspath(path, cwd=backend_cwd)
+ # Glob patterns are POSIX-style strings (matched by fnmatch),
+ # not real filesystem paths — do NOT use backend.join_path here.
+ pattern = abs_path.rstrip("/\\") + "/**"
return [
PermissionRule(
@@ -355,7 +355,7 @@ class Grep(ToolBase):
n: Show line numbers (content mode only, default True)
**kwargs: Additional parameters (-A, -B, -C)
"""
- search_path = path or os.getcwd()
+ search_path = path or await self._backend.getcwd()
if head_limit is not None and head_limit < 0:
return ToolChunk(
diff --git a/src/agentscope/tool/_builtin/_read.py b/src/agentscope/tool/_builtin/_read.py
index b45e2e6c7..9d18006fb 100644
--- a/src/agentscope/tool/_builtin/_read.py
+++ b/src/agentscope/tool/_builtin/_read.py
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
"""The read tool in agentscope."""
import fnmatch
-import os
from typing import Any, List
from .._base import ToolBase, ToolMiddlewareBase
@@ -111,7 +110,7 @@ Usage:
message="File reading is read-only.",
)
- def match_rule(
+ async def match_rule(
self,
rule_content: str | None,
tool_input: dict[str, Any],
@@ -142,7 +141,7 @@ Usage:
return False
return fnmatch.fnmatch(file_path, rule_content)
- def generate_suggestions(
+ async def generate_suggestions(
self,
tool_input: dict[str, Any],
) -> List[PermissionRule]:
@@ -164,8 +163,10 @@ Usage:
if not file_path:
return []
- parent = os.path.dirname(file_path)
- pattern = (parent.rstrip("/") + "/**") if parent else "**"
+ parent = self._backend.dirname(file_path)
+ # Glob patterns are POSIX-style strings (matched by fnmatch),
+ # not real filesystem paths — do NOT use backend.join_path here.
+ pattern = (parent.rstrip("/\\") + "/**") if parent else "**"
return [
PermissionRule(
@@ -186,7 +187,7 @@ Usage:
"""Read the file and return the content with line numbers."""
# Validate file_path is absolute
- if not os.path.isabs(file_path):
+ if not self._backend.isabs(file_path):
return ToolChunk(
content=[
TextBlock(
diff --git a/src/agentscope/tool/_builtin/_write.py b/src/agentscope/tool/_builtin/_write.py
index 7215c4b5a..a4fdd11ba 100644
--- a/src/agentscope/tool/_builtin/_write.py
+++ b/src/agentscope/tool/_builtin/_write.py
@@ -2,7 +2,6 @@
"""The write tool in agentscope."""
import difflib
import fnmatch
-import os
from pathlib import Path
from typing import Any, List
@@ -158,7 +157,7 @@ Usage:
message="",
)
- def match_rule(
+ async def match_rule(
self,
rule_content: str | None,
tool_input: dict[str, Any],
@@ -188,7 +187,7 @@ Usage:
return False
return fnmatch.fnmatch(file_path, rule_content)
- def generate_suggestions(
+ async def generate_suggestions(
self,
tool_input: dict[str, Any],
) -> List[PermissionRule]:
@@ -210,8 +209,10 @@ Usage:
if not file_path:
return []
- parent = os.path.dirname(file_path)
- pattern = (parent.rstrip("/") + "/**") if parent else "**"
+ parent = self._backend.dirname(file_path)
+ # Glob patterns are POSIX-style strings (matched by fnmatch),
+ # not real filesystem paths — do NOT use backend.join_path here.
+ pattern = (parent.rstrip("/\\") + "/**") if parent else "**"
return [
PermissionRule(
@@ -230,7 +231,7 @@ Usage:
) -> ToolChunk:
"""Write content to a file and return the result."""
# Validate that file_path is absolute
- if not os.path.isabs(file_path):
+ if not self._backend.isabs(file_path):
return ToolChunk(
content=[
TextBlock(
diff --git a/src/agentscope/workspace/_base.py b/src/agentscope/workspace/_base.py
index 828197a33..b82fa46f1 100644
--- a/src/agentscope/workspace/_base.py
+++ b/src/agentscope/workspace/_base.py
@@ -21,6 +21,7 @@ Consumers:
- **User** — dynamically adds/removes MCPs and skills via
``add_mcp``, ``remove_mcp``, ``add_skill``, ``remove_skill``.
- **Developer** — manages lifecycle via ``initialize`` / ``close``.
+- **Backend consumers** access the active backend via ``get_backend``.
"""
from abc import abstractmethod
@@ -30,7 +31,7 @@ from .._utils._common import _generate_id
from ..mcp import MCPClient
from ..message import Msg, ToolResultBlock
from ..skill import Skill
-from ..tool import ToolBase
+from ..tool import BackendBase, ToolBase
class WorkspaceBase:
@@ -58,6 +59,9 @@ class WorkspaceBase:
is_alive: bool
"""If the workspace is still operational."""
+ _backend: BackendBase | None
+ """Current execution backend, available through :meth:`get_backend`."""
+
def __init__(self, workspace_id: str | None) -> None:
"""Initialize the workspace base instance."""
self.workspace_id = workspace_id or _generate_id()
@@ -86,6 +90,26 @@ class WorkspaceBase:
state must override this.
"""
+ def get_backend(self) -> BackendBase:
+ """Return the workspace's active filesystem/execution backend.
+
+ Docker and E2B workspaces may replace their backend when reconnecting,
+ so callers should resolve it from the workspace when beginning an
+ operation rather than retaining a stale private ``_backend`` value.
+
+ Raises:
+ RuntimeError:
+ If the workspace has not been initialized or has no active
+ backend.
+ """
+ backend = getattr(self, "_backend", None)
+ if not isinstance(backend, BackendBase):
+ raise RuntimeError(
+ f"{type(self).__name__} has no active backend. "
+ "Initialize the workspace before requesting its backend.",
+ )
+ return backend
+
async def __aenter__(self) -> Self:
"""Context manager support for ``async with``. Calls ``initialize()``
and returns the workspace instance.
diff --git a/src/agentscope/workspace/_docker/_docker_backend.py b/src/agentscope/workspace/_docker/_docker_backend.py
index 8b2afa4f6..7989f9d74 100644
--- a/src/agentscope/workspace/_docker/_docker_backend.py
+++ b/src/agentscope/workspace/_docker/_docker_backend.py
@@ -52,6 +52,19 @@ class DockerBackend(BackendBase):
# ── exec ───────────────────────────────────────────────────────
+ async def getcwd(self) -> str:
+ """Return the container's default working directory.
+
+ Overrides the base class default (which would shell out to
+ ``pwd``) with the cached ``workdir`` supplied at construction,
+ avoiding a per-call container ``exec`` round-trip.
+
+ Returns:
+ `str`:
+ The container's default working directory.
+ """
+ return self._workdir
+
async def exec_shell(
self,
command: list[str],
diff --git a/src/agentscope/workspace/_e2b/_e2b_backend.py b/src/agentscope/workspace/_e2b/_e2b_backend.py
index 0794507db..509c408c8 100644
--- a/src/agentscope/workspace/_e2b/_e2b_backend.py
+++ b/src/agentscope/workspace/_e2b/_e2b_backend.py
@@ -50,6 +50,19 @@ class E2BBackend(BackendBase):
# ── exec ───────────────────────────────────────────────────────
+ async def getcwd(self) -> str:
+ """Return the sandbox's default working directory.
+
+ Overrides the base class default (which would shell out to
+ ``pwd``) with the cached ``workdir`` supplied at construction,
+ avoiding a per-call sandbox round-trip.
+
+ Returns:
+ `str`:
+ The sandbox's default working directory.
+ """
+ return self._workdir
+
async def exec_shell(
self,
command: list[str],
diff --git a/tests/builtin_bash_test.py b/tests/builtin_bash_test.py
index 659436230..d78bc0956 100644
--- a/tests/builtin_bash_test.py
+++ b/tests/builtin_bash_test.py
@@ -261,7 +261,7 @@ class BashToolMatchRuleTest(IsolatedAsyncioTestCase):
"""Test match_rule with prefix patterns (e.g., git:*)."""
# Test exact command match
self.assertTrue(
- self.bash_tool.match_rule(
+ await self.bash_tool.match_rule(
"git:*",
{"command": "git"},
),
@@ -269,7 +269,7 @@ class BashToolMatchRuleTest(IsolatedAsyncioTestCase):
# Test command with arguments
self.assertTrue(
- self.bash_tool.match_rule(
+ await self.bash_tool.match_rule(
"git:*",
{"command": "git status"},
),
@@ -277,7 +277,7 @@ class BashToolMatchRuleTest(IsolatedAsyncioTestCase):
# Test non-matching command
self.assertFalse(
- self.bash_tool.match_rule(
+ await self.bash_tool.match_rule(
"git:*",
{"command": "npm install"},
),
@@ -287,7 +287,7 @@ class BashToolMatchRuleTest(IsolatedAsyncioTestCase):
"""Test match_rule with wildcard patterns."""
# Test wildcard matching
self.assertTrue(
- self.bash_tool.match_rule(
+ await self.bash_tool.match_rule(
"git * -m *",
{"command": "git commit -m 'test'"},
),
@@ -295,7 +295,7 @@ class BashToolMatchRuleTest(IsolatedAsyncioTestCase):
# Test non-matching wildcard
self.assertFalse(
- self.bash_tool.match_rule(
+ await self.bash_tool.match_rule(
"git * -m *",
{"command": "git status"},
),
@@ -305,7 +305,7 @@ class BashToolMatchRuleTest(IsolatedAsyncioTestCase):
"""Test match_rule with substring patterns."""
# Test substring matching
self.assertTrue(
- self.bash_tool.match_rule(
+ await self.bash_tool.match_rule(
"install",
{"command": "npm install package"},
),
@@ -313,7 +313,7 @@ class BashToolMatchRuleTest(IsolatedAsyncioTestCase):
# Test non-matching substring
self.assertFalse(
- self.bash_tool.match_rule(
+ await self.bash_tool.match_rule(
"install",
{"command": "npm run build"},
),
@@ -323,7 +323,7 @@ class BashToolMatchRuleTest(IsolatedAsyncioTestCase):
"""Test match_rule with escaped characters."""
# Test escaped asterisk
self.assertTrue(
- self.bash_tool.match_rule(
+ await self.bash_tool.match_rule(
r"echo \*",
{"command": "echo *"},
),
@@ -331,7 +331,7 @@ class BashToolMatchRuleTest(IsolatedAsyncioTestCase):
# Test escaped backslash
self.assertTrue(
- self.bash_tool.match_rule(
+ await self.bash_tool.match_rule(
r"echo \\",
{"command": "echo \\"},
),
@@ -341,7 +341,7 @@ class BashToolMatchRuleTest(IsolatedAsyncioTestCase):
"""Test generate_suggestions for bash commands."""
# Test two-word command
- suggestions = self.bash_tool.generate_suggestions(
+ suggestions = await self.bash_tool.generate_suggestions(
{"command": "git commit -m 'test'"},
)
@@ -355,7 +355,7 @@ class BashToolMatchRuleTest(IsolatedAsyncioTestCase):
async def test_generate_suggestions_single_word(self) -> None:
"""Test generate_suggestions for single-word commands."""
- suggestions = self.bash_tool.generate_suggestions(
+ suggestions = await self.bash_tool.generate_suggestions(
{"command": "npm install"},
)
diff --git a/tests/builtin_edit_test.py b/tests/builtin_edit_test.py
index b342d1e6e..9d4bbec22 100644
--- a/tests/builtin_edit_test.py
+++ b/tests/builtin_edit_test.py
@@ -121,7 +121,7 @@ class EditToolTest(IsolatedAsyncioTestCase):
"""Test match_rule with glob patterns."""
# Test exact match
self.assertTrue(
- self.edit_tool.match_rule(
+ await self.edit_tool.match_rule(
"test.py",
{"file_path": "test.py"},
),
@@ -129,7 +129,7 @@ class EditToolTest(IsolatedAsyncioTestCase):
# Test wildcard pattern
self.assertTrue(
- self.edit_tool.match_rule(
+ await self.edit_tool.match_rule(
"*.py",
{"file_path": "test.py"},
),
@@ -137,7 +137,7 @@ class EditToolTest(IsolatedAsyncioTestCase):
# Test directory pattern
self.assertTrue(
- self.edit_tool.match_rule(
+ await self.edit_tool.match_rule(
"/tmp/**",
{"file_path": "/tmp/test.py"},
),
@@ -145,7 +145,7 @@ class EditToolTest(IsolatedAsyncioTestCase):
# Test non-matching pattern
self.assertFalse(
- self.edit_tool.match_rule(
+ await self.edit_tool.match_rule(
"*.txt",
{"file_path": "test.py"},
),
@@ -153,7 +153,7 @@ class EditToolTest(IsolatedAsyncioTestCase):
# Test empty file_path
self.assertFalse(
- self.edit_tool.match_rule(
+ await self.edit_tool.match_rule(
"*.py",
{"file_path": ""},
),
@@ -163,7 +163,7 @@ class EditToolTest(IsolatedAsyncioTestCase):
"""Test generate_suggestions for file operations."""
# Test suggestion for file in subdirectory
- suggestions = self.edit_tool.generate_suggestions(
+ suggestions = await self.edit_tool.generate_suggestions(
{"file_path": "/tmp/project/src/main.py"},
)
@@ -176,7 +176,7 @@ class EditToolTest(IsolatedAsyncioTestCase):
self.assertIn("/tmp/project/src/**", suggestion_contents)
# Test suggestion for file in root
- suggestions = self.edit_tool.generate_suggestions(
+ suggestions = await self.edit_tool.generate_suggestions(
{"file_path": "/test.py"},
)
self.assertGreater(len(suggestions), 0)
diff --git a/tests/builtin_glob_test.py b/tests/builtin_glob_test.py
index 24da9ae5a..22d2c034c 100644
--- a/tests/builtin_glob_test.py
+++ b/tests/builtin_glob_test.py
@@ -144,7 +144,7 @@ class GlobToolTest(IsolatedAsyncioTestCase):
"""Test match_rule with path patterns."""
# Test matching explicit path
self.assertTrue(
- self.glob_tool.match_rule(
+ await self.glob_tool.match_rule(
self.temp_dir,
{"path": self.temp_dir, "pattern": "*.py"},
),
@@ -153,7 +153,7 @@ class GlobToolTest(IsolatedAsyncioTestCase):
# Test wildcard pattern matching path
parent_dir = os.path.dirname(self.temp_dir)
self.assertTrue(
- self.glob_tool.match_rule(
+ await self.glob_tool.match_rule(
parent_dir + "/**",
{"path": self.temp_dir, "pattern": "*.py"},
),
@@ -161,7 +161,7 @@ class GlobToolTest(IsolatedAsyncioTestCase):
# Test non-matching path
self.assertFalse(
- self.glob_tool.match_rule(
+ await self.glob_tool.match_rule(
"/some/other/path/**",
{"path": self.temp_dir, "pattern": "*.py"},
),
@@ -171,7 +171,7 @@ class GlobToolTest(IsolatedAsyncioTestCase):
"""Test match_rule with pattern matching."""
# Test matching against the pattern itself
self.assertTrue(
- self.glob_tool.match_rule(
+ await self.glob_tool.match_rule(
"*.py",
{"pattern": "*.py"},
),
@@ -179,7 +179,7 @@ class GlobToolTest(IsolatedAsyncioTestCase):
# Test wildcard pattern matching
self.assertTrue(
- self.glob_tool.match_rule(
+ await self.glob_tool.match_rule(
"**/*.py",
{"pattern": "src/**/*.py"},
),
@@ -187,7 +187,7 @@ class GlobToolTest(IsolatedAsyncioTestCase):
# Test non-matching pattern
self.assertFalse(
- self.glob_tool.match_rule(
+ await self.glob_tool.match_rule(
"*.txt",
{"pattern": "*.py"},
),
@@ -197,7 +197,7 @@ class GlobToolTest(IsolatedAsyncioTestCase):
"""Test that path matching takes priority over pattern matching."""
# If path matches, should return True even if pattern doesn't
self.assertTrue(
- self.glob_tool.match_rule(
+ await self.glob_tool.match_rule(
self.temp_dir,
{"path": self.temp_dir, "pattern": "*.txt"},
),
@@ -206,7 +206,7 @@ class GlobToolTest(IsolatedAsyncioTestCase):
async def test_generate_suggestions_with_path(self) -> None:
"""Test generate_suggestions for glob with explicit path."""
- suggestions = self.glob_tool.generate_suggestions(
+ suggestions = await self.glob_tool.generate_suggestions(
{"path": self.temp_dir, "pattern": "*.py"},
)
@@ -223,7 +223,7 @@ class GlobToolTest(IsolatedAsyncioTestCase):
async def test_generate_suggestions_defaults_to_cwd(self) -> None:
"""Test generate_suggestions defaults to cwd when no path provided."""
- suggestions = self.glob_tool.generate_suggestions(
+ suggestions = await self.glob_tool.generate_suggestions(
{"pattern": "*.py"},
)
diff --git a/tests/builtin_grep_test.py b/tests/builtin_grep_test.py
index a790c6c8e..17593f145 100644
--- a/tests/builtin_grep_test.py
+++ b/tests/builtin_grep_test.py
@@ -178,7 +178,7 @@ class GrepToolTest(IsolatedAsyncioTestCase):
"""Test match_rule with search path patterns."""
# Test matching explicit path
self.assertTrue(
- self.grep_tool.match_rule(
+ await self.grep_tool.match_rule(
self.temp_dir,
{"path": self.temp_dir},
),
@@ -187,7 +187,7 @@ class GrepToolTest(IsolatedAsyncioTestCase):
# Test wildcard pattern matching path
parent_dir = os.path.dirname(self.temp_dir)
self.assertTrue(
- self.grep_tool.match_rule(
+ await self.grep_tool.match_rule(
parent_dir + "/**",
{"path": self.temp_dir},
),
@@ -195,7 +195,7 @@ class GrepToolTest(IsolatedAsyncioTestCase):
# Test non-matching path
self.assertFalse(
- self.grep_tool.match_rule(
+ await self.grep_tool.match_rule(
"/some/other/path/**",
{"path": self.temp_dir},
),
@@ -207,7 +207,7 @@ class GrepToolTest(IsolatedAsyncioTestCase):
# When no path provided, should match against cwd
self.assertTrue(
- self.grep_tool.match_rule(
+ await self.grep_tool.match_rule(
cwd,
{"pattern": "hello"},
),
@@ -215,7 +215,7 @@ class GrepToolTest(IsolatedAsyncioTestCase):
# Should not match a different path
self.assertFalse(
- self.grep_tool.match_rule(
+ await self.grep_tool.match_rule(
"/some/other/path",
{"pattern": "hello"},
),
@@ -224,7 +224,7 @@ class GrepToolTest(IsolatedAsyncioTestCase):
async def test_generate_suggestions_with_path(self) -> None:
"""Test generate_suggestions for grep with explicit path."""
- suggestions = self.grep_tool.generate_suggestions(
+ suggestions = await self.grep_tool.generate_suggestions(
{"path": self.temp_dir, "pattern": "hello"},
)
@@ -241,7 +241,7 @@ class GrepToolTest(IsolatedAsyncioTestCase):
async def test_generate_suggestions_defaults_to_cwd(self) -> None:
"""Test generate_suggestions defaults to cwd when no path provided."""
- suggestions = self.grep_tool.generate_suggestions(
+ suggestions = await self.grep_tool.generate_suggestions(
{"pattern": "hello"},
)
diff --git a/tests/builtin_read_test.py b/tests/builtin_read_test.py
index 9c1d623d6..ad82659ea 100644
--- a/tests/builtin_read_test.py
+++ b/tests/builtin_read_test.py
@@ -127,7 +127,7 @@ class ReadToolTest(IsolatedAsyncioTestCase):
"""Test match_rule with glob patterns."""
# Test exact match
self.assertTrue(
- self.read_tool.match_rule(
+ await self.read_tool.match_rule(
"test.py",
{"file_path": "test.py"},
),
@@ -135,7 +135,7 @@ class ReadToolTest(IsolatedAsyncioTestCase):
# Test wildcard pattern
self.assertTrue(
- self.read_tool.match_rule(
+ await self.read_tool.match_rule(
"*.py",
{"file_path": "test.py"},
),
@@ -143,7 +143,7 @@ class ReadToolTest(IsolatedAsyncioTestCase):
# Test directory pattern
self.assertTrue(
- self.read_tool.match_rule(
+ await self.read_tool.match_rule(
"/tmp/**",
{"file_path": "/tmp/test.py"},
),
@@ -151,7 +151,7 @@ class ReadToolTest(IsolatedAsyncioTestCase):
# Test non-matching pattern
self.assertFalse(
- self.read_tool.match_rule(
+ await self.read_tool.match_rule(
"*.txt",
{"file_path": "test.py"},
),
@@ -159,7 +159,7 @@ class ReadToolTest(IsolatedAsyncioTestCase):
# Test empty file_path
self.assertFalse(
- self.read_tool.match_rule(
+ await self.read_tool.match_rule(
"*.py",
{"file_path": ""},
),
@@ -169,7 +169,7 @@ class ReadToolTest(IsolatedAsyncioTestCase):
"""Test generate_suggestions for file operations."""
# Test suggestion for file in subdirectory
- suggestions = self.read_tool.generate_suggestions(
+ suggestions = await self.read_tool.generate_suggestions(
{"file_path": "/tmp/project/src/main.py"},
)
@@ -182,7 +182,7 @@ class ReadToolTest(IsolatedAsyncioTestCase):
self.assertIn("/tmp/project/src/**", suggestion_contents)
# Test suggestion for file in root
- suggestions = self.read_tool.generate_suggestions(
+ suggestions = await self.read_tool.generate_suggestions(
{"file_path": "/test.py"},
)
self.assertGreater(len(suggestions), 0)
diff --git a/tests/builtin_write_test.py b/tests/builtin_write_test.py
index e23570364..29b77447c 100644
--- a/tests/builtin_write_test.py
+++ b/tests/builtin_write_test.py
@@ -151,7 +151,7 @@ class WriteToolTest(IsolatedAsyncioTestCase):
"""Test match_rule with glob patterns."""
# Test exact match
self.assertTrue(
- self.write_tool.match_rule(
+ await self.write_tool.match_rule(
"test.py",
{"file_path": "test.py"},
),
@@ -159,7 +159,7 @@ class WriteToolTest(IsolatedAsyncioTestCase):
# Test wildcard pattern
self.assertTrue(
- self.write_tool.match_rule(
+ await self.write_tool.match_rule(
"*.py",
{"file_path": "test.py"},
),
@@ -167,7 +167,7 @@ class WriteToolTest(IsolatedAsyncioTestCase):
# Test directory pattern
self.assertTrue(
- self.write_tool.match_rule(
+ await self.write_tool.match_rule(
"/tmp/**",
{"file_path": "/tmp/test.py"},
),
@@ -175,7 +175,7 @@ class WriteToolTest(IsolatedAsyncioTestCase):
# Test non-matching pattern
self.assertFalse(
- self.write_tool.match_rule(
+ await self.write_tool.match_rule(
"*.txt",
{"file_path": "test.py"},
),
@@ -183,7 +183,7 @@ class WriteToolTest(IsolatedAsyncioTestCase):
# Test empty file_path
self.assertFalse(
- self.write_tool.match_rule(
+ await self.write_tool.match_rule(
"*.py",
{"file_path": ""},
),
@@ -193,7 +193,7 @@ class WriteToolTest(IsolatedAsyncioTestCase):
"""Test generate_suggestions for file operations."""
# Test suggestion for file in subdirectory
- suggestions = self.write_tool.generate_suggestions(
+ suggestions = await self.write_tool.generate_suggestions(
{"file_path": "/tmp/project/src/main.py"},
)
@@ -206,7 +206,7 @@ class WriteToolTest(IsolatedAsyncioTestCase):
self.assertIn("/tmp/project/src/**", suggestion_contents)
# Test suggestion for file in root
- suggestions = self.write_tool.generate_suggestions(
+ suggestions = await self.write_tool.generate_suggestions(
{"file_path": "/test.py"},
)
self.assertGreater(len(suggestions), 0)
diff --git a/tests/middleware_filesystem_memory_test.py b/tests/middleware_filesystem_memory_test.py
new file mode 100644
index 000000000..826638c7b
--- /dev/null
+++ b/tests/middleware_filesystem_memory_test.py
@@ -0,0 +1,772 @@
+# -*- coding: utf-8 -*-
+"""Unit tests for AgenticMemoryMiddleware with real Agent execution."""
+import os
+import shutil
+import tempfile
+from typing import Any, Type
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from pydantic import BaseModel
+from utils import AnyString, AnyValue, MockModel
+
+from agentscope.agent import Agent
+from agentscope.message import (
+ HintBlock,
+ Msg,
+ TextBlock,
+ ToolCallBlock,
+ UserMsg,
+)
+from agentscope.middleware import AgenticMemoryMiddleware
+from agentscope.model import ChatResponse, StructuredResponse
+from agentscope.permission import (
+ PermissionBehavior,
+ PermissionContext,
+ PermissionDecision,
+)
+from agentscope.tool import ToolBase, ToolChunk, Toolkit
+
+
+class _RecordingMockModel(MockModel):
+ """A ``MockModel`` that records chat and structured-output calls."""
+
+ def __init__(self, **kwargs: Any) -> None:
+ """Initialize the recording mock model.
+
+ Args:
+ **kwargs (`Any`):
+ Keyword arguments forwarded to :class:`MockModel`.
+ """
+ kwargs.setdefault("context_size", 100_000)
+ super().__init__(**kwargs)
+ self.chat_messages: list[list[Msg]] = []
+ self.structured_messages: list[list[Msg]] = []
+
+ async def _call_api(
+ self,
+ *args: Any,
+ **kwargs: Any,
+ ) -> ChatResponse:
+ """Record the chat messages and delegate to ``MockModel``.
+
+ Args:
+ *args (`Any`):
+ Positional arguments forwarded to ``MockModel``.
+ **kwargs (`Any`):
+ Keyword arguments forwarded to ``MockModel``.
+
+ Returns:
+ `ChatResponse`:
+ The configured mock chat response.
+ """
+ self.chat_messages.append(kwargs["messages"])
+ return await super()._call_api(*args, **kwargs)
+
+ async def _call_api_with_structured_output(
+ self,
+ model_name: str,
+ messages: list[Msg],
+ structured_model: Type[BaseModel] | dict,
+ **kwargs: Any,
+ ) -> StructuredResponse:
+ """Record structured-output messages and delegate to ``MockModel``.
+
+ Args:
+ model_name (`str`):
+ The model name.
+ messages (`list[Msg]`):
+ The structured-output prompt messages.
+ structured_model (`Type[BaseModel] | dict`):
+ The expected structured-output schema.
+ **kwargs (`Any`):
+ Extra keyword arguments forwarded to ``MockModel``.
+
+ Returns:
+ `StructuredResponse`:
+ The configured mock structured response.
+ """
+ self.structured_messages.append(messages)
+ return await super()._call_api_with_structured_output(
+ model_name,
+ messages,
+ structured_model,
+ **kwargs,
+ )
+
+
+class _DummyTool(ToolBase):
+ """A minimal tool that forces a second Agent reasoning iteration."""
+
+ name: str = "dummy"
+ description: str = "A dummy tool for middleware tests."
+ input_schema: dict[str, Any] = {"type": "object", "properties": {}}
+ is_concurrency_safe: bool = True
+ is_read_only: bool = True
+ is_external_tool: bool = False
+ is_mcp: bool = False
+
+ async def check_permissions(
+ self,
+ tool_input: dict[str, Any],
+ context: PermissionContext,
+ ) -> PermissionDecision:
+ """Allow every dummy tool call.
+
+ Args:
+ tool_input (`dict[str, Any]`):
+ The tool input.
+ context (`PermissionContext`):
+ The permission context.
+
+ Returns:
+ `PermissionDecision`:
+ The allow decision.
+ """
+ return PermissionDecision(
+ behavior=PermissionBehavior.ALLOW,
+ decision_reason="Dummy tool always allows.",
+ message="Dummy tool always allows.",
+ )
+
+ async def __call__(self, **kwargs: Any) -> ToolChunk:
+ """Return a fixed tool result.
+
+ Args:
+ **kwargs (`Any`):
+ Ignored tool arguments.
+
+ Returns:
+ `ToolChunk`:
+ The fixed tool output.
+ """
+ return ToolChunk(content=[TextBlock(text="tool result")])
+
+
+def _text_response(text: str) -> ChatResponse:
+ """Build a text-only chat response.
+
+ Args:
+ text (`str`):
+ The response text.
+
+ Returns:
+ `ChatResponse`:
+ A complete chat response with one text block.
+ """
+ return ChatResponse(content=[TextBlock(text=text)], is_last=True)
+
+
+def _tool_response() -> ChatResponse:
+ """Build a chat response that calls the dummy tool.
+
+ Returns:
+ `ChatResponse`:
+ A complete chat response with one tool call block.
+ """
+ return ChatResponse(
+ content=[
+ ToolCallBlock(
+ id="call_dummy",
+ name="dummy",
+ input="{}",
+ ),
+ ],
+ is_last=True,
+ )
+
+
+def _structured_response(selected_files: list[str]) -> StructuredResponse:
+ """Build a structured memory-selection response.
+
+ Args:
+ selected_files (`list[str]`):
+ The selected memory filenames.
+
+ Returns:
+ `StructuredResponse`:
+ The structured response consumed by the middleware.
+ """
+ return StructuredResponse(content={"selected_files": selected_files})
+
+
+def _block_to_dict(block: Any) -> dict:
+ """Convert a message block into a stable assertion dictionary.
+
+ Args:
+ block (`Any`):
+ The message block to convert.
+
+ Returns:
+ `dict`:
+ The stable block representation.
+ """
+ if isinstance(block, TextBlock):
+ return {
+ "type": "text",
+ "text": block.text,
+ "id": AnyString(),
+ }
+ if isinstance(block, HintBlock):
+ return {
+ "type": "hint",
+ "hint": block.hint,
+ "id": AnyString(),
+ "source": block.source,
+ }
+ if isinstance(block, ToolCallBlock):
+ return {
+ "type": "tool_call",
+ "id": AnyString(),
+ "name": block.name,
+ "input": block.input,
+ "state": block.state,
+ "suggested_rules": block.suggested_rules,
+ }
+ return block.model_dump()
+
+
+def _message_to_dict(msg: Msg) -> dict:
+ """Convert a message into a stable assertion dictionary.
+
+ Args:
+ msg (`Msg`):
+ The message to convert.
+
+ Returns:
+ `dict`:
+ The stable message representation.
+ """
+ return {
+ "id": AnyString(),
+ "name": msg.name,
+ "role": msg.role,
+ "content": [_block_to_dict(block) for block in msg.content],
+ "metadata": msg.metadata,
+ }
+
+
+def _hint_texts(agent: Agent) -> list[str]:
+ """Collect hint texts from an agent context.
+
+ Args:
+ agent (`Agent`):
+ The agent whose context is inspected.
+
+ Returns:
+ `list[str]`:
+ The hint texts in context order.
+ """
+ return [
+ block.hint
+ for msg in agent.state.context
+ for block in msg.content
+ if isinstance(block, HintBlock)
+ ]
+
+
+def _write_memory_file(
+ memory_dir: str,
+ filename: str,
+ description: str,
+ memory_type: str,
+ body: str,
+) -> None:
+ """Write one Markdown memory file with frontmatter.
+
+ Args:
+ memory_dir (`str`):
+ The memory directory.
+ filename (`str`):
+ The memory filename relative to ``memory_dir``.
+ description (`str`):
+ The frontmatter description.
+ memory_type (`str`):
+ The frontmatter memory type.
+ body (`str`):
+ The Markdown body.
+ """
+ path = os.path.join(memory_dir, filename)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(
+ "---\n"
+ f"name: {filename}\n"
+ f"description: {description}\n"
+ f"type: {memory_type}\n"
+ "---\n\n"
+ f"{body}\n",
+ )
+
+
+class AgenticMemoryMiddlewareTest(IsolatedAsyncioTestCase):
+ """Agent-level tests for :class:`AgenticMemoryMiddleware`."""
+
+ async def asyncSetUp(self) -> None:
+ """Create a temporary workspace for each test."""
+ self.temp_dir = tempfile.mkdtemp()
+
+ async def asyncTearDown(self) -> None:
+ """Remove the temporary workspace after each test."""
+ shutil.rmtree(self.temp_dir, ignore_errors=True)
+
+ def _make_agent(
+ self,
+ model: _RecordingMockModel,
+ middleware: AgenticMemoryMiddleware,
+ toolkit: Toolkit | None = None,
+ ) -> Agent:
+ """Build an Agent with the filesystem memory middleware attached.
+
+ Args:
+ model (`_RecordingMockModel`):
+ The mock model used by the agent.
+ middleware (`AgenticMemoryMiddleware`):
+ The middleware under test.
+ toolkit (`Toolkit | None`, optional):
+ The toolkit for the agent. Defaults to an empty toolkit.
+
+ Returns:
+ `Agent`:
+ The configured agent.
+ """
+ return Agent(
+ name="assistant",
+ system_prompt="You are helpful.",
+ model=model,
+ toolkit=toolkit or Toolkit(),
+ middlewares=[middleware],
+ )
+
+ async def test_agent_reply_creates_layout_and_injects_memory_prompt(
+ self,
+ ) -> None:
+ """Agent reply should create layout and inject memory instructions."""
+ model = _RecordingMockModel()
+ model.set_responses([_text_response("done")])
+ middleware = AgenticMemoryMiddleware(workdir=self.temp_dir)
+ agent = self._make_agent(model, middleware)
+
+ reply = await agent.reply(UserMsg("user", "hello"))
+ memory_dir = os.path.join(self.temp_dir, "Memory")
+ system_prompt = model.chat_messages[0][0].get_text_content()
+
+ self.assertDictEqual(
+ {
+ "reply": _message_to_dict(reply),
+ "memory_dir_exists": os.path.isdir(memory_dir),
+ "memory_md_exists": os.path.isfile(
+ os.path.join(memory_dir, "MEMORY.md"),
+ ),
+ "system_prompt": {
+ "has_memory_dir": memory_dir in system_prompt,
+ "has_placeholder": "{memory_dir}" in system_prompt,
+ "has_memory_header": "## MEMORY.md" in system_prompt,
+ "has_empty_memory_text": (
+ "Your MEMORY.md is currently empty" in system_prompt
+ ),
+ },
+ },
+ {
+ "reply": {
+ "id": AnyString(),
+ "name": "assistant",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "done",
+ "id": AnyString(),
+ },
+ ],
+ "metadata": {},
+ },
+ "memory_dir_exists": True,
+ "memory_md_exists": True,
+ "system_prompt": {
+ "has_memory_dir": True,
+ "has_placeholder": False,
+ "has_memory_header": True,
+ "has_empty_memory_text": True,
+ },
+ },
+ )
+
+ async def test_agent_reasoning_injects_selected_memory_hint(
+ self,
+ ) -> None:
+ """Agent reasoning should inject content selected by structured
+ output."""
+ memory_dir = os.path.join(self.temp_dir, "Memory")
+ os.makedirs(memory_dir)
+ with open(
+ os.path.join(memory_dir, "MEMORY.md"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write("- [User profile](user_profile.md) — User profile.\n")
+ _write_memory_file(
+ memory_dir,
+ "user_profile.md",
+ "User profile details",
+ "user",
+ "The user prefers concise Chinese answers.",
+ )
+
+ model = _RecordingMockModel()
+ model.set_structured_response(
+ _structured_response(["user_profile.md"]),
+ )
+ model.set_responses([_tool_response(), _text_response("final answer")])
+ middleware = AgenticMemoryMiddleware(workdir=self.temp_dir)
+ agent = self._make_agent(
+ model,
+ middleware,
+ toolkit=Toolkit(tools=[_DummyTool()]),
+ )
+
+ reply = await agent.reply(UserMsg("user", "what do you remember?"))
+ hint_texts = _hint_texts(agent)
+
+ self.assertDictEqual(
+ {
+ "reply": _message_to_dict(reply),
+ "hints": [
+ {
+ "has_selected_content": (
+ "The user prefers concise Chinese answers." in hint
+ ),
+ "has_selected_path": "user_profile.md" in hint,
+ }
+ for hint in hint_texts
+ ],
+ "context": [
+ _message_to_dict(msg) for msg in agent.state.context
+ ],
+ "structured_call_count": len(model.structured_messages),
+ },
+ {
+ "reply": {
+ "id": AnyString(),
+ "name": "assistant",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "final answer",
+ "id": AnyString(),
+ },
+ ],
+ "metadata": {},
+ },
+ "hints": [
+ {
+ "has_selected_content": True,
+ "has_selected_path": True,
+ },
+ ],
+ "context": [
+ {
+ "id": AnyString(),
+ "name": "user",
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "what do you remember?",
+ "id": AnyString(),
+ },
+ ],
+ "metadata": {},
+ },
+ {
+ "id": AnyString(),
+ "name": "assistant",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_call",
+ "id": AnyString(),
+ "name": "dummy",
+ "input": "{}",
+ "state": "finished",
+ "suggested_rules": [],
+ },
+ AnyValue(),
+ {
+ "type": "hint",
+ "hint": AnyString(),
+ "id": AnyString(),
+ "source": None,
+ },
+ {
+ "type": "text",
+ "text": "final answer",
+ "id": AnyString(),
+ },
+ ],
+ "metadata": {},
+ },
+ ],
+ "structured_call_count": 1,
+ },
+ )
+
+ async def test_agent_filters_hallucinated_memory_filenames(self) -> None:
+ """Agent retrieval should ignore filenames not present in memory."""
+ memory_dir = os.path.join(self.temp_dir, "Memory")
+ os.makedirs(memory_dir)
+ with open(
+ os.path.join(memory_dir, "MEMORY.md"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write("- [User profile](user_profile.md) — User profile.\n")
+ _write_memory_file(
+ memory_dir,
+ "user_profile.md",
+ "User profile details",
+ "user",
+ "Only this real memory should be injected.",
+ )
+
+ model = _RecordingMockModel()
+ model.set_structured_response(
+ _structured_response(["user_profile.md", "missing.md"]),
+ )
+ model.set_responses([_tool_response(), _text_response("filtered")])
+ middleware = AgenticMemoryMiddleware(workdir=self.temp_dir)
+ agent = self._make_agent(
+ model,
+ middleware,
+ toolkit=Toolkit(tools=[_DummyTool()]),
+ )
+
+ await agent.reply(UserMsg("user", "recall memory"))
+ hint_texts = _hint_texts(agent)
+
+ self.assertListEqual(
+ [
+ {
+ "has_real_memory": (
+ "Only this real memory should be injected." in hint
+ ),
+ "has_missing_memory": "missing.md" in hint,
+ }
+ for hint in hint_texts
+ ],
+ [
+ {
+ "has_real_memory": True,
+ "has_missing_memory": False,
+ },
+ ],
+ )
+
+ async def test_agent_does_not_inject_hint_when_no_file_selected(
+ self,
+ ) -> None:
+ """Agent retrieval should inject no hint when selection is empty."""
+ memory_dir = os.path.join(self.temp_dir, "Memory")
+ os.makedirs(memory_dir)
+ with open(
+ os.path.join(memory_dir, "MEMORY.md"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write("- [User profile](user_profile.md) — User profile.\n")
+ _write_memory_file(
+ memory_dir,
+ "user_profile.md",
+ "User profile details",
+ "user",
+ "This memory is available but not selected.",
+ )
+
+ model = _RecordingMockModel()
+ model.set_structured_response(_structured_response([]))
+ model.set_responses([_tool_response(), _text_response("no hint")])
+ middleware = AgenticMemoryMiddleware(workdir=self.temp_dir)
+ agent = self._make_agent(
+ model,
+ middleware,
+ toolkit=Toolkit(tools=[_DummyTool()]),
+ )
+
+ reply = await agent.reply(UserMsg("user", "ignore memories"))
+
+ self.assertDictEqual(
+ {
+ "reply": _message_to_dict(reply),
+ "hints": _hint_texts(agent),
+ "structured_call_count": len(model.structured_messages),
+ },
+ {
+ "reply": {
+ "id": AnyString(),
+ "name": "assistant",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "no hint",
+ "id": AnyString(),
+ },
+ ],
+ "metadata": {},
+ },
+ "hints": [],
+ "structured_call_count": 1,
+ },
+ )
+
+ async def test_agent_does_not_retrieve_when_only_memory_index_exists(
+ self,
+ ) -> None:
+ """Agent retrieval should skip structured output without topic
+ files."""
+ model = _RecordingMockModel()
+ model.set_structured_response(_structured_response(["missing.md"]))
+ model.set_responses([_tool_response(), _text_response("index only")])
+ middleware = AgenticMemoryMiddleware(workdir=self.temp_dir)
+ agent = self._make_agent(
+ model,
+ middleware,
+ toolkit=Toolkit(tools=[_DummyTool()]),
+ )
+
+ reply = await agent.reply(UserMsg("user", "hello"))
+
+ self.assertDictEqual(
+ {
+ "reply": _message_to_dict(reply),
+ "hints": _hint_texts(agent),
+ "structured_call_count": len(model.structured_messages),
+ "memory_md_exists": os.path.isfile(
+ os.path.join(self.temp_dir, "Memory", "MEMORY.md"),
+ ),
+ },
+ {
+ "reply": {
+ "id": AnyString(),
+ "name": "assistant",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "index only",
+ "id": AnyString(),
+ },
+ ],
+ "metadata": {},
+ },
+ "hints": [],
+ "structured_call_count": 0,
+ "memory_md_exists": True,
+ },
+ )
+
+ async def test_agent_system_prompt_contains_truncation_reminder(
+ self,
+ ) -> None:
+ """Agent system prompt should contain reminder for truncated index."""
+ memory_dir = os.path.join(self.temp_dir, "Memory")
+ os.makedirs(memory_dir)
+ with open(
+ os.path.join(memory_dir, "MEMORY.md"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write("0123456789" * 80)
+
+ model = _RecordingMockModel()
+ model.set_responses([_text_response("truncated")])
+ middleware = AgenticMemoryMiddleware(
+ workdir=self.temp_dir,
+ parameters=AgenticMemoryMiddleware.Parameters(
+ memory_max_tokens=10,
+ retrieval_async=False,
+ ),
+ )
+ agent = self._make_agent(model, middleware)
+
+ await agent.reply(UserMsg("user", "hello"))
+ system_prompt = model.chat_messages[0][0].get_text_content()
+
+ self.assertDictEqual(
+ {
+ "has_truncated_marker": "<<<TRUNCATED>>>" in system_prompt,
+ "has_offset_reminder": "Use the `Read` tool with offset"
+ in system_prompt,
+ "has_memory_path": os.path.join(memory_dir, "MEMORY.md")
+ in system_prompt,
+ },
+ {
+ "has_truncated_marker": True,
+ "has_offset_reminder": True,
+ "has_memory_path": True,
+ },
+ )
+
+ async def test_agent_skips_retrieval_when_async_retrieval_disabled(
+ self,
+ ) -> None:
+ """Agent should not run retrieval when ``retrieval_async`` is false."""
+ memory_dir = os.path.join(self.temp_dir, "Memory")
+ os.makedirs(memory_dir)
+ with open(
+ os.path.join(memory_dir, "MEMORY.md"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write("- [User profile](user_profile.md) — User profile.\n")
+ _write_memory_file(
+ memory_dir,
+ "user_profile.md",
+ "User profile details",
+ "user",
+ "This memory should not be retrieved.",
+ )
+
+ model = _RecordingMockModel()
+ model.set_structured_response(
+ _structured_response(["user_profile.md"]),
+ )
+ model.set_responses([_tool_response(), _text_response("disabled")])
+ middleware = AgenticMemoryMiddleware(
+ workdir=self.temp_dir,
+ parameters=AgenticMemoryMiddleware.Parameters(
+ retrieval_async=False,
+ ),
+ )
+ agent = self._make_agent(
+ model,
+ middleware,
+ toolkit=Toolkit(tools=[_DummyTool()]),
+ )
+
+ reply = await agent.reply(UserMsg("user", "remember?"))
+
+ self.assertDictEqual(
+ {
+ "reply": _message_to_dict(reply),
+ "hints": _hint_texts(agent),
+ "structured_call_count": len(model.structured_messages),
+ },
+ {
+ "reply": {
+ "id": AnyString(),
+ "name": "assistant",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "disabled",
+ "id": AnyString(),
+ },
+ ],
+ "metadata": {},
+ },
+ "hints": [],
+ "structured_call_count": 0,
+ },
+ )
diff --git a/tests/permission_bash_parser_test.py b/tests/permission_bash_parser_test.py
index b41c2d044..4c20dc287 100644
--- a/tests/permission_bash_parser_test.py
+++ b/tests/permission_bash_parser_test.py
@@ -975,7 +975,7 @@ class BashWildcardMatchingTest(IsolatedAsyncioTestCase):
]
for pattern, command, expected in test_cases:
with self.subTest(pattern=pattern, command=command):
- result = self.bash_tool.match_rule(
+ result = await self.bash_tool.match_rule(
pattern,
{"command": command},
)
@@ -990,7 +990,7 @@ class BashWildcardMatchingTest(IsolatedAsyncioTestCase):
]
for pattern, command, expected in test_cases:
with self.subTest(pattern=pattern, command=command):
- result = self.bash_tool.match_rule(
+ result = await self.bash_tool.match_rule(
pattern,
{"command": command},
)
@@ -1006,7 +1006,7 @@ class BashWildcardMatchingTest(IsolatedAsyncioTestCase):
]
for pattern, command, expected in test_cases:
with self.subTest(pattern=pattern, command=command):
- result = self.bash_tool.match_rule(
+ result = await self.bash_tool.match_rule(
pattern,
{"command": command},
)
@@ -1023,7 +1023,7 @@ class BashWildcardMatchingTest(IsolatedAsyncioTestCase):
]
for pattern, command, expected in test_cases:
with self.subTest(pattern=pattern, command=command):
- result = self.bash_tool.match_rule(
+ result = await self.bash_tool.match_rule(
pattern,
{"command": command},
)
@@ -1039,7 +1039,7 @@ class BashWildcardMatchingTest(IsolatedAsyncioTestCase):
]
for pattern, command, expected in test_cases:
with self.subTest(pattern=pattern, command=command):
- result = self.bash_tool.match_rule(
+ result = await self.bash_tool.match_rule(
pattern,
{"command": command},
)