Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(tool): validate read offset and limit at runtime (#3297)
GG bond4fef03b0a480
diff --git a/src/agentscope/tool/_builtin/_read.py b/src/agentscope/tool/_builtin/_read.pyindex bc6463d53..8903de865 100644--- a/src/agentscope/tool/_builtin/_read.py+++ b/src/agentscope/tool/_builtin/_read.py@@ -507,6 +507,30 @@ Usage:) -> ToolChunk:"""Read a text file and return with line numbers."""try:+ if offset < 1:+ return ToolChunk(+ content=[+ TextBlock(+ text=f"Error: offset must be at least 1, "+ f"got: {offset}.",+ ),+ ],+ state=ToolResultState.ERROR,+ is_last=True,+ )++ if limit < 1 or limit > 2000:+ return ToolChunk(+ content=[+ TextBlock(+ text=f"Error: limit must be between 1 and 2000, "+ f"got: {limit}.",+ ),+ ],+ state=ToolResultState.ERROR,+ is_last=True,+ )+# Read file content via backendlines = Noneif _agent_state is not None:diff --git a/tests/builtin_read_test.py b/tests/builtin_read_test.pyindex bb898e655..b75e0da75 100644--- a/tests/builtin_read_test.py+++ b/tests/builtin_read_test.py@@ -6,16 +6,17 @@ import osimport tempfileimport uuidfrom unittest.async_case import IsolatedAsyncioTestCase-from unittest.mock import patch+from unittest.mock import AsyncMock, patchfrom utils import AnyString-from agentscope.tool import ToolChunk, Read+from agentscope.tool import ToolChunk, Read, LocalBackendfrom agentscope.permission import (PermissionContext,PermissionBehavior,PermissionRule,)from agentscope.message import TextBlock+from agentscope.state import AgentState, ToolContext# pylint: disable=too-many-public-methods@@ -178,6 +179,146 @@ class ReadToolTest(IsolatedAsyncioTestCase):self.assertIn("Line 3", content)self.assertNotIn("Line 4", content)+ async def test_invalid_pagination_skips_reading_and_cache(self) -> None:+ """Reject invalid pagination before reading or accessing the cache."""+ state = AgentState()+ backend = LocalBackend()+ read_tool = Read(backend=backend)+ with (+ patch.object(+ backend,+ "read_file",+ new_callable=AsyncMock,+ return_value=b"Line 1\nLine 2\n",+ ) as read_file,+ patch.object(+ backend,+ "stat_mtime",+ new_callable=AsyncMock,+ return_value=1.0,+ ) as stat_mtime,+ patch.object(+ ToolContext,+ "get_cache",+ new_callable=AsyncMock,+ return_value=None,+ ) as get_cache,+ patch.object(+ ToolContext,+ "cache_file",+ new_callable=AsyncMock,+ ) as cache_file,+ ):+ for parameter, value in [+ ("offset", 0),+ ("offset", -1),+ ("offset", -3),+ ("limit", 0),+ ("limit", -1),+ ("limit", 2001),+ ]:+ with self.subTest(parameter=parameter, value=value):+ invoke = (+ read_tool.call if parameter == "offset" else read_tool+ )+ chunk = await invoke(+ file_path=self.temp_file.name,+ _agent_state=state,+ **{parameter: value},+ )++ expected_text = (+ f"Error: offset must be at least 1, got: {value}."+ if parameter == "offset"+ else "Error: limit must be between 1 and 2000, "+ f"got: {value}."+ )+ self.assertDictEqual(+ chunk.model_dump(mode="json"),+ {+ "content": [+ {+ "type": "text",+ "id": AnyString(),+ "text": expected_text,+ "created_at": AnyString(),+ "finished_at": None,+ },+ ],+ "state": "error",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )+ read_file.assert_not_called()+ stat_mtime.assert_not_called()+ get_cache.assert_not_called()+ cache_file.assert_not_called()++ async def test_read_pagination_boundaries(self) -> None:+ """Valid pagination preserves exact line numbers and content."""+ all_lines = "\n".join(f"{i:6d}\tLine {i}" for i in range(1, 11))+ for offset, limit, expected in [+ (1, 1, " 1\tLine 1"),+ (10, 1, " 10\tLine 10"),+ (1, 2000, all_lines),+ (10, 2000, " 10\tLine 10"),+ (11, 1, ""),+ ]:+ with self.subTest(offset=offset, limit=limit):+ chunk = await self.read_tool(+ file_path=self.temp_file.name,+ offset=offset,+ limit=limit,+ )++ self.assertDictEqual(+ chunk.model_dump(mode="json"),+ {+ "content": [+ {+ "type": "text",+ "id": AnyString(),+ "text": expected,+ "created_at": AnyString(),+ "finished_at": None,+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ async def test_read_empty_file_with_valid_pagination(self) -> None:+ """An empty file remains a successful empty result."""+ with tempfile.NamedTemporaryFile(delete=False, suffix=".txt") as f:+ pass+ self.addCleanup(os.unlink, f.name)++ chunk = await self.read_tool(file_path=f.name, offset=1, limit=1)++ self.assertDictEqual(+ chunk.model_dump(mode="json"),+ {+ "content": [+ {+ "type": "text",+ "id": AnyString(),+ "text": "",+ "created_at": AnyString(),+ "finished_at": None,+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )+async def test_read_nonexistent_file(self) -> None:"""Test reading a non-existent file."""missing_path = os.path.join(