diff options
| author | dev <dev@local> | 2026-10-05 16:40:10 +0530 |
|---|---|---|
| committer | dev <dev@local> | 2026-10-05 16:40:10 +0530 |
| commit | ed4889134aa77d912d7e0fc0d69f7def0dd772fc (patch) | |
| tree | 4317f0b80491c02e37d1f752bce8462b5b4b24ff | |
Working agent before enhancements: 205 tests passing
29 files changed, 5263 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a4ab1cb --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +# Python +__pycache__/ +*.py[cod] +*.egg-info/ +.eggs/ +build/ +dist/ +*.so + +# Environments +.venv/ +venv/ +env/ +.env +.env.* + +# Testing +.pytest_cache/ +.coverage +htmlcov/ +.mypy_cache/ +.ruff_cache/ + +# Editors / OS +.idea/ +.vscode/ +.DS_Store + +# Never commit credentials. Agentux reads AGENTUX_API_KEY from the +# environment; a stray .env with a real key must not be committed. +*.key +*.pem +secrets.* @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Agentux contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c0b5ce9 --- /dev/null +++ b/README.md @@ -0,0 +1,386 @@ +# Agentux + +**A terminal-native, provider-agnostic AI coding agent.** + +Agentux is an independent open-source agent that lives in your terminal. Give it a +task, and it will inspect your project, read and edit files, run commands, recover +from failures, and tell you what it did. + +Agentux is the product. The model provider is infrastructure — Agentux talks to any +server that speaks the OpenAI-compatible API, so you can point it at OpenAI, Ollama, +LiteLLM, vLLM, LM Studio, Qwen, or your own gateway without changing the agent. + +```bash +agentux "fix the failing tests" +``` + +## Features + +- **Real structured tool calling.** Agentux uses the provider's native + function-calling mechanism. It does not ask a model to print JSON and pretend the + JSON was a tool call — if a model or provider cannot do tool calling, Agentux fails + loudly rather than pretending. This includes detecting local models that return + tool calls as plain text. +- **A genuine agent loop.** Model → tool call → validate → execute → result → model, + for as many steps as the task needs, bounded by a configurable ceiling. +- **Filesystem tools** for reading, writing, targeted edits, directory listing, + globbing, moving, and deleting — all confined to the workspace root. +- **Shell tool** with timeouts, working-directory support, and captured + stdout/stderr/exit code. +- **Safety layer.** Destructive commands are shown to you and require explicit + confirmation. Read-only commands never prompt. +- **Project awareness.** A dedicated tool maps the repository — language, build + system, source and test layout — without reading the whole tree. +- **Provider-agnostic by construction.** The agent loop contains no HTTP and no + provider-specific logic. + +## Installation + +```bash +git clone https://github.com/agentux/agentux.git +cd agentux +pip install -e . +``` + +Requires Python 3.10+. Dependencies are deliberately few: `httpx`, `pydantic`, +`rich`. No agent framework is required to build an agent. + +Verify the install: + +```bash +agentux --version +agentux --help +python -m agentux --help +``` + +## Configuration + +Agentux is configured entirely through environment variables. **No credentials are +stored in the source, read from a config file, or printed in logs.** + +| Variable | Description | Default | +|---|---|---| +| `AGENTUX_API_KEY` | API key for your provider | required for remote, optional for local | +| `AGENTUX_BASE_URL` | API root, ending in `/v1` | `https://api.openai.com/v1` | +| `AGENTUX_MODEL` | Model name | `gpt-4o-mini` | +| `AGENTUX_TEMPERATURE` | Sampling temperature | `0.0` | +| `AGENTUX_MAX_TOKENS` | Max tokens per response | `4096` | +| `AGENTUX_MAX_STEPS` | Max agent iterations per task | `25` | +| `AGENTUX_TIMEOUT` | Request/command timeout (seconds) | `120` | +| `AGENTUX_CWD` | Workspace root | current directory | + +```bash +export AGENTUX_API_KEY="..." +export AGENTUX_BASE_URL="https://example.com/v1" +export AGENTUX_MODEL="some-model" +``` + +`AGENTUX_API_KEY` is required for remote providers. When `AGENTUX_BASE_URL` points +at localhost, Agentux fills in a placeholder and runs without one — local servers +don't authenticate. + +### Provider setup + +Because everything is OpenAI-compatible, switching providers is a two-line change. + +#### Ollama (local) + +```bash +ollama serve # if it is not already running +ollama pull granite4.1:3b # or any tool-capable model + +export AGENTUX_BASE_URL="http://localhost:11434/v1" +export AGENTUX_MODEL="granite4.1:3b" +agentux "explain this project" # no API key needed +``` + +Find out what is available, and whether it can call tools: + +```bash +agentux --list-models +``` + +``` + granite4.1:3b ✓ tools + qwen2.5-coder:7b ✓ tools + smollm:135m ✗ no tools + gpt-oss:20b ✓ tools (thinking) + +18 model(s) available. +Models marked 'no tools' cannot run Agentux's tools; use --no-tools with those. +``` + +Agentux asks Ollama's native endpoint for capabilities, because Ollama's +OpenAI-compatible `/v1/models` does not report them. + +**Not every model that claims a `tools` capability actually emits native tool +calls.** Some return `{"name": ..., "arguments": ...}` as ordinary text. Agentux +detects that and refuses to run it: + +``` +qwen2.5-coder:7b returned a tool call as plain text instead of using native tool +calling. + +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. +``` + +That is a deliberate refusal, not a bug. Emulating tool calls by parsing prose +would mean any JSON-shaped text in a model's answer could execute a command, so +Agentux reports the mismatch and lets you pick a different model. + +Two more Ollama notes: + +- **Timeouts.** A cold model can take a while to load. Raise the timeout for + large models: `AGENTUX_TIMEOUT=600`. +- **Thinking models** (`gpt-oss`, `qwen3`, `gemma4`) emit a separate `reasoning` + field, which Agentux ignores and keeps out of the conversation. + +#### OpenAI + +```bash +export AGENTUX_API_KEY="sk-..." +export AGENTUX_BASE_URL="https://api.openai.com/v1" +export AGENTUX_MODEL="gpt-4o-mini" +``` + +#### LiteLLM / vLLM / LM Studio / OpenRouter / Together / Groq + +```bash +export AGENTUX_API_KEY="..." +export AGENTUX_BASE_URL="http://localhost:4000/v1" # or your gateway +export AGENTUX_MODEL="your/model-name" +``` + +If you get an authentication error, check the key; a 404 usually means the model +name is wrong or `AGENTUX_BASE_URL` is missing its `/v1` suffix. The CLI says which. + +## Usage + +### One-shot + +```bash +agentux "inspect this project and explain its architecture" +agentux "fix the failing tests" +agentux "add a README section explaining installation" +``` + +### Interactive + +```bash +agentux +``` + +``` +Agentux 0.1.0 +Model: gpt-4o-mini | Workspace: /path/to/project +Tools: filesystem, project, shell + +❯ what does this repo do? +``` + +Conversation history persists across turns. `/exit` quits, `/reset` clears history, +`/tools` lists available tools. + +### Options + +| Flag | Meaning | +|---|---| +| `--model MODEL` | Override `AGENTUX_MODEL` | +| `--base-url URL` | Override `AGENTUX_BASE_URL` | +| `--api-key KEY` | Override the API key (prefer the environment variable) | +| `--list-models` | List the provider's models and whether they support tools | +| `--cwd PATH` | Workspace root for file and shell tools | +| `--max-steps N` | Maximum agent iterations before giving up | +| `--timeout S` | Shell command timeout in seconds | +| `--no-tools` | Plain conversation, no tool access | +| `--read-only` | Filesystem tool cannot write, move, or delete | +| `--allow-destructive` | Run destructive commands without asking (**use with care**) | +| `-v, --verbose` | Show full tool arguments and output | +| `--system-prompt TEXT` | Override the built-in system prompt | +| `--version` | Print the version | + +## Tools + +Agentux ships three tools. Each declares a name, a description, and a JSON Schema; +the model addresses tools by name and never sees the implementation. + +### `filesystem` + +Operations: `ls`, `read`, `write`, `edit`, `mkdir`, `rm`, `mv`, `glob`. + +```jsonc +// read a file +{"operation": "read", "path": "src/agentux/agent.py"} + +// targeted edit — replaces one exact occurrence, leaves everything else alone +{"operation": "edit", "path": "README.md", + "old_string": "Install with pip", "new_string": "Install with uv"} + +// create or fully rewrite +{"operation": "write", "path": "docs/usage.md", "content": "# Usage\n"} +``` + +`edit` is the important one: it refuses to proceed if the target text is missing or +ambiguous, and it returns a unified diff. That makes accidental clobbering hard +rather than merely unlikely. + +Every path is resolved and checked against the workspace root, so `../../etc/passwd` +and symlinks pointing outside the tree are rejected. Reads are size-capped and +directory listings are truncated, so the model gets a summary instead of a firehose. + +### `shell` + +Runs a command and returns stdout, stderr, and the exit code. + +```jsonc +{"command": "pytest -q", "cwd": "tests", "timeout": 60} +``` + +Commands have a timeout; on expiry the process is killed and the model is told, so a +hang cannot stall the session. Multi-step output is truncated in the middle, keeping +both the head and the tail. + +### `project` + +Maps the repository without reading all of it. + +```jsonc +{"action": "overview"} // language, build system, key files, src/test dirs +{"action": "tree", "max_depth": 3} +{"action": "tracked"} // files tracked by git +``` + +Start here. It tells the model what kind of project it is in and where things live, +so the agent can target its next reads instead of wandering. + +## Safety behaviour + +Agentux treats the safety layer as a **prompt for you, not a security boundary**. A +blacklist can never be complete — commands can be obfuscated, aliased, generated at +runtime, or run through another interpreter. What actually protects you is that +nothing destructive runs without being shown to you first. + +When a command is flagged (recursive deletes, `sudo`, `mkfs`, raw disk writes, +`git reset --hard`, `git push --force`, credential destruction, `curl | sh`, fork +bombs, and similar), Agentux shows you the exact command and the reason: + +``` +╭─ Destructive command ─────────────────────────────╮ +│ │ +│ rm -rf build │ +│ │ +│ Flagged as: recursive delete │ +╰────────────────────────────────────────────────────╯ +Run it? [y/N] +``` + +- Interactive mode: you decide. +- One-shot mode: the command is refused and the model is told not to retry it. +- Read-only commands never prompt — `ls`, `pytest`, `git status` just run. + +`--allow-destructive` skips the prompt. `--read-only` makes the filesystem tool +incapable of modifying anything. Both are opt-in. + +## Architecture + +``` +CLI + ↓ +Agent (the loop; no HTTP, no provider specifics) + ↓ +Provider abstraction (BaseProvider) + ↓ +OpenAI-compatible provider (the only HTTP in the project) + ↓ +Model API +``` + +``` +Agent + ↓ +Tool registry + ├── filesystem + ├── project + └── shell +``` + +The agent depends only on `BaseProvider` and `ToolRegistry`. Adding a provider means +implementing one interface; adding a tool means implementing one class and registering +it. Neither requires touching the loop. + +``` +src/agentux/ +├── cli.py presentation: parsing, output, confirmation +├── agent.py the loop +├── config.py environment configuration +├── safety.py destructive-command detection +├── models.py provider-neutral Message / ToolCall / ToolDefinition +├── errors.py exception hierarchy +├── providers/ base.py, openai_compatible.py, mock.py +└── tools/ base.py, registry.py, filesystem.py, shell.py, project.py +``` + +## Development + +```bash +git clone https://github.com/agentux/agentux.git +cd agentux +pip install -e ".[dev]" +``` + +### Testing + +```bash +pytest -q +``` + +The suite needs no API key and makes no network calls — HTTP is mocked and the +provider layer is exercised against recorded responses. Async tests run via a small +hook in `tests/conftest.py`, so `pytest-asyncio` is not required. + +What is covered: configuration loading and validation, missing configuration, +provider initialization, mocked provider responses, structured tool calls, multiple +tool calls per turn, multi-iteration agent loops, tool-failure recovery, filesystem +read/write/edit/glob/listing, path-escape rejection, shell execution, shell timeouts, +destructive-command confirmation, Ollama-specific response shapes and error mapping, +emulated-tool-call refusal, and CLI behavior. + +### Adding a tool + +```python +from agentux.tools.base import BaseTool +from agentux.errors import ToolError + +class GrepTool(BaseTool): + @property + def name(self) -> str: + return "grep" + + @property + def description(self) -> str: + return "Search file contents with a regular expression." + + @property + def parameters(self) -> dict: + return { + "type": "object", + "properties": {"pattern": {"type": "string"}, "path": {"type": "string"}}, + "required": ["pattern"], + } + + async def execute(self, pattern: str, path: str = ".", **kwargs) -> str: + # Raise ToolError on failure; the model sees the message and can adapt. + ... +``` + +Register it in `build_agent` in `cli.py`. The agent loop needs no changes. + +### Adding a provider + +Implement `BaseProvider` (a `chat` method and `supports_tool_calling`) and add it to +`REGISTRY` in `providers/__init__.py`. + +## License + +MIT — see [LICENSE](LICENSE). diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..8984f24 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,52 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "agentux" +version = "0.1.0" +description = "A terminal-native, provider-agnostic AI coding agent" +readme = "README.md" +requires-python = ">=3.10" +license = { text = "MIT" } +authors = [{ name = "Agentux contributors" }] +keywords = ["ai", "agent", "cli", "llm", "openai-compatible", "ollama", "tools"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Environment :: Console", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Software Development :: Code Generators", +] + +# Deliberately minimal: an HTTP client and terminal rendering. Pydantic is used +# for the message/tool schemas, which is where validation actually earns its +# keep. No agent framework is required to build an agent. +dependencies = [ + "httpx>=0.27.0", + "pydantic>=2.6.0", + "rich>=13.0.0", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.0.0", +] + +[project.urls] +Homepage = "https://github.com/agentux/agentux" +Issues = "https://github.com/agentux/agentux/issues" + +[project.scripts] +agentux = "agentux.cli:cli" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-ra" 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"] diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..5a19bfb --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,77 @@ +"""Shared test fixtures. + +Agentux's core is async, but the suite runs on a bare pytest install. This +module supplies the small hook that executes ``async def`` tests, so the +project needs no pytest plugin (``pytest-asyncio``) and no asyncio-mode +configuration to be maintained alongside the code. +""" + +from __future__ import annotations + +import asyncio +import inspect + +import pytest + +from agentux.config import Config +from agentux.providers.mock import MockProvider +from agentux.tools.filesystem import FilesystemTool +from agentux.tools.project import ProjectTool +from agentux.tools.registry import ToolRegistry +from agentux.tools.shell import ShellTool + + +def pytest_pyfunc_call(pyfuncitem): + """Run coroutine tests on a fresh event loop.""" + test_function = pyfuncitem.obj + if not inspect.iscoroutinefunction(test_function): + return None + + kwargs = { + name: pyfuncitem.funcargs[name] + for name in pyfuncitem._fixtureinfo.argnames + } + loop = asyncio.new_event_loop() + try: + asyncio.set_event_loop(loop) + loop.run_until_complete(test_function(**kwargs)) + finally: + asyncio.set_event_loop(None) + loop.close() + return True + + +def run_async(coroutine): + """Run a coroutine from a synchronous test.""" + loop = asyncio.new_event_loop() + try: + return loop.run_until_complete(coroutine) + finally: + loop.close() + + +@pytest.fixture +def config(tmp_path): + return Config( + api_key="test-key", + base_url="http://api.test/v1", + model="test-model", + working_dir=str(tmp_path), + max_steps=10, + ) + + +@pytest.fixture +def provider(): + return MockProvider([]) + + +@pytest.fixture +def registry(tmp_path): + return ToolRegistry( + [ + FilesystemTool(root=str(tmp_path)), + ShellTool(cwd=str(tmp_path)), + ProjectTool(root=str(tmp_path)), + ] + ) diff --git a/tests/test_agent.py b/tests/test_agent.py new file mode 100644 index 0000000..a8b5b7c --- /dev/null +++ b/tests/test_agent.py @@ -0,0 +1,324 @@ +"""The agent loop: tool dispatch, history, and failure recovery.""" + +from pathlib import Path + +import pytest + +from agentux.agent import Agent +from agentux.config import Config +from agentux.errors import MaxStepsError, UnsupportedToolCallingError +from agentux.models import Message, ToolCall +from agentux.providers.base import BaseProvider +from agentux.providers.mock import MockProvider, text, tool_call +from agentux.tools.filesystem import FilesystemTool +from agentux.tools.registry import ToolRegistry + + +class NoToolProvider(BaseProvider): + """A provider that cannot do structured tool calling.""" + + async def chat(self, messages, tools=None): + return Message(role="assistant", content="plain text only") + + def supports_tool_calling(self): + return False + + +def make_agent(provider, config, registry=None): + return Agent(config, provider, registry if registry is not None else ToolRegistry()) + + +async def test_returns_final_text_without_tools(config): + provider = MockProvider([text("The answer is 42.")]) + agent = make_agent(provider, config) + + answer = await agent.run("What is the answer?") + + assert answer == "The answer is 42." + + +async def test_history_records_system_user_assistant(config): + provider = MockProvider([text("Hi there")]) + agent = make_agent(provider, config) + + await agent.run("Hello") + + assert [m.role for m in agent.history] == ["system", "user", "assistant"] + assert agent.history[1].content == "Hello" + + +async def test_system_prompt_includes_workspace_and_tools(config): + provider = MockProvider([text("ok")]) + agent = Agent(config, provider, ToolRegistry([FilesystemTool(root=config.working_dir)])) + + await agent.run("hello") + + system = agent.history[0].content + assert config.working_dir in system + assert "filesystem" in system + + +async def test_custom_system_prompt_is_used(config): + provider = MockProvider([text("ok")]) + agent = make_agent(provider, config, None) + agent._system_prompt = "BE BRIEF." + + await agent.run("hello") + + assert agent.history[0].content.startswith("BE BRIEF.") + + +async def test_executes_a_tool_then_returns_the_answer(config, tmp_path): + """The core loop: model asks, tool runs, result goes back, model answers.""" + target = tmp_path / "note.txt" + target.write_text("hello from disk") + + provider = MockProvider( + [ + tool_call("call_1", "filesystem", operation="read", path="note.txt"), + text("The file says: hello from disk"), + ] + ) + agent = make_agent(provider, config, ToolRegistry([FilesystemTool(root=str(tmp_path))])) + + answer = await agent.run("What is in note.txt?") + + assert answer == "The file says: hello from disk" + assert [m.role for m in agent.history] == [ + "system", "user", "assistant", "tool", "assistant", + ] + assert agent.history[3].content == "hello from disk" + assert agent.history[3].tool_call_id == "call_1" + assert target.read_text() == "hello from disk" + + +async def test_assistant_tool_call_turn_is_preserved(config, tmp_path): + """Providers reject histories whose tool calls are not answered in order.""" + (tmp_path / "a.txt").write_text("A") + (tmp_path / "b.txt").write_text("B") + + provider = MockProvider( + [ + Message( + role="assistant", + tool_calls=[ + ToolCall(id="c1", name="filesystem", arguments={"operation": "read", "path": "a.txt"}), + ToolCall(id="c2", name="filesystem", arguments={"operation": "read", "path": "b.txt"}), + ], + ), + text("Both read."), + ] + ) + agent = make_agent(provider, config, ToolRegistry([FilesystemTool(root=str(tmp_path))])) + + await agent.run("read both") + + roles = [m.role for m in agent.history] + assert roles == ["system", "user", "assistant", "tool", "tool", "assistant"] + assert agent.history[3].tool_call_id == "c1" + assert agent.history[4].tool_call_id == "c2" + + +async def test_multiple_tool_calls_in_one_turn_all_execute(config, tmp_path): + (tmp_path / "a.txt").write_text("A") + (tmp_path / "b.txt").write_text("B") + + provider = MockProvider( + [ + Message( + role="assistant", + tool_calls=[ + ToolCall(id="c1", name="filesystem", arguments={"operation": "read", "path": "a.txt"}), + ToolCall(id="c2", name="filesystem", arguments={"operation": "read", "path": "b.txt"}), + ], + ), + text("done"), + ] + ) + agent = make_agent(provider, config, ToolRegistry([FilesystemTool(root=str(tmp_path))])) + + await agent.run("read both") + + tool_messages = [m for m in agent.history if m.role == "tool"] + assert [m.content for m in tool_messages] == ["A", "B"] + assert agent.tool_calls_made == 2 + + +async def test_multiple_iterations(config, tmp_path): + """Two separate tool round-trips before the final answer.""" + (tmp_path / "one.txt").write_text("1") + (tmp_path / "two.txt").write_text("2") + + provider = MockProvider( + [ + tool_call("c1", "filesystem", operation="read", path="one.txt"), + tool_call("c2", "filesystem", operation="read", path="two.txt"), + text("Read both files."), + ] + ) + agent = make_agent(provider, config, ToolRegistry([FilesystemTool(root=str(tmp_path))])) + + answer = await agent.run("read one.txt then two.txt") + + assert answer == "Read both files." + assert len([m for m in agent.history if m.role == "tool"]) == 2 + assert provider.calls.__len__() == 3 + + +async def test_tool_failure_is_returned_to_the_model_for_recovery(config, tmp_path): + """A failing tool must not abort the run; the model gets the error.""" + provider = MockProvider( + [ + tool_call("c1", "filesystem", operation="read", path="missing.txt"), + text("That file does not exist."), + ] + ) + agent = make_agent(provider, config, ToolRegistry([FilesystemTool(root=str(tmp_path))])) + + answer = await agent.run("read missing.txt") + + assert answer == "That file does not exist." + assert "ERROR" in agent.history[3].content + assert "does not exist" in agent.history[3].content + + +async def test_unknown_tool_is_reported_to_the_model(config): + provider = MockProvider( + [tool_call("c1", "nonexistent_tool", foo="bar"), text("I cannot do that.")] + ) + agent = make_agent(provider, config, ToolRegistry([FilesystemTool(root="/tmp")])) + + answer = await agent.run("do something impossible") + + assert answer == "I cannot do that." + assert "No tool named" in agent.history[3].content + + +async def test_invalid_arguments_are_reported_to_the_model(config): + provider = MockProvider( + [tool_call("c1", "filesystem", operation="read", nonexistent_arg="x"), text("Bad args.")] + ) + agent = make_agent(provider, config, ToolRegistry([FilesystemTool(root="/tmp")])) + + await agent.run("bad call") + + assert "ERROR" in agent.history[3].content + + +async def test_tool_definitions_are_passed_to_the_provider(config, tmp_path): + provider = MockProvider([text("ok")]) + agent = make_agent(provider, config, ToolRegistry([FilesystemTool(root=str(tmp_path))])) + + await agent.run("hello") + + tools = provider.tools_seen[0] + assert tools is not None + assert [t.name for t in tools] == ["filesystem"] + assert tools[0].parameters["type"] == "object" + + +async def test_no_tools_registered_sends_no_definitions(config): + provider = MockProvider([text("ok")]) + agent = make_agent(provider, config, ToolRegistry()) + + await agent.run("hello") + + assert provider.tools_seen[0] is None + + +async def test_max_steps_prevents_an_infinite_loop(config): + """A model that keeps calling tools must not loop forever.""" + looping = [ + tool_call(f"c{i}", "filesystem", operation="ls", path=".") for i in range(50) + ] + config.max_steps = 5 + agent = make_agent(MockProvider(looping), config, ToolRegistry([FilesystemTool(root=str(config.working_dir))])) + + with pytest.raises(MaxStepsError) as exc: + await agent.run("loop forever") + + assert "5 steps" in str(exc.value) + + +async def test_refuses_tools_when_provider_cannot_call_them(config): + agent = make_agent(NoToolProvider(config), config, ToolRegistry([FilesystemTool(root="/tmp")])) + + with pytest.raises(UnsupportedToolCallingError) as exc: + await agent.run("do something") + + assert "will not fake tool calls" in str(exc.value) + + +async def test_history_is_preserved_across_turns(config): + provider = MockProvider([text("first"), text("second")]) + agent = make_agent(provider, config) + + await agent.run("one") + await agent.run("two") + + assert [m.content for m in agent.history if m.role == "user"] == ["one", "two"] + assert sum(1 for m in agent.history if m.role == "system") == 1 + + +async def test_reset_clears_history_but_keeps_tools(config, tmp_path): + provider = MockProvider([text("a"), text("b")]) + registry = ToolRegistry([FilesystemTool(root=str(tmp_path))]) + agent = make_agent(provider, config, registry) + + await agent.run("one") + agent.reset() + await agent.run("two") + + assert len(agent.history) == 3 + assert len(registry) == 1 + + +async def test_events_are_reported(config, tmp_path): + (tmp_path / "f.txt").write_text("data") + events = [] + provider = MockProvider( + [tool_call("c1", "filesystem", operation="read", path="f.txt"), text("done")] + ) + agent = Agent( + config, + provider, + ToolRegistry([FilesystemTool(root=str(tmp_path))]), + on_event=lambda role, text: events.append((role, text)), + ) + + await agent.run("read f.txt") + + kinds = [kind for kind, _ in events] + assert "user" in kinds and "tool_call" in kinds and "assistant" in kinds + + +async def test_a_broken_event_callback_does_not_break_the_run(config): + (Path(config.working_dir) / "f.txt").write_text("data") + + def explode(role, text): + raise RuntimeError("display is on fire") + + provider = MockProvider( + [tool_call("c1", "filesystem", operation="read", path="f.txt"), text("done")] + ) + agent = Agent( + config, + provider, + ToolRegistry([FilesystemTool(root=config.working_dir)]), + on_event=explode, + ) + + assert await agent.run("read f.txt") == "done" + + +async def test_empty_tool_output_is_reported(config): + class SilentTool(FilesystemTool): + async def execute(self, **kwargs): + return "" + + provider = MockProvider([tool_call("c1", "filesystem", operation="ls", path="."), text("ok")]) + agent = make_agent(provider, config, ToolRegistry([SilentTool(root=str(config.working_dir))])) + + await agent.run("go") + + assert agent.history[3].content == "(no output)" diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..efa8663 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,324 @@ +"""CLI behaviour: argument parsing, wiring, and error reporting. + +No network access: the provider is stubbed where a run is needed. +""" + +import sys + +import pytest + +from agentux import __version__ +from agentux.cli import build_parser, main, resolve_config +from agentux.errors import AuthenticationError +from agentux.tools.filesystem import FilesystemTool +from agentux.tools.project import ProjectTool +from agentux.tools.shell import ShellTool + + +def test_parser_accepts_a_prompt(): + args = build_parser().parse_args(["fix the failing tests"]) + assert args.prompt == "fix the failing tests" + + +def test_parser_prompt_is_optional(): + assert build_parser().parse_args([]).prompt is None + + +def test_parser_flags(): + args = build_parser().parse_args( + ["--model", "m", "--base-url", "http://x/v1", "--no-tools", + "--read-only", "--max-steps", "3", "--timeout", "5", "--cwd", "/tmp", "-v"] + ) + assert args.model == "m" + assert args.base_url == "http://x/v1" + assert args.no_tools is True + assert args.read_only is True + assert args.max_steps == 3 + assert args.timeout == 5 + assert args.cwd == "/tmp" + assert args.verbose is True + + +def test_help_exits_zero(capsys): + with pytest.raises(SystemExit) as exit_info: + build_parser().parse_args(["--help"]) + assert exit_info.value.code == 0 + assert "agentux" in capsys.readouterr().out + + +def test_version_flag_prints_version(capsys): + with pytest.raises(SystemExit) as exit_info: + main(["--version"]) + assert exit_info.value.code == 0 + assert __version__ in capsys.readouterr().out + + +def test_missing_api_key_is_reported(monkeypatch, capsys): + monkeypatch.delenv("AGENTUX_API_KEY", raising=False) + assert main(["say hello"]) == 1 + assert "Configuration error" in capsys.readouterr().err + + +def test_invalid_base_url_is_reported(monkeypatch, capsys): + monkeypatch.setenv("AGENTUX_API_KEY", "k") + monkeypatch.setenv("AGENTUX_BASE_URL", "not-a-url") + assert main(["hello"]) == 1 + assert "Configuration error" in capsys.readouterr().err + + +def test_flags_override_environment(monkeypatch, tmp_path): + monkeypatch.setenv("AGENTUX_API_KEY", "env-key") + monkeypatch.setenv("AGENTUX_MODEL", "env-model") + monkeypatch.delenv("AGENTUX_MAX_STEPS", raising=False) + + args = build_parser().parse_args(["--model", "flag-model", "--max-steps", "7", "--cwd", str(tmp_path)]) + config = resolve_config(args) + + assert config.model == "flag-model" + assert config.max_steps == 7 + assert config.working_dir == str(tmp_path) + + +def test_config_falls_back_to_environment(monkeypatch): + monkeypatch.setenv("AGENTUX_API_KEY", "env-key") + monkeypatch.setenv("AGENTUX_MODEL", "env-model") + config = resolve_config(build_parser().parse_args(["hello"])) + assert config.model == "env-model" + + +def test_no_api_key_is_ever_printed(monkeypatch, capsys): + """A secret in the environment must not leak into CLI output.""" + monkeypatch.setenv("AGENTUX_API_KEY", "sk-super-secret-value") + with pytest.raises(SystemExit): + main(["--version"]) + assert "sk-super-secret-value" not in capsys.readouterr().out + assert "sk-super-secret-value" not in capsys.readouterr().err + + +def test_build_agent_wires_tools(monkeypatch, tmp_path): + from agentux.cli import build_agent + + monkeypatch.setenv("AGENTUX_API_KEY", "k") + args = build_parser().parse_args(["--cwd", str(tmp_path)]) + agent = build_agent(resolve_config(args), args) + + assert isinstance(agent.registry.get("shell"), ShellTool) + assert isinstance(agent.registry.get("filesystem"), FilesystemTool) + assert isinstance(agent.registry.get("project"), ProjectTool) + assert agent.provider is not None + + +def test_no_tools_flag_registers_nothing(monkeypatch, tmp_path): + from agentux.cli import build_agent + + monkeypatch.setenv("AGENTUX_API_KEY", "k") + args = build_parser().parse_args(["--no-tools", "--cwd", str(tmp_path)]) + agent = build_agent(resolve_config(args), args) + + assert len(agent.registry) == 0 + + +def test_read_only_flag_propagates(monkeypatch, tmp_path): + from agentux.cli import build_agent + + monkeypatch.setenv("AGENTUX_API_KEY", "k") + args = build_parser().parse_args(["--read-only", "--cwd", str(tmp_path)]) + agent = build_agent(resolve_config(args), args) + + assert agent.registry.get("filesystem").read_only is True + + +def test_shell_tool_confirms_by_default(monkeypatch, tmp_path): + from agentux.cli import build_agent + + monkeypatch.setenv("AGENTUX_API_KEY", "k") + args = build_parser().parse_args(["--cwd", str(tmp_path)]) + agent = build_agent(resolve_config(args), args) + + assert agent.registry.get("shell").confirm is not None + + +def test_allow_destructive_disables_the_prompt(monkeypatch, tmp_path): + from agentux.cli import build_agent + + monkeypatch.setenv("AGENTUX_API_KEY", "k") + args = build_parser().parse_args(["--allow-destructive", "--cwd", str(tmp_path)]) + agent = build_agent(resolve_config(args), args) + + assert agent.registry.get("shell").allow_destructive is True + + +def test_single_prompt_runs_and_prints(monkeypatch, capsys): + """End-to-end through main(), with only the model stubbed out.""" + import asyncio + + from agentux.models import Message + + monkeypatch.setenv("AGENTUX_API_KEY", "k") + + async def fake_run(self, prompt, interactive=False): + self.history.append(Message(role="assistant", content="All done.")) + return "All done." + + monkeypatch.setattr("agentux.agent.Agent.run", fake_run) + + assert main(["do a thing"]) == 0 + assert "All done." in capsys.readouterr().out + + +def test_provider_errors_are_reported_and_exit_nonzero(monkeypatch, capsys): + monkeypatch.setenv("AGENTUX_API_KEY", "k") + + async def fake_run(self, prompt, interactive=False): + raise AuthenticationError("bad key") + + monkeypatch.setattr("agentux.agent.Agent.run", fake_run) + + assert main(["do a thing"]) == 1 + assert "Authentication failed" in capsys.readouterr().err + + +def test_unexpected_errors_do_not_traceback(monkeypatch, capsys): + monkeypatch.setenv("AGENTUX_API_KEY", "k") + + async def fake_run(self, prompt, interactive=False): + raise ValueError("something odd") + + monkeypatch.setattr("agentux.agent.Agent.run", fake_run) + + assert main(["do a thing"]) == 1 + assert "Unexpected error" in capsys.readouterr().err + + +def test_explain_error_covers_each_type(): + """Every error class must render without raising.""" + from agentux.cli import explain_error + from agentux.errors import ( + AgentuxError, MaxStepsError, NetworkError, ProviderError, + RateLimitError, SafetyError, + ) + + for exc in ( + AuthenticationError("x"), RateLimitError("x"), NetworkError("x"), + MaxStepsError("x"), SafetyError("x"), ProviderError("x"), + AgentuxError("x"), ValueError("x"), + ): + explain_error(exc) + + +def test_make_confirmer_denies_on_eof(monkeypatch): + from agentux.cli import make_confirmer + + confirm = make_confirmer() + monkeypatch.setattr("rich.console.Console.input", lambda *a, **k: (_ for _ in ()).throw(EOFError())) + assert confirm("rm -rf /", ["recursive delete"]) is False + + +def test_make_confirmer_accepts_yes(monkeypatch): + from agentux.cli import make_confirmer + + confirm = make_confirmer() + monkeypatch.setattr("rich.console.Console.input", lambda *a, **k: "y") + assert confirm("rm -rf /", ["recursive delete"]) is True + + +def test_make_confirmer_denies_on_empty(monkeypatch): + from agentux.cli import make_confirmer + + confirm = make_confirmer() + monkeypatch.setattr("rich.console.Console.input", lambda *a, **k: "") + assert confirm("rm -rf /", ["recursive delete"]) is False + + +def test_module_entry_point_exists(): + """``python -m agentux`` must be wired up.""" + import importlib + + module = importlib.import_module("agentux.__main__") + assert callable(module.cli) + + +# ------------------------------------------------------------- --list-models +def test_list_models_flag_is_parsed(): + assert build_parser().parse_args(["--list-models"]).list_models is True + + +def test_list_models_prints_models(monkeypatch, capsys): + monkeypatch.setenv("AGENTUX_API_KEY", "ollama") + monkeypatch.setenv("AGENTUX_BASE_URL", "http://localhost:11434/v1") + + async def fake_detailed(self): + return [{"name": "granite4.1:3b", "capabilities": ["completion", "tools"]}] + + monkeypatch.setattr( + "agentux.providers.openai_compatible.OpenAICompatibleProvider.list_models_detailed", + fake_detailed, + ) + + assert main(["--list-models"]) == 0 + assert "granite4.1:3b" in capsys.readouterr().out + + +def test_list_models_warns_about_models_without_tools(monkeypatch, capsys): + monkeypatch.setenv("AGENTUX_API_KEY", "ollama") + + async def fake_detailed(self): + return [{"name": "smollm:135m", "capabilities": ["completion"]}] + + monkeypatch.setattr( + "agentux.providers.openai_compatible.OpenAICompatibleProvider.list_models_detailed", + fake_detailed, + ) + + assert main(["--list-models"]) == 0 + out = capsys.readouterr().out + assert "smollm:135m" in out + assert "no tools" in out + + +def test_list_models_reports_an_unreachable_server(monkeypatch, capsys): + from agentux.errors import NetworkError + + monkeypatch.setenv("AGENTUX_API_KEY", "ollama") + + async def boom(self): + raise NetworkError("Could not reach the provider. Is Ollama running? Try: ollama serve") + + monkeypatch.setattr( + "agentux.providers.openai_compatible.OpenAICompatibleProvider.list_models_detailed", + boom, + ) + + assert main(["--list-models"]) == 1 + assert "Network error" in capsys.readouterr().err + + +def test_list_models_handles_no_models(monkeypatch, capsys): + monkeypatch.setenv("AGENTUX_API_KEY", "ollama") + + async def empty(self): + return [] + + monkeypatch.setattr( + "agentux.providers.openai_compatible.OpenAICompatibleProvider.list_models_detailed", + empty, + ) + + assert main(["--list-models"]) == 1 + + +def test_local_ollama_needs_no_api_key(monkeypatch, capsys): + """The headline Ollama workflow: two env vars, no credential.""" + monkeypatch.delenv("AGENTUX_API_KEY", raising=False) + monkeypatch.setenv("AGENTUX_BASE_URL", "http://localhost:11434/v1") + monkeypatch.setenv("AGENTUX_MODEL", "granite4.1:3b") + + async def fake_detailed(self): + return [{"name": "granite4.1:3b", "capabilities": ["completion", "tools"]}] + + monkeypatch.setattr( + "agentux.providers.openai_compatible.OpenAICompatibleProvider.list_models_detailed", + fake_detailed, + ) + + assert main(["--list-models"]) == 0 diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..2f43b72 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,170 @@ +"""Configuration loading and validation.""" + +import pytest + +from agentux.config import DEFAULT_BASE_URL, Config, load_config +from agentux.errors import ConfigurationError + + +def test_missing_api_key_raises_with_guidance(monkeypatch): + monkeypatch.delenv("AGENTUX_API_KEY", raising=False) + with pytest.raises(ConfigurationError) as exc: + load_config() + assert "AGENTUX_API_KEY is not set" in str(exc.value) + + +def test_key_is_optional_when_not_required(monkeypatch): + monkeypatch.delenv("AGENTUX_API_KEY", raising=False) + config = load_config(require_api_key=False) + assert config.api_key is None + + +def test_loads_from_environment(monkeypatch): + monkeypatch.setenv("AGENTUX_API_KEY", "test-key") + monkeypatch.setenv("AGENTUX_MODEL", "test-model") + monkeypatch.setenv("AGENTUX_BASE_URL", "https://example.test/v1") + monkeypatch.delenv("AGENTUX_TEMPERATURE", raising=False) + monkeypatch.delenv("AGENTUX_MAX_STEPS", raising=False) + + config = load_config() + + assert config.api_key == "test-key" + assert config.model == "test-model" + assert config.base_url == "https://example.test/v1" + + +def test_default_base_url(monkeypatch): + monkeypatch.setenv("AGENTUX_API_KEY", "k") + monkeypatch.delenv("AGENTUX_BASE_URL", raising=False) + assert load_config().base_url == DEFAULT_BASE_URL + + +def test_whitespace_only_key_is_rejected(monkeypatch): + monkeypatch.setenv("AGENTUX_API_KEY", " ") + with pytest.raises(ConfigurationError): + load_config() + + +@pytest.mark.parametrize( + "name,value,message", + [ + ("AGENTUX_MAX_STEPS", "not-an-int", "must be an integer"), + ("AGENTUX_MAX_TOKENS", "many", "must be an integer"), + ("AGENTUX_TEMPERATURE", "warm", "must be a number"), + ("AGENTUX_TIMEOUT", "slow", "must be a number"), + ], +) +def test_invalid_numeric_values(monkeypatch, name, value, message): + monkeypatch.setenv("AGENTUX_API_KEY", "k") + monkeypatch.setenv(name, value) + with pytest.raises(ConfigurationError) as exc: + load_config() + assert name in str(exc.value) + assert message in str(exc.value) + + +def test_blank_numeric_value_falls_back_to_default(monkeypatch): + monkeypatch.setenv("AGENTUX_API_KEY", "k") + monkeypatch.setenv("AGENTUX_MAX_STEPS", " ") + assert load_config().max_steps == 25 + + +def test_repr_never_leaks_the_api_key(): + config = Config(api_key="super-secret-key") + assert "super-secret-key" not in repr(config) + assert "super-secret-key" not in str(config) + assert "***" in repr(config) + + +def test_chat_url_joins_correctly(): + config = Config(api_key="k", base_url="https://x.test/v1/") + assert config.chat_url == "https://x.test/v1/chat/completions" + assert Config(api_key="k", base_url="https://x.test/v1").chat_url.endswith( + "/chat/completions" + ) + + +@pytest.mark.parametrize( + "kwargs", + [ + {"base_url": ""}, + {"base_url": "ftp://x.test"}, + {"model": ""}, + {"max_steps": 0}, + {"max_tokens": 0}, + {"timeout": 0}, + ], +) +def test_validate_rejects_bad_settings(kwargs): + with pytest.raises(ConfigurationError): + Config(api_key="k", **kwargs).validate() + + +def test_validate_accepts_good_settings(): + assert Config(api_key="k").validate() is not None + + +# --------------------------------------------------------------- local servers +@pytest.mark.parametrize( + "url", + [ + "http://localhost:11434/v1", + "http://127.0.0.1:1234/v1", + "http://0.0.0.0:8000/v1", + "http://[::1]:11434/v1", + ], +) +def test_local_urls_are_detected(url): + from agentux.config import is_local_url + + assert is_local_url(url) is True + + +@pytest.mark.parametrize( + "url", + [ + "https://api.openai.com/v1", + "http://ollama.internal:11434/v1", + "https://example.com/v1", + "", + ], +) +def test_remote_urls_are_not_local(url): + from agentux.config import is_local_url + + assert is_local_url(url) is False + + +def test_no_api_key_needed_for_a_local_server(monkeypatch): + """Ollama has no auth; demanding a key there is busywork.""" + monkeypatch.delenv("AGENTUX_API_KEY", raising=False) + monkeypatch.setenv("AGENTUX_BASE_URL", "http://localhost:11434/v1") + monkeypatch.setenv("AGENTUX_MODEL", "granite4.1:3b") + + config = load_config() + + assert config.api_key, "a placeholder is filled in for local servers" + assert config.model == "granite4.1:3b" + + +def test_explicit_key_still_wins_for_local(monkeypatch): + monkeypatch.setenv("AGENTUX_API_KEY", "my-key") + monkeypatch.setenv("AGENTUX_BASE_URL", "http://localhost:11434/v1") + assert load_config().api_key == "my-key" + + +def test_remote_server_still_requires_a_key(monkeypatch): + monkeypatch.delenv("AGENTUX_API_KEY", raising=False) + monkeypatch.setenv("AGENTUX_BASE_URL", "https://api.openai.com/v1") + with pytest.raises(ConfigurationError): + load_config() + + +def test_config_exposes_endpoints_and_locality(): + config = Config(api_key="k", base_url="http://localhost:11434/v1") + assert config.is_local is True + assert config.models_url == "http://localhost:11434/v1/models" + assert config.chat_url == "http://localhost:11434/v1/chat/completions" + + remote = Config(api_key="k", base_url="https://api.openai.com/v1") + assert remote.is_local is False diff --git a/tests/test_providers.py b/tests/test_providers.py new file mode 100644 index 0000000..1ecff83 --- /dev/null +++ b/tests/test_providers.py @@ -0,0 +1,594 @@ +"""Provider layer: request shaping, response parsing, and error mapping. + +httpx is mocked throughout; nothing here touches the network. +""" + +import json + +import httpx +import pytest + +from agentux.config import Config +from agentux.errors import ( + AuthenticationError, + MalformedResponseError, + ModelNotFoundError, + NetworkError, + ProviderError, + RateLimitError, + UnsupportedToolCallingError, +) +from agentux.models import Message, ToolCall, ToolDefinition +from agentux.providers.openai_compatible import OpenAICompatibleProvider + + +@pytest.fixture +def config(): + return Config(api_key="test-key", base_url="http://api.test/v1", model="test-model") + + +@pytest.fixture +def provider(config): + return OpenAICompatibleProvider(config) + + +def _response(payload, status_code=200): + """Build a fake httpx.Response.""" + response = httpx.Response( + status_code=status_code, + json=payload, + request=httpx.Request("POST", "http://api.test/v1/chat/completions"), + ) + return response + + +def _patch_post(monkeypatch, response): + async def fake_post(self, url, **kwargs): + fake_post.last_call = {"url": url, **kwargs} + return response + + monkeypatch.setattr(httpx.AsyncClient, "post", fake_post) + return fake_post + + +async def test_returns_assistant_content(provider, monkeypatch): + _patch_post(monkeypatch, _response({"choices": [{"message": {"content": "Hi"}}]})) + + message = await provider.chat([Message(role="user", content="Hello")]) + + assert message.role == "assistant" + assert message.content == "Hi" + assert message.tool_calls is None + + +async def test_sends_model_and_authorization(provider, monkeypatch): + fake = _patch_post(monkeypatch, _response({"choices": [{"message": {"content": "ok"}}]})) + + await provider.chat([Message(role="user", content="Hello")]) + + assert fake.last_call["url"] == "http://api.test/v1/chat/completions" + assert fake.last_call["headers"]["Authorization"] == "Bearer test-key" + assert fake.last_call["json"]["model"] == "test-model" + + +async def test_parses_structured_tool_calls(provider, monkeypatch): + """The model must be able to request tools through the native mechanism.""" + _patch_post( + monkeypatch, + _response( + { + "choices": [ + { + "message": { + "content": None, + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": { + "name": "shell", + "arguments": '{"command": "ls"}', + }, + } + ], + } + } + ] + } + ), + ) + + message = await provider.chat([Message(role="user", content="List files")]) + + assert len(message.tool_calls) == 1 + assert message.tool_calls[0].name == "shell" + assert message.tool_calls[0].arguments == {"command": "ls"} + assert message.tool_calls[0].id == "call_1" + + +async def test_parses_multiple_tool_calls(provider, monkeypatch): + _patch_post( + monkeypatch, + _response( + { + "choices": [ + { + "message": { + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": {"name": "read", "arguments": '{"path": "a"}'}, + }, + { + "id": "call_2", + "type": "function", + "function": {"name": "read", "arguments": '{"path": "b"}'}, + }, + ] + } + } + ] + } + ), + ) + + message = await provider.chat([Message(role="user", content="go")]) + + assert [c.name for c in message.tool_calls] == ["read", "read"] + assert [c.id for c in message.tool_calls] == ["call_1", "call_2"] + + +async def test_tool_definitions_are_sent_with_openai_schema(provider, monkeypatch): + fake = _patch_post(monkeypatch, _response({"choices": [{"message": {"content": "ok"}}]})) + tools = [ + ToolDefinition( + name="filesystem", + description="Files", + parameters={"type": "object", "properties": {"path": {"type": "string"}}}, + ) + ] + + await provider.chat([Message(role="user", content="x")], tools) + + payload = fake.last_call["json"] + assert payload["tools"][0]["type"] == "function" + assert payload["tools"][0]["function"]["name"] == "filesystem" + assert payload["tool_choice"] == "auto" + + +async def test_omits_tools_key_when_no_tools(provider, monkeypatch): + fake = _patch_post(monkeypatch, _response({"choices": [{"message": {"content": "ok"}}]})) + + await provider.chat([Message(role="user", content="x")], []) + + assert "tools" not in fake.last_call["json"] + + +async def test_tool_result_message_round_trips(provider, monkeypatch): + """A tool result must be sent back with its tool_call_id intact.""" + fake = _patch_post(monkeypatch, _response({"choices": [{"message": {"content": "ok"}}]})) + + await provider.chat( + [ + Message(role="user", content="run ls"), + Message( + role="assistant", + tool_calls=[ToolCall(id="call_1", name="shell", arguments={"command": "ls"})], + ), + Message(role="tool", content="file.txt", tool_call_id="call_1"), + ] + ) + + sent = fake.last_call["json"]["messages"] + assert sent[1]["tool_calls"][0]["id"] == "call_1" + assert json.loads(sent[1]["tool_calls"][0]["function"]["arguments"]) == {"command": "ls"} + assert sent[2]["role"] == "tool" + assert sent[2]["tool_call_id"] == "call_1" + + +@pytest.mark.parametrize( + "status,expected", + [ + (401, AuthenticationError), + (403, AuthenticationError), + (404, ModelNotFoundError), + (429, RateLimitError), + (500, ProviderError), + (400, ProviderError), + (418, ProviderError), + ], +) +async def test_http_errors_map_to_useful_exceptions(provider, monkeypatch, status, expected): + _patch_post(monkeypatch, _response({"error": "nope"}, status_code=status)) + + with pytest.raises(expected): + await provider.chat([Message(role="user", content="x")]) + + +async def test_auth_error_mentions_the_env_var(provider, monkeypatch): + _patch_post(monkeypatch, _response({"error": "bad key"}, status_code=401)) + + with pytest.raises(AuthenticationError) as exc: + await provider.chat([Message(role="user", content="x")]) + + assert "AGENTUX_API_KEY" in str(exc.value) + + +async def test_network_failure_is_reported(provider, monkeypatch): + async def boom(self, url, **kwargs): + raise httpx.ConnectError("connection refused") + + monkeypatch.setattr(httpx.AsyncClient, "post", boom) + + with pytest.raises(NetworkError): + await provider.chat([Message(role="user", content="x")]) + + +async def test_timeout_is_reported(provider, monkeypatch): + async def boom(self, url, **kwargs): + raise httpx.ReadTimeout("too slow") + + monkeypatch.setattr(httpx.AsyncClient, "post", boom) + + with pytest.raises(ProviderError) as exc: + await provider.chat([Message(role="user", content="x")]) + + assert "timeout" in str(exc.value).lower() + + +@pytest.mark.parametrize( + "payload", + [ + {}, + {"choices": []}, + {"choices": [{}]}, + {"choices": [{"message": "not an object"}]}, + [1, 2, 3], + ], +) +async def test_malformed_responses_raise(provider, monkeypatch, payload): + _patch_post(monkeypatch, _response(payload)) + + with pytest.raises(MalformedResponseError): + await provider.chat([Message(role="user", content="x")]) + + +async def test_unparseable_tool_arguments_raise(provider, monkeypatch): + _patch_post( + monkeypatch, + _response( + { + "choices": [ + { + "message": { + "tool_calls": [ + { + "id": "c1", + "type": "function", + "function": {"name": "shell", "arguments": "{not json"}, + } + ] + } + } + ] + } + ), + ) + + with pytest.raises(MalformedResponseError): + await provider.chat([Message(role="user", content="x")]) + + +async def test_empty_tool_arguments_become_empty_dict(provider, monkeypatch): + _patch_post( + monkeypatch, + _response( + { + "choices": [ + { + "message": { + "tool_calls": [ + { + "id": "c1", + "type": "function", + "function": {"name": "shell", "arguments": ""}, + } + ] + } + } + ] + } + ), + ) + + message = await provider.chat([Message(role="user", content="x")]) + assert message.tool_calls[0].arguments == {} + + +async def test_tool_call_without_function_name_raises(provider, monkeypatch): + _patch_post( + monkeypatch, + _response( + { + "choices": [ + {"message": {"tool_calls": [{"id": "c1", "type": "function"}]}} + ] + } + ), + ) + + with pytest.raises(MalformedResponseError): + await provider.chat([Message(role="user", content="x")]) + + +async def test_non_json_body_raises(provider, monkeypatch): + response = httpx.Response( + status_code=200, + text="<html>login page</html>", + request=httpx.Request("POST", "http://api.test/v1/chat/completions"), + ) + _patch_post(monkeypatch, response) + + with pytest.raises(MalformedResponseError): + await provider.chat([Message(role="user", content="x")]) + + +def test_supports_tool_calling(provider): + assert provider.supports_tool_calling() is True + + +def test_get_model_name(provider): + assert provider.get_model_name() == "test-model" + + +# ------------------------------------------------------- Ollama compatibility +def _ollama_provider(): + return OpenAICompatibleProvider( + Config(api_key="ollama", base_url="http://localhost:11434/v1", model="qwen2.5-coder:7b") + ) + + +async def test_ollama_tool_calls_are_parsed(monkeypatch): + """Ollama returns standard OpenAI-shaped tool calls; they must work.""" + _patch_post( + monkeypatch, + _response( + { + "choices": [ + { + "message": { + "role": "assistant", + "content": "", + "tool_calls": [ + { + "id": "call_2jhbt3ex", + "index": 0, + "type": "function", + "function": { + "name": "filesystem", + "arguments": '{"action":"overview"}', + }, + } + ], + }, + "finish_reason": "tool_calls", + } + ] + } + ), + ) + + message = await _ollama_provider().chat( + [Message(role="user", content="look")], + [ToolDefinition(name="filesystem", description="f", parameters={"type": "object"})], + ) + + assert message.tool_calls[0].name == "filesystem" + assert message.tool_calls[0].arguments == {"action": "overview"} + assert message.content is None, "empty content beside tool calls becomes None" + + +async def test_emulated_tool_call_is_refused_not_executed(monkeypatch): + """A model printing JSON as text must be rejected, never parsed and run.""" + _patch_post( + monkeypatch, + _response( + { + "choices": [ + { + "message": { + "role": "assistant", + "content": '{"name": "filesystem", "arguments": {"operation": "rm"}}', + } + } + ] + } + ), + ) + + with pytest.raises(UnsupportedToolCallingError) as exc: + await _ollama_provider().chat( + [Message(role="user", content="delete things")], + [ToolDefinition(name="filesystem", description="f", parameters={"type": "object"})], + ) + + assert "plain text" in str(exc.value) + + +async def test_plain_prose_is_not_mistaken_for_a_tool_call(monkeypatch): + """Normal answers must never trip the emulation check.""" + _patch_post( + monkeypatch, + _response({"choices": [{"message": {"content": "I can read files for you."}}]}), + ) + + message = await _ollama_provider().chat( + [Message(role="user", content="hi")], + [ToolDefinition(name="filesystem", description="f", parameters={"type": "object"})], + ) + + assert message.content == "I can read files for you." + + +async def test_json_for_an_unknown_tool_is_left_alone(monkeypatch): + """Only shapes naming a real tool count as a botched tool call.""" + _patch_post( + monkeypatch, + _response( + {"choices": [{"message": {"content": '{"name": "rm_rf_slash", "arguments": {}}'}}]} + ), + ) + + message = await _ollama_provider().chat( + [Message(role="user", content="hi")], + [ToolDefinition(name="filesystem", description="f", parameters={"type": "object"})], + ) + + assert message.content.startswith('{"name"') + + +async def test_ollama_no_tool_support_error_is_actionable(monkeypatch): + _patch_post( + monkeypatch, + _response( + { + "error": { + "message": "registry.ollama.ai/library/deepseek-coder:33b does not support tools", + "type": "invalid_request_error", + } + }, + status_code=400, + ), + ) + + with pytest.raises(UnsupportedToolCallingError) as exc: + await _ollama_provider().chat([Message(role="user", content="x")]) + + message = str(exc.value) + assert "deepseek-coder:33b" in message + assert "--no-tools" in message + + +async def test_ollama_404_suggests_pull(monkeypatch): + _patch_post( + monkeypatch, + _response({"error": {"message": "model 'nope' not found", "type": "not_found_error"}}, + status_code=404), + ) + + with pytest.raises(ModelNotFoundError) as exc: + await _ollama_provider().chat([Message(role="user", content="x")]) + + assert "ollama pull" in str(exc.value) + assert "--list-models" in str(exc.value) + + +async def test_thinking_model_reasoning_field_is_ignored(monkeypatch): + """Ollama thinking models add a 'reasoning' key; it must not corrupt the answer.""" + _patch_post( + monkeypatch, + _response( + { + "choices": [ + { + "message": { + "role": "assistant", + "content": "The answer is 4.", + "reasoning": "Let me think about this...", + } + } + ] + } + ), + ) + + message = await _ollama_provider().chat([Message(role="user", content="2+2?")]) + + assert message.content == "The answer is 4." + assert "reasoning" not in message.content + + +async def test_list_models_reads_the_openai_shapes(provider, monkeypatch): + async def fake_get(self, url, **kwargs): + fake_get.url = url + return _response({"object": "list", "data": [{"id": "granite4.1:3b"}, {"id": "llama3.1:8b"}]}) + + monkeypatch.setattr(httpx.AsyncClient, "get", fake_get) + + names = await provider.list_models() + + assert names == ["granite4.1:3b", "llama3.1:8b"] + assert fake_get.url == "http://api.test/v1/models" + + +async def test_list_models_merges_ollama_capabilities(monkeypatch): + """Ollama's native /api/tags is what reports tool support.""" + provider = _ollama_provider() + calls = [] + + async def fake_get(self, url, **kwargs): + calls.append(url) + if url.endswith("/v1/models"): + return _response({"data": [{"id": "granite4.1:3b"}, {"id": "smollm:135m"}]}) + return _response( + { + "models": [ + {"name": "granite4.1:3b", "capabilities": ["completion", "tools"]}, + {"name": "smollm:135m", "capabilities": ["completion"]}, + ] + } + ) + + monkeypatch.setattr(httpx.AsyncClient, "get", fake_get) + + models = await provider.list_models_detailed() + by_name = {m["name"]: m for m in models} + + assert by_name["granite4.1:3b"]["capabilities"] == ["completion", "tools"] + assert by_name["smollm:135m"]["capabilities"] == ["completion"] + assert "http://localhost:11434/api/tags" in calls + + +async def test_list_models_degrades_when_capabilities_are_unavailable(monkeypatch): + """A local server that is not Ollama must still list models.""" + provider = OpenAICompatibleProvider( + Config(api_key="k", base_url="http://localhost:1234/v1", model="m") + ) + + async def fake_get(self, url, **kwargs): + if url.endswith("/v1/models"): + return _response({"data": [{"id": "some-model"}]}) + return _response({"error": "not found"}, status_code=404) + + monkeypatch.setattr(httpx.AsyncClient, "get", fake_get) + + models = await provider.list_models_detailed() + + assert models == [{"name": "some-model"}] + + +async def test_list_models_reports_an_unreachable_server(provider, monkeypatch): + async def boom(self, url, **kwargs): + raise httpx.ConnectError("connection refused") + + monkeypatch.setattr(httpx.AsyncClient, "get", boom) + + with pytest.raises(NetworkError) as exc: + await provider.list_models() + + assert "ollama serve" in str(exc.value) + + +def test_looks_like_emulated_tool_call_shapes(): + from agentux.providers.openai_compatible import looks_like_emulated_tool_call + + tools = [ToolDefinition(name="filesystem", description="f", parameters={})] + + assert looks_like_emulated_tool_call('{"name": "filesystem", "arguments": {}}', tools) + assert looks_like_emulated_tool_call( + '{"name": "filesystem", "arguments": "{\\"path\\": \\"a\\"}"}', tools + ) + assert not looks_like_emulated_tool_call("just prose", tools) + assert not looks_like_emulated_tool_call('{"name": "other", "arguments": {}}', tools) + assert not looks_like_emulated_tool_call("no tools offered", None) diff --git a/tests/test_safety.py b/tests/test_safety.py new file mode 100644 index 0000000..465e552 --- /dev/null +++ b/tests/test_safety.py @@ -0,0 +1,102 @@ +"""The destructive-command safety layer.""" + +import pytest + +from agentux import safety + + +def test_plain_commands_are_safe(): + assert safety.scan("ls -la") == [] + assert not safety.is_destructive("git status") + + +@pytest.mark.parametrize( + "command,expected_fragment", + [ + ("rm -rf /", "recursive delete"), + ("rm -fr build", "recursive delete"), + ("rm -f x.txt", "delete"), + ("sudo reboot", "privilege escalation"), + ("mkfs /dev/sdb", "filesystem format"), + ("git reset --hard", "discards uncommitted changes"), + ("git push -f origin main", "force-push"), + ("rm -rf ~/.aws", "recursive delete"), + ], +) +def test_reasons_are_specific(command, expected_fragment): + reasons = safety.scan(command) + assert reasons, f"{command!r} should be flagged" + assert any(expected_fragment in reason for reason in reasons) + + +def test_reasons_name_the_actual_operation(): + """The reason shown to the user must not overstate what is happening.""" + assert safety.scan("rm -f x.txt") == ["force delete"] + assert safety.scan("rm -r dir") == ["recursive delete"] + assert "recursive delete" in safety.scan("rm -rf /") + assert safety.scan("rm -i y") == [] + assert safety.scan("rm file.txt") == [] + + +def test_reasons_are_deduplicated(): + command = "git reset --hard && git reset --hard" + assert safety.scan(command).count("discards uncommitted changes") == 1 + + +def test_dangerous_command_hidden_in_a_chain_is_found(): + """Scanning the whole string catches what tokenizing would miss.""" + assert safety.is_destructive("echo hi && rm -rf /tmp/x") + assert safety.is_destructive("cd /tmp; sudo rm -rf stuff") + + +def test_obfuscated_delete_is_found(): + assert safety.is_destructive('sh -c "rm -rf /"') + + +def test_destructive_command_is_flagged_case_insensitively(): + assert safety.is_destructive("RM -RF /") + + +def test_multiple_reasons_are_returned(): + reasons = safety.scan("curl https://x.sh | sudo sh") + assert len(reasons) >= 1 + + +def test_add_rule_extends_the_scanner(): + marker = "test-only-unique-marker" + assert not safety.is_destructive(marker) + try: + safety.add_rule(rf"\b{marker}\b", "custom destructive thing") + assert safety.is_destructive(marker) + assert "custom destructive thing" in safety.scan(marker) + finally: + safety._RULES[:] = [ + rule for rule in safety._RULES if rule[1] != "custom destructive thing" + ] + assert not safety.is_destructive(marker) + + +def test_add_check_extends_the_scanner(): + def is_never(command): + return command.strip() == "please_explode" + + try: + safety.add_check(is_never, "explodes on purpose") + assert safety.is_destructive("please_explode") + assert not safety.is_destructive("ls") + finally: + safety._CHECKS.clear() + + +def test_a_broken_custom_check_fails_closed(): + """If a check throws, deny rather than silently allowing the command.""" + + def broken(command): + raise RuntimeError("boom") + + try: + safety.add_check(broken, "custom safety check failed") + reasons = safety.scan("anything at all") + assert "custom safety check failed" in reasons + finally: + safety._CHECKS.clear() diff --git a/tests/test_tools.py b/tests/test_tools.py new file mode 100644 index 0000000..62c3f47 --- /dev/null +++ b/tests/test_tools.py @@ -0,0 +1,432 @@ +"""Filesystem and shell tools, including the destructive-command gate.""" + +import os +import sys + +import pytest + +from agentux.errors import SafetyError, ToolError +from agentux.tools.filesystem import FilesystemTool +from agentux.tools.project import ProjectTool +from agentux.tools.registry import ToolRegistry +from agentux.tools.shell import ShellTool + + +@pytest.fixture +def fs(tmp_path): + return FilesystemTool(root=str(tmp_path)) + + +# ---------------------------------------------------------------- filesystem +async def test_write_then_read(fs, tmp_path): + await fs.execute(operation="write", path="a.txt", content="hello world") + assert (tmp_path / "a.txt").read_text() == "hello world" + assert await fs.execute(operation="read", path="a.txt") == "hello world" + + +async def test_read_missing_file_reports_clearly(fs): + with pytest.raises(ToolError) as exc: + await fs.execute(operation="read", path="nope.txt") + assert "does not exist" in str(exc.value) + + +async def test_read_a_directory_reports_clearly(fs, tmp_path): + (tmp_path / "d").mkdir() + with pytest.raises(ToolError) as exc: + await fs.execute(operation="read", path="d") + assert "is a directory" in str(exc.value) + + +async def test_write_creates_parent_directories(fs, tmp_path): + await fs.execute(operation="write", path="deep/nested/a.txt", content="x") + assert (tmp_path / "deep" / "nested" / "a.txt").read_text() == "x" + + +async def test_ls_lists_files_and_marks_directories(fs, tmp_path): + (tmp_path / "file1.txt").write_text("1") + (tmp_path / "dir1").mkdir() + + result = await fs.execute(operation="ls", path=".") + + assert "file1.txt" in result + assert "dir1/" in result + + +async def test_ls_on_a_file_is_rejected(fs, tmp_path): + (tmp_path / "f.txt").write_text("x") + with pytest.raises(ToolError) as exc: + await fs.execute(operation="ls", path="f.txt") + assert "not a directory" in str(exc.value) + + +async def test_mkdir(fs, tmp_path): + await fs.execute(operation="mkdir", path="new/dir") + assert (tmp_path / "new" / "dir").is_dir() + + +async def test_edit_replaces_only_the_target_text(fs, tmp_path): + (tmp_path / "a.py").write_text("def one():\n return 1\n\ndef two():\n return 2\n") + + result = await fs.execute( + operation="edit", + path="a.py", + old_string=" return 2", + new_string=" return 200", + ) + + content = (tmp_path / "a.py").read_text() + assert "return 200" in content + assert "def one():\n return 1" in content, "unrelated content must survive" + assert "Edited a.py" in result + assert "+ return 200" in result, "the diff should show the change" + + +async def test_edit_fails_when_text_is_absent(fs, tmp_path): + (tmp_path / "a.py").write_text("hello\n") + with pytest.raises(ToolError) as exc: + await fs.execute(operation="edit", path="a.py", old_string="goodbye", new_string="x") + assert "not found" in str(exc.value) + assert (tmp_path / "a.py").read_text() == "hello\n", "file must be unchanged" + + +async def test_edit_refuses_ambiguous_matches(fs, tmp_path): + (tmp_path / "a.py").write_text("x = 1\nx = 1\n") + with pytest.raises(ToolError) as exc: + await fs.execute(operation="edit", path="a.py", old_string="x = 1", new_string="x = 2") + assert "2 times" in str(exc.value) + assert (tmp_path / "a.py").read_text() == "x = 1\nx = 1\n" + + +async def test_edit_can_delete_text(fs, tmp_path): + (tmp_path / "a.py").write_text("keep\nremove\nkeep\n") + await fs.execute(operation="edit", path="a.py", old_string="remove\n", new_string="") + assert (tmp_path / "a.py").read_text() == "keep\nkeep\n" + + +async def test_write_to_a_directory_is_rejected(fs, tmp_path): + (tmp_path / "d").mkdir() + with pytest.raises(ToolError): + await fs.execute(operation="write", path="d", content="x") + + +async def test_rm_file_and_directory(fs, tmp_path): + (tmp_path / "gone.txt").write_text("x") + (tmp_path / "d").mkdir() + + await fs.execute(operation="rm", path="gone.txt") + await fs.execute(operation="rm", path="d") + + assert not (tmp_path / "gone.txt").exists() + assert not (tmp_path / "d").exists() + + +async def test_rm_missing_path_is_reported(fs): + with pytest.raises(ToolError) as exc: + await fs.execute(operation="rm", path="ghost") + assert "does not exist" in str(exc.value) + + +async def test_rm_refuses_to_delete_the_workspace_root(fs, tmp_path): + with pytest.raises(ToolError) as exc: + await fs.execute(operation="rm", path=str(tmp_path)) + assert "workspace root" in str(exc.value) + + +async def test_mv(fs, tmp_path): + (tmp_path / "a.txt").write_text("x") + await fs.execute(operation="mv", path="a.txt", destination="b.txt") + assert (tmp_path / "b.txt").read_text() == "x" + assert not (tmp_path / "a.txt").exists() + + +async def test_mv_onto_existing_file_is_rejected(fs, tmp_path): + (tmp_path / "a.txt").write_text("x") + (tmp_path / "b.txt").write_text("y") + with pytest.raises(ToolError) as exc: + await fs.execute(operation="mv", path="a.txt", destination="b.txt") + assert "already exists" in str(exc.value) + + +@pytest.mark.parametrize( + "escape", + ["../outside.txt", "../../etc/passwd", "/etc/passwd", "sub/../../escape.txt"], +) +async def test_paths_outside_the_workspace_are_rejected(fs, tmp_path, escape): + with pytest.raises(ToolError) as exc: + await fs.execute(operation="write", path=escape, content="x") + assert "outside the workspace" in str(exc.value) + + +async def test_symlink_escape_is_rejected(fs, tmp_path): + outside = tmp_path.parent / "outside_target" + outside.mkdir(exist_ok=True) + secret = outside / "secret.txt" + secret.write_text("classified") + link = tmp_path / "link" + os.symlink(outside, link) + + with pytest.raises(ToolError) as exc: + await fs.execute(operation="read", path="link/secret.txt") + assert "outside the workspace" in str(exc.value) + + +async def test_glob_finds_files(fs, tmp_path): + (tmp_path / "src").mkdir() + (tmp_path / "src" / "a.py").write_text("") + (tmp_path / "src" / "b.py").write_text("") + + result = await fs.execute(operation="glob", path=".", pattern="**/*.py") + + assert "src/a.py" in result + assert "src/b.py" in result + + +async def test_unsupported_operation_is_rejected(fs): + with pytest.raises(ToolError) as exc: + await fs.execute(operation="chmod", path="a") + assert "Unsupported operation" in str(exc.value) + + +async def test_read_only_tool_refuses_writes(tmp_path): + tool = FilesystemTool(root=str(tmp_path), read_only=True) + with pytest.raises(ToolError) as exc: + await tool.execute(operation="write", path="a.txt", content="x") + assert "read-only" in str(exc.value) + + +async def test_read_only_tool_still_reads(tmp_path): + (tmp_path / "a.txt").write_text("readable") + tool = FilesystemTool(root=str(tmp_path), read_only=True) + assert await tool.execute(operation="read", path="a.txt") == "readable" + + +async def test_tool_definition_shape(fs): + definition = fs.to_definition() + assert definition.name == "filesystem" + assert "read" in definition.parameters["properties"]["operation"]["enum"] + assert definition.parameters["required"] == ["operation", "path"] + + +# -------------------------------------------------------------------- shell +async def test_shell_returns_stdout_and_exit_code(tmp_path): + tool = ShellTool(cwd=str(tmp_path)) + result = await tool.execute(command="echo hello") + assert "hello" in result + assert "EXIT CODE: 0" in result + + +async def test_shell_returns_stderr_and_nonzero_exit(tmp_path): + tool = ShellTool(cwd=str(tmp_path)) + result = await tool.execute(command=f"{sys.executable} -c \"import sys; sys.stderr.write('bad'); sys.exit(3)\"") + assert "bad" in result + assert "EXIT CODE: 3" in result + + +async def test_shell_respects_timeout(tmp_path): + tool = ShellTool(cwd=str(tmp_path), timeout=1) + with pytest.raises(ToolError) as exc: + await tool.execute(command="sleep 30") + assert "timed out" in str(exc.value) + + +async def test_shell_runs_in_the_working_directory(tmp_path): + (tmp_path / "marker.txt").write_text("here") + tool = ShellTool(cwd=str(tmp_path)) + assert "marker.txt" in await tool.execute(command="ls") + + +async def test_shell_honors_cwd_argument(tmp_path): + (tmp_path / "sub").mkdir() + (tmp_path / "sub" / "inner.txt").write_text("x") + tool = ShellTool(cwd=str(tmp_path)) + assert "inner.txt" in await tool.execute(command="ls", cwd="sub") + + +async def test_shell_rejects_empty_command(tmp_path): + tool = ShellTool(cwd=str(tmp_path)) + with pytest.raises(ToolError): + await tool.execute(command=" ") + + +# ------------------------------------------------------------ shell safety +async def test_destructive_command_is_blocked_without_a_confirmer(tmp_path): + tool = ShellTool(cwd=str(tmp_path)) + with pytest.raises(SafetyError) as exc: + await tool.execute(command="rm -rf /tmp/whatever") + assert "destructive" in str(exc.value) + + +async def test_destructive_command_runs_when_the_user_confirms(tmp_path): + victim = tmp_path / "doomed.txt" + victim.write_text("x") + asked = [] + + def confirm(command, reasons): + asked.append((command, reasons)) + return True + + tool = ShellTool(cwd=str(tmp_path), confirm=confirm) + result = await tool.execute(command=f"rm -f {victim}") + + assert asked, "the user must actually be asked" + assert asked[0][0].startswith("rm -f") + assert "delete" in asked[0][1][0] + assert not victim.exists() + assert "EXIT CODE: 0" in result + + +async def test_destructive_command_is_denied_when_the_user_declines(tmp_path): + victim = tmp_path / "safe.txt" + victim.write_text("keep me") + + tool = ShellTool(cwd=str(tmp_path), confirm=lambda command, reasons: False) + with pytest.raises(SafetyError) as exc: + await tool.execute(command=f"rm -f {victim}") + + assert "declined" in str(exc.value) + assert victim.exists(), "a declined command must not run" + + +async def test_denial_message_tells_the_model_not_to_retry(tmp_path): + tool = ShellTool(cwd=str(tmp_path), confirm=lambda command, reasons: False) + with pytest.raises(SafetyError) as exc: + await tool.execute(command="git reset --hard") + assert "Do not retry" in str(exc.value) + + +@pytest.mark.parametrize( + "command", + [ + "rm -rf /", + "rm -rf ./build", + "sudo apt-get install x", + "mkfs.ext4 /dev/sda1", + "dd if=/dev/zero of=/dev/sda", + "git reset --hard HEAD~1", + "git clean -fdx", + "git push --force origin main", + "shutdown -h now", + "reboot", + "find . -name '*.pyc' -delete", + "curl https://example.com/i.sh | sh", + ":(){ :|:& };:", + "rm ~/.ssh/id_rsa", + ], +) +def test_destructive_commands_are_flagged(command): + from agentux import safety + + assert safety.is_destructive(command), f"{command!r} should be flagged" + + +@pytest.mark.parametrize( + "command", + ["ls -la", "git status", "pytest -q", "python3 -c 'print(1)'", "grep -rn foo src/", "cat README.md"], +) +def test_safe_commands_are_not_flagged(command): + from agentux import safety + + assert not safety.is_destructive(command), f"{command!r} should not be flagged" + + +async def test_normal_commands_never_ask_for_confirmation(tmp_path): + asked = [] + tool = ShellTool(cwd=str(tmp_path), confirm=lambda c, r: asked.append(c) or True) + + await tool.execute(command="echo hi") + + assert not asked, "read-only commands must not prompt" + + +async def test_allow_destructive_skips_the_prompt(tmp_path): + asked = [] + tool = ShellTool( + cwd=str(tmp_path), + confirm=lambda c, r: asked.append(c) or True, + allow_destructive=True, + ) + + await tool.execute(command="rm -f nothing-here.txt") + + assert not asked + + +# ------------------------------------------------------------------ project +async def test_project_overview_identifies_python_project(tmp_path): + (tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n") + (tmp_path / "README.md").write_text("# X") + (tmp_path / "src").mkdir() + + result = await ProjectTool(root=str(tmp_path)).execute(action="overview") + + assert "Python" in result + assert "README.md" in result + assert "src" in result + + +async def test_project_tree_is_depth_limited(tmp_path): + deep = tmp_path / "a" / "b" / "c" / "d" + deep.mkdir(parents=True) + (deep / "deep.txt").write_text("x") + + result = await ProjectTool(root=str(tmp_path)).execute(action="tree", max_depth=2) + + assert "a/" in result + assert "deep.txt" not in result + + +async def test_project_overview_skips_noise_directories(tmp_path): + (tmp_path / "node_modules").mkdir() + (tmp_path / "node_modules" / "junk.js").write_text("x") + (tmp_path / "src").mkdir() + + result = await ProjectTool(root=str(tmp_path)).execute(action="overview") + + assert "node_modules" not in result + assert "src" in result + + +async def test_project_tracked_requires_git(tmp_path): + from agentux.errors import ToolError as AgentuxToolError + + if not os.path.isdir(str(tmp_path / ".git")): + with pytest.raises(AgentuxToolError): + await ProjectTool(root=str(tmp_path)).execute(action="tracked") + + +async def test_project_rejects_unknown_action(tmp_path): + with pytest.raises(ToolError) as exc: + await ProjectTool(root=str(tmp_path)).execute(action="explode") + assert "Unsupported action" in str(exc.value) + + +# ----------------------------------------------------------------- registry +def test_registry_lookup_and_definitions(tmp_path): + registry = ToolRegistry([FilesystemTool(root=str(tmp_path)), ShellTool()]) + + assert len(registry) == 2 + assert "filesystem" in registry + assert "shell" in registry.names + assert [d.name for d in registry.definitions()] == ["filesystem", "shell"] + assert registry.get("shell").name == "shell" + + +def test_registry_unknown_tool_raises_with_options(tmp_path): + from agentux.errors import ToolNotFoundError + + registry = ToolRegistry([FilesystemTool(root=str(tmp_path))]) + + with pytest.raises(ToolNotFoundError) as exc: + registry.get("teleport") + + assert "Available tools: filesystem" in str(exc.value) + + +def test_registry_rejects_unsupported_tool(): + class NotATool: + name = "fake" + + from agentux.tools.base import BaseTool + + assert issubclass(FilesystemTool, BaseTool) + assert not issubclass(NotATool, BaseTool) |
