diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/agentux/__init__.py | 28 | ||||
| -rw-r--r-- | src/agentux/__main__.py | 6 | ||||
| -rwxr-xr-x | src/agentux/agent.py | 228 | ||||
| -rw-r--r-- | src/agentux/cli.py | 406 | ||||
| -rw-r--r-- | src/agentux/config.py | 181 | ||||
| -rw-r--r-- | src/agentux/errors.py | 91 | ||||
| -rw-r--r-- | src/agentux/models.py | 81 | ||||
| -rw-r--r-- | src/agentux/providers/__init__.py | 43 | ||||
| -rw-r--r-- | src/agentux/providers/base.py | 71 | ||||
| -rw-r--r-- | src/agentux/providers/mock.py | 71 | ||||
| -rw-r--r-- | src/agentux/providers/openai_compatible.py | 485 | ||||
| -rw-r--r-- | src/agentux/safety.py | 111 | ||||
| -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 |
18 files changed, 2748 insertions, 0 deletions
diff --git a/src/agentux/__init__.py b/src/agentux/__init__.py new file mode 100644 index 0000000..948692d --- /dev/null +++ b/src/agentux/__init__.py @@ -0,0 +1,28 @@ +"""Agentux - a terminal-native, provider-agnostic AI coding agent. + +Agentux is the product; the model provider is infrastructure. The core depends +only on the :class:`~agentux.providers.base.BaseProvider` interface, so it runs +against any server exposing an OpenAI-compatible API (OpenAI, Ollama, +LiteLLM, vLLM, LM Studio, ...) without changing a line of the agent loop. + +Quick start:: + + export AGENTUX_API_KEY="..." + export AGENTUX_BASE_URL="https://api.openai.com/v1" + export AGENTUX_MODEL="gpt-4o-mini" + agentux "explain this project" +""" + +__version__ = "0.1.0" + +from .agent import Agent +from .config import Config, load_config +from .errors import AgentuxError + +__all__ = [ + "__version__", + "Agent", + "Config", + "load_config", + "AgentuxError", +] diff --git a/src/agentux/__main__.py b/src/agentux/__main__.py new file mode 100644 index 0000000..e4f58d1 --- /dev/null +++ b/src/agentux/__main__.py @@ -0,0 +1,6 @@ +"""Support ``python -m agentux``.""" + +from .cli import cli + +if __name__ == "__main__": + cli() diff --git a/src/agentux/agent.py b/src/agentux/agent.py new file mode 100755 index 0000000..f61424d --- /dev/null +++ b/src/agentux/agent.py @@ -0,0 +1,228 @@ +"""The Agentux agent loop. + +This module contains no HTTP and no provider-specific code. It talks to a +:class:`~agentux.providers.base.BaseProvider` and a +:class:`~agentux.tools.registry.ToolRegistry`, which is what makes the +provider layer swappable. + +The loop is:: + + user message + | + v + provider.chat(history, tools) <-----------+ + | | + +-- no tool calls --> return content | + | | + +-- tool calls --> validate, execute, | + | append results ----+ +""" + +from __future__ import annotations + +import os +from typing import Any, Awaitable, Callable, List, Optional + +from .config import Config +from .errors import ( + AgentuxError, + MaxStepsError, + ToolNotFoundError, + UnsupportedToolCallingError, +) +from .models import Message, ToolCall +from .providers.base import BaseProvider +from .tools.registry import ToolRegistry + +#: Called with each message of the run, for CLI display. ``(role, text)``. +EventCallback = Callable[[str, str], None] + +SYSTEM_PROMPT = """\ +You are Agentux, a terminal-based coding and automation agent working inside \ +the user's project. + +Work by observing before acting: +- Call the 'project' tool once at the start to learn what kind of repository \ +this is, then use the 'filesystem' and 'shell' tools to gather specifics. +- Read a file before editing it. Use the 'edit' operation for changes to part \ +of a file; it replaces only the exact text you target and reports a diff. +- Prefer 'edit' over 'write'. Use 'write' only for new files or full rewrites. +- Run tests or builds with the 'shell' tool when that verifies the work, and \ +read what they actually printed before claiming success. + +Rules: +- Never invent file contents, test results, or command output. Report only \ +what you actually observed. +- If a tool fails, read the error and adapt rather than repeating the same \ +call. +- Destructive commands are gated by the user. If one is declined, do not retry \ +it; say what you wanted to do instead. +- Stop calling tools once you can answer, and answer concisely. + +When you finish, state plainly what you did, what you verified, and anything \ +the user still needs to decide.\ +""" + + +class Agent: + """Runs a multi-step tool-using conversation against a provider.""" + + def __init__( + self, + config: Config, + provider: BaseProvider, + registry: Optional[ToolRegistry] = None, + system_prompt: Optional[str] = None, + on_event: Optional[EventCallback] = None, + ) -> None: + self.config = config + self.provider = provider + self.registry = registry if registry is not None else ToolRegistry() + self.on_event = on_event + self.history: List[Message] = [] + #: Counts tool calls across the whole session, for reporting. + self.tool_calls_made = 0 + self._system_prompt = system_prompt if system_prompt is not None else SYSTEM_PROMPT + + # ------------------------------------------------------------------ + # Conversation state + # ------------------------------------------------------------------ + def reset(self) -> None: + """Clear the conversation, keeping configuration and tools.""" + self.history = [] + self.tool_calls_made = 0 + + def _emit(self, role: str, text: str) -> None: + if self.on_event and text: + try: + self.on_event(role, text) + except Exception: + # Display must never break the run. + pass + + def _ensure_system_prompt(self) -> None: + if not self.history or self.history[0].role != "system": + self.history.insert( + 0, + Message( + role="system", + content=self._build_system_prompt(), + ), + ) + + def _build_system_prompt(self) -> str: + root = self.config.working_dir or os.getcwd() + tools = self.registry.names + context = [ + "", + "Environment:", + f"- Workspace root: {root}", + f"- Available tools: {', '.join(tools) if tools else '(none)'}", + ] + if not tools: + context.append( + "- You have no tools. Answer from the conversation and say so " + "if the task needs tools." + ) + return self._system_prompt + "\n".join(context) + + # ------------------------------------------------------------------ + # Tool execution + # ------------------------------------------------------------------ + async def _execute_tool(self, call: ToolCall) -> str: + """Run one tool call and return the text to send back to the model. + + Failures are returned as text rather than raised: the model needs to + see *why* a call failed so it can recover on the next iteration. + """ + try: + tool = self.registry.get(call.name) + except ToolNotFoundError as exc: + return f"ERROR: {exc}" + + try: + result = await tool.execute(**call.arguments) + except TypeError as exc: + # Most often an unknown or missing argument from the model. + return ( + f"ERROR: invalid arguments for tool {call.name!r}: {exc}\n" + f"Expected arguments matching this schema: " + f"{tool.parameters.get('properties', {})}" + ) + except AgentuxError as exc: + return f"ERROR: {exc}" + except Exception as exc: # pragma: no cover - defensive + return f"ERROR: tool {call.name!r} raised {type(exc).__name__}: {exc}" + + text = "" if result is None else str(result) + if not text: + text = "(no output)" + if len(text) > 100_000: + text = text[:100_000] + "\n... [tool output truncated]" + return text + + def _format_tool_call(self, call: ToolCall) -> str: + """Render a tool call compactly for the terminal.""" + import json + + try: + args = json.dumps(call.arguments) + except (TypeError, ValueError): + args = str(call.arguments) + if len(args) > 300: + args = args[:300] + "..." + return f"{call.name}({args})" + + # ------------------------------------------------------------------ + # The loop + # ------------------------------------------------------------------ + async def run(self, prompt: str, interactive: bool = False) -> str: + """Run one user request to completion and return the final answer.""" + self._ensure_system_prompt() + self.history.append(Message(role="user", content=prompt)) + self._emit("user", prompt) + + tools = self.registry.definitions() + if tools and not self.provider.supports_tool_calling(): + raise UnsupportedToolCallingError( + f"Provider {type(self.provider).__name__} cannot use structured " + "tool calls, but this session has tools enabled. Agentux will " + "not fake tool calls by asking the model to print JSON, so this " + "cannot continue. Use a provider with native tool-calling " + "support, or re-run with --no-tools." + ) + + for step in range(self.config.max_steps): + message = await self.provider.chat(self.history, tools or None) + + if message.tool_calls: + # Preserve the assistant turn verbatim: providers reject a + # conversation whose tool calls are not answered in order. + self.history.append(message) + self.tool_calls_made += len(message.tool_calls) + + for call in message.tool_calls: + self._emit("tool_call", self._format_tool_call(call)) + output = await self._execute_tool(call) + self._emit("tool_result", output) + self.history.append( + Message( + role="tool", + content=output, + tool_call_id=call.id, + ) + ) + continue + + self.history.append(message) + answer = message.content or "" + self._emit("assistant", answer) + return answer + + raise MaxStepsError( + f"Stopped after {self.config.max_steps} steps without a final " + "answer. Raise AGENTUX_MAX_STEPS if the task genuinely needs more, " + "or try breaking the task into smaller pieces." + ) + + __all__ = ["Agent", "SYSTEM_PROMPT"] diff --git a/src/agentux/cli.py b/src/agentux/cli.py new file mode 100644 index 0000000..72b0d4e --- /dev/null +++ b/src/agentux/cli.py @@ -0,0 +1,406 @@ +"""Command-line interface. + +Presentation only: argument parsing, terminal output, and the confirmation +prompt live here. Everything substantive is in :mod:`agentux.agent`. +""" + +from __future__ import annotations + +import argparse +import asyncio +import os +import sys +from typing import List, Optional + +from rich.console import Console +from rich.markdown import Markdown +from rich.panel import Panel + +from . import __version__ +from .agent import Agent +from .config import Config, load_config +from .errors import ( + AgentuxError, + AuthenticationError, + MaxStepsError, + NetworkError, + ProviderError, + RateLimitError, + SafetyError, + UnsupportedToolCallingError, + UserAbort, +) +from .providers.openai_compatible import OpenAICompatibleProvider +from .tools.filesystem import FilesystemTool +from .tools.project import ProjectTool +from .tools.registry import ToolRegistry +from .tools.shell import ShellTool + +console = Console() +error_console = Console(stderr=True) + +#: Commands run directly in the shell that are safe without asking. +SAFE_COMMANDS = { + "ls", "pwd", "cd", "echo", "cat", "head", "tail", "wc", "which", "whoami", + "date", "git", "grep", "find", "diff", "tree", "stat", "file", "env", + "python", "python3", "pip", "pytest", "npm", "node", "make", "cargo", "go", + "ruff", "mypy", "black", "flake8", "sort", "uniq", "du", "df", +} + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="agentux", + description=( + "Agentux - a terminal-native AI agent. Works with any " + "OpenAI-compatible provider (OpenAI, Ollama, LiteLLM, vLLM, ...)." + ), + epilog=( + "Examples:\n" + " agentux\n" + ' agentux "explain the architecture of this project"\n' + ' agentux "fix the failing tests"\n' + " agentux --list-models\n" + " agentux --no-tools 'explain this shell script'\n" + "\n" + "Ollama (local, no API key needed):\n" + ' export AGENTUX_BASE_URL="http://localhost:11434/v1"\n' + ' export AGENTUX_MODEL="granite4.1:3b"\n' + " agentux\n" + "\n" + "Configuration (environment variables):\n" + " AGENTUX_API_KEY API key (required for remote providers)\n" + " AGENTUX_BASE_URL API root (default: https://api.openai.com/v1)\n" + " AGENTUX_MODEL Model name (default: gpt-4o-mini)\n" + " AGENTUX_MAX_STEPS Maximum agent iterations (default: 25)\n" + " AGENTUX_TIMEOUT Request/command timeout in seconds (default: 120)\n" + ), + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument( + "prompt", nargs="?", help="Task for the agent. Omit to start an interactive session." + ) + parser.add_argument("--version", action="version", version=f"agentux {__version__}") + parser.add_argument( + "--list-models", + action="store_true", + help="List the models the configured provider offers, then exit.", + ) + parser.add_argument("--model", help="Override AGENTUX_MODEL.") + parser.add_argument( + "--base-url", help="Override AGENTUX_BASE_URL (the API root, ending in /v1)." + ) + parser.add_argument("--api-key", help="Override AGENTUX_API_KEY. Prefer the environment variable.") + parser.add_argument( + "--cwd", default=None, help="Workspace root for file and shell tools (default: current directory)." + ) + parser.add_argument( + "--max-steps", type=int, help="Maximum agent iterations before giving up." + ) + parser.add_argument( + "--no-tools", action="store_true", help="Disable all tools (plain conversation)." + ) + parser.add_argument( + "--read-only", action="store_true", help="Give the agent a read-only filesystem." + ) + parser.add_argument( + "--allow-destructive", + action="store_true", + help="Run destructive shell commands without asking. Use with care.", + ) + parser.add_argument( + "--timeout", type=float, help="Shell command timeout in seconds (default: 120)." + ) + parser.add_argument( + "-v", "--verbose", action="store_true", help="Show tool arguments in full." + ) + parser.add_argument( + "--system-prompt", default=None, help="Override the built-in system prompt." + ) + return parser + + +def resolve_config(args: argparse.Namespace) -> Config: + """Build the config, letting explicit flags win over the environment.""" + # argparse handles --version/--help before we get here, so an API key is + # always required by the time this runs. + config = load_config() + if args.model: + config.model = args.model + if args.base_url: + config.base_url = args.base_url + if args.api_key: + config.api_key = args.api_key + if args.max_steps is not None: + config.max_steps = args.max_steps + if args.timeout is not None: + config.timeout = args.timeout + if args.cwd: + config.working_dir = os.path.abspath(os.path.expanduser(args.cwd)) + return config.validate() + + +def _shorten(text: str, limit: int) -> str: + text = text.strip() + if len(text) <= limit: + return text + return text[:limit] + f"\n... [{len(text) - limit} more characters]" + + +def make_reporter(verbose: bool): + """Render agent activity to the terminal as it happens.""" + + def report(kind: str, text: str) -> None: + if kind == "tool_call": + console.print(f" [dim]›[/dim] [bold cyan]{text}[/bold cyan]") + elif kind == "tool_result": + if text.startswith("ERROR:"): + console.print( + f" [red]✗[/red] [red]{_shorten(text, 400 if not verbose else 4000)}[/red]" + ) + else: + body = _shorten(text, 1200 if not verbose else 8000) + console.print( + Panel(body, title="result", border_style="dim", padding=(0, 1)) + ) + + return report + + +def make_confirmer(): + """Ask the user before running a destructive command. + + Returning False denies the command. EOF and Ctrl-C deny too: an + unattended run must never escalate on a technicality. + """ + + def confirm(command: str, reasons: List[str]) -> bool: + reason = ", ".join(reasons) + console.print() + console.print( + Panel( + f"[bold red]Destructive command[/bold red]\n\n" + f" [bold]{command}[/bold]\n\n" + f"Flagged as: [yellow]{reason}[/yellow]", + border_style="red", + ) + ) + try: + answer = console.input("[bold]Run it? [y/N] [/bold]").strip().lower() + except (EOFError, KeyboardInterrupt): + console.print() + return False + return answer in ("y", "yes") + + return confirm + + +async def list_models(config: Config) -> int: + """Print the models the provider offers, flagging tool support.""" + provider = OpenAICompatibleProvider(config) + lister = getattr(provider, "list_models_detailed", None) + try: + models = ( + await lister() if callable(lister) else + [{"name": name} for name in await provider.list_models()] + ) + except AgentuxError as exc: + explain_error(exc) + return 1 + + if not models: + console.print("[yellow]The provider returned no models.[/yellow]") + return 1 + + usable = [m for m in models if "tools" in (m.get("capabilities") or [])] + detail = bool(models and models[0].get("capabilities") is not None) + + for model in sorted(models, key=lambda m: m["name"]): + caps = model.get("capabilities") + if detail: + can_tools = "tools" in (caps or []) + marker = "[green]✓ tools[/green]" if can_tools else "[red]✗ no tools[/red]" + thinking = " [dim](thinking)[/dim]" if "thinking" in (caps or []) else "" + console.print(f" {model['name']:<40} {marker}{thinking}") + else: + console.print(f" {model['name']}") + + console.print(f"\n[dim]{len(models)} model(s) available.[/dim]") + if detail and usable: + console.print( + f"[dim]Models marked 'no tools' cannot run Agentux's tools; use " + f"--no-tools with those.[/dim]" + ) + elif detail: + console.print( + "[yellow]None of these models report tool support. Agentux needs a " + "tool-capable model.[/yellow]" + ) + return 0 + + +def build_agent(config: Config, args: argparse.Namespace) -> Agent: + """Wire up provider, tools, and agent. Kept separate so tests can call it.""" + registry = ToolRegistry() + if not args.no_tools: + if args.allow_destructive: + registry.register(ShellTool( + cwd=config.working_dir, timeout=config.timeout, allow_destructive=True + )) + else: + registry.register(ShellTool( + cwd=config.working_dir, + timeout=config.timeout, + confirm=make_confirmer(), + )) + registry.register(FilesystemTool(root=config.working_dir, read_only=args.read_only)) + registry.register(ProjectTool(root=config.working_dir)) + + provider = OpenAICompatibleProvider(config) + return Agent( + config=config, + provider=provider, + registry=registry, + system_prompt=args.system_prompt, + on_event=make_reporter(args.verbose), + ) + + +def print_answer(answer: str) -> None: + """Render the final response as markdown when it looks like markdown.""" + if any(marker in answer for marker in ("```", "\n- ", "\n#", "**")): + console.print() + console.print(Markdown(answer)) + else: + console.print() + console.print(answer) + + +def explain_error(exc: BaseException) -> None: + """Print an actionable error message.""" + if isinstance(exc, AuthenticationError): + error_console.print(f"[bold red]Authentication failed[/bold red]\n{exc}") + elif isinstance(exc, RateLimitError): + error_console.print(f"[bold yellow]Rate limited[/bold yellow]\n{exc}") + elif isinstance(exc, NetworkError): + error_console.print(f"[bold red]Network error[/bold red]\n{exc}") + elif isinstance(exc, MaxStepsError): + error_console.print(f"[bold yellow]Stopped early[/bold yellow]\n{exc}") + elif isinstance(exc, SafetyError): + error_console.print(f"[bold red]Command blocked[/bold red]\n{exc}") + elif isinstance(exc, UnsupportedToolCallingError): + error_console.print(f"[bold red]Tools unavailable[/bold red]\n{exc}") + elif isinstance(exc, ProviderError): + error_console.print(f"[bold red]Provider error[/bold red]\n{exc}") + elif isinstance(exc, AgentuxError): + error_console.print(f"[bold red]Error[/bold red]\n{exc}") + else: + error_console.print(f"[bold red]Unexpected error[/bold red]\n{type(exc).__name__}: {exc}") + + +async def run_once(agent: Agent, prompt: str) -> int: + """Run a single request. Returns a process exit code.""" + try: + with console.status("[bold blue]thinking...", spinner="dots"): + answer = await agent.run(prompt) + except AgentuxError as exc: + explain_error(exc) + return 1 + except KeyboardInterrupt: + console.print("\n[dim]Interrupted.[/dim]") + return 130 + except Exception as exc: + # A bug in Agentux should read as a message, not a traceback dump. + explain_error(exc) + return 1 + print_answer(answer) + return 0 + + +async def run_interactive(agent: Agent) -> int: + """Run a REPL, keeping history across turns.""" + console.print( + Panel( + f"[bold blue]Agentux {__version__}[/bold blue]\n" + f"Model: [cyan]{agent.provider.get_model_name()}[/cyan] | " + f"Workspace: [cyan]{agent.config.working_dir}[/cyan]\n" + f"Tools: [cyan]{', '.join(agent.registry.names) or 'none'}[/cyan]\n\n" + "[dim]/exit to quit, /reset to clear history, /tools to list tools[/dim]", + border_style="blue", + ) + ) + + while True: + try: + user_input = console.input("\n[bold green]❯[/bold green] ").strip() + except (EOFError, KeyboardInterrupt): + console.print("\n[dim]Bye.[/dim]") + return 0 + + if not user_input: + continue + if user_input in ("/exit", "/quit"): + return 0 + if user_input == "/reset": + agent.reset() + console.print("[dim]Conversation cleared.[/dim]") + continue + if user_input == "/tools": + console.print( + "[dim]Tools:[/dim] " + + (", ".join(agent.registry.names) or "none") + ) + continue + + try: + with console.status("[bold blue]thinking...", spinner="dots"): + answer = await agent.run(user_input, interactive=True) + print_answer(answer) + except UserAbort: + console.print("[yellow]Interrupted.[/yellow]") + except AgentuxError as exc: + explain_error(exc) + except KeyboardInterrupt: + console.print("\n[yellow]Interrupted.[/yellow]") + except Exception as exc: + # Keep the session alive rather than dropping the user into a + # traceback and losing their conversation. + explain_error(exc) + + +def main(argv: Optional[List[str]] = None) -> int: + """Entry point for the ``agentux`` command.""" + parser = build_parser() + args = parser.parse_args(argv) + + try: + config = resolve_config(args) + except AgentuxError as exc: + error_console.print(f"[bold red]Configuration error[/bold red]\n{exc}") + return 1 + + if args.list_models: + return asyncio.run(list_models(config)) + + try: + agent = build_agent(config, args) + except AgentuxError as exc: + explain_error(exc) + return 1 + + try: + if args.prompt: + return asyncio.run(run_once(agent, args.prompt)) + return asyncio.run(run_interactive(agent)) + except KeyboardInterrupt: + console.print("\n[dim]Interrupted.[/dim]") + return 130 + + +def cli() -> None: + """Console-script wrapper that propagates the exit code.""" + sys.exit(main()) + + +if __name__ == "__main__": + cli() diff --git a/src/agentux/config.py b/src/agentux/config.py new file mode 100644 index 0000000..e4aaae1 --- /dev/null +++ b/src/agentux/config.py @@ -0,0 +1,181 @@ +"""Configuration loaded from environment variables. + +Agentux is provider-agnostic: it speaks the OpenAI-compatible HTTP API, and +every provider that exposes that shape (OpenAI, Ollama, LiteLLM, vLLM, Qwen, +LM Studio, ...) works by changing ``AGENTUX_BASE_URL`` and ``AGENTUX_MODEL``. +No credentials are ever read from a file or hardcoded in the source. +""" + +from __future__ import annotations + +import os +from dataclasses import dataclass, field +from typing import Optional +from urllib.parse import urlparse + +from .errors import ConfigurationError + +DEFAULT_BASE_URL = "https://api.openai.com/v1" +DEFAULT_MODEL = "gpt-4o-mini" +DEFAULT_TEMPERATURE = 0.0 +DEFAULT_MAX_TOKENS = 4096 +DEFAULT_MAX_STEPS = 25 +DEFAULT_TIMEOUT = 120 + +#: Hosts that serve models locally and therefore need no credential. +#: Ollama, LM Studio, vLLM and friends listen on loopback without auth. +LOCAL_HOSTS = { + "localhost", "127.0.0.1", "0.0.0.0", "::1", "[::1]", + "host.docker.internal", +} + +#: Keeps ``repr(config)`` from ever leaking the key into logs or tracebacks. +REDACTED = "***" + + +def is_local_url(base_url: str) -> bool: + """Whether ``base_url`` points at a server on this machine. + + Local servers (Ollama, LM Studio, a local vLLM) do not authenticate, so + requiring a key for them would be busywork. + """ + try: + host = (urlparse(base_url).hostname or "").lower() + except ValueError: + return False + return host in LOCAL_HOSTS + + +@dataclass +class Config: + """Runtime settings for one Agentux session.""" + + api_key: Optional[str] = None + base_url: str = DEFAULT_BASE_URL + model: str = DEFAULT_MODEL + temperature: float = DEFAULT_TEMPERATURE + max_tokens: int = DEFAULT_MAX_TOKENS + max_steps: int = DEFAULT_MAX_STEPS + timeout: float = DEFAULT_TIMEOUT + #: Working directory the agent is confined to and runs commands in. + working_dir: str = field(default_factory=os.getcwd) + + def __repr__(self) -> str: + key = REDACTED if self.api_key else None + return ( + f"Config(api_key={key!r}, base_url={self.base_url!r}, " + f"model={self.model!r}, temperature={self.temperature!r}, " + f"max_tokens={self.max_tokens!r}, max_steps={self.max_steps!r}, " + f"timeout={self.timeout!r}, working_dir={self.working_dir!r})" + ) + + def __str__(self) -> str: + return self.__repr__() + + def validate(self) -> "Config": + """Fail fast on settings that cannot possibly work.""" + if not self.base_url: + raise ConfigurationError( + "AGENTUX_BASE_URL is empty. Set it to your provider's " + f"OpenAI-compatible endpoint (default: {DEFAULT_BASE_URL})." + ) + if not self.base_url.startswith(("http://", "https://")): + raise ConfigurationError( + f"AGENTUX_BASE_URL must start with http:// or https://, got {self.base_url!r}." + ) + if not self.model: + raise ConfigurationError("AGENTUX_MODEL is empty. Set the model name to use.") + if self.max_steps < 1: + raise ConfigurationError("AGENTUX_MAX_STEPS must be at least 1.") + if self.max_tokens < 1: + raise ConfigurationError("AGENTUX_MAX_TOKENS must be at least 1.") + if self.timeout <= 0: + raise ConfigurationError("AGENTUX_TIMEOUT must be greater than 0.") + return self + + @property + def chat_url(self) -> str: + """The chat-completions endpoint for this provider.""" + return f"{self.base_url.rstrip('/')}/chat/completions" + + @property + def models_url(self) -> str: + """The models-listing endpoint for this provider.""" + return f"{self.base_url.rstrip('/')}/models" + + @property + def is_local(self) -> bool: + """Whether this points at a server running on this machine.""" + return is_local_url(self.base_url) + + +def _env_str(name: str, default: str) -> str: + value = os.getenv(name) + return value.strip() if value and value.strip() else default + + +def _env_float(name: str, default: float) -> float: + raw = os.getenv(name) + if raw is None or not raw.strip(): + return default + try: + return float(raw) + except ValueError: + raise ConfigurationError( + f"{name} must be a number, got {raw!r}. Fix it by setting " + f"{name} to a numeric value, or unset it to use {default}." + ) + + +def _env_int(name: str, default: int) -> int: + raw = os.getenv(name) + if raw is None or not raw.strip(): + return default + try: + return int(raw) + except ValueError: + raise ConfigurationError( + f"{name} must be an integer, got {raw!r}. Fix it by setting " + f"{name} to a whole number, or unset it to use {default}." + ) + + +def load_config(require_api_key: bool = True) -> Config: + """Build a :class:`Config` from ``AGENTUX_*`` environment variables. + + An API key is required for remote providers but not for local ones: + Ollama and friends listen on loopback without authentication, so + ``AGENTUX_API_KEY`` is filled in with a placeholder when the base URL is + local and no key was supplied. + """ + api_key = os.getenv("AGENTUX_API_KEY", "").strip() or None + base_url = _env_str("AGENTUX_BASE_URL", DEFAULT_BASE_URL) + + if require_api_key and not api_key: + if is_local_url(base_url): + # Ollama ignores the header; send a placeholder so the provider + # layer has something to work with. + api_key = "ollama" + else: + raise ConfigurationError( + "AGENTUX_API_KEY is not set.\n" + "Set it to your provider's API key, for example:\n" + ' export AGENTUX_API_KEY="..."\n' + "\n" + "Using a local model? Point Agentux at Ollama and no key is " + "needed:\n" + ' export AGENTUX_BASE_URL="http://localhost:11434/v1"\n' + ' export AGENTUX_MODEL="qwen2.5-coder"' + ) + + config = Config( + api_key=api_key, + base_url=base_url, + model=_env_str("AGENTUX_MODEL", DEFAULT_MODEL), + temperature=_env_float("AGENTUX_TEMPERATURE", DEFAULT_TEMPERATURE), + max_tokens=_env_int("AGENTUX_MAX_TOKENS", DEFAULT_MAX_TOKENS), + max_steps=_env_int("AGENTUX_MAX_STEPS", DEFAULT_MAX_STEPS), + timeout=_env_float("AGENTUX_TIMEOUT", DEFAULT_TIMEOUT), + working_dir=_env_str("AGENTUX_CWD", os.getcwd()), + ) + return config.validate() diff --git a/src/agentux/errors.py b/src/agentux/errors.py new file mode 100644 index 0000000..69b8386 --- /dev/null +++ b/src/agentux/errors.py @@ -0,0 +1,91 @@ +"""Exception hierarchy for Agentux. + +Every error raised on purpose by Agentux derives from :class:`AgentuxError`. +The CLI relies on that to tell an expected, user-facing failure (a missing API +key, a rate limit, a declined command) apart from a genuine bug, so new error +types should subclass ``AgentuxError`` rather than ``Exception``. +""" + + +class AgentuxError(Exception): + """Base class for all Agentux exceptions.""" + + +class ConfigurationError(AgentuxError): + """Raised when configuration is missing or invalid.""" + + +class ProviderError(AgentuxError): + """Raised when a provider call fails.""" + + +class AuthenticationError(ProviderError): + """Raised when the provider rejects the API key.""" + + +class ModelNotFoundError(ProviderError): + """Raised when the requested model does not exist on the provider.""" + + +class RateLimitError(ProviderError): + """Raised when the provider rate-limits the request.""" + + +class NetworkError(ProviderError): + """Raised when the provider cannot be reached.""" + + +class MalformedResponseError(ProviderError): + """Raised when the provider returns a response Agentux cannot parse.""" + + +class UnsupportedToolCallingError(AgentuxError): + """Raised when tool use is requested from a provider that cannot do it. + + Agentux refuses to emulate structured tool calls by asking a model to print + JSON as plain text, so this is a hard failure rather than a silent + downgrade. + """ + + +class ToolError(AgentuxError): + """Raised when a tool fails to execute.""" + + +class ToolNotFoundError(ToolError): + """Raised when the model asks for a tool that is not registered.""" + + +class ToolValidationError(ToolError): + """Raised when a tool call's arguments do not match the tool's schema.""" + + +class SafetyError(ToolError): + """Raised when a destructive command is blocked or declined.""" + + +class MaxStepsError(AgentuxError): + """Raised when the agent loop hits its iteration ceiling.""" + + +class UserAbort(AgentuxError): + """Raised when the user interrupts an in-flight operation.""" + + +__all__ = [ + "AgentuxError", + "ConfigurationError", + "ProviderError", + "AuthenticationError", + "ModelNotFoundError", + "RateLimitError", + "NetworkError", + "MalformedResponseError", + "UnsupportedToolCallingError", + "ToolError", + "ToolNotFoundError", + "ToolValidationError", + "SafetyError", + "MaxStepsError", + "UserAbort", +] diff --git a/src/agentux/models.py b/src/agentux/models.py new file mode 100644 index 0000000..afb17cd --- /dev/null +++ b/src/agentux/models.py @@ -0,0 +1,81 @@ +"""Provider-neutral data types shared by the agent, providers, and tools. + +These deliberately contain no HTTP or provider-specific concepts. A provider +translates its own wire format into these and the agent loop only ever reads +them, which is what keeps the provider layer replaceable. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Literal, Optional + +from pydantic import BaseModel, Field + +Role = Literal["system", "user", "assistant", "tool"] + + +class ToolCall(BaseModel): + """A structured request from the model to run one tool. + + This is only ever populated from a provider's native function-calling + mechanism -- never from text the model printed. + """ + + id: str + name: str + arguments: Dict[str, Any] = Field(default_factory=dict) + + +class Message(BaseModel): + """One turn of the conversation.""" + + role: Role + content: Optional[str] = None + tool_calls: Optional[List[ToolCall]] = None + tool_call_id: Optional[str] = None + + def to_dict(self) -> Dict[str, Any]: + """Serialize to the OpenAI chat-completions wire shape.""" + payload: Dict[str, Any] = {"role": self.role} + if self.content is not None: + payload["content"] = self.content + if self.tool_calls: + payload["tool_calls"] = [ + { + "id": call.id, + "type": "function", + "function": { + "name": call.name, + "arguments": _dumps(call.arguments), + }, + } + for call in self.tool_calls + ] + if self.tool_call_id: + payload["tool_call_id"] = self.tool_call_id + return payload + + +class ToolDefinition(BaseModel): + """A tool advertised to the model. + + ``parameters`` is a JSON Schema object describing the accepted arguments. + """ + + name: str + description: str + parameters: Dict[str, Any] + + +class ToolResult(BaseModel): + """The outcome of running a tool, ready to be sent back to the model.""" + + tool_call_id: str + output: str + is_error: bool = False + + +def _dumps(value: Any) -> str: + import json + + return json.dumps(value) diff --git a/src/agentux/providers/__init__.py b/src/agentux/providers/__init__.py new file mode 100644 index 0000000..2368b87 --- /dev/null +++ b/src/agentux/providers/__init__.py @@ -0,0 +1,43 @@ +"""Providers: the model backends Agentux can talk to. + +The agent loop depends only on :class:`BaseProvider`. To add a provider, +implement that interface and register it in :func:`create_provider` -- no +change to the agent is required. +""" + +from __future__ import annotations + +from typing import Optional + +from ..config import Config +from .base import BaseProvider +from .mock import MockProvider +from .openai_compatible import OpenAICompatibleProvider + +#: Providers selectable by name via AGENTUX_PROVIDER. +REGISTRY = { + "openai": OpenAICompatibleProvider, + "openai-compatible": OpenAICompatibleProvider, + "ollama": OpenAICompatibleProvider, + "litellm": OpenAICompatibleProvider, + "mock": MockProvider, +} + + +def create_provider(name: str, config: Config) -> BaseProvider: + """Instantiate a provider by name.""" + try: + provider_class = REGISTRY[name.lower()] + except KeyError: + known = ", ".join(sorted(REGISTRY)) + raise ValueError(f"Unknown provider {name!r}. Known providers: {known}") from None + return provider_class(config) + + +__all__ = [ + "BaseProvider", + "OpenAICompatibleProvider", + "MockProvider", + "create_provider", + "REGISTRY", +] diff --git a/src/agentux/providers/base.py b/src/agentux/providers/base.py new file mode 100644 index 0000000..f20980b --- /dev/null +++ b/src/agentux/providers/base.py @@ -0,0 +1,71 @@ +"""Provider interface. + +The agent loop depends only on :class:`BaseProvider`. It never imports a +concrete provider and never contains HTTP logic, so adding a provider is a +matter of implementing this interface -- the agent loop does not change. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import AsyncIterator, List, Optional + +from ..config import Config +from ..models import Message, ToolDefinition + + +class BaseProvider(ABC): + """A model backend Agentux can drive.""" + + def __init__(self, config: Config) -> None: + self.config = config + + @abstractmethod + async def chat( + self, + messages: List[Message], + tools: Optional[List[ToolDefinition]] = None, + ) -> Message: + """Return the model's next message. + + If the model wants tools, the returned message carries ``tool_calls``. + If it is done, ``tool_calls`` is empty and ``content`` is the answer. + """ + raise NotImplementedError + + @abstractmethod + def supports_tool_calling(self) -> bool: + """Whether this provider can use native structured tool calls. + + Providers that return ``False`` are rejected when tools are requested: + Agentux will not fake tool calls by asking for JSON in plain text. + """ + raise NotImplementedError + + def get_model_name(self) -> str: + return self.config.model + + async def list_models(self) -> List[str]: + """Return the model names this provider offers. + + Used by ``agentux --list-models`` so a local user can discover what is + available instead of guessing. + """ + return [] + + async def stream( + self, + messages: List[Message], + tools: Optional[List[ToolDefinition]] = None, + ) -> AsyncIterator[str]: + """Yield text deltas as they arrive. + + The default implementation falls back to a single chunk from + :meth:`chat`, so providers only need to override this to get streaming. + """ + message = await self.chat(messages, tools) + if message.content: + yield message.content + + +__all__ = ["BaseProvider"] diff --git a/src/agentux/providers/mock.py b/src/agentux/providers/mock.py new file mode 100644 index 0000000..49c6b6d --- /dev/null +++ b/src/agentux/providers/mock.py @@ -0,0 +1,71 @@ +"""Deterministic in-memory provider for tests and offline development. + +It never performs network I/O and never uses randomness, so a test that +scripts a sequence of responses gets the same loop every time. +""" + +from __future__ import annotations + +from typing import List, Optional, Sequence + +from ..models import Message, ToolCall, ToolDefinition +from .base import BaseProvider + + +class MockProvider(BaseProvider): + """Replays a scripted list of responses. + + Each call to :meth:`chat` pops the next scripted message. Once the script + is exhausted the last message repeats, which keeps a runaway loop from + raising inside the provider (the agent's step ceiling catches it instead). + """ + + def __init__(self, responses: Sequence[Message], config=None) -> None: + if config is None: + from ..config import Config + + config = Config(api_key="mock-key") + super().__init__(config) + self.responses = list(responses) + self.calls: List[List[Message]] = [] + self.tools_seen: List[Optional[List[ToolDefinition]]] = [] + + def queue(self, *responses: Message) -> "MockProvider": + """Append more scripted responses and return self, for chaining.""" + self.responses.extend(responses) + return self + + async def chat( + self, + messages: List[Message], + tools: Optional[List[ToolDefinition]] = None, + ) -> Message: + self.calls.append(list(messages)) + self.tools_seen.append(tools) + if not self.responses: + return Message(role="assistant", content="") + if len(self.responses) == 1: + return self.responses[0] + return self.responses.pop(0) + + def supports_tool_calling(self) -> bool: + return True + + def get_model_name(self) -> str: + return "mock-model" + + +def tool_call(call_id: str, name: str, **arguments) -> Message: + """Build an assistant message that requests a single tool call.""" + return Message( + role="assistant", + tool_calls=[ToolCall(id=call_id, name=name, arguments=arguments)], + ) + + +def text(content: str) -> Message: + """Build a plain assistant reply.""" + return Message(role="assistant", content=content) + + +__all__ = ["MockProvider", "tool_call", "text"] diff --git a/src/agentux/providers/openai_compatible.py b/src/agentux/providers/openai_compatible.py new file mode 100644 index 0000000..939ce9d --- /dev/null +++ b/src/agentux/providers/openai_compatible.py @@ -0,0 +1,485 @@ +"""OpenAI-compatible provider. + +Implements the ``/chat/completions`` contract that OpenAI, Ollama, LiteLLM, +vLLM, LM Studio, Qwen and most other servers expose. Nothing here is +OpenAI-*specific* in behaviour -- only in wire format. +""" + +from __future__ import annotations + +import json +from typing import Any, AsyncIterator, Dict, List, Optional + +import httpx + +from ..config import is_local_url +from ..errors import ( + AuthenticationError, + MalformedResponseError, + ModelNotFoundError, + NetworkError, + ProviderError, + RateLimitError, + UnsupportedToolCallingError, +) +from ..models import Message, ToolCall, ToolDefinition +from .base import BaseProvider + +#: Server-sent-event prefix used by the streaming endpoint. +_SSE_PREFIX = "data:" +#: Sentinel that terminates an OpenAI-compatible SSE stream. +_SSE_DONE = "[DONE]" + + +def _tool_schema(tools: List[ToolDefinition]) -> List[Dict[str, Any]]: + return [ + { + "type": "function", + "function": { + "name": tool.name, + "description": tool.description, + "parameters": tool.parameters, + }, + } + for tool in tools + ] + + +def _parse_arguments(raw: Any) -> Dict[str, Any]: + """Parse the JSON string a provider sends for tool arguments. + + Providers send arguments as a JSON-encoded string; some send an object. + An empty or malformed string becomes ``{}`` so the tool's own validation + produces a useful message instead of an opaque JSONDecodeError. + """ + if raw is None: + return {} + if isinstance(raw, dict): + return raw + if isinstance(raw, str): + text = raw.strip() + if not text: + return {} + try: + parsed = json.loads(text) + except json.JSONDecodeError as exc: + raise MalformedResponseError( + f"Provider sent unparseable tool arguments ({raw!r}): {exc}" + ) from exc + if not isinstance(parsed, dict): + raise MalformedResponseError( + f"Provider sent tool arguments that were not an object: {raw!r}" + ) + return parsed + raise MalformedResponseError(f"Unexpected tool arguments type: {type(raw).__name__}") + + +def _error_detail(body: str) -> str: + """Pull the human-readable message out of an error body. + + OpenAI-style servers wrap errors in ``{"error": {"message": ...}}``; + Ollama uses the same shape, so one parser covers both. + """ + text = (body or "").strip() + if not text: + return "" + try: + data = json.loads(text) + except (json.JSONDecodeError, ValueError): + return text[:500] + if isinstance(data, dict): + error = data.get("error") + if isinstance(error, dict): + message = error.get("message") or error.get("detail") + if message: + return str(message)[:500] + elif isinstance(error, str): + return error[:500] + if isinstance(data.get("message"), str): + return data["message"][:500] + return text[:500] + return text[:500] + + +def looks_like_emulated_tool_call(content: str, tools: Optional[List[ToolDefinition]]) -> bool: + """Detect a model that printed a tool call as text instead of calling it. + + Some local models advertise a ``tools`` capability but, when served through + an OpenAI-compatible shim, return ``{"name": ..., "arguments": ...}`` as + ordinary content. Agentux deliberately does **not** execute that: parsing + arbitrary text as a tool call would be exactly the faking the design + forbids, and it would let any prose that happens to look like JSON run + commands. Instead we recognise the shape and report it, so the user can + pick a model that uses native tool calling. + """ + if not content or not tools: + return False + text = content.strip() + if not (text.startswith("{") and text.endswith("}")): + return False + try: + parsed = json.loads(text) + except (json.JSONDecodeError, ValueError): + return False + if not isinstance(parsed, dict): + return False + # Accept both the bare and the wrapped shapes seen in the wild. + candidate = parsed.get("tool_call") if isinstance(parsed.get("tool_call"), dict) else parsed + name = candidate.get("name") or candidate.get("function") + if isinstance(name, dict): + name = name.get("name") + if not isinstance(name, str): + return False + known = {tool.name for tool in tools} + return name in known and isinstance(candidate.get("arguments"), (dict, str)) + + +def _raise_for_status(status: int, body: str, base_url: str = "") -> None: + """Translate an HTTP error into a message that says how to fix it.""" + detail = _error_detail(body) + is_local = is_local_url(base_url) + + if status in (401, 403): + if is_local: + raise AuthenticationError( + f"The server at {base_url} rejected the API key (HTTP {status}).\n" + "Local servers such as Ollama normally ignore the key, so this " + "is unusual. Another service may be listening on that port.\n" + f"Server said: {detail}" + ) + raise AuthenticationError( + f"The provider rejected the API key (HTTP {status}).\n" + "Check AGENTUX_API_KEY. If you changed providers, remember that " + "each one has its own key.\n" + f"Provider said: {detail}" + ) + + if status == 404: + raise ModelNotFoundError( + f"The model was not found (HTTP 404).\n" + "Run 'agentux --list-models' to see what this server offers.\n" + "For Ollama, pull the model first: ollama pull <name>\n" + f"Server said: {detail}" + ) + + if status == 429: + raise RateLimitError( + f"Rate limited by the provider (HTTP 429). Wait a moment and retry. " + f"Provider said: {detail}" + ) + + if status >= 500: + raise ProviderError( + f"The provider failed with HTTP {status}. This is a server-side " + f"problem; retrying later may help. Provider said: {detail}" + ) + + if status == 400: + # Ollama says this explicitly when the model lacks the tools capability. + if "does not support tools" in detail.lower(): + raise UnsupportedToolCallingError( + f"The model {self_model_from_detail(detail)!r} does not support " + "tool calling.\n" + "Some models are completion-only and cannot use tools at all. " + "Pick one that lists 'tools' in its capabilities:\n" + " ollama list # look for 'tools' in the capabilities\n" + "or run a plain conversation with --no-tools.\n" + f"Server said: {detail}" + ) + raise ProviderError( + f"The provider rejected the request (HTTP 400). Common causes: a " + "model that cannot use tools, a context window that is too small " + "for the conversation, or an unsupported parameter.\n" + f"Server said: {detail}" + ) + + raise ProviderError(f"Provider returned HTTP {status}: {detail}") + + +def self_model_from_detail(detail: str) -> str: + """Pull the model name out of an Ollama tool-support error.""" + marker = "library/" + if marker in detail: + return detail.split(marker, 1)[1].split()[0].strip() + return detail.split()[0] if detail else "unknown" + + +class OpenAICompatibleProvider(BaseProvider): + """Talks to any server implementing the OpenAI chat-completions API.""" + + def _payload( + self, + messages: List[Message], + tools: Optional[List[ToolDefinition]], + stream: bool, + ) -> Dict[str, Any]: + payload: Dict[str, Any] = { + "model": self.config.model, + "messages": [m.to_dict() for m in messages], + "temperature": self.config.temperature, + "max_tokens": self.config.max_tokens, + } + if tools: + payload["tools"] = _tool_schema(tools) + payload["tool_choice"] = "auto" + if stream: + payload["stream"] = True + return payload + + def _headers(self) -> Dict[str, str]: + return { + "Authorization": f"Bearer {self.config.api_key}", + "Content-Type": "application/json", + } + + def supports_tool_calling(self) -> bool: + return True + + def _parse_message(self, raw: Dict[str, Any]) -> Message: + """Convert a raw assistant message into a :class:`Message`.""" + if not isinstance(raw, dict): + raise MalformedResponseError( + f"Expected an object for the assistant message, got {type(raw).__name__}." + ) + + tool_calls: List[ToolCall] = [] + for index, entry in enumerate(raw.get("tool_calls") or []): + if not isinstance(entry, dict): + raise MalformedResponseError( + f"Tool call #{index} was not an object: {entry!r}" + ) + function = entry.get("function") + if not isinstance(function, dict) or "name" not in function: + raise MalformedResponseError( + f"Tool call #{index} is missing a function name: {entry!r}" + ) + tool_calls.append( + ToolCall( + id=str(entry.get("id") or f"call_{index}"), + name=str(function["name"]), + arguments=_parse_arguments(function.get("arguments")), + ) + ) + + return Message( + role="assistant", + content=raw.get("content") or None, + tool_calls=tool_calls or None, + ) + + def _first_choice(self, data: Any) -> Dict[str, Any]: + if not isinstance(data, dict): + raise MalformedResponseError( + f"Provider returned {type(data).__name__}, expected a JSON object." + ) + choices = data.get("choices") + if not choices: + raise MalformedResponseError( + "Provider returned no choices. The model may have been rejected " + f"or the response was empty. Full response: {json.dumps(data)[:500]}" + ) + message = choices[0].get("message") if isinstance(choices[0], dict) else None + if message is None: + raise MalformedResponseError( + f"Provider choice had no 'message' field: {choices[0]!r}" + ) + return message + + async def chat( + self, + messages: List[Message], + tools: Optional[List[ToolDefinition]] = None, + ) -> Message: + async with httpx.AsyncClient(timeout=self.config.timeout) as client: + try: + response = await client.post( + self.config.chat_url, + headers=self._headers(), + json=self._payload(messages, tools, stream=False), + ) + except httpx.TimeoutException as exc: + raise ProviderError( + f"The provider did not respond within {self.config.timeout:g}s. " + "Raise AGENTUX_TIMEOUT if the model is simply slow, or check " + "that AGENTUX_BASE_URL is reachable." + ) from exc + except httpx.RequestError as exc: + raise NetworkError( + f"Could not reach the provider at {self.config.base_url}: {exc}\n" + "Check your network connection and AGENTUX_BASE_URL." + ) from exc + + if response.status_code >= 400: + _raise_for_status(response.status_code, response.text, self.config.base_url) + + try: + data = response.json() + except ValueError as exc: + raise MalformedResponseError( + "Provider returned a response that is not valid JSON. This " + "usually means the base URL points at a web page or proxy " + "rather than an API endpoint." + ) from exc + + message = self._parse_message(self._first_choice(data)) + + if tools and not message.tool_calls and looks_like_emulated_tool_call( + message.content, tools + ): + raise UnsupportedToolCallingError( + f"{self.config.model} returned a tool call as plain text instead " + "of using native tool calling.\n\n" + "Agentux will not run tool calls that were printed as text: " + "parsing prose as a command is how an agent runs something it " + "was never asked to run. It is treated as an error instead.\n\n" + "This model advertises a 'tools' capability but its chat " + "template does not emit structured calls. Try a model whose " + "template supports tool use (run 'agentux --list-models'), " + "update the model with 'ollama pull', or use --no-tools." + ) + + return message + + async def list_models(self) -> List[str]: + """List the models this server offers. + + Works against the OpenAI-compatible ``/models`` endpoint. When the + server is a local Ollama, the native ``/api/tags`` endpoint is also + queried because it reports each model's capabilities -- which is how a + user finds out whether a model can call tools at all. + """ + names: List[str] = [] + async with httpx.AsyncClient(timeout=self.config.timeout) as client: + try: + response = await client.get( + self.config.models_url, headers=self._headers() + ) + if response.status_code < 400: + data = response.json() + for entry in data.get("data") or []: + name = entry.get("id") + if name: + names.append(str(name)) + elif response.status_code == 404: + raise ModelNotFoundError( + f"{self.config.base_url} does not expose a /models " + "endpoint, so Agentux cannot list models. Set " + "AGENTUX_MODEL explicitly." + ) + else: + _raise_for_status( + response.status_code, response.text, self.config.base_url + ) + except httpx.TimeoutException as exc: + raise ProviderError( + f"Listing models timed out after {self.config.timeout:g}s." + ) from exc + except httpx.RequestError as exc: + raise NetworkError( + f"Could not reach the provider at {self.config.base_url}: {exc}\n" + "Is Ollama running? Try: ollama serve" + ) from exc + except ValueError as exc: + raise MalformedResponseError( + "The model list was not valid JSON; the base URL may point " + "at a web page rather than an API endpoint." + ) from exc + + return names + + async def list_models_detailed(self) -> List[Dict[str, Any]]: + """Model names plus Ollama capabilities, when the server reports them. + + Returns the same shape as :meth:`list_models` (names only, empty dict + values) for servers that do not expose capabilities, so callers can use + one code path. + """ + names = await self.list_models() + details: List[Dict[str, Any]] = [{"name": name} for name in names] + + if not self.config.is_local: + return details + + # Ollama's native endpoint reports capabilities; try it, but do not + # fail the command if this server is some other local provider. + ollama_root = self.config.base_url.rstrip("/") + if ollama_root.endswith("/v1"): + ollama_root = ollama_root[: -len("/v1")] + try: + async with httpx.AsyncClient(timeout=self.config.timeout) as client: + response = await client.get(f"{ollama_root}/api/tags") + if response.status_code >= 400: + return details + payload = response.json() + except Exception: + return details + + capabilities = {} + for entry in payload.get("models") or []: + name = entry.get("name") or entry.get("model") + if name: + capabilities[name] = entry.get("capabilities") or [] + + for item in details: + for name, caps in capabilities.items(): + if name == item["name"] or item["name"].startswith(name.split(":")[0]): + item["capabilities"] = caps + break + return details + + async def stream( + self, + messages: List[Message], + tools: Optional[List[ToolDefinition]] = None, + ) -> AsyncIterator[str]: + """Yield text deltas from a streaming completion. + + Tool calls are not streamed: a partial tool call cannot be executed + safely. When the model starts calling a tool we stop yielding text and + let the caller fall back to :meth:`chat`. + """ + async with httpx.AsyncClient(timeout=self.config.timeout) as client: + try: + async with client.stream( + "POST", + self.config.chat_url, + headers=self._headers(), + json=self._payload(messages, tools, stream=True), + ) as response: + if response.status_code >= 400: + await response.aread() + _raise_for_status( + response.status_code, + response.text_content, + self.config.base_url, + ) + async for line in response.aiter_lines(): + if not line or not line.startswith(_SSE_PREFIX): + continue + data = line[len(_SSE_PREFIX):].strip() + if not data or data == _SSE_DONE: + continue + try: + chunk = json.loads(data) + except json.JSONDecodeError: + continue + for choice in chunk.get("choices") or []: + delta = choice.get("delta") or {} + if delta.get("tool_calls"): + # Partial tool calls are not executable. + return + piece = delta.get("content") + if piece: + yield piece + except httpx.TimeoutException as exc: + raise ProviderError( + f"The provider did not respond within {self.config.timeout:g}s " + "while streaming." + ) from exc + except httpx.RequestError as exc: + raise NetworkError( + f"Could not reach the provider at {self.config.base_url}: {exc}" + ) from exc + + +__all__ = ["OpenAICompatibleProvider"] diff --git a/src/agentux/safety.py b/src/agentux/safety.py new file mode 100644 index 0000000..5cec13f --- /dev/null +++ b/src/agentux/safety.py @@ -0,0 +1,111 @@ +"""Destructive-command detection. + +This is deliberately a small, extensible *prompt* for the user -- not a +security boundary. A blacklist cannot be complete: commands can be obfuscated, +generated at runtime, aliased, or run through another interpreter. The real +protection is that nothing executes without the user seeing it. + +To extend it, add a ``(regex, reason)`` pair to ``_RULES`` or register your own +callable with :func:`add_rule`. +""" + +from __future__ import annotations + +import re +from typing import Callable, List, Pattern, Tuple + +#: A rule maps a pattern to the reason shown to the user. +Rule = Tuple[Pattern[str], str] +_RULES: List[Rule] = [] + + +def _add(pattern: str, reason: str) -> None: + _RULES.append((re.compile(pattern, re.IGNORECASE), reason)) + + +# Destructive filesystem operations. Recursive flags are called out +# separately from plain force-delete so the reason shown to the user is +# accurate rather than alarmist. +_add(r"\brm\s+-[a-z]*r[a-z]*\b", "recursive delete") +_add(r"\brm\s+-[a-z]*f[a-z]*\b", "force delete") +_add(r"\brmdir\b.*-", "recursive directory delete") +_add(r"\bfind\b.*-delete", "mass file deletion") +_add(r"\btruncate\b.*-s\s*0", "truncating a file to zero bytes") + +# Disk and filesystem formatting. +_add(r"\bmkfs(\.\w+)?\b", "filesystem format") +_add(r"\bdd\b[^|;]*\bof=/dev/", "raw disk write") +_add(r"\bdiskutil\b[^|;]*\b(erase|reformat|partition)", "disk erase/repartition") +_add(r">\s*/dev/[sh]d[a-z]", "raw write to a block device") + +# Process and machine control. +_add(r"\bsudo\b", "privilege escalation") +_add(r"\b(shutdown|reboot|halt|poweroff)\b", "system shutdown") +_add(r"\bkillall\s+-9\b", "killing all processes") +_add(r"\bpkill\b.*-9", "killing processes by pattern") + +# Git history and remote operations that lose work. +_add(r"\bgit\s+reset\s+--hard\b", "discards uncommitted changes") +_add(r"\bgit\s+clean\b[^|;]*-[a-z]*[fd]", "deletes untracked files") +_add(r"\bgit\s+push\b[^|;]*(--force|-f)\b", "force-push overwrites remote history") +_add(r"\bgit\s+branch\b[^|;]*\s-D\b", "force-deletes a branch") + +# Credential and secret destruction. +_add(r"\brm\b[^|;]*(\.ssh|\.aws|\.gnupg|\.kube|id_rsa|credentials)", "credential destruction") +_add(r"\bsecurity\s+delete-(generic|internet)-password\b", "keychain deletion") +_add(r"\bhistory\s+-c\b", "erasing shell history") +_add(r"\b(shred|srm)\b", "secure file erasure") + +# Obvious fork bombs. +_add(r":\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:", "fork bomb") + +# Obfuscation used to slip destructive commands past a naive scan. +_add(r"(ba|z|k|)sh\s+-c\s+['\"].*\brm\b", "obfuscated delete") + +# Piping downloaded content straight into a shell interpreter. +_add(r"\b(curl|wget|fetch)\b[^|]*\|\s*(sudo\s+)?(ba|z|k|)?sh\b", "piping a download into a shell") +_add(r"\b(curl|wget)\b[^|;]*\|\s*(sudo\s+)?(python3?|perl|ruby)\b", "piping a download into an interpreter") + + +def add_rule(pattern: str, reason: str) -> None: + """Register an extra destructive-command pattern.""" + _add(pattern, reason) + + +def add_check(fn: Callable[[str], bool], reason: str = "custom safety check") -> None: + """Register an arbitrary predicate for a destructive command.""" + _RULES.append((re.compile(r"(?!)"), reason)) # never matches on its own + _CHECKS.append((fn, reason)) + + +#: Predicates added via :func:`add_check`. +_CHECKS: List[Tuple[Callable[[str], bool], str]] = [] + + +def scan(command: str) -> List[str]: + """Return the reasons ``command`` looks destructive (empty if it looks safe). + + A command is scanned in full, not token by token, so a destructive command + hidden inside an ``&&`` chain or a subshell is still caught. + """ + reasons: List[str] = [] + for pattern, reason in _RULES: + if pattern.search(command) and reason not in reasons: + reasons.append(reason) + for check, reason in _CHECKS: + try: + if check(command) and reason not in reasons: + reasons.append(reason) + except Exception: + # A broken custom check must not silently allow a command through. + if "custom safety check failed" not in reasons: + reasons.append("custom safety check failed") + return reasons + + +def is_destructive(command: str) -> bool: + """Whether ``command`` requires explicit confirmation before running.""" + return bool(scan(command)) + + +__all__ = ["scan", "is_destructive", "add_rule", "add_check"] 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"] |
