Skip to content

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

fix(tool): treat dash-prefixed grep paths as operands (#2988)

SIcheng Han0d7a7f6a660a
diff --git a/src/agentscope/tool/_builtin/_grep.py b/src/agentscope/tool/_builtin/_grep.py
index c70005944..8d59b9326 100644
--- a/src/agentscope/tool/_builtin/_grep.py
+++ b/src/agentscope/tool/_builtin/_grep.py
@@ -286,7 +286,7 @@ class Grep(ToolBase):
a shell), so the same code path works for local, Docker, and E2B
backends and needs no platform-specific argument quoting.
"""
- command = ["rg", *args, search_path]
+ command = ["rg", *args, "--", search_path]
result = await self._backend.exec_shell(
command,
diff --git a/tests/builtin_grep_test.py b/tests/builtin_grep_test.py
index 4718344b1..fcc52919f 100644
--- a/tests/builtin_grep_test.py
+++ b/tests/builtin_grep_test.py
@@ -2,10 +2,12 @@
"""Grep tool test case."""
import os
import tempfile
+from typing import Any
from unittest.async_case import IsolatedAsyncioTestCase
+from unittest.mock import patch
from agentscope.message import ToolResultState
-from agentscope.tool import Grep
+from agentscope.tool import ExecResult, Grep, LocalBackend
from agentscope.permission import (
PermissionContext,
PermissionBehavior,
@@ -94,6 +96,65 @@ class GrepToolTest(IsolatedAsyncioTestCase):
self.assertIn("test1.py", content)
self.assertIn("test.txt", content)
+ async def test_dash_prefixed_paths(self) -> None:
+ """Relative paths must not be interpreted as ripgrep options."""
+ backend = LocalBackend()
+ 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)
+ if name == "-folder":
+ os.makedirs(target)
+ target = os.path.join(target, "notes.txt")
+ with open(target, "w", encoding="utf-8") as stream:
+ stream.write("-needle\n")
+
+ 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,
+ )
+ expected_text = "-needle"
+ if name == "-folder":
+ expected_text = (
+ os.path.join("-folder", "notes.txt") + ":-needle"
+ )
+ self.assertEqual(
+ chunk.model_dump(
+ exclude={
+ "id": True,
+ "content": {"__all__": {"id", "created_at"}},
+ },
+ ),
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": expected_text,
+ "finished_at": None,
+ },
+ ],
+ "state": ToolResultState.SUCCESS,
+ "is_last": True,
+ "metadata": {},
+ },
+ )
+
async def test_content_mode(self) -> None:
"""Test grep with content output mode."""
chunk = await self.grep_tool(