diff options
Diffstat (limited to 'src/agentux/tools')
| -rw-r--r-- | src/agentux/tools/__init__.py | 15 | ||||
| -rw-r--r-- | src/agentux/tools/base.py | 51 | ||||
| -rw-r--r-- | src/agentux/tools/filesystem.py | 401 | ||||
| -rw-r--r-- | src/agentux/tools/project.py | 236 | ||||
| -rw-r--r-- | src/agentux/tools/registry.py | 56 | ||||
| -rw-r--r-- | src/agentux/tools/shell.py | 187 |
6 files changed, 946 insertions, 0 deletions
diff --git a/src/agentux/tools/__init__.py b/src/agentux/tools/__init__.py new file mode 100644 index 0000000..03cd0f9 --- /dev/null +++ b/src/agentux/tools/__init__.py @@ -0,0 +1,15 @@ +"""Built-in tools.""" + +from .base import BaseTool +from .filesystem import FilesystemTool +from .project import ProjectTool +from .registry import ToolRegistry +from .shell import ShellTool + +__all__ = [ + "BaseTool", + "FilesystemTool", + "ProjectTool", + "ShellTool", + "ToolRegistry", +] diff --git a/src/agentux/tools/base.py b/src/agentux/tools/base.py new file mode 100644 index 0000000..5c13069 --- /dev/null +++ b/src/agentux/tools/base.py @@ -0,0 +1,51 @@ +"""Tool interface. + +A tool is anything the agent can run on the model's behalf. The model only +ever sees a tool's name, description, and JSON Schema -- it addresses tools by +name, and the registry decides what actually runs. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import Any, Dict + +from ..models import ToolDefinition + + +class BaseTool(ABC): + """Abstract base class for all Agentux tools.""" + + @property + @abstractmethod + def name(self) -> str: + """The unique name the model uses to call this tool.""" + + @property + @abstractmethod + def description(self) -> str: + """A description of what the tool does, used for the LLM prompt.""" + + @property + @abstractmethod + def parameters(self) -> Dict[str, Any]: + """JSON Schema defining the tool's input parameters.""" + + @abstractmethod + async def execute(self, **kwargs: Any) -> str: + """Run the tool and return its result as text. + + Raise ``ToolError`` to report failure; the agent turns the message into + tool output so the model can recover instead of aborting the run. + """ + + def to_definition(self) -> ToolDefinition: + """Describe this tool in the shape providers expect.""" + return ToolDefinition( + name=self.name, + description=self.description, + parameters=self.parameters, + ) + + +__all__ = ["BaseTool"] diff --git a/src/agentux/tools/filesystem.py b/src/agentux/tools/filesystem.py new file mode 100644 index 0000000..6a9acc0 --- /dev/null +++ b/src/agentux/tools/filesystem.py @@ -0,0 +1,401 @@ +"""Filesystem tool. + +Every path is resolved against a workspace root and rejected if it escapes +it, so a confused or adversarial model cannot wander into ``/etc`` or +``~/.ssh``. Reads are size-capped and writes report a real diff so the agent +does not blindly clobber files. +""" + +from __future__ import annotations + +import difflib +import os +import shutil +from pathlib import Path +from typing import Any, Dict, List, Optional + +from ..errors import ToolError +from .base import BaseTool + +#: Reads larger than this are truncated rather than dumped into the context. +MAX_READ_BYTES = 400_000 +#: Directory listings are capped so the model gets a summary, not a firehose. +MAX_LIST_ENTRIES = 500 +#: Directories that are noise in almost every project. +SKIP_DIRS = { + ".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv", + ".mypy_cache", ".pytest_cache", ".ruff_cache", ".tox", "dist", "build", + ".idea", ".vscode", "target", ".next", ".gradle", +} + +_OPERATIONS = ["ls", "read", "write", "edit", "mkdir", "rm", "mv", "glob"] + + +class FilesystemTool(BaseTool): + """Read and modify files inside the workspace.""" + + def __init__(self, root: Optional[str] = None, read_only: bool = False) -> None: + self.root = Path(root or os.getcwd()).resolve() + self.read_only = read_only + + @property + def name(self) -> str: + return "filesystem" + + @property + def description(self) -> str: + return ( + "Read and modify files in the workspace. Prefer 'edit' over 'write' " + "when changing part of an existing file, since edit only replaces " + "the exact text you target and leaves the rest untouched. " + "Paths may be absolute or relative to the workspace root." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "operation": { + "type": "string", + "enum": _OPERATIONS, + "description": "The filesystem operation to perform.", + }, + "path": { + "type": "string", + "description": "Path to the file or directory, absolute or relative to the root.", + }, + "content": { + "type": "string", + "description": "Full new content. Required for 'write'.", + }, + "old_string": { + "type": "string", + "description": ( + "Exact existing text to replace. Required for 'edit'. " + "Must appear exactly once." + ), + }, + "new_string": { + "type": "string", + "description": "Replacement text for 'edit'. Use an empty string to delete.", + }, + "destination": { + "type": "string", + "description": "Destination path. Required for 'mv'.", + }, + "pattern": { + "type": "string", + "description": "Glob pattern such as '**/*.py'. Used by 'glob'.", + }, + }, + "required": ["operation", "path"], + } + + # ------------------------------------------------------------------ + # Path handling + # ------------------------------------------------------------------ + def _resolve(self, path: str) -> Path: + """Resolve ``path`` inside the workspace, or raise. + + Uses ``Path.resolve`` (which collapses ``..`` symlinks and relative + segments) *before* the containment check, so neither ``../../etc`` nor + a symlink pointing outside the root can escape. + """ + if not path or not str(path).strip(): + raise ToolError("A non-empty 'path' is required.") + candidate = Path(str(path).strip()).expanduser() + resolved = (candidate if candidate.is_absolute() else self.root / candidate).resolve() + try: + resolved.relative_to(self.root) + except ValueError: + raise ToolError( + f"Path {str(path)!r} is outside the workspace root {str(self.root)!r}. " + "Agentux only touches files inside the workspace." + ) from None + return resolved + + def _relative(self, path: Path) -> str: + try: + rel = path.relative_to(self.root) + except ValueError: + return str(path) + return str(rel) if str(rel) != "." else "." + + def _require_writable(self) -> None: + if self.read_only: + raise ToolError( + "This filesystem tool is read-only. Files cannot be created, " + "modified, moved, or deleted." + ) + + # ------------------------------------------------------------------ + # Operations + # ------------------------------------------------------------------ + def _ls(self, target: Path, show_all: bool) -> str: + if not target.exists(): + raise ToolError(f"Path does not exist: {self._relative(target)}") + if not target.is_dir(): + raise ToolError(f"Path is not a directory: {self._relative(target)}") + try: + entries = sorted(target.iterdir(), key=lambda p: (not p.is_dir(), p.name.lower())) + except PermissionError as exc: + raise ToolError( + f"Permission denied listing {self._relative(target)}: {exc}" + ) from exc + + lines: List[str] = [] + hidden = 0 + for entry in entries: + if entry.name.startswith(".") and not show_all: + hidden += 1 + continue + if entry.is_dir(): + lines.append(f"{entry.name}/") + elif entry.is_symlink(): + lines.append(f"{entry.name} -> (symlink)") + else: + try: + size = entry.stat().st_size + except OSError: + size = 0 + lines.append(f"{entry.name} ({size} bytes)") + if len(lines) >= MAX_LIST_ENTRIES: + lines.append(f"... truncated at {MAX_LIST_ENTRIES} entries") + break + + if hidden: + lines.append(f"({hidden} hidden entries omitted)") + header = f"{self._relative(target)}/ - {len(entries)} entries" + return header + "\n" + ("\n".join(lines) if lines else "(empty)") + + def _read(self, target: Path) -> str: + if not target.exists(): + raise ToolError(f"File does not exist: {self._relative(target)}") + if target.is_dir(): + raise ToolError( + f"{self._relative(target)} is a directory, not a file. " + "Use the 'ls' operation to list it." + ) + try: + size = target.stat().st_size + except OSError as exc: + raise ToolError(f"Cannot stat {self._relative(target)}: {exc}") from exc + + try: + data = target.read_bytes() + except PermissionError as exc: + raise ToolError( + f"Permission denied reading {self._relative(target)}: {exc}" + ) from exc + except OSError as exc: + raise ToolError(f"Failed to read {self._relative(target)}: {exc}") from exc + + text = data.decode("utf-8", errors="replace") + if size > MAX_READ_BYTES: + return ( + text[:MAX_READ_BYTES] + + f"\n\n... [truncated: file is {size} bytes, showing first " + f"{MAX_READ_BYTES}. Use 'grep' via the shell tool to search it.]" + ) + return text + + def _write(self, target: Path, content: str) -> str: + existed = target.exists() + if target.is_dir(): + raise ToolError( + f"{self._relative(target)} is a directory, not a file." + ) + try: + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + except PermissionError as exc: + raise ToolError( + f"Permission denied writing {self._relative(target)}: {exc}" + ) from exc + except OSError as exc: + raise ToolError(f"Failed to write {self._relative(target)}: {exc}") from exc + + verb = "Overwrote" if existed else "Created" + return f"{verb} {self._relative(target)} ({len(content)} bytes)." + + def _edit(self, target: Path, old: str, new: str) -> str: + if not target.exists(): + raise ToolError( + f"Cannot edit {self._relative(target)}: the file does not exist. " + "Use the 'write' operation to create it." + ) + if target.is_dir(): + raise ToolError(f"{self._relative(target)} is a directory, not a file.") + + content = self._read(target) + if not old: + raise ToolError( + "'old_string' is required for the 'edit' operation and cannot be empty." + ) + + occurrences = content.count(old) + if occurrences == 0: + preview = old if len(old) <= 200 else old[:200] + "..." + raise ToolError( + f"'old_string' was not found in {self._relative(target)}. " + f"Read the file again and copy the exact text to replace.\n" + f"Searched for: {preview!r}" + ) + if occurrences > 1: + raise ToolError( + f"'old_string' appears {occurrences} times in " + f"{self._relative(target)}, so the edit would be ambiguous. " + "Include more surrounding context to make it unique." + ) + + updated = content.replace(old, new, 1) + try: + target.write_text(updated, encoding="utf-8") + except PermissionError as exc: + raise ToolError( + f"Permission denied writing {self._relative(target)}: {exc}" + ) from exc + + diff = list( + difflib.unified_diff( + content.splitlines(keepends=True), + updated.splitlines(keepends=True), + fromfile=f"a/{self._relative(target)}", + tofile=f"b/{self._relative(target)}", + n=2, + ) + ) + report = "".join(diff[:200]) + if len(diff) > 200: + report += f"\n... [diff truncated, {len(diff)} lines total]" + return f"Edited {self._relative(target)}.\n{report}".rstrip() + + def _mkdir(self, target: Path) -> str: + if target.exists(): + if target.is_dir(): + return f"Directory already exists: {self._relative(target)}" + raise ToolError( + f"Cannot create directory {self._relative(target)}: a file with " + "that name already exists." + ) + try: + target.mkdir(parents=True, exist_ok=True) + except PermissionError as exc: + raise ToolError( + f"Permission denied creating {self._relative(target)}: {exc}" + ) from exc + except OSError as exc: + raise ToolError( + f"Failed to create directory {self._relative(target)}: {exc}" + ) from exc + return f"Created directory {self._relative(target)}." + + def _rm(self, target: Path) -> str: + if not target.exists() and not target.is_symlink(): + raise ToolError(f"Path does not exist: {self._relative(target)}") + if target == self.root: + raise ToolError("Refusing to delete the workspace root.") + try: + if target.is_dir() and not target.is_symlink(): + shutil.rmtree(target) + else: + target.unlink() + except PermissionError as exc: + raise ToolError( + f"Permission denied deleting {self._relative(target)}: {exc}" + ) from exc + return f"Deleted {self._relative(target)}." + + def _mv(self, source: Path, destination: str) -> str: + if not source.exists(): + raise ToolError(f"Path does not exist: {self._relative(source)}") + dest = self._resolve(destination) + if dest == self.root: + raise ToolError("Cannot move onto the workspace root.") + if dest.exists(): + raise ToolError( + f"Destination already exists: {self._relative(dest)}. " + "Remove it first or choose another path." + ) + try: + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(source), str(dest)) + except OSError as exc: + raise ToolError( + f"Failed to move {self._relative(source)} to " + f"{self._relative(dest)}: {exc}" + ) from exc + return f"Moved {self._relative(source)} -> {self._relative(dest)}." + + def _glob(self, target: Path, pattern: str) -> str: + if not target.is_dir(): + raise ToolError( + f"{self._relative(target)} is not a directory, so 'glob' cannot " + "search it. Use 'ls'." + ) + if not pattern: + raise ToolError("'pattern' is required for the 'glob' operation.") + matches: List[str] = [] + for path in sorted(target.glob(pattern)): + rel = self._relative(path) + if any(part in SKIP_DIRS for part in path.relative_to(self.root).parts[:-1]): + continue + matches.append(rel) + if len(matches) >= MAX_LIST_ENTRIES: + matches.append(f"... truncated at {MAX_LIST_ENTRIES} matches") + break + if not matches: + return f"No files matching {pattern!r} under {self._relative(target)}." + return f"{len(matches)} match(es) for {pattern!r}:\n" + "\n".join(matches) + + # ------------------------------------------------------------------ + async def execute( + self, + operation: str, + path: str, + content: Optional[str] = None, + old_string: Optional[str] = None, + new_string: Optional[str] = None, + destination: Optional[str] = None, + pattern: Optional[str] = None, + show_all: bool = False, + **kwargs: Any, + ) -> str: + if operation not in _OPERATIONS: + raise ToolError( + f"Unsupported operation {operation!r}. Use one of: {', '.join(_OPERATIONS)}." + ) + target = self._resolve(path) + + read_only_ops = {"ls", "read", "glob"} + if operation not in read_only_ops: + self._require_writable() + + if operation == "ls": + return self._ls(target, show_all) + if operation == "read": + return self._read(target) + if operation == "write": + if content is None: + raise ToolError("'content' is required for the 'write' operation.") + return self._write(target, content) + if operation == "edit": + if old_string is None or new_string is None: + raise ToolError( + "'old_string' and 'new_string' are both required for the " + "'edit' operation." + ) + return self._edit(target, old_string, new_string) + if operation == "mkdir": + return self._mkdir(target) + if operation == "rm": + return self._rm(target) + if operation == "mv": + if not destination: + raise ToolError("'destination' is required for the 'mv' operation.") + return self._mv(target, destination) + return self._glob(target, pattern or "") + + +__all__ = ["FilesystemTool"] diff --git a/src/agentux/tools/project.py b/src/agentux/tools/project.py new file mode 100644 index 0000000..4141078 --- /dev/null +++ b/src/agentux/tools/project.py @@ -0,0 +1,236 @@ +"""Project awareness. + +Gives the model a compact map of a repository -- what kind of project it is, +which files matter, what the test layout looks like -- without reading the +whole tree. Inspection is targeted and depth-limited on purpose. +""" + +from __future__ import annotations + +import os +from typing import Any, Dict, List, Optional + +from ..errors import ToolError +from .base import BaseTool + +#: Files that identify a project and its dependencies. +MANIFESTS = { + "pyproject.toml": "Python (pyproject)", + "setup.py": "Python (setup.py)", + "requirements.txt": "Python requirements", + "package.json": "Node/TypeScript", + "Cargo.toml": "Rust", + "go.mod": "Go", + "pom.xml": "Java (Maven)", + "build.gradle": "Java/Kotlin (Gradle)", + "Gemfile": "Ruby", + "composer.json": "PHP", + "CMakeLists.txt": "C/C++ (CMake)", +} + +#: Other files worth surfacing during orientation. +SIGNALS = [ + "README.md", "README.rst", "README.txt", "Makefile", "Justfile", + "Dockerfile", "docker-compose.yml", ".gitignore", "LICENSE", "CHANGELOG.md", +] + +#: Directories that usually hold the interesting source. +SOURCE_DIRS = ["src", "lib", "app", "pkg", "internal", "cmd", "tests", "test", "spec"] + +#: Directories that are noise in essentially every repository. +SKIP_DIRS = { + ".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv", + ".mypy_cache", ".pytest_cache", ".ruff_cache", ".tox", "dist", "build", + ".idea", ".vscode", "target", ".next", ".gradle", ".cache", "site-packages", +} + +MAX_DEPTH = 3 +MAX_ENTRIES_PER_DIR = 40 + + +class ProjectTool(BaseTool): + """Summarize the layout and conventions of the current project.""" + + def __init__(self, root: Optional[str] = None) -> None: + self.root = os.path.realpath(root or os.getcwd()) + + @property + def name(self) -> str: + return "project" + + @property + def description(self) -> str: + return ( + "Inspect the current repository: identify the language and build " + "system, list the directory structure, and show entry points, test " + "locations, and tracked files. Use this once at the start of a task " + "to orient yourself, then use the filesystem and shell tools for " + "details. Do not read the whole repository -- this returns a map." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": ["overview", "tree", "tracked"], + "description": ( + "overview: project type, key files, source and test dirs. " + "tree: directory structure to a limited depth. " + "tracked: list files tracked by git." + ), + }, + "path": { + "type": "string", + "description": "Subdirectory to inspect. Defaults to the project root.", + }, + "max_depth": { + "type": "integer", + "description": "Depth limit for the 'tree' action. Defaults to 3.", + }, + }, + "required": ["action"], + } + + def _base(self, path: Optional[str]) -> str: + if not path: + return self.root + candidate = path if os.path.isabs(path) else os.path.join(self.root, path) + resolved = os.path.realpath(os.path.expanduser(candidate)) + if not os.path.isdir(resolved): + raise ToolError(f"Not a directory: {path}") + return resolved + + def _overview(self, base: str) -> str: + lines: List[str] = [f"Project root: {self.root}"] + + try: + entries = sorted(os.listdir(base)) + except PermissionError as exc: + raise ToolError(f"Permission denied reading {base}: {exc}") from exc + + kinds = [label for name, label in MANIFESTS.items() if name in entries] + if kinds: + lines.append(f"Type: {', '.join(sorted(set(kinds)))}") + else: + lines.append("Type: unknown (no recognised manifest file at the root)") + + found_signals = [name for name in SIGNALS if name in entries] + if found_signals: + lines.append(f"Key files: {', '.join(found_signals)}") + + sources = [ + d for d in SOURCE_DIRS + if os.path.isdir(os.path.join(base, d)) and d not in SKIP_DIRS + ] + if sources: + lines.append(f"Source/test directories: {', '.join(sources)}") + + script_dirs = [] + package_json = os.path.join(base, "package.json") + if os.path.isfile(package_json): + try: + import json + + with open(package_json, encoding="utf-8") as handle: + data = json.load(handle) + script_dirs = sorted((data.get("scripts") or {}).keys()) + except Exception: + script_dirs = [] + if script_dirs: + lines.append(f"npm scripts: {', '.join(script_dirs)}") + + lines.append("") + lines.append("Top level:") + for entry in entries[:MAX_ENTRIES_PER_DIR]: + if entry in SKIP_DIRS: + continue + full = os.path.join(base, entry) + suffix = "/" if os.path.isdir(full) else "" + lines.append(f" {entry}{suffix}") + return "\n".join(lines) + + def _tree(self, base: str, max_depth: int) -> str: + depth_limit = max(1, min(int(max_depth or MAX_DEPTH), 6)) + lines: List[str] = [] + total = 0 + + def walk(directory: str, prefix: str, depth: int) -> None: + nonlocal total + if depth > depth_limit or total > 500: + return + try: + entries = sorted(os.listdir(directory)) + except PermissionError: + lines.append(f"{prefix}[permission denied]") + return + visible = [e for e in entries if e not in SKIP_DIRS] + hidden = len(entries) - len(visible) + for index, entry in enumerate(visible): + if total > 500: + lines.append(f"{prefix}...") + return + total += 1 + full = os.path.join(directory, entry) + last = index == len(visible) - 1 and not hidden + branch = "└── " if last else "├── " + if os.path.isdir(full): + lines.append(f"{prefix}{branch}{entry}/") + walk(full, prefix + (" " if last else "│ "), depth + 1) + else: + lines.append(f"{prefix}{branch}{entry}") + if hidden: + lines.append(f"{prefix}└── ... ({hidden} hidden or generated entries omitted)") + + lines.append(f"{os.path.relpath(base, self.root) or '.'}/ (depth {depth_limit})") + walk(base, "", 1) + return "\n".join(lines) + + def _tracked(self, base: str) -> str: + import subprocess + + try: + result = subprocess.run( + ["git", "ls-files"], + cwd=base, capture_output=True, text=True, timeout=15, + ) + except FileNotFoundError: + raise ToolError("git is not available on this system.") from None + except subprocess.TimeoutExpired: + raise ToolError("git ls-files timed out.") from None + + if result.returncode != 0: + raise ToolError( + f"This directory is not a git repository (or git failed): " + f"{result.stderr.strip() or 'no output'}" + ) + files = [f for f in result.stdout.splitlines() if f.strip()] + if not files: + return "No tracked files (the repository is empty)." + listing = "\n".join(files[:300]) + if len(files) > 300: + listing += f"\n... {len(files) - 300} more tracked files" + return f"{len(files)} tracked file(s):\n{listing}" + + async def execute( + self, + action: str, + path: Optional[str] = None, + max_depth: Optional[int] = None, + **kwargs: Any, + ) -> str: + if action not in ("overview", "tree", "tracked"): + raise ToolError( + f"Unsupported action {action!r}. Use 'overview', 'tree', or 'tracked'." + ) + base = self._base(path) + if action == "overview": + return self._overview(base) + if action == "tree": + return self._tree(base, max_depth or MAX_DEPTH) + return self._tracked(base) + + +__all__ = ["ProjectTool"] diff --git a/src/agentux/tools/registry.py b/src/agentux/tools/registry.py new file mode 100644 index 0000000..d605136 --- /dev/null +++ b/src/agentux/tools/registry.py @@ -0,0 +1,56 @@ +"""Tool registry. + +Holds the tools the agent may call and exposes them to providers as tool +definitions. The agent depends on this, not on individual tools. +""" + +from __future__ import annotations + +from typing import Dict, List, Optional + +from ..errors import ToolNotFoundError +from ..models import ToolDefinition +from .base import BaseTool + + +class ToolRegistry: + """Registry for managing and looking up tools.""" + + def __init__(self, tools: Optional[List[BaseTool]] = None) -> None: + self._tools: Dict[str, BaseTool] = {} + for tool in tools or []: + self.register(tool) + + def register(self, tool: BaseTool) -> None: + """Register a tool, replacing any existing tool with the same name.""" + self._tools[tool.name] = tool + + def get(self, name: str) -> BaseTool: + """Return a registered tool, or raise :class:`ToolNotFoundError`.""" + tool = self._tools.get(name) + if tool is None: + available = ", ".join(sorted(self._tools)) or "(none registered)" + raise ToolNotFoundError( + f"No tool named {name!r}. Available tools: {available}" + ) + return tool + + def list_tools(self) -> List[BaseTool]: + return list(self._tools.values()) + + @property + def names(self) -> List[str]: + return sorted(self._tools) + + def definitions(self) -> List[ToolDefinition]: + """Generate the tool schemas sent to the model.""" + return [tool.to_definition() for tool in self._tools.values()] + + def __len__(self) -> int: + return len(self._tools) + + def __contains__(self, name: object) -> bool: + return name in self._tools + + +__all__ = ["ToolRegistry"] diff --git a/src/agentux/tools/shell.py b/src/agentux/tools/shell.py new file mode 100644 index 0000000..2c9aac4 --- /dev/null +++ b/src/agentux/tools/shell.py @@ -0,0 +1,187 @@ +"""Shell tool. + +Runs commands with a timeout and captures stdout, stderr, and the exit code. +Destructive commands are not blocked outright -- they are routed to a +confirmation callback so the user sees the exact command and decides. That +callback is injected by the CLI, which keeps this module testable and free of +terminal I/O. +""" + +from __future__ import annotations + +import asyncio +import os +from typing import Any, Callable, Dict, Optional + +from .. import safety +from ..errors import SafetyError, ToolError +from .base import BaseTool + +#: Signature of the confirmation hook: ``(command, reasons) -> bool``. +ConfirmCallback = Callable[[str, list], bool] + +#: Ceiling on captured output, so one noisy command cannot flood the context. +MAX_OUTPUT_CHARS = 30_000 + + +class ShellTool(BaseTool): + """Execute shell commands in the workspace.""" + + def __init__( + self, + cwd: Optional[str] = None, + timeout: float = 120.0, + confirm: Optional[ConfirmCallback] = None, + allow_destructive: bool = False, + ) -> None: + self.cwd = cwd or os.getcwd() + self.timeout = timeout + #: Called for destructive commands. ``None`` means "always deny". + self.confirm = confirm + #: When True, destructive commands run without asking. Opt-in only. + self.allow_destructive = allow_destructive + + @property + def name(self) -> str: + return "shell" + + @property + def description(self) -> str: + return ( + "Execute a shell command in the workspace and return its stdout, " + "stderr, and exit code. Use it for tests, builds, git status, and " + "searching files. Prefer reading files with the filesystem tool when " + "you only need their contents. Destructive commands require the " + "user's confirmation." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The shell command to execute.", + }, + "cwd": { + "type": "string", + "description": ( + "Working directory relative to the workspace root. " + "Defaults to the workspace root." + ), + }, + "timeout": { + "type": "number", + "description": "Timeout in seconds. Defaults to the tool's configured timeout.", + }, + }, + "required": ["command"], + } + + def _resolve_cwd(self, cwd: Optional[str]) -> str: + if not cwd: + return self.cwd + candidate = cwd if os.path.isabs(cwd) else os.path.join(self.cwd, cwd) + resolved = os.path.realpath(os.path.expanduser(candidate)) + if not os.path.isdir(resolved): + raise ToolError(f"Working directory does not exist: {cwd}") + return resolved + + @staticmethod + def _truncate(text: str) -> str: + if len(text) <= MAX_OUTPUT_CHARS: + return text + half = MAX_OUTPUT_CHARS // 2 + return ( + text[:half] + + f"\n\n... [truncated {len(text) - MAX_OUTPUT_CHARS} characters] ...\n\n" + + text[-half:] + ) + + async def execute( + self, + command: str, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + **kwargs: Any, + ) -> str: + if not command or not str(command).strip(): + raise ToolError("A non-empty 'command' is required.") + + command = str(command).strip() + limit = float(timeout) if timeout else self.timeout + + reasons = safety.scan(command) + if reasons and not self.allow_destructive: + approved = self._ask_permission(command, reasons) + if not approved: + raise SafetyError( + f"The user declined to run this command: {command}\n" + f"Reason it was flagged: {', '.join(reasons)}.\n" + "Do not retry it. Ask the user how to proceed, or find a " + "safer alternative." + ) + + workdir = self._resolve_cwd(cwd) + + try: + process = await asyncio.create_subprocess_shell( + command, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + cwd=workdir, + env={**os.environ, "AGENTUX": "1"}, + ) + except OSError as exc: + raise ToolError(f"Failed to start command: {exc}") from exc + + try: + stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=limit) + except asyncio.TimeoutError: + # Kill the whole process group: a shell pipeline's children can + # outlive the shell itself and keep writing to the pipes. + self._terminate(process) + try: + await asyncio.wait_for(process.wait(), timeout=5) + except asyncio.TimeoutError: + pass + raise ToolError( + f"Command timed out after {limit:g}s and was killed: {command}\n" + "Use a smaller scope, add a timeout to the command itself, or " + "raise the tool's timeout." + ) from None + + out = self._truncate(stdout.decode("utf-8", errors="replace").rstrip()) + err = self._truncate(stderr.decode("utf-8", errors="replace").rstrip()) + code = process.returncode + + parts = [] + if out: + parts.append(f"STDOUT:\n{out}") + if err: + parts.append(f"STDERR:\n{err}") + if not out and not err: + parts.append("(no output)") + parts.append(f"EXIT CODE: {code}") + return "\n".join(parts) + + def _ask_permission(self, command: str, reasons: list) -> bool: + if self.confirm is None: + raise SafetyError( + f"This command looks destructive ({', '.join(reasons)}) and " + f"cannot run without confirmation: {command}\n" + "It was not executed. Tell the user what you wanted to run and " + "why, and ask them to run it themselves if it is essential." + ) + return bool(self.confirm(command, reasons)) + + @staticmethod + def _terminate(process) -> None: + try: + process.kill() + except (ProcessLookupError, OSError): + pass + + +__all__ = ["ShellTool", "ConfirmCallback"] |
