Execute shell command with optional background execution. Args: command: The shell command to execute timeout: Timeout in seconds (default: 120, max: 600) run_in_background: Set true to run command in background Returns: BashExecution
(
self,
command: str,
timeout: int = 120,
run_in_background: bool = False,
)
| 307 | } |
| 308 | |
| 309 | async def execute( |
| 310 | self, |
| 311 | command: str, |
| 312 | timeout: int = 120, |
| 313 | run_in_background: bool = False, |
| 314 | ) -> ToolResult: |
| 315 | """Execute shell command with optional background execution. |
| 316 | |
| 317 | Args: |
| 318 | command: The shell command to execute |
| 319 | timeout: Timeout in seconds (default: 120, max: 600) |
| 320 | run_in_background: Set true to run command in background |
| 321 | |
| 322 | Returns: |
| 323 | BashExecutionResult with command output and status |
| 324 | """ |
| 325 | |
| 326 | try: |
| 327 | # Validate timeout |
| 328 | if timeout > 600: |
| 329 | timeout = 600 |
| 330 | elif timeout < 1: |
| 331 | timeout = 120 |
| 332 | |
| 333 | # Prepare shell-specific command execution |
| 334 | if self.is_windows: |
| 335 | # Windows: Use PowerShell with appropriate encoding |
| 336 | shell_cmd = ["powershell.exe", "-NoProfile", "-Command", command] |
| 337 | else: |
| 338 | # Unix/Linux/macOS: Use bash |
| 339 | shell_cmd = command |
| 340 | |
| 341 | if run_in_background: |
| 342 | # Background execution: Create isolated process |
| 343 | bash_id = str(uuid.uuid4())[:8] |
| 344 | |
| 345 | # Start background process with combined stdout/stderr |
| 346 | if self.is_windows: |
| 347 | process = await asyncio.create_subprocess_exec( |
| 348 | *shell_cmd, |
| 349 | stdout=asyncio.subprocess.PIPE, |
| 350 | stderr=asyncio.subprocess.STDOUT, |
| 351 | cwd=self.workspace_dir, |
| 352 | ) |
| 353 | else: |
| 354 | process = await asyncio.create_subprocess_shell( |
| 355 | shell_cmd, |
| 356 | stdout=asyncio.subprocess.PIPE, |
| 357 | stderr=asyncio.subprocess.STDOUT, |
| 358 | cwd=self.workspace_dir, |
| 359 | ) |
| 360 | |
| 361 | # Create background shell and add to manager |
| 362 | bg_shell = BackgroundShell(bash_id=bash_id, command=command, process=process, start_time=time.time()) |
| 363 | BackgroundShellManager.add(bg_shell) |
| 364 | |
| 365 | # Start monitoring task |
| 366 | await BackgroundShellManager.start_monitor(bash_id) |