Skip to content

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

feat(tool): add PowerShell support for Windows workspaces (#2132)

qiuC123798bc1814eea
diff --git a/src/agentscope/tool/__init__.py b/src/agentscope/tool/__init__.py
index f58f5f3c8..9593e6bfa 100644
--- a/src/agentscope/tool/__init__.py
+++ b/src/agentscope/tool/__init__.py
@@ -9,6 +9,7 @@ from ._adapters import MCPTool, FunctionTool
from ._builtin import (
ResetTools,
Bash,
+ PowerShell,
Edit,
Glob,
Grep,
@@ -46,6 +47,7 @@ __all__ = [
"ExecResult",
"ResetTools",
"Bash",
+ "PowerShell",
"Edit",
"Glob",
"Grep",
diff --git a/src/agentscope/tool/_builtin/__init__.py b/src/agentscope/tool/_builtin/__init__.py
index 5e63a9561..15755149e 100644
--- a/src/agentscope/tool/_builtin/__init__.py
+++ b/src/agentscope/tool/_builtin/__init__.py
@@ -7,6 +7,7 @@ from ._edit import Edit
from ._glob import Glob
from ._grep import Grep
from ._meta import ResetTools
+from ._powershell import PowerShell
from ._read import Read
from ._skill import SkillViewer
from ._write import Write
@@ -15,6 +16,7 @@ __all__ = [
"ResetTools",
"SkillViewer",
"Bash",
+ "PowerShell",
"Edit",
"Glob",
"Grep",
diff --git a/src/agentscope/tool/_builtin/_powershell.py b/src/agentscope/tool/_builtin/_powershell.py
new file mode 100644
index 000000000..1403dbcc7
--- /dev/null
+++ b/src/agentscope/tool/_builtin/_powershell.py
@@ -0,0 +1,281 @@
+# -*- coding: utf-8 -*-
+"""The PowerShell tool in agentscope."""
+
+import base64
+import os
+from typing import AsyncGenerator, Any, List
+
+from ._backend import BackendBase, LocalBackend, _normalize_newlines
+from .._base import ToolBase, ToolMiddlewareBase
+from .._response import ToolChunk
+from ...message import TextBlock, ToolResultState
+from ...permission import (
+ PermissionBehavior,
+ PermissionContext,
+ PermissionDecision,
+ PermissionRule,
+)
+
+
+_SHELL_CANDIDATES = ("pwsh", "powershell.exe")
+
+
+class PowerShell(ToolBase):
+ """Execute PowerShell commands through a workspace backend."""
+
+ name: str = "PowerShell"
+ """The tool name presented to the agent."""
+
+ description: str = """Executes a PowerShell command and returns its output.
+
+Each command starts in the configured working directory, but PowerShell
+session state does not persist between commands. Commands run without
+loading the user's PowerShell profile.
+
+IMPORTANT: Avoid using this tool for filesystem operations when a dedicated
+tool can accomplish the task. Prefer the dedicated tools because their calls
+are easier for the user to review and authorize:
+
+ - File search: Use Glob (NOT Get-ChildItem)
+ - Content search: Use Grep (NOT Select-String)
+ - Read files: Use Read (NOT Get-Content)
+ - Edit files: Use Edit
+ - Write files: Use Write (NOT Set-Content or Out-File)
+ - Communication: Output text directly (NOT Write-Output)
+
+# Instructions
+ - Verify the parent directory before creating new directories or files.
+ - Quote paths containing spaces, for example: Get-Item "path with spaces".
+ - Prefer absolute paths and avoid Set-Location so the working directory is
+ clear in every command.
+ - You may specify an optional timeout in milliseconds (up to 600000ms /
+ 10 minutes). The default timeout is 120000ms (2 minutes).
+ - Write a concise description of what the command does. Include more context
+ for pipelines, uncommon parameters, or commands with side effects.
+ - Run independent commands in parallel tool calls. Keep dependent commands
+ together and use PowerShell-native error handling when later work depends
+ on earlier work succeeding.
+ - Prefer new git commits over amending existing commits. Avoid destructive
+ git operations and never bypass hooks unless the user explicitly asks."""
+ """The description presented to the agent."""
+
+ input_schema: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "command": {
+ "type": "string",
+ "description": "The PowerShell command to execute.",
+ },
+ "description": {
+ "type": "string",
+ "description": (
+ "Clear, concise description of what this command does."
+ ),
+ },
+ "timeout": {
+ "type": "integer",
+ "description": (
+ "Optional timeout in milliseconds "
+ "(default: 120000, max: 600000)"
+ ),
+ "default": 120000,
+ "maximum": 600000,
+ "minimum": 0,
+ },
+ },
+ "required": ["command"],
+ }
+
+ is_mcp: bool = False
+ is_read_only: bool = False
+ is_concurrency_safe: bool = False
+ is_external_tool: bool = False
+ is_state_injected: bool = False
+
+ def __init__(
+ self,
+ cwd: str | os.PathLike[str] | None = None,
+ middlewares: List[ToolMiddlewareBase] | None = None,
+ backend: BackendBase | None = None,
+ ) -> None:
+ """Initialize the PowerShell tool.
+
+ Args:
+ cwd (`str | os.PathLike[str] | None`, optional):
+ Working directory used when executing commands.
+ middlewares (`List[ToolMiddlewareBase] | None`, optional):
+ Tool middlewares wrapping command execution.
+ backend (`BackendBase | None`, optional):
+ Backend used for subprocess execution. Defaults to the
+ host-local backend.
+ """
+ super().__init__(middlewares=middlewares)
+ self._cwd = os.fspath(cwd) if cwd is not None else None
+ self._backend = backend or LocalBackend()
+ self._executable: str | None = None
+
+ async def _resolve_executable(self) -> str:
+ """Prefer PowerShell 6+ and cache the first available executable."""
+ if self._executable is None:
+ for candidate in _SHELL_CANDIDATES:
+ probe = await self._backend.exec_shell(
+ [
+ candidate,
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "exit 0",
+ ],
+ timeout=10.0,
+ )
+ if probe.exit_code != 127:
+ self._executable = candidate
+ break
+ else:
+ self._executable = "powershell.exe"
+ return self._executable
+
+ async def check_permissions(
+ self,
+ tool_input: dict[str, Any],
+ context: PermissionContext,
+ ) -> PermissionDecision:
+ """Ask the user to confirm every PowerShell command.
+
+ PowerShell-specific command validation is intentionally outside this
+ implementation. Since no command is classified as safe, every
+ invocation prompts the user. This is a regular ASK that allow rules
+ and BYPASS mode may still override.
+ """
+ return PermissionDecision(
+ behavior=PermissionBehavior.ASK,
+ message="Execute PowerShell command",
+ decision_reason="PowerShell command validation is not enabled",
+ )
+
+ async def generate_suggestions(
+ self,
+ tool_input: dict[str, Any],
+ ) -> List[PermissionRule]:
+ """Return no automatic allow-rule suggestions.
+
+ A broad rule would weaken the conservative permission boundary before
+ PowerShell-specific command validation is available.
+ """
+ return []
+
+ async def call( # type: ignore[override] # pylint: disable=unused-argument
+ self,
+ command: str,
+ description: str = "",
+ timeout: int = 120000,
+ ) -> AsyncGenerator[ToolChunk, None]:
+ """Execute a PowerShell command through the configured backend.
+
+ Args:
+ command (`str`):
+ PowerShell source text to execute.
+ description (`str`, optional):
+ Human-readable description of the command.
+ timeout (`int`, optional):
+ Timeout in milliseconds, capped at 600000.
+
+ Yields:
+ `ToolChunk`:
+ A final chunk containing the command output.
+ """
+ timeout_ms = min(timeout, 600000)
+ encoded_user_command = base64.b64encode(
+ command.encode("utf-16-le"),
+ ).decode("ascii")
+ powershell_script = (
+ "$ProgressPreference = "
+ "[System.Management.Automation.ActionPreference]::"
+ "SilentlyContinue\n"
+ "$OutputEncoding = [Console]::OutputEncoding = "
+ "[System.Text.UTF8Encoding]::new($false)\n"
+ "$AgentScopeCommand = [System.Text.Encoding]::Unicode.GetString("
+ "[System.Convert]::FromBase64String("
+ f"'{encoded_user_command}'))\n"
+ "& ([ScriptBlock]::Create($AgentScopeCommand))"
+ )
+ encoded_command = base64.b64encode(
+ powershell_script.encode("utf-16-le"),
+ ).decode("ascii")
+ try:
+ executable = await self._resolve_executable()
+ result = await self._backend.exec_shell(
+ [
+ executable,
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-EncodedCommand",
+ encoded_command,
+ ],
+ cwd=self._cwd,
+ timeout=timeout_ms / 1000.0,
+ )
+ except Exception as exc:
+ yield ToolChunk(
+ content=[
+ TextBlock(
+ text=f"Command failed: {command}\nError: {exc}",
+ ),
+ ],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+ return
+
+ stdout = _normalize_newlines(
+ result.stdout.decode("utf-8", errors="replace"),
+ )
+ stderr = _normalize_newlines(
+ result.stderr.decode("utf-8", errors="replace"),
+ )
+ if result.exit_code == -1 and result.stderr == b"timed out":
+ yield ToolChunk(
+ content=[
+ TextBlock(
+ text=(
+ f"Command timed out after {timeout_ms}ms: "
+ f"{command}"
+ ),
+ ),
+ ],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+ return
+
+ if not result.ok():
+ error_result = f"Command failed: {command}\n"
+ if stdout:
+ error_result += f"\nStdout:\n{stdout}"
+ if stderr:
+ error_result += f"\nStderr:\n{stderr}"
+ if len(error_result) > 30000:
+ error_result = (
+ error_result[:30000] + "\n... (output truncated)"
+ )
+ yield ToolChunk(
+ content=[TextBlock(text=error_result)],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+ return
+
+ output = stdout
+ if stderr:
+ if output:
+ output += "\n"
+ output += stderr
+ if len(output) > 30000:
+ output = output[:30000] + "\n... (output truncated)"
+ yield ToolChunk(
+ content=[TextBlock(text=output)],
+ state=ToolResultState.RUNNING,
+ is_last=True,
+ )
diff --git a/src/agentscope/workspace/_local_workspace.py b/src/agentscope/workspace/_local_workspace.py
index 29424eb03..1e4468ddb 100644
--- a/src/agentscope/workspace/_local_workspace.py
+++ b/src/agentscope/workspace/_local_workspace.py
@@ -15,6 +15,7 @@ from ._utils import DEFAULT_WORKSPACE_INSTRUCTIONS
from .._logging import logger
from ..mcp import MCPClient
from ..skill import Skill
+from ..tool import ToolBase
from ..tool._builtin._backend import LocalBackend
from ._base import WorkspaceBase
@@ -118,6 +119,29 @@ class LocalWorkspace(WorkspaceBase):
self._skill_lock = asyncio.Lock()
self._mcp_lock = asyncio.Lock()
+ async def list_tools(self) -> list[ToolBase]:
+ """Return builtin tools, using PowerShell as the shell on Windows."""
+ from ..tool import Bash, Edit, Glob, Grep, PowerShell, Read, Write
+
+ backend = self.get_backend()
+ glob_kwargs: dict = {"backend": backend}
+ if self._glob_helper_path is not None:
+ glob_kwargs["glob_helper_path"] = self._glob_helper_path
+
+ if os.name == "nt":
+ shell: ToolBase = PowerShell(cwd=self.workdir, backend=backend)
+ else:
+ shell = Bash(cwd=self.workdir, backend=backend)
+
+ return [
+ shell,
+ Edit(backend=backend),
+ Glob(**glob_kwargs),
+ Grep(backend=backend),
+ Read(backend=backend),
+ Write(backend=backend),
+ ]
+
async def initialize(self) -> None:
"""Initialise the workspace.
diff --git a/tests/builtin_powershell_test.py b/tests/builtin_powershell_test.py
new file mode 100644
index 000000000..fa84127cc
--- /dev/null
+++ b/tests/builtin_powershell_test.py
@@ -0,0 +1,382 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""PowerShell tool test cases."""
+
+import base64
+import sys
+import unittest
+from unittest.async_case import IsolatedAsyncioTestCase
+from unittest.mock import AsyncMock
+
+from agentscope.permission import PermissionBehavior, PermissionContext
+from agentscope.tool import ExecResult, LocalBackend, PowerShell
+
+
+class PowerShellInterfaceTest(IsolatedAsyncioTestCase):
+ """Test the public PowerShell interface and conservative permissions."""
+
+ async def test_public_interface_is_conservative(self) -> None:
+ """Expose the command schema without auto-allowing any command."""
+ backend = LocalBackend()
+ tool = PowerShell(cwd="workspace", backend=backend)
+
+ self.assertEqual(tool.name, "PowerShell")
+ self.assertFalse(tool.is_read_only)
+ self.assertFalse(tool.is_concurrency_safe)
+ self.assertIn("command", tool.input_schema["properties"])
+ self.assertEqual(tool.input_schema["required"], ["command"])
+ self.assertEqual(tool._cwd, "workspace")
+ self.assertIs(tool._backend, backend)
+ self.assertIn("Glob", tool.description)
+ self.assertIn("Read", tool.description)
+ self.assertIn("Write", tool.description)
+ self.assertIn("600000", tool.description)
+
+ decision = await tool.check_permissions(
+ {"command": "Get-Location"},
+ PermissionContext(),
+ )
+ self.assertEqual(
+ decision.behavior,
+ PermissionBehavior.ASK,
+ )
+ self.assertFalse(decision.bypass_immune)
+ self.assertEqual(
+ await tool.generate_suggestions(
+ {"command": "Get-Location"},
+ ),
+ [],
+ )
+
+
+class PowerShellExecutionTest(IsolatedAsyncioTestCase):
+ """Test PowerShell command execution through the backend."""
+
+ async def test_call_uses_encoded_command_and_cwd(self) -> None:
+ """Encode commands for PowerShell and pass cwd to the backend."""
+ backend = AsyncMock()
+ backend.exec_shell.side_effect = [
+ ExecResult(0, b"", b""),
+ ExecResult(0, b"ok\r\n", b""),
+ ]
+ tool = PowerShell(cwd="workspace", backend=backend)
+
+ chunks = [
+ chunk
+ async for chunk in await tool(
+ command="Get-Location",
+ )
+ ]
+
+ argv = backend.exec_shell.await_args_list[1].args[0]
+ self.assertEqual(
+ argv[:-1],
+ [
+ "pwsh",
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-EncodedCommand",
+ ],
+ )
+ decoded_command = base64.b64decode(argv[-1]).decode("utf-16-le")
+ encoded_user_command = base64.b64encode(
+ "Get-Location".encode("utf-16-le"),
+ ).decode("ascii")
+ self.assertIn("[Console]::OutputEncoding", decoded_command)
+ self.assertIn(
+ f"FromBase64String('{encoded_user_command}')",
+ decoded_command,
+ )
+ self.assertIn("[ScriptBlock]::Create", decoded_command)
+ self.assertEqual(
+ backend.exec_shell.await_args_list[1].kwargs,
+ {"cwd": "workspace", "timeout": 120.0},
+ )
+ self.assertEqual(chunks[0].content[0].text, "ok\n")
+ self.assertEqual(chunks[0].state, "running")
+
+ async def test_prefers_pwsh_and_caches_resolution(self) -> None:
+ """Probe modern PowerShell once and reuse it for later calls."""
+ backend = AsyncMock()
+ backend.exec_shell.side_effect = [
+ ExecResult(0, b"", b""),
+ ExecResult(0, b"first", b""),
+ ExecResult(0, b"second", b""),
+ ]
+ tool = PowerShell(backend=backend)
+
+ first = [chunk async for chunk in await tool(command="'first'")]
+ second = [chunk async for chunk in await tool(command="'second'")]
+
+ self.assertEqual(first[0].content[0].text, "first")
+ self.assertEqual(second[0].content[0].text, "second")
+ self.assertEqual(backend.exec_shell.await_count, 3)
+ self.assertEqual(
+ [call.args[0][0] for call in backend.exec_shell.await_args_list],
+ ["pwsh", "pwsh", "pwsh"],
+ )
+
+ async def test_falls_back_to_windows_powershell(self) -> None:
+ """Use powershell.exe when pwsh is unavailable."""
+ backend = AsyncMock()
+ backend.exec_shell.side_effect = [
+ ExecResult(127, b"", b"not found"),
+ ExecResult(0, b"", b""),
+ ExecResult(0, b"legacy", b""),
+ ]
+ tool = PowerShell(backend=backend)
+
+ chunks = [chunk async for chunk in await tool(command="'legacy'")]
+
+ self.assertEqual(chunks[0].content[0].text, "legacy")
+ self.assertEqual(
+ [call.args[0][0] for call in backend.exec_shell.await_args_list],
+ ["pwsh", "powershell.exe", "powershell.exe"],
+ )
+
+ async def test_nonzero_exit_returns_error_with_both_streams(self) -> None:
+ """Report stdout and stderr when PowerShell exits unsuccessfully."""
+ backend = AsyncMock()
+ backend.exec_shell.return_value = ExecResult(
+ 3,
+ b"partial\r\n",
+ b"failed\r\n",
+ )
+ tool = PowerShell(backend=backend)
+
+ chunks = [
+ chunk
+ async for chunk in await tool(
+ command="Write-Error 'failed'; exit 3",
+ )
+ ]
+
+ self.assertEqual(chunks[0].state, "error")
+ self.assertEqual(
+ chunks[0].content[0].text,
+ "Command failed: Write-Error 'failed'; exit 3\n"
+ "\nStdout:\npartial\n"
+ "\nStderr:\nfailed\n",
+ )
+
+ async def test_timeout_returns_specific_error(self) -> None:
+ """Translate the backend timeout sentinel into a clear message."""
+ backend = AsyncMock()
+ backend.exec_shell.return_value = ExecResult(
+ -1,
+ b"",
+ b"timed out",
+ )
+ tool = PowerShell(backend=backend)
+
+ chunks = [
+ chunk
+ async for chunk in await tool(
+ command="Start-Sleep -Seconds 5",
+ timeout=100,
+ )
+ ]
+
+ self.assertEqual(chunks[0].state, "error")
+ self.assertEqual(
+ chunks[0].content[0].text,
+ "Command timed out after 100ms: Start-Sleep -Seconds 5",
+ )
+
+ async def test_success_preserves_unicode_and_normalizes_newlines(
+ self,
+ ) -> None:
+ """Decode UTF-8 and normalize CRLF and lone CR line endings."""
+ backend = AsyncMock()
+ backend.exec_shell.return_value = ExecResult(
+ 0,
+ "你好\r\nPowerShell\rAgentScope".encode("utf-8"),
+ b"",
+ )
+ tool = PowerShell(backend=backend)
+
+ chunks = [
+ chunk
+ async for chunk in await tool(
+ command="Write-Output '你好'",
+ )
+ ]
+
+ self.assertEqual(
+ chunks[0].content[0].text,
+ "你好\nPowerShell\nAgentScope",
+ )
+
+ async def test_success_output_is_truncated(self) -> None:
+ """Cap large PowerShell output to the builtin tool limit."""
+ backend = AsyncMock()
+ backend.exec_shell.return_value = ExecResult(
+ 0,
+ b"x" * 30001,
+ b"",
+ )
+ tool = PowerShell(backend=backend)
+
+ chunks = [
+ chunk
+ async for chunk in await tool(
+ command="Write-Output ('x' * 30001)",
+ )
+ ]
+
+ self.assertEqual(
+ chunks[0].content[0].text,
+ "x" * 30000 + "\n... (output truncated)",
+ )
+
+ async def test_success_includes_stderr(self) -> None:
+ """Preserve stderr even when the command exits successfully."""
+ backend = AsyncMock()
+ backend.exec_shell.return_value = ExecResult(
+ 0,
+ b"output",
+ b"warning",
+ )
+ tool = PowerShell(backend=backend)
+
+ chunks = [
+ chunk
+ async for chunk in await tool(
+ command="native-command",
+ )
+ ]
+
+ self.assertEqual(
+ chunks[0].content[0].text,
+ "output\nwarning",
+ )
+
+ async def test_error_output_is_truncated(self) -> None:
+ """Apply the output limit to failed commands as well."""
+ backend = AsyncMock()
+ backend.exec_shell.return_value = ExecResult(
+ 1,
+ b"",
+ b"x" * 30001,
+ )
+ tool = PowerShell(backend=backend)
+
+ chunks = [
+ chunk
+ async for chunk in await tool(
+ command="Write-Error 'x'",
+ )
+ ]
+
+ suffix = "\n... (output truncated)"
+ text = chunks[0].content[0].text
+ self.assertEqual(chunks[0].state, "error")
+ self.assertTrue(text.endswith(suffix))
+ self.assertEqual(len(text), 30000 + len(suffix))
+
+ async def test_backend_exception_returns_error_chunk(self) -> None:
+ """Convert unexpected backend failures into tool errors."""
+ backend = AsyncMock()
+ backend.exec_shell.side_effect = RuntimeError("backend unavailable")
+ tool = PowerShell(backend=backend)
+
+ chunks = [
+ chunk
+ async for chunk in await tool(
+ command="Get-Location",
+ )
+ ]
+
+ self.assertEqual(chunks[0].state, "error")
+ self.assertEqual(
+ chunks[0].content[0].text,
+ "Command failed: Get-Location\nError: backend unavailable",
+ )
+
+ async def test_timeout_is_capped_at_ten_minutes(self) -> None:
+ """Clamp direct calls that exceed the input-schema maximum."""
+ backend = AsyncMock()
+ backend.exec_shell.return_value = ExecResult(0, b"", b"")
+ tool = PowerShell(backend=backend)
+
+ chunks = [
+ chunk
+ async for chunk in await tool(
+ command="Get-Location",
+ timeout=900000,
+ )
+ ]
+
+ self.assertEqual(len(chunks), 1)
+ self.assertEqual(
+ backend.exec_shell.await_args.kwargs["timeout"],
+ 600.0,
+ )
+
+
+ sys.platform == "win32",
+ "Windows PowerShell is only guaranteed on Windows",
+)
+class PowerShellWindowsIntegrationTest(IsolatedAsyncioTestCase):
+ """Smoke-test the real Windows PowerShell executable."""
+
+ async def test_real_powershell_returns_unicode_output(self) -> None:
+ """Execute a Unicode command through LocalBackend end to end."""
+ tool = PowerShell()
+
+ chunks = [
+ chunk
+ async for chunk in await tool(
+ command="Write-Output '你好 AgentScope'",
+ )
+ ]
+
+ self.assertEqual(chunks[0].state, "running")
+ self.assertEqual(
+ chunks[0].content[0].text.strip(),
+ "你好 AgentScope",
+ )
+
+ async def test_real_powershell_handles_script_preamble(self) -> None:
+ """Preserve param blocks, comments, and quoted arguments."""
+ tool = PowerShell()
+
+ chunks = [
+ chunk
+ async for chunk in await tool(
+ command=(
+ "param()\n"
+ "# A leading script comment must not swallow the command\n"
+ 'Write-Output "a b"'
+ ),
+ )
+ ]
+
+ self.assertEqual(chunks[0].state, "running")
+ self.assertEqual(chunks[0].content[0].text.strip(), "a b")
+
+ async def test_real_powershell_preserves_user_line_numbers(self) -> None:
+ """Report line numbers relative to the user's command text."""
+ tool = PowerShell()
+
+ chunks = [
+ chunk
+ async for chunk in await tool(
+ command=(
+ "try {\n"
+ " throw 'boom'\n"
+ "} catch {\n"
+ " Write-Output $_.InvocationInfo.ScriptLineNumber\n"
+ "}"
+ ),
+ )
+ ]
+
+ self.assertEqual(chunks[0].state, "running")
+ self.assertEqual(chunks[0].content[0].text.strip(), "2")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/workspace_local_test.py b/tests/workspace_local_test.py
index 559177aa7..1d6071f34 100644
--- a/tests/workspace_local_test.py
+++ b/tests/workspace_local_test.py
@@ -7,8 +7,10 @@ import base64
import hashlib
import tempfile
from pathlib import Path
+from types import SimpleNamespace
from typing import Any
from unittest.async_case import IsolatedAsyncioTestCase
+from unittest.mock import AsyncMock, patch
from dataclasses import asdict
from urllib.parse import urlparse
from urllib.request import url2pathname
@@ -24,6 +26,7 @@ from agentscope.tool import (
Glob,
Grep,
LocalBackend,
+ PowerShell,
Read,
Toolkit,
ToolBase,
@@ -31,7 +34,7 @@ from agentscope.tool import (
Write,
)
from agentscope.permission import PermissionDecision, PermissionBehavior
-from agentscope.workspace import LocalWorkspace
+from agentscope.workspace import LocalWorkspace, WorkspaceBase
from agentscope.mcp import MCPClient, StdioMCPConfig
from agentscope.message import (
Msg,
@@ -95,13 +98,17 @@ class _LongResultTool(ToolBase):
class TestLocalWorkspaceTools(IsolatedAsyncioTestCase):
"""Test cases for LocalWorkspace builtin tools."""
- async def test_list_tools_builtin(self) -> None:
- """Return all six builtin tools backed by LocalBackend."""
+ 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:
workspace = LocalWorkspace(workdir=workdir)
await workspace.initialize()
try:
- tools = await workspace.list_tools()
+ with patch(
+ "agentscope.workspace._local_workspace.os",
+ SimpleNamespace(name="posix"),
+ ):
+ tools = await workspace.list_tools()
finally:
await workspace.close()
@@ -113,6 +120,51 @@ class TestLocalWorkspaceTools(IsolatedAsyncioTestCase):
for tool in tools:
self.assertIsInstance(tool._backend, LocalBackend)
+ async def test_list_tools_builtin_windows_uses_powershell(self) -> None:
+ """A Windows local workspace returns PowerShell, not Bash."""
+ with tempfile.TemporaryDirectory() as workdir:
+ workspace = LocalWorkspace(workdir=workdir)
+ await workspace.initialize()
+ try:
+ with patch(
+ "agentscope.workspace._local_workspace.os",
+ SimpleNamespace(name="nt"),
+ ):
+ tools = await workspace.list_tools()
+ finally:
+ await workspace.close()
+
+ self.assertEqual(len(tools), 6)
+ self.assertSetEqual(
+ {type(tool) for tool in tools},
+ {PowerShell, Edit, Glob, Grep, Read, Write},
+ )
+ for tool in tools:
+ self.assertIsInstance(tool._backend, LocalBackend)
+
+ async def test_windows_shell_switch_is_local_workspace_behavior(
+ self,
+ ) -> None:
+ """Build the tool list in LocalWorkspace without delegating up."""
+ workspace = LocalWorkspace(workdir="workspace")
+ backend = workspace.get_backend()
+
+ with (
+ patch.object(
+ WorkspaceBase,
+ "list_tools",
+ new=AsyncMock(side_effect=AssertionError("must not delegate")),
+ ),
+ patch(
+ "agentscope.workspace._local_workspace.os",
+ SimpleNamespace(name="nt"),
+ ),
+ ):
+ tools = await workspace.list_tools()
+
+ self.assertIsInstance(tools[0], PowerShell)
+ self.assertIs(tools[0]._backend, backend)
+
class TestLocalWorkspaceOffload(IsolatedAsyncioTestCase):
"""Test cases for LocalWorkspace offload functionality."""