Skip to content

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

fix(tool): bound glob search tool output (#2572)

guanyi liu0727cbf912c3
diff --git a/src/agentscope/tool/_builtin/_glob.py b/src/agentscope/tool/_builtin/_glob.py
index f5261c195..f58f17c5e 100644
--- a/src/agentscope/tool/_builtin/_glob.py
+++ b/src/agentscope/tool/_builtin/_glob.py
@@ -21,6 +21,9 @@ from .._response import ToolChunk
if TYPE_CHECKING:
from ._backend import BackendBase
+# Default cap on glob results when head_limit is unspecified
+DEFAULT_HEAD_LIMIT = 250
+
def _default_glob_helper_path() -> str:
"""Resolve the on-disk path of the bundled ``_glob_helper.py`` script.
@@ -52,7 +55,9 @@ Supports glob patterns like "**/*.js" or "src/**/*.ts" and returns
matching file paths sorted by modification time (newest first).
Use this tool when you need to find files by pattern across the
-codebase.""" # ignore: E501
+codebase.
+
+Use head_limit to cap the number of results returned.""" # ignore: E501
"""The description presented to the agent."""
input_schema: dict[str, Any] = {
@@ -68,6 +73,19 @@ codebase.""" # ignore: E501
"description": "The base directory to search from "
"(defaults to current working directory)",
},
+ "head_limit": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "Limit output to first N paths. Defaults to "
+ "250 when unspecified. Pass 0 for unlimited.",
+ },
+ "offset": {
+ "type": "integer",
+ "minimum": 0,
+ "default": 0,
+ "description": "Number of matching files to skip before "
+ "returning results",
+ },
},
"required": ["pattern"],
}
@@ -207,6 +225,8 @@ codebase.""" # ignore: E501
self,
pattern: str,
path: str | None = None,
+ head_limit: int | None = None,
+ offset: int = 0,
) -> ToolChunk:
"""Execute the glob pattern matching and return the results.
@@ -224,6 +244,12 @@ codebase.""" # ignore: E501
path (`str | None`, optional):
Base directory to search from. Defaults to the current
working directory when ``None``.
+ head_limit (`int | None`, optional):
+ Maximum number of matching paths to return. Defaults to
+ ``250``. Pass ``0`` for unlimited.
+ offset (`int`, optional):
+ Number of matching paths to skip before returning results.
+ Defaults to ``0``.
Returns:
`ToolChunk`:
@@ -232,6 +258,24 @@ codebase.""" # ignore: E501
is missing or the helper fails, an error chunk with
``ToolResultState.ERROR``.
"""
+ if head_limit is not None and head_limit < 0:
+ return ToolChunk(
+ content=[
+ TextBlock(text="Error: head_limit must be non-negative."),
+ ],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+
+ if offset < 0:
+ return ToolChunk(
+ content=[
+ TextBlock(text="Error: offset must be non-negative."),
+ ],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+
base_dir = path if path else await self._backend.getcwd()
# The base must be an existing directory; a regular file would
@@ -298,8 +342,26 @@ codebase.""" # ignore: E501
is_last=True,
)
+ effective_limit = (
+ head_limit if head_limit is not None else DEFAULT_HEAD_LIMIT
+ )
+ limited = (
+ matches[offset : offset + effective_limit]
+ if effective_limit
+ else matches[offset:]
+ )
+ output = "\n".join(limited)
+ if effective_limit and len(matches) - offset > effective_limit:
+ output += (
+ f"\n\n[Showing results with pagination = "
+ f"limit: {effective_limit}"
+ )
+ if offset:
+ output += f", offset: {offset}"
+ output += "]"
+
return ToolChunk(
- content=[TextBlock(text="\n".join(matches))],
+ content=[TextBlock(text=output)],
state=ToolResultState.RUNNING,
is_last=True,
)
diff --git a/tests/builtin_glob_test.py b/tests/builtin_glob_test.py
index d682e4ed5..771d76514 100644
--- a/tests/builtin_glob_test.py
+++ b/tests/builtin_glob_test.py
@@ -102,6 +102,106 @@ class GlobToolTest(IsolatedAsyncioTestCase):
self.assertIn("test2.py", content)
self.assertIn("test3.py", content)
+ async def test_default_head_limit_truncates_large_result(self) -> None:
+ """Test the default head limit returns the newest 250 files."""
+ expected_paths = []
+ for index in range(251):
+ file_path = os.path.join(self.temp_dir, f"match_{index}.log")
+ with open(file_path, "w", encoding="utf-8"):
+ pass
+ os.utime(file_path, (index, index))
+ expected_paths.append(file_path)
+
+ chunk = await self.glob_tool(
+ pattern="match_*.log",
+ path=self.temp_dir,
+ )
+
+ expected = "\n".join(reversed(expected_paths[1:]))
+ expected += "\n\n[Showing results with pagination = limit: 250]"
+ self.assertEqual(chunk.content[0].text, expected)
+
+ async def test_head_limit_zero_returns_all_results(self) -> None:
+ """Test zero disables the default head limit."""
+ expected_paths = []
+ for index in range(4):
+ file_path = os.path.join(self.temp_dir, f"unlimited_{index}.txt")
+ with open(file_path, "w", encoding="utf-8"):
+ pass
+ os.utime(file_path, (index, index))
+ expected_paths.append(file_path)
+
+ chunk = await self.glob_tool(
+ pattern="unlimited_*.txt",
+ path=self.temp_dir,
+ head_limit=0,
+ )
+ self.assertEqual(
+ chunk.content[0].text,
+ "\n".join(reversed(expected_paths)),
+ )
+
+ async def test_negative_head_limit_returns_error(self) -> None:
+ """Test a negative head limit returns an error."""
+ chunk = await self.glob_tool(
+ pattern="*.py",
+ path=self.temp_dir,
+ head_limit=-1,
+ )
+
+ self.assertEqual(chunk.state, "error")
+ self.assertEqual(
+ chunk.content[0].text,
+ "Error: head_limit must be non-negative.",
+ )
+
+ async def test_offset_paginates_results(self) -> None:
+ """Test that callers can retrieve later pages of results."""
+ expected_paths = []
+ for index in range(6):
+ file_path = os.path.join(self.temp_dir, f"paged_{index}.txt")
+ with open(file_path, "w", encoding="utf-8"):
+ pass
+ os.utime(file_path, (index, index))
+ expected_paths.append(file_path)
+
+ second_page = await self.glob_tool(
+ pattern="paged_*.txt",
+ path=self.temp_dir,
+ head_limit=2,
+ offset=2,
+ )
+ self.assertEqual(
+ second_page.content[0].text,
+ f"{expected_paths[3]}\n{expected_paths[2]}\n\n"
+ "[Showing results with pagination = limit: 2, offset: 2]",
+ )
+
+ last_page = await self.glob_tool(
+ pattern="paged_*.txt",
+ path=self.temp_dir,
+ head_limit=2,
+ offset=4,
+ )
+ self.assertEqual(
+ last_page.content[0].text,
+ "\n".join([expected_paths[1], expected_paths[0]]),
+ )
+
+ async def test_negative_offset_returns_error(self) -> None:
+ """Test a negative offset returns an error."""
+ chunk = await self.glob_tool(
+ pattern="*.py",
+ path=self.temp_dir,
+ offset=-1,
+ )
+
+ self.assertEqual(chunk.state, "error")
+ self.assertEqual(
+ chunk.content[0].text,
+ "Error: offset must be non-negative.",
+ )
+
async def test_windows_style_separator_pattern(self) -> None:
"""Test glob patterns that use backslashes as path separators."""
chunk = await self.glob_tool(
@@ -140,7 +240,10 @@ class GlobToolTest(IsolatedAsyncioTestCase):
)
self.assertEqual(chunk.state, "running")
- self.assertIn("No files found", chunk.content[0].text)
+ self.assertEqual(
+ chunk.content[0].text,
+ "No files found matching pattern: *.nonexistent",
+ )
async def test_match_rule_path(self) -> None:
"""Test match_rule with path patterns."""