Skip to content

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

feat(bash): support to set `cwd` in `Bash` tool (#1822)

Yufeng He7b7e531cb359
diff --git a/src/agentscope/tool/_builtin/_bash.py b/src/agentscope/tool/_builtin/_bash.py
index 0697a347d..029fc9795 100644
--- a/src/agentscope/tool/_builtin/_bash.py
+++ b/src/agentscope/tool/_builtin/_bash.py
@@ -154,6 +154,7 @@ easier to review tool calls and give permission.
self,
dangerous_files: list[str] = DEFAULT_DANGEROUS_FILES,
dangerous_directories: list[str] = DEFAULT_DANGEROUS_DIRECTORIES,
+ cwd: str | os.PathLike[str] | None = None,
) -> None:
"""Initialize the bash tool.
@@ -171,12 +172,15 @@ easier to review tool calls and give permission.
`DEFAULT_DANGEROUS_DIRECTORIES`. Pass a custom list to
fully replace the defaults, or `[]` to disable the
directory check.
+ cwd (`str | os.PathLike[str] | None`, optional):
+ The working directory used when executing bash commands.
"""
self._bash_parser = BashCommandParser()
self.dangerous_files = list(dangerous_files)
self.dangerous_directories = list(dangerous_directories)
+ self._cwd = os.fspath(cwd) if cwd is not None else None
async def check_read_only(
self,
@@ -682,11 +686,14 @@ easier to review tool calls and give permission.
try:
# Create subprocess
+ subprocess_kwargs = _subprocess_creation_kwargs()
+ if self._cwd is not None:
+ subprocess_kwargs["cwd"] = self._cwd
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
- **_subprocess_creation_kwargs(),
+ **subprocess_kwargs,
)
# Wait for completion with timeout
diff --git a/tests/builtin_bash_test.py b/tests/builtin_bash_test.py
index fd8b2110d..5e807c303 100644
--- a/tests/builtin_bash_test.py
+++ b/tests/builtin_bash_test.py
@@ -3,7 +3,7 @@
import sys
import unittest
from unittest.async_case import IsolatedAsyncioTestCase
-from unittest.mock import patch
+from unittest.mock import AsyncMock, MagicMock, patch
from agentscope.tool import ToolChunk, Bash
from agentscope.tool._builtin._bash import _subprocess_creation_kwargs
@@ -32,6 +32,28 @@ class BashSubprocessKwargsTest(unittest.TestCase):
)
+class BashCwdTest(IsolatedAsyncioTestCase):
+ """Test Bash working-directory wiring."""
+
+ async def test_cwd_is_passed_to_subprocess(self) -> None:
+ """The constructor-level cwd should be used for each command."""
+ process = MagicMock()
+ process.returncode = 0
+ process.communicate = AsyncMock(return_value=(b"ok\n", b""))
+
+ create_process = AsyncMock(return_value=process)
+ with patch(
+ "agentscope.tool._builtin._bash.asyncio.create_subprocess_shell",
+ create_process,
+ ):
+ chunks = []
+ async for chunk in Bash(cwd="workspace")(command="pwd"):
+ chunks.append(chunk)
+
+ self.assertEqual(create_process.call_args.kwargs["cwd"], "workspace")
+ self.assertEqual(chunks[0].state, "running")
+
+
@unittest.skipIf(
sys.platform == "win32",
"Bash tool is not supported on Windows",