|
| 1 | +import asyncio |
| 2 | +import contextlib |
| 3 | +import sys |
| 4 | + |
| 5 | +from loguru import logger |
| 6 | + |
| 7 | +from dreadnode.agent.tools.base import tool |
| 8 | + |
| 9 | + |
| 10 | +@tool(catch=True) |
| 11 | +async def command( |
| 12 | + cmd: list[str], |
| 13 | + *, |
| 14 | + timeout: int = 120, |
| 15 | + cwd: str | None = None, |
| 16 | + env: dict[str, str] | None = None, |
| 17 | +) -> str: |
| 18 | + """ |
| 19 | + Execute a shell command. |
| 20 | +
|
| 21 | + Use this tool to run system utilities and command-line programs (e.g., `ls`, `cat`, `grep`). \ |
| 22 | + It is designed for straightforward, single-shot operations and returns the combined output and error streams. |
| 23 | +
|
| 24 | + ## Best Practices |
| 25 | + - Argument Format: The command and its arguments *must* be provided as a \ |
| 26 | + list of strings (e.g., `["ls", "-la", "/tmp"]`), not as a single string. |
| 27 | + - No Shell Syntax: Does not use a shell. Features like pipes (`|`), \ |
| 28 | + redirection (`>`), and variable expansion (`$VAR`) are not supported. |
| 29 | + - Error on Failure: The tool will raise a `RuntimeError` if the command returns a non-zero exit code. |
| 30 | +
|
| 31 | + Args: |
| 32 | + cmd: The command to execute, provided as a list of strings. |
| 33 | + timeout: Maximum time in seconds to allow for command execution. |
| 34 | + cwd: The working directory in which to execute the command. |
| 35 | + env: Optional environment variables to set for the command. |
| 36 | + """ |
| 37 | + try: |
| 38 | + command_str = " ".join(cmd) |
| 39 | + logger.debug(f"Executing '{command_str}'") |
| 40 | + proc = await asyncio.create_subprocess_exec( |
| 41 | + *cmd, |
| 42 | + stdout=asyncio.subprocess.PIPE, |
| 43 | + stderr=asyncio.subprocess.PIPE, |
| 44 | + env=env, |
| 45 | + cwd=cwd, |
| 46 | + ) |
| 47 | + stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout) |
| 48 | + output = stdout.decode() + stderr.decode() |
| 49 | + except asyncio.TimeoutError as e: |
| 50 | + logger.warning(f"Command '{command_str}' timed out after {timeout} seconds.") |
| 51 | + with contextlib.suppress(OSError): |
| 52 | + proc.kill() |
| 53 | + raise TimeoutError(f"Command timed out after {timeout} seconds") from e |
| 54 | + except Exception as e: |
| 55 | + logger.error(f"Error executing '{command_str}': {e}") |
| 56 | + raise |
| 57 | + |
| 58 | + if proc.returncode != 0: |
| 59 | + logger.error(f"Command '{command_str}' failed with return code {proc.returncode}: {output}") |
| 60 | + raise RuntimeError(f"Command failed ({proc.returncode}): {output}") |
| 61 | + |
| 62 | + logger.debug(f"Command '{command_str}':\n{output}") |
| 63 | + return output |
| 64 | + |
| 65 | + |
| 66 | +@tool(catch=True) |
| 67 | +async def python(code: str, *, timeout: int = 120) -> str: |
| 68 | + """ |
| 69 | + Execute Python code. |
| 70 | +
|
| 71 | + This tool is ideal for tasks that require custom logic like loops and conditionals, \ |
| 72 | + or for parsing and transforming the output from other tools. Use it to implement a \ |
| 73 | + sequence of actions, perform file I/O, or create functionality not covered by other \ |
| 74 | + available tools. |
| 75 | +
|
| 76 | + ## Best Practices |
| 77 | + - Capture Output: Your script *must* print results to standard output (`print(...)`) to be captured. |
| 78 | + - Self-Contained: Import all required standard libraries (e.g., `os`, `json`) within the script. |
| 79 | + - Handle Errors: Write robust code. Unhandled exceptions in your script will cause the tool to fail. |
| 80 | + - String-Based I/O: Ensure all printed output can be represented as a string. Use formats like JSON (`json.dumps`) for complex data. |
| 81 | +
|
| 82 | + Args: |
| 83 | + code: The Python code to execute as a string. |
| 84 | + timeout: Maximum time in seconds to allow for code execution. |
| 85 | + """ |
| 86 | + try: |
| 87 | + logger.debug(f"Executing python:\n{code}") |
| 88 | + proc = await asyncio.create_subprocess_exec( |
| 89 | + *[sys.executable, "-"], |
| 90 | + stdin=asyncio.subprocess.PIPE, |
| 91 | + stdout=asyncio.subprocess.PIPE, |
| 92 | + stderr=asyncio.subprocess.PIPE, |
| 93 | + ) |
| 94 | + stdout, stderr = await asyncio.wait_for( |
| 95 | + proc.communicate(input=code.encode("utf-8")), timeout=timeout |
| 96 | + ) |
| 97 | + output = stdout.decode(errors="ignore") + stderr.decode(errors="ignore") |
| 98 | + except asyncio.TimeoutError as e: |
| 99 | + with contextlib.suppress(ProcessLookupError): |
| 100 | + proc.kill() |
| 101 | + raise TimeoutError(f"Execution timed out after {timeout} seconds") from e |
| 102 | + except Exception as e: |
| 103 | + logger.error(f"Error executing code in Python: {e}") |
| 104 | + raise |
| 105 | + |
| 106 | + if proc.returncode != 0: |
| 107 | + logger.error(f"Execution failed with return code {proc.returncode}:\n{output}") |
| 108 | + raise RuntimeError(f"Execution failed ({proc.returncode}):\n{output}") |
| 109 | + |
| 110 | + logger.debug(f"Execution successful. Output:\n{output}") |
| 111 | + return output |
0 commit comments