Datasets:
Download src/tools.py from tesraghavan/agent-trace: direct link, hf CLI and curl.
- Browser
- Download file 4.29 kB
-
https://huggingface.co/datasets/tesraghavan/agent-trace/resolve/main/src/tools.py
- Command line
-
hf download hf://datasets/tesraghavan/agent-trace/src/tools.py
-
curl -L -o tools.py https://huggingface.co/datasets/tesraghavan/agent-trace/resolve/main/src/tools.py
4.29 kB
| """Custom tools for the agent.""" | |
| import re | |
| import subprocess | |
| from pathlib import Path | |
| from smolagents import Tool | |
| VIRTUAL_TESTDATA_ROOT = "/testdata" | |
| # Patterns that could escape the sandbox even with cwd restriction. | |
| # Matches absolute paths outside the allowed directory and common escape tricks. | |
| _DANGEROUS_PATTERNS = [ | |
| re.compile(r"\.\./"), # directory traversal | |
| re.compile(r"\bcd\s+/"), # cd to absolute path | |
| re.compile(r"\brm\s+-[rf]*\s+/"), # rm with absolute path | |
| re.compile(r"\bmv\s+.+\s+/"), # mv to absolute path | |
| re.compile(r"\bcp\s+.+\s+/"), # cp to absolute path | |
| re.compile(r">\s*/"), # redirect to absolute path | |
| re.compile(r"\bchmod\b.*\s+/"), # chmod on absolute path | |
| re.compile(r"\bchown\b.*\s+/"), # chown on absolute path | |
| re.compile(r"\bsudo\b"), # privilege escalation | |
| re.compile(r"\bcurl\b"), # network access | |
| re.compile(r"\bwget\b"), # network access | |
| ] | |
| def _is_command_safe(command: str, allowed_dir: Path) -> str | None: | |
| """Check if a command is safe to execute. Returns an error message if not, None if safe.""" | |
| allowed = str(allowed_dir.resolve()) | |
| for pattern in _DANGEROUS_PATTERNS: | |
| if pattern.search(command): | |
| return f"Command blocked: matches dangerous pattern '{pattern.pattern}'" | |
| # Block absolute paths that point outside the allowed directory. | |
| # Find all absolute paths in the command (sequences starting with /). | |
| abs_paths = re.findall(r"(?<![\w./-])(/[^\s;|&>'\"]+)", command) | |
| for p in abs_paths: | |
| try: | |
| resolved = str(Path(p).resolve()) | |
| except (OSError, ValueError): | |
| continue | |
| if not resolved.startswith(allowed): | |
| return f"Command blocked: path '{p}' is outside allowed directory '{allowed}'" | |
| return None | |
| class BashTool(Tool): | |
| """Execute bash commands in a sandboxed directory.""" | |
| name = "bash" | |
| description = ( | |
| "Execute a bash command in the shell and return its output. " | |
| "Use this for file operations, running CLI tools like ripgrep (rg), " | |
| "listing directories, and other shell commands. " | |
| "Returns the exit code, stdout, and stderr. " | |
| "When sandboxed, commands are restricted to the testdata directory " | |
| f"and may refer to it via the virtual root {VIRTUAL_TESTDATA_ROOT}." | |
| ) | |
| inputs = { | |
| "command": { | |
| "type": "string", | |
| "description": "The bash command to execute", | |
| } | |
| } | |
| output_type = "string" | |
| def __init__(self, timeout: int = 30, allowed_dir: Path | None = None): | |
| super().__init__() | |
| self.timeout = timeout | |
| self.allowed_dir = allowed_dir | |
| def _translate_virtual_paths(self, command: str) -> str: | |
| """Map the virtual /testdata root to the sandbox working directory.""" | |
| if self.allowed_dir is None: | |
| return command | |
| return re.sub(r"(?<![\w/])/testdata(?=/|\b)", ".", command) | |
| def forward(self, command: str) -> str: | |
| """Execute the command and return formatted output.""" | |
| cwd = None | |
| translated_command = command | |
| if self.allowed_dir is not None: | |
| translated_command = self._translate_virtual_paths(command) | |
| error = _is_command_safe(translated_command, self.allowed_dir) | |
| if error: | |
| return f"exit_code: -1\nstderr:\n{error}" | |
| cwd = str(self.allowed_dir) | |
| try: | |
| result = subprocess.run( | |
| translated_command, | |
| shell=True, | |
| capture_output=True, | |
| text=True, | |
| timeout=self.timeout, | |
| cwd=cwd, | |
| ) | |
| output = f"exit_code: {result.returncode}\n" | |
| if result.stdout: | |
| output += f"stdout:\n{result.stdout}\n" | |
| if result.stderr: | |
| output += f"stderr:\n{result.stderr}\n" | |
| return output.strip() | |
| except subprocess.TimeoutExpired: | |
| return f"exit_code: -1\nstderr:\nCommand timed out after {self.timeout}s" | |
| except Exception as e: | |
| return f"exit_code: -1\nstderr:\nError executing command: {e}" | |