|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | +from typing import ClassVar, Literal |
| 4 | + |
| 5 | +from anthropic.types.beta import BetaToolBash20241022Param |
| 6 | + |
| 7 | +from .base import BaseAnthropicTool, CLIResult, ToolError, ToolResult |
| 8 | + |
| 9 | +print("Using simple bash tool") |
| 10 | + |
| 11 | + |
| 12 | +class BashTool(BaseAnthropicTool): |
| 13 | + """A tool that executes bash commands and returns their output.""" |
| 14 | + |
| 15 | + name: ClassVar[Literal["bash"]] = "bash" |
| 16 | + api_type: ClassVar[Literal["bash_20241022"]] = "bash_20241022" |
| 17 | + |
| 18 | + async def __call__( |
| 19 | + self, command: str | None = None, restart: bool = False, **kwargs |
| 20 | + ): |
| 21 | + if not command: |
| 22 | + raise ToolError("no command provided") |
| 23 | + |
| 24 | + try: |
| 25 | + # Create process with shell=True to handle all bash features properly |
| 26 | + process = await asyncio.create_subprocess_shell( |
| 27 | + command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE |
| 28 | + ) |
| 29 | + |
| 30 | + try: |
| 31 | + stdout, stderr = await asyncio.wait_for( |
| 32 | + process.communicate(), timeout=300 |
| 33 | + ) |
| 34 | + |
| 35 | + # Decode and combine output |
| 36 | + output = stdout.decode() + stderr.decode() |
| 37 | + |
| 38 | + # Print output |
| 39 | + print(output, end="", flush=True) |
| 40 | + |
| 41 | + # Return combined output |
| 42 | + return CLIResult(output=output if output else "<No output>") |
| 43 | + |
| 44 | + except asyncio.TimeoutError: |
| 45 | + process.kill() |
| 46 | + msg = "Command timed out after 5 minutes" |
| 47 | + print(msg) |
| 48 | + return ToolResult(error=msg) |
| 49 | + |
| 50 | + except Exception as e: |
| 51 | + msg = f"Failed to run command: {str(e)}" |
| 52 | + print(msg) |
| 53 | + return ToolResult(error=msg) |
| 54 | + |
| 55 | + def to_params(self) -> BetaToolBash20241022Param: |
| 56 | + return { |
| 57 | + "type": self.api_type, |
| 58 | + "name": self.name, |
| 59 | + } |
0 commit comments