Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(workspace): resolve local search paths from the workspace directory (#2637)
ShiZai02cf7666c942
diff --git a/src/agentscope/tool/_builtin/_backend.py b/src/agentscope/tool/_builtin/_backend.pyindex 5b30798bb..682c74d14 100644--- a/src/agentscope/tool/_builtin/_backend.py+++ b/src/agentscope/tool/_builtin/_backend.py@@ -761,6 +761,19 @@ class LocalBackend(BackendBase):# OS is the host OS.os_name = os.name+ def __init__(self, workdir: str | None = None) -> None:+ """Initialize the local backend.++ Args:+ workdir (`str | None`, optional):+ Directory returned by :meth:`getcwd`, resolved to an+ absolute path. When ``None``, use the host process's+ current working directory at call time.+ """+ self._workdir = (+ os.path.abspath(workdir) if workdir is not None else None+ )+async def exec_shell(self,command: list[str],@@ -909,13 +922,13 @@ class LocalBackend(BackendBase):yield chunkasync def getcwd(self) -> str:- """Return the host process's current working directory.+ """Return the configured directory or the host process's current one.Returns:`str`:- ``os.getcwd()`` — avoids spawning a ``pwd`` subprocess.+ The configured workdir, or ``os.getcwd()`` when unset."""- return os.getcwd()+ return self._workdir if self._workdir is not None else os.getcwd()async def expanduser(self, path: str) -> str:"""Expand ``~`` using the host process's ``$HOME``.diff --git a/src/agentscope/tool/_builtin/_glob.py b/src/agentscope/tool/_builtin/_glob.pyindex 6c5f9def6..5af666891 100644--- a/src/agentscope/tool/_builtin/_glob.py+++ b/src/agentscope/tool/_builtin/_glob.py@@ -276,7 +276,15 @@ Use head_limit to cap the number of results returned.""" # ignore: E501is_last=True,)- base_dir = path if path else await self._backend.getcwd()+ base_dir = path or "."+ if base_dir == ".":+ base_dir = await self._backend.getcwd()+ elif not self._backend.isabs(base_dir):+ # Preserve '..' so the filesystem can resolve symlinks first.+ base_dir = self._backend.join_path(+ await self._backend.getcwd(),+ base_dir,+ )# The base must be an existing directory; a regular file would# otherwise be accepted here and fail later with a confusingdiff --git a/src/agentscope/tool/_builtin/_grep.py b/src/agentscope/tool/_builtin/_grep.pyindex ca8e46d95..3fc70a819 100644--- a/src/agentscope/tool/_builtin/_grep.py+++ b/src/agentscope/tool/_builtin/_grep.py@@ -358,7 +358,15 @@ class Grep(ToolBase):n: Show line numbers (content mode only, default True)**kwargs: Additional parameters (-A, -B, -C)"""- search_path = path or await self._backend.getcwd()+ search_path = path or "."+ if search_path == ".":+ search_path = await self._backend.getcwd()+ elif not self._backend.isabs(search_path):+ # Preserve '..' so the filesystem can resolve symlinks first.+ search_path = self._backend.join_path(+ await self._backend.getcwd(),+ search_path,+ )if head_limit is not None and head_limit < 0:return ToolChunk(diff --git a/src/agentscope/workspace/_local_workspace.py b/src/agentscope/workspace/_local_workspace.pyindex 6ad1ae8c1..b80b06a1f 100644--- a/src/agentscope/workspace/_local_workspace.py+++ b/src/agentscope/workspace/_local_workspace.py@@ -126,7 +126,7 @@ class LocalWorkspace(WorkspaceBase):)# ── runtime state ───────────────────────────────────────- self._backend = LocalBackend()+ self._backend = LocalBackend(workdir=self.workdir)self._skill_lock = asyncio.Lock()self._mcp_lock = asyncio.Lock()diff --git a/tests/backend_local_test.py b/tests/backend_local_test.pyindex 3cd8692ad..c37e4e8bd 100644--- a/tests/backend_local_test.py+++ b/tests/backend_local_test.py@@ -20,6 +20,7 @@ import tempfileimport unittestfrom unittest import mockfrom unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import patchfrom agentscope.tool import ExecResult, LocalBackendfrom agentscope.tool._builtin._backend import _normalize_newlines@@ -203,6 +204,19 @@ class TestLocalBackendFileIO(IsolatedAsyncioTestCase):class TestLocalBackendFilesystemHelpers(IsolatedAsyncioTestCase):"""Test cases for the derived filesystem helpers (native ``os.*``)."""+ async def test_getcwd_defaults_to_process_directory(self) -> None:+ """An unconfigured backend follows the process cwd at call time."""+ backend = LocalBackend()+ with patch("os.getcwd", return_value=self.temp_dir.name):+ self.assertEqual(await backend.getcwd(), self.temp_dir.name)++ async def test_getcwd_keeps_configured_workdir(self) -> None:+ """Resolve a relative workdir once, regardless of later cwd changes."""+ expected = os.path.abspath("workspace")+ backend = LocalBackend(workdir="workspace")+ with patch("os.getcwd", return_value=self.temp_dir.name):+ self.assertEqual(await backend.getcwd(), expected)+async def asyncSetUp(self) -> None:"""Build a backend and a temp dir per test."""# pylint: disable=consider-using-withdiff --git a/tests/builtin_grep_test.py b/tests/builtin_grep_test.pyindex 7080b16c8..3d6c3c944 100644--- a/tests/builtin_grep_test.py+++ b/tests/builtin_grep_test.py@@ -2,12 +2,10 @@"""Grep tool test case."""import osimport tempfile-from typing import Anyfrom unittest.async_case import IsolatedAsyncioTestCase-from unittest.mock import patchfrom agentscope.message import ToolResultState-from agentscope.tool import Edit, ExecResult, Grep, LocalBackend+from agentscope.tool import Edit, Grep, LocalBackendfrom agentscope.permission import (PermissionContext,PermissionBehavior,@@ -98,15 +96,8 @@ class GrepToolTest(IsolatedAsyncioTestCase):async def test_dash_prefixed_paths(self) -> None:"""Relative paths must not be interpreted as ripgrep options."""- backend = LocalBackend()+ backend = LocalBackend(workdir=self.temp_dir)grep = Grep(backend=backend)- exec_shell = backend.exec_shell-- async def exec_in_temp(- command: list[str],- **kwargs: Any,- ) -> ExecResult:- return await exec_shell(command, cwd=self.temp_dir, **kwargs)for name in ("-notes.txt", "--help", "-folder"):target = os.path.join(self.temp_dir, name)@@ -118,22 +109,15 @@ class GrepToolTest(IsolatedAsyncioTestCase):for pattern in ("needle", "-needle"):with self.subTest(path=name, pattern=pattern):- with patch.object(- backend,- "exec_shell",- side_effect=exec_in_temp,- ):- chunk = await grep(- pattern=pattern,- path=name,- output_mode="content",- n=False,- )+ chunk = await grep(+ pattern=pattern,+ path=name,+ output_mode="content",+ n=False,+ )expected_text = "-needle"if name == "-folder":- expected_text = (- os.path.join("-folder", "notes.txt") + ":-needle"- )+ expected_text = f"{target}:-needle"self.assertEqual(chunk.model_dump(exclude={diff --git a/tests/workspace_local_test.py b/tests/workspace_local_test.pyindex 7b440e01a..f7d7fe5bb 100644--- a/tests/workspace_local_test.py+++ b/tests/workspace_local_test.py@@ -105,6 +105,101 @@ class _LongResultTool(ToolBase):class TestLocalWorkspaceTools(IsolatedAsyncioTestCase):"""Test cases for LocalWorkspace builtin tools."""+ async def _assert_search_result(+ self,+ workspace: LocalWorkspace,+ expected: Path,+ path: str | None = None,+ ) -> None:+ """Both search tools find the same file in the requested directory."""+ tools = await workspace.list_tools()+ for tool in tools:+ if isinstance(tool, (Glob, Grep)):+ pattern = "**/*.txt" if isinstance(tool, Glob) else "needle"+ result = await tool(pattern=pattern, path=path)+ self.assertEqual(result.content[0].text, str(expected))++ async def test_search_defaults_to_each_workspace(self) -> None:+ """Independent workspaces search their own roots without chdir."""+ process_cwd = os.getcwd()+ with tempfile.TemporaryDirectory() as root:+ for name in ("first", "second"):+ workdir = Path(root) / name+ workdir.mkdir()+ expected = workdir / "match.txt"+ expected.write_text("needle\n", encoding="utf-8")+ workspace = LocalWorkspace(workdir=str(workdir))+ await self._assert_search_result(workspace, expected)+ tools = await workspace.list_tools()+ for tool in tools:+ if isinstance(tool, (Glob, Grep)):+ suggestions = await tool.generate_suggestions({})+ self.assertEqual(+ suggestions[0].rule_content,+ str(workdir).rstrip("/\\") + "/**",+ )+ self.assertEqual(os.getcwd(), process_cwd)++ async def test_search_paths_resolve_from_workspace(self) -> None:+ """Dot and nested paths use the workspace; absolute paths override."""+ with tempfile.TemporaryDirectory() as root:+ workdir = Path(root) / "project"+ source = workdir / "src"+ source.mkdir(parents=True)+ expected = source / "match.txt"+ expected.write_text("needle\n", encoding="utf-8")+ external_dir = Path(root) / "external"+ external_dir.mkdir()+ external = external_dir / "match.txt"+ external.write_text("needle\n", encoding="utf-8")+ workspace = LocalWorkspace(workdir=str(workdir))+ await self._assert_search_result(workspace, expected, ".")+ await self._assert_search_result(workspace, expected, "src")+ await self._assert_search_result(+ workspace,+ external,+ str(external_dir),+ )++ async def test_search_preserves_symlink_parent_paths(self) -> None:+ """Preserve native filesystem semantics for symlink parent paths."""+ with tempfile.TemporaryDirectory() as root:+ workdir = Path(root) / "project"+ workdir.mkdir()+ external = Path(root) / "external"+ target = external / "nested"+ target.mkdir(parents=True)+ link = workdir / "link"+ try:+ link.symlink_to(target, target_is_directory=True)+ except OSError as exc:+ if getattr(exc, "winerror", None) == 1314:+ self.skipTest("Creating symlinks requires privileges.")+ raise+ (workdir / "wrong.txt").write_text("needle\n", encoding="utf-8")+ (external / "match.txt").write_text("needle\n", encoding="utf-8")+ workspace = LocalWorkspace(workdir=str(workdir))+ tools = await workspace.list_tools()+ expected = [+ str(entry)+ for entry in (link / "..").iterdir()+ if entry.suffix == ".txt"+ ]+ for path in (os.path.join("link", ".."), str(link / "..")):+ for tool in tools:+ if isinstance(tool, (Glob, Grep)):+ with self.subTest(path=path, tool=tool.name):+ pattern = (+ "**/*.txt"+ if isinstance(tool, Glob)+ else "needle"+ )+ result = await tool(pattern=pattern, path=path)+ self.assertEqual(+ [block.text for block in result.content],+ expected,+ )+async def test_list_tools_builtin_posix_uses_bash(self) -> None:"""A POSIX local workspace returns Bash and filesystem tools."""with tempfile.TemporaryDirectory() as workdir: